code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def connect_ssh(*args, **kwargs): """ Create a new connected :class:`SSHClient` instance. All arguments are passed to :meth:`SSHClient.connect`. """ client = SSHClient() client.connect(*args, **kwargs) return client
Create a new connected :class:`SSHClient` instance. All arguments are passed to :meth:`SSHClient.connect`.
def _iflat_tasks_wti(self, status=None, op="==", nids=None, with_wti=True): """ Generators that produces a flat sequence of task. if status is not None, only the tasks with the specified status are selected. nids is an optional list of node identifiers used to filter the tasks. ...
Generators that produces a flat sequence of task. if status is not None, only the tasks with the specified status are selected. nids is an optional list of node identifiers used to filter the tasks. Returns: (task, work_index, task_index) if with_wti is True else task
def check_network_health(self): r""" This method check the network topological health by checking for: (1) Isolated pores (2) Islands or isolated clusters of pores (3) Duplicate throats (4) Bidirectional throats (ie. symmetrical adjacency matrix) ...
r""" This method check the network topological health by checking for: (1) Isolated pores (2) Islands or isolated clusters of pores (3) Duplicate throats (4) Bidirectional throats (ie. symmetrical adjacency matrix) (5) Headless throats Return...
def cli(ctx, timeout, proxy, output, quiet, lyric, again): """A command tool to download NetEase-Music's songs.""" ctx.obj = NetEase(timeout, proxy, output, quiet, lyric, again)
A command tool to download NetEase-Music's songs.
def flush_to_index(self): """Flush changes in our configuration file to the index""" assert self._smref is not None # should always have a file here assert not isinstance(self._file_or_files, BytesIO) sm = self._smref() if sm is not None: index = self._index ...
Flush changes in our configuration file to the index
def _getphoto_location(self,pid): """Asks fb for photo location information returns tuple with lat,lon,accuracy """ logger.debug('%s - Getting location from fb'%(pid)) lat=None lon=None accuracy=None resp=self.fb.photos_geo_getLocation(photo_id=pid) ...
Asks fb for photo location information returns tuple with lat,lon,accuracy
def view_page(name=None): """Serve a page name. .. note:: this is a bottle view * if the view is called with the POST method, write the new page content to the file, commit the modification and then display the html rendering of the restructured text file * if the view is called with the ...
Serve a page name. .. note:: this is a bottle view * if the view is called with the POST method, write the new page content to the file, commit the modification and then display the html rendering of the restructured text file * if the view is called with the GET method, directly display the ...
def send(node_name): """ Send our information to a remote nago instance Arguments: node -- node_name or token for the node this data belongs to """ my_data = nago.core.get_my_info() if not node_name: node_name = nago.settings.get('server') node = nago.core.get_node(node_name) ...
Send our information to a remote nago instance Arguments: node -- node_name or token for the node this data belongs to
def logger_init(level): """ Initialize the logger for this thread. Sets the log level to ERROR (0), WARNING (1), INFO (2), or DEBUG (3), depending on the argument `level`. """ levellist = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG] handler = logging.StreamHandler() fmt...
Initialize the logger for this thread. Sets the log level to ERROR (0), WARNING (1), INFO (2), or DEBUG (3), depending on the argument `level`.
def serialize(self): """Serialize the full configuration to a single dictionary. For any instance that has passed validate() (which happens in __init__), it matches the Configuration contract. Note that args are not serialized. :returns dict: The serialized configuration. ...
Serialize the full configuration to a single dictionary. For any instance that has passed validate() (which happens in __init__), it matches the Configuration contract. Note that args are not serialized. :returns dict: The serialized configuration.
def traverse(self, id_=None): """Traverse groups and yield info dicts for jobs""" if id_ is None: id_ = self.group nodes = r_client.smembers(_children_key(id_)) while nodes: current_id = nodes.pop() details = r_client.get(current_id) if d...
Traverse groups and yield info dicts for jobs
async def connect( self, hostname: str = None, port: int = None, source_address: DefaultStrType = _default, timeout: DefaultNumType = _default, loop: asyncio.AbstractEventLoop = None, use_tls: bool = None, validate_certs: bool = None, client_cert: ...
Initialize a connection to the server. Options provided to :meth:`.connect` take precedence over those used to initialize the class. :keyword hostname: Server name (or IP) to connect to :keyword port: Server port. Defaults to 25 if ``use_tls`` is False, 465 if ``use_tls`` i...
def update(self, other=None, **kwargs): """x.update(E, **F) -> None. update x from trie/dict/iterable E or F. If E has a .keys() method, does: for k in E: x[k] = E[k] If E lacks .keys() method, does: for (k, v) in E: x[k] = v In either case, this is followed by: for k in F: x[k] ...
x.update(E, **F) -> None. update x from trie/dict/iterable E or F. If E has a .keys() method, does: for k in E: x[k] = E[k] If E lacks .keys() method, does: for (k, v) in E: x[k] = v In either case, this is followed by: for k in F: x[k] = F[k]
def formatted(text, *args, **kwargs): """ Args: text (str | unicode): Text to format *args: Objects to extract values from (as attributes) **kwargs: Optional values provided as named args Returns: (str): Attributes from this class are expanded if mentioned """ if not...
Args: text (str | unicode): Text to format *args: Objects to extract values from (as attributes) **kwargs: Optional values provided as named args Returns: (str): Attributes from this class are expanded if mentioned
def _isstring(dtype): """Given a numpy dtype, determines whether it is a string. Returns True if the dtype is string or unicode. """ return dtype.type == numpy.unicode_ or dtype.type == numpy.string_
Given a numpy dtype, determines whether it is a string. Returns True if the dtype is string or unicode.
def parse(self) -> Statement: """Parse a complete YANG module or submodule. Args: mtext: YANG module text. Raises: EndOfInput: If past the end of input. ModuleNameMismatch: If parsed module name doesn't match `self.name`. ModuleRevisionMismatch: ...
Parse a complete YANG module or submodule. Args: mtext: YANG module text. Raises: EndOfInput: If past the end of input. ModuleNameMismatch: If parsed module name doesn't match `self.name`. ModuleRevisionMismatch: If parsed revision date doesn't match `se...
def username(anon, obj, field, val): """ Generates a random username """ return anon.faker.user_name(field=field)
Generates a random username
def max_brightness(self): """ Returns the maximum allowable brightness value. """ self._max_brightness, value = self.get_cached_attr_int(self._max_brightness, 'max_brightness') return value
Returns the maximum allowable brightness value.
def snyder_opt(self, structure): """ Calculates Snyder's optical sound velocity (in SI units) Args: structure: pymatgen structure object Returns: Snyder's optical sound velocity (in SI units) """ nsites = structure.num_sites volume = structure.volum...
Calculates Snyder's optical sound velocity (in SI units) Args: structure: pymatgen structure object Returns: Snyder's optical sound velocity (in SI units)
def set_gss_host(self, gss_host, trust_dns=True, gssapi_requested=True): """ Normalize/canonicalize ``self.gss_host`` depending on various factors. :param str gss_host: The explicitly requested GSS-oriented hostname to connect to (i.e. what the host's name is in the Kerb...
Normalize/canonicalize ``self.gss_host`` depending on various factors. :param str gss_host: The explicitly requested GSS-oriented hostname to connect to (i.e. what the host's name is in the Kerberos database.) Defaults to ``self.hostname`` (which will be the 'real' target ho...
def rnaseq2ga(quantificationFilename, sqlFilename, localName, rnaType, dataset=None, featureType="gene", description="", programs="", featureSetNames="", readGroupSetNames="", biosampleId=""): """ Reads RNA Quantification data in one of several formats and stores the da...
Reads RNA Quantification data in one of several formats and stores the data in a sqlite database for use by the GA4GH reference server. Supports the following quantification output types: Cufflinks, kallisto, RSEM.
def get_links(self, recall, timeout): """Gets links in page :param recall: max times to attempt to fetch url :param timeout: max times :return: array of out_links """ for _ in range(recall): try: # setting timeout soup = BeautifulSoup(self.so...
Gets links in page :param recall: max times to attempt to fetch url :param timeout: max times :return: array of out_links
def disable_signing(self): '''disable MAVLink2 signing''' self.mav.signing.secret_key = None self.mav.signing.sign_outgoing = False self.mav.signing.allow_unsigned_callback = None self.mav.signing.link_id = 0 self.mav.signing.timestamp = 0
disable MAVLink2 signing
def view_hmap(token, dstore): """ Display the highest 20 points of the mean hazard map. Called as $ oq show hmap:0.1 # 10% PoE """ try: poe = valid.probability(token.split(':')[1]) except IndexError: poe = 0.1 mean = dict(extract(dstore, 'hcurves?kind=mean'))['mean'] oq ...
Display the highest 20 points of the mean hazard map. Called as $ oq show hmap:0.1 # 10% PoE
def _popup(self): """recursively find commutative binary operator among child formulas and pop up them at the same level""" res = () for child in self.formulas: if type(child) == type(self): superchilds = child.formulas res += superchilds ...
recursively find commutative binary operator among child formulas and pop up them at the same level
def load_config(path): """ Loads configuration from a path. Path can be a json file, or a directory containing config.json and zero or more *.txt files with word lists or phrase lists. Returns config dict. Raises InitializationError when something is wrong. """ path = os.path.abspath(...
Loads configuration from a path. Path can be a json file, or a directory containing config.json and zero or more *.txt files with word lists or phrase lists. Returns config dict. Raises InitializationError when something is wrong.
def to_json(self): """ Serialises the content of the KnowledgeBase as JSON. :return: TODO """ return json.dumps({ "statistics": self.get_statistics() , "authors": [json.loads(author.to_json()) for author in self.get_authors()] }, indent=2)
Serialises the content of the KnowledgeBase as JSON. :return: TODO
def start(self, *args, **kwargs): """Starts the instance. :raises RuntimeError: has been already started. :raises TypeError: :meth:`run` is not canonical. """ if self.is_running(): raise RuntimeError('Already started') self._running = self.run(*args, **kwarg...
Starts the instance. :raises RuntimeError: has been already started. :raises TypeError: :meth:`run` is not canonical.
def multchoicebox(message='Pick as many items as you like.', title='', choices=['program logic error - no choices specified']): """Original doc: Present the user with a list of choices. allow him to select multiple items and return them in a list. if the user doesn't choose anything from the list, r...
Original doc: Present the user with a list of choices. allow him to select multiple items and return them in a list. if the user doesn't choose anything from the list, return the empty list. return None if he cancelled selection.
def count(self): """ Total number of array cells """ return functools.reduce(lambda x, y: x * y, (x.count for x in self.bounds))
Total number of array cells
def get_resource_siblings(raml_resource): """ Get siblings of :raml_resource:. :param raml_resource: Instance of ramlfications.raml.ResourceNode. """ path = raml_resource.path return [res for res in raml_resource.root.resources if res.path == path]
Get siblings of :raml_resource:. :param raml_resource: Instance of ramlfications.raml.ResourceNode.
def nsx_controller_connection_addr_port(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") nsx_controller = ET.SubElement(config, "nsx-controller", xmlns="urn:brocade.com:mgmt:brocade-tunnels") name_key = ET.SubElement(nsx_controller, "name") name_k...
Auto Generated Code
def mag_to_fnu(self, mag): """SDSS *primed* magnitudes to F_ν. The primed magnitudes are the "USNO" standard-star system defined in Smith+ (2002AJ....123.2121S) and Fukugita+ (1996AJ....111.1748F). This system is anchored to the AB magnitude system, and as far as I can tell it is not kno...
SDSS *primed* magnitudes to F_ν. The primed magnitudes are the "USNO" standard-star system defined in Smith+ (2002AJ....123.2121S) and Fukugita+ (1996AJ....111.1748F). This system is anchored to the AB magnitude system, and as far as I can tell it is not known to have measurable offsets ...
def loads(string, triples=False, cls=PENMANCodec, **kwargs): """ Deserialize a list of PENMAN-encoded graphs from *string*. Args: string: a string containing graph data triples: if True, read graphs as triples instead of as PENMAN cls: serialization codec class kwargs: keywo...
Deserialize a list of PENMAN-encoded graphs from *string*. Args: string: a string containing graph data triples: if True, read graphs as triples instead of as PENMAN cls: serialization codec class kwargs: keyword arguments passed to the constructor of *cls* Returns: a li...
def search_dashboard_deleted_for_facet(self, facet, **kwargs): # noqa: E501 """Lists the values of a specific facet over the customer's deleted dashboards # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please ...
Lists the values of a specific facet over the customer's deleted dashboards # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.search_dashboard_deleted_for_facet(facet, a...
def analyze_text( self, text, **kwargs ): ''' Analyzes given Text for noun phrase chunks. As result of analysis, a layer NOUN_CHUNKS will be attached to the input Text object, containing a noun phrases detected from the Text; Note: for preprocessing the Text,...
Analyzes given Text for noun phrase chunks. As result of analysis, a layer NOUN_CHUNKS will be attached to the input Text object, containing a noun phrases detected from the Text; Note: for preprocessing the Text, MaltParser is used by default. In order to obtain a de...
def output_to_table(obj, olist='inputs', oformat='latex', table_ends=False, prefix=""): """ Compile the properties to a table. :param olist: list, Names of the parameters to be in the output table :param oformat: str, The type of table to be output :param table_ends: bool, Add ends to the table ...
Compile the properties to a table. :param olist: list, Names of the parameters to be in the output table :param oformat: str, The type of table to be output :param table_ends: bool, Add ends to the table :param prefix: str, A string to be added to the start of each parameter name :return: para, str...
def main(): """Main entry point""" parser = OptionParser() parser.add_option('-a', '--hostname', help='ClamAV source server hostname', dest='hostname', type='str', default='db.de.clamav.net') parser.add_option('-r', ...
Main entry point
def get_filepath(self, filename): """ Creates file path for the file. :param filename: name of the file :type filename: str :return: filename with path on disk :rtype: str """ return os.path.join(self.parent_folder, self.product_id, self.add_file_extensio...
Creates file path for the file. :param filename: name of the file :type filename: str :return: filename with path on disk :rtype: str
async def _connect(self, connection_lost_callbk=None): """Asyncio connection to Elk.""" self.connection_lost_callbk = connection_lost_callbk url = self._config['url'] LOG.info("Connecting to ElkM1 at %s", url) scheme, dest, param, ssl_context = parse_url(url) conn = parti...
Asyncio connection to Elk.
def add_install_defaults(args): """Add any saved installation defaults to the upgrade. """ # Ensure we install data if we've specified any secondary installation targets if len(args.genomes) > 0 or len(args.aligners) > 0 or len(args.datatarget) > 0: args.install_data = True install_config = ...
Add any saved installation defaults to the upgrade.
def set_line_join(self, line_join): """Set the current :ref:`LINE_JOIN` within the cairo context. As with the other stroke parameters, the current line cap style is examined by :meth:`stroke`, :meth:`stroke_extents`, and :meth:`stroke_to_path`, but does not have any effect during...
Set the current :ref:`LINE_JOIN` within the cairo context. As with the other stroke parameters, the current line cap style is examined by :meth:`stroke`, :meth:`stroke_extents`, and :meth:`stroke_to_path`, but does not have any effect during path construction. The default line c...
def get_blank_row(self, filler="-", splitter="+"): """Gets blank row :param filler: Fill empty columns with this char :param splitter: Separate columns with this char :return: Pretty formatted blank row (with no meaningful data in it) """ return self.get_pretty_row( ...
Gets blank row :param filler: Fill empty columns with this char :param splitter: Separate columns with this char :return: Pretty formatted blank row (with no meaningful data in it)
def filter_by_analysis_period(self, analysis_period): """ Filter a Data Collection based on an analysis period. Args: analysis period: A Ladybug analysis period Return: A new Data Collection with filtered data """ self._check_analysis_period(analy...
Filter a Data Collection based on an analysis period. Args: analysis period: A Ladybug analysis period Return: A new Data Collection with filtered data
def hardware_custom_profile_kap_custom_profile_xstp_xstp_hello_interval(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware") custom_profile = ET.SubElement(hardware, "...
Auto Generated Code
def setSignals(self, vehID, signals): """setSignals(string, integer) -> None Sets an integer encoding the state of the vehicle's signals. """ self._connection._sendIntCmd( tc.CMD_SET_VEHICLE_VARIABLE, tc.VAR_SIGNALS, vehID, signals)
setSignals(string, integer) -> None Sets an integer encoding the state of the vehicle's signals.
def pix2vec(nside, ipix, nest=False): """Drop-in replacement for healpy `~healpy.pixelfunc.pix2vec`.""" lon, lat = healpix_to_lonlat(ipix, nside, order='nested' if nest else 'ring') return ang2vec(*_lonlat_to_healpy(lon, lat))
Drop-in replacement for healpy `~healpy.pixelfunc.pix2vec`.
def getSegmentOnCell(self, c, i, segIdx): """ Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.getSegmentOnCell`. """ segList = self.cells4.getNonEmptySegList(c,i) seg = self.cells4.getSegment(c, i, segList[segIdx]) numSyn = seg.size() assert numSyn != 0 # Accumulate seg...
Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.getSegmentOnCell`.
def append(self, data: Union[bytes, bytearray, memoryview]) -> None: """ Append the given piece of data (should be a buffer-compatible object). """ size = len(data) if size > self._large_buf_threshold: if not isinstance(data, memoryview): data = memory...
Append the given piece of data (should be a buffer-compatible object).
def preprocess(self): ''' Performs initial cell conversions to standard types. This will strip units, scale numbers, and identify numeric data where it's convertible. ''' self.processed_tables = [] self.flags_by_table = [] self.units_by_table = [] for work...
Performs initial cell conversions to standard types. This will strip units, scale numbers, and identify numeric data where it's convertible.
def p_sigtypes(self, p): 'sigtypes : sigtypes sigtype' p[0] = p[1] + (p[2],) p.set_lineno(0, p.lineno(1))
sigtypes : sigtypes sigtype
def document_from_string(self, schema, request_string): # type: (GraphQLSchema, str) -> GraphQLDocument """This method returns a GraphQLQuery (from cache if present)""" key = self.get_key_for_schema_and_document_string(schema, request_string) if key not in self.cache_map: # W...
This method returns a GraphQLQuery (from cache if present)
def get_bins_by_resource(self, resource_id): """Gets the list of ``Bin`` objects mapped to a ``Resource``. arg: resource_id (osid.id.Id): ``Id`` of a ``Resource`` return: (osid.resource.BinList) - list of bins raise: NotFound - ``resource_id`` is not found raise: NullArgume...
Gets the list of ``Bin`` objects mapped to a ``Resource``. arg: resource_id (osid.id.Id): ``Id`` of a ``Resource`` return: (osid.resource.BinList) - list of bins raise: NotFound - ``resource_id`` is not found raise: NullArgument - ``resource_id`` is ``null`` raise: Operati...
def calc_acceleration(xdata, dt): """ Calculates the acceleration from the position Parameters ---------- xdata : ndarray Position data dt : float time between measurements Returns ------- acceleration : ndarray values of acceleration from position ...
Calculates the acceleration from the position Parameters ---------- xdata : ndarray Position data dt : float time between measurements Returns ------- acceleration : ndarray values of acceleration from position 2 to N.
def _get_layer_converter_fn(layer, add_custom_layers = False): """Get the right converter function for Keras """ layer_type = type(layer) if layer_type in _KERAS_LAYER_REGISTRY: convert_func = _KERAS_LAYER_REGISTRY[layer_type] if convert_func is _layers2.convert_activation: a...
Get the right converter function for Keras
def text(what="sentence", *args, **kwargs): """An aggregator for all above defined public methods.""" if what == "character": return character(*args, **kwargs) elif what == "characters": return characters(*args, **kwargs) elif what == "word": return word(*args, **kwargs) eli...
An aggregator for all above defined public methods.
def reference_to_greatcircle(reference_frame, greatcircle_frame): """Convert a reference coordinate to a great circle frame.""" # Define rotation matrices along the position angle vector, and # relative to the origin. pole = greatcircle_frame.pole.transform_to(coord.ICRS) ra0 = greatcircle_frame.ra...
Convert a reference coordinate to a great circle frame.
def QA_util_code_tolist(code, auto_fill=True): """转换code==> list Arguments: code {[type]} -- [description] Keyword Arguments: auto_fill {bool} -- 是否自动补全(一般是用于股票/指数/etf等6位数,期货不适用) (default: {True}) Returns: [list] -- [description] """ if isinstance(code, str): ...
转换code==> list Arguments: code {[type]} -- [description] Keyword Arguments: auto_fill {bool} -- 是否自动补全(一般是用于股票/指数/etf等6位数,期货不适用) (default: {True}) Returns: [list] -- [description]
def _compute_dependencies(self): """Recompute this distribution's dependencies.""" from _markerlib import compile as compile_marker dm = self.__dep_map = {None: []} reqs = [] # Including any condition expressions for req in self._parsed_pkg_info.get_all('Requires-Dist') ...
Recompute this distribution's dependencies.
def previous(self, cli): """ Return the previously focussed :class:`.Buffer` or `None`. """ if len(self.focus_stack) > 1: try: return self[self.focus_stack[-2]] except KeyError: pass
Return the previously focussed :class:`.Buffer` or `None`.
def foreach(self, f): """ Sets the output of the streaming query to be processed using the provided writer ``f``. This is often used to write the output of a streaming query to arbitrary storage systems. The processing logic can be specified in two ways. #. A **function** that t...
Sets the output of the streaming query to be processed using the provided writer ``f``. This is often used to write the output of a streaming query to arbitrary storage systems. The processing logic can be specified in two ways. #. A **function** that takes a row as input. This is a...
def mu(self): """See docs for `Model` abstract base class.""" mu = self._models[0].mu assert all([mu == model.mu for model in self._models]) return mu
See docs for `Model` abstract base class.
def set_url_part(url, **kwargs): """Change one or more parts of a URL""" d = parse_url_to_dict(url) d.update(kwargs) return unparse_url_dict(d)
Change one or more parts of a URL
def add_oxidation_state_by_site_fraction(structure, oxidation_states): """ Add oxidation states to a structure by fractional site. Args: oxidation_states (list): List of list of oxidation states for each site fraction for each site. E.g., [[2, 4], [3]...
Add oxidation states to a structure by fractional site. Args: oxidation_states (list): List of list of oxidation states for each site fraction for each site. E.g., [[2, 4], [3], [-2], [-2], [-2]]
def clear_cached_values(self): """Removes all of the cached values and interpolators """ self._prof_interp = None self._prof_y = None self._prof_z = None self._marg_interp = None self._marg_z = None self._post = None self._post_interp = None ...
Removes all of the cached values and interpolators
def filter_data(data, kernel, mode='constant', fill_value=0.0, check_normalization=False): """ Convolve a 2D image with a 2D kernel. The kernel may either be a 2D `~numpy.ndarray` or a `~astropy.convolution.Kernel2D` object. Parameters ---------- data : array_like T...
Convolve a 2D image with a 2D kernel. The kernel may either be a 2D `~numpy.ndarray` or a `~astropy.convolution.Kernel2D` object. Parameters ---------- data : array_like The 2D array of the image. kernel : array-like (2D) or `~astropy.convolution.Kernel2D` The 2D kernel used t...
def register_surrogateescape(): """ Registers the surrogateescape error handler on Python 2 (only) """ if six.PY3: return try: codecs.lookup_error(FS_ERRORS) except LookupError: codecs.register_error(FS_ERRORS, surrogateescape_handler)
Registers the surrogateescape error handler on Python 2 (only)
def get_clients(self, limit=None, offset=None): """ Returns a list of clients. """ data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/clients', data=json.dumps(data)) return ...
Returns a list of clients.
def hmget(self, name, keys, *args): "Returns a list of values ordered identically to ``keys``" args = list_or_args(keys, args) return self.execute_command('HMGET', name, *args)
Returns a list of values ordered identically to ``keys``
def p_subidentifiers(self, p): """subidentifiers : subidentifiers subidentifier | subidentifier""" n = len(p) if n == 3: p[0] = p[1] + [p[2]] elif n == 2: p[0] = [p[1]]
subidentifiers : subidentifiers subidentifier | subidentifier
def run(path, code=None, params=None, ignore=None, select=None, **meta): """Check code with Radon. :return list: List of errors. """ complexity = params.get('complexity', 10) no_assert = params.get('no_assert', False) show_closures = params.get('show_closures', False) ...
Check code with Radon. :return list: List of errors.
def obj_to_json(self, file_path=None, indent=2, sort_keys=False, quote_numbers=True): """ This will return a str of a json list. :param file_path: path to data file, defaults to self's contents if left alone :param indent: i...
This will return a str of a json list. :param file_path: path to data file, defaults to self's contents if left alone :param indent: int if set to 2 will indent to spaces and include line breaks. :param sort_keys: so...
def hr_size(num, suffix='B') -> str: """ Human-readable data size From https://stackoverflow.com/a/1094933 :param num: number of bytes :param suffix: Optional size specifier :return: Formatted string """ for unit in ' KMGTPEZ': if abs(num) < 1024.0: return "%3.1f%s%s"...
Human-readable data size From https://stackoverflow.com/a/1094933 :param num: number of bytes :param suffix: Optional size specifier :return: Formatted string
def output(self, stream, disabletransferencoding = None): """ Set output stream and send response immediately """ if self._sendHeaders: raise HttpProtocolException('Cannot modify response, headers already sent') self.outputstream = stream try: cont...
Set output stream and send response immediately
def encrypt(self, plaintext): """Encrypt the given plaintext value""" if not isinstance(plaintext, int): raise ValueError('Plaintext must be an integer value') if not self.in_range.contains(plaintext): raise OutOfRangeError('Plaintext is not within the input range') ...
Encrypt the given plaintext value
def add_access_policy_filter(request, query, column_name): """Filter records that do not have ``read`` or better access for one or more of the active subjects. Since ``read`` is the lowest access level that a subject can have, this method only has to filter on the presence of the subject. """ ...
Filter records that do not have ``read`` or better access for one or more of the active subjects. Since ``read`` is the lowest access level that a subject can have, this method only has to filter on the presence of the subject.
def xml_endtag (self, name): """ Write XML end tag. """ self.level -= 1 assert self.level >= 0 self.write(self.indent*self.level) self.writeln(u"</%s>" % xmlquote(name))
Write XML end tag.
def get_angle(self, verify = False): """ Retuns measured angle in degrees in range 0-360. """ LSB = self.bus.read_byte_data(self.address, self.angle_LSB) MSB = self.bus.read_byte_data(self.address, self.angle_MSB) DATA = (MSB << 6) + LSB if not verify: ...
Retuns measured angle in degrees in range 0-360.
def interconnect_link_topologies(self): """ Gets the InterconnectLinkTopologies API client. Returns: InterconnectLinkTopologies: """ if not self.__interconnect_link_topologies: self.__interconnect_link_topologies = InterconnectLinkTopologies(self.__connec...
Gets the InterconnectLinkTopologies API client. Returns: InterconnectLinkTopologies:
def DiscreteUniform(n=10,LB=1,UB=99,B=100): """DiscreteUniform: create random, uniform instance for the bin packing problem.""" B = 100 s = [0]*n for i in range(n): s[i] = random.randint(LB,UB) return s,B
DiscreteUniform: create random, uniform instance for the bin packing problem.
def iflatten(seq, isSeq=isSeq): r"""Like `flatten` but lazy.""" for elt in seq: if isSeq(elt): for x in iflatten(elt, isSeq): yield x else: yield elt
r"""Like `flatten` but lazy.
def _mark_started(self): """ Set the state information for a task once it has completely started. In particular, the time limit is applied as of this time (ie after and start delay has been taking. """ log = self._params.get('log', self._discard) now = time.time() ...
Set the state information for a task once it has completely started. In particular, the time limit is applied as of this time (ie after and start delay has been taking.
def get(key, value=None, conf_file=_DEFAULT_CONF): ''' Get the value for a specific configuration line. :param str key: The command or stanza block to configure. :param str value: The command value or command of the block specified by the key parameter. :param str conf_file: The logrotate configura...
Get the value for a specific configuration line. :param str key: The command or stanza block to configure. :param str value: The command value or command of the block specified by the key parameter. :param str conf_file: The logrotate configuration file. :return: The value for a specific configuration...
def parse_string(self, timestr, subfmts): """Read time from a single string, using a set of possible formats.""" # Datetime components required for conversion to JD by ERFA, along # with the default values. components = ('year', 'mon', 'mday') defaults = (None, 1, 1, 0) #...
Read time from a single string, using a set of possible formats.
def classify_tangent_intersection( intersection, nodes1, tangent1, nodes2, tangent2 ): """Helper for func:`classify_intersection` at tangencies. .. note:: This is a helper used only by :func:`classify_intersection`. Args: intersection (.Intersection): An intersection object. no...
Helper for func:`classify_intersection` at tangencies. .. note:: This is a helper used only by :func:`classify_intersection`. Args: intersection (.Intersection): An intersection object. nodes1 (numpy.ndarray): Control points for the first curve at the intersection. ...
def get_flight_rules(vis: Number, ceiling: Cloud) -> int: """ Returns int based on current flight rules from parsed METAR data 0=VFR, 1=MVFR, 2=IFR, 3=LIFR Note: Common practice is to report IFR if visibility unavailable """ # Parse visibility if not vis: return 2 if vis.repr =...
Returns int based on current flight rules from parsed METAR data 0=VFR, 1=MVFR, 2=IFR, 3=LIFR Note: Common practice is to report IFR if visibility unavailable
def calc_avr_uvr_v1(self): """Calculate the flown through area and the wetted perimeter of both outer embankments. Note that each outer embankment lies beyond its foreland and that all water flowing exactly above the a embankment is added to |AVR|. The theoretical surface seperating water above the...
Calculate the flown through area and the wetted perimeter of both outer embankments. Note that each outer embankment lies beyond its foreland and that all water flowing exactly above the a embankment is added to |AVR|. The theoretical surface seperating water above the foreland from water above its...
def energy_ratio_by_chunks(x, param): """ Calculates the sum of squares of chunk i out of N chunks expressed as a ratio with the sum of squares over the whole series. Takes as input parameters the number num_segments of segments to divide the series into and segment_focus which is the segment numbe...
Calculates the sum of squares of chunk i out of N chunks expressed as a ratio with the sum of squares over the whole series. Takes as input parameters the number num_segments of segments to divide the series into and segment_focus which is the segment number (starting at zero) to return a feature on. ...
def connect(self, port=None, baud_rate=115200): ''' Parameters ---------- port : str or list-like, optional Port (or list of ports) to try to connect to as a DMF Control Board. baud_rate : int, optional Returns ------- str ...
Parameters ---------- port : str or list-like, optional Port (or list of ports) to try to connect to as a DMF Control Board. baud_rate : int, optional Returns ------- str Port DMF control board was connected on. Raises ...
def standard_parsing_functions(Block, Tx): """ Return the standard parsing functions for a given Block and Tx class. The return value is expected to be used with the standard_streamer function. """ def stream_block(f, block): assert isinstance(block, Block) block.stream(f) def s...
Return the standard parsing functions for a given Block and Tx class. The return value is expected to be used with the standard_streamer function.
def save(self, index=None, force=False): """Save file""" editorstack = self.get_current_editorstack() return editorstack.save(index=index, force=force)
Save file
def pverb(self, *args, **kwargs): """ Console verbose message to STDOUT """ if not self.verbose: return self.pstd(*args, **kwargs)
Console verbose message to STDOUT
def createPREMISEventXML(eventType, agentIdentifier, eventDetail, eventOutcome, outcomeDetail=None, eventIdentifier=None, linkObjectList=[], eventDate=None): """ Actually create our PREMIS Event XML """ eventXML = etree.Element(PREMIS + "event", nsmap=P...
Actually create our PREMIS Event XML
def get_instance(self, payload): """ Build an instance of NotificationInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.notification.NotificationInstance :rtype: twilio.rest.api.v2010.account.notification.NotificationInstance ...
Build an instance of NotificationInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.notification.NotificationInstance :rtype: twilio.rest.api.v2010.account.notification.NotificationInstance
def _update_port_locations(self, initial_coordinates): """Adjust port locations after particles have moved Compares the locations of Particles between 'self' and an array of reference coordinates. Shifts Ports in accordance with how far anchors have been moved. This conserves the loca...
Adjust port locations after particles have moved Compares the locations of Particles between 'self' and an array of reference coordinates. Shifts Ports in accordance with how far anchors have been moved. This conserves the location of Ports with respect to their anchor Particles, but ...
def remove_outcome_hook(self, outcome_id): """Removes internal transition going to the outcome """ for transition_id in list(self.transitions.keys()): transition = self.transitions[transition_id] if transition.to_outcome == outcome_id and transition.to_state == self.state...
Removes internal transition going to the outcome
def _metric_when_multiplied_with_sig_vec(self, sig): """return D^-1 B^T diag(sig) B D as a measure for C^-1/2 diag(sig) C^1/2 :param sig: a vector "used" as diagonal matrix :return: """ return dot((self.B * self.D**-1.).T * sig, self.B * self.D)
return D^-1 B^T diag(sig) B D as a measure for C^-1/2 diag(sig) C^1/2 :param sig: a vector "used" as diagonal matrix :return:
def collect_modules(self): """ Collect up the list of modules in use """ try: res = {} m = sys.modules for k in m: # Don't report submodules (e.g. django.x, django.y, django.z) # Skip modules that begin with underscore i...
Collect up the list of modules in use
def cross_validate(self, ax): ''' Performs the cross-validation step. ''' # The CDPP to beat cdpp_opt = self.get_cdpp_arr() # Loop over all chunks for b, brkpt in enumerate(self.breakpoints): log.info("Cross-validating chunk %d/%d..." % ...
Performs the cross-validation step.
def get_products(self): """ List of formulas of potential products. E.g., ['Li','O2','Mn']. """ products = set() for _, _, _, react, _ in self.get_kinks(): products = products.union(set([k.reduced_formula for k in react.produ...
List of formulas of potential products. E.g., ['Li','O2','Mn'].