code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _unknown_args(self, args): """Log argparser unknown arguments. Args: args (list): List of unknown arguments """ for u in args: self.tcex.log.warning(u'Unsupported arg found ({}).'.format(u))
Log argparser unknown arguments. Args: args (list): List of unknown arguments
def lookup_camera_by_id(self, device_id): """Return camera object by device_id.""" camera = list(filter( lambda cam: cam.device_id == device_id, self.cameras))[0] if camera: return camera return None
Return camera object by device_id.
def _check_pillar_minions(self, expr, delimiter, greedy): ''' Return the minions found by looking via pillar ''' return self._check_cache_minions(expr, delimiter, greedy, 'pillar')
Return the minions found by looking via pillar
def wait_for_binary_interface(self, **kwargs): """ Waits for the Binary CQL interface to be listening. If > 1.2 will check log for 'Starting listening for CQL clients' before checking for the interface to be listening. Emits a warning if not listening after 30 seconds. ...
Waits for the Binary CQL interface to be listening. If > 1.2 will check log for 'Starting listening for CQL clients' before checking for the interface to be listening. Emits a warning if not listening after 30 seconds.
def _fullqualname_method_py3(obj): """Fully qualified name for 'method' objects in Python 3. """ if inspect.isclass(obj.__self__): cls = obj.__self__.__qualname__ else: cls = obj.__self__.__class__.__qualname__ return obj.__self__.__module__ + '.' + cls + '.' + obj.__name__
Fully qualified name for 'method' objects in Python 3.
def for_user(self, user): """ All folders the given user can do something with. """ qs = SharedMemberQuerySet(model=self.model, using=self._db, user=user) qs = qs.filter(Q(author=user) | Q(foldershareduser__user=user)) return qs.distinct() & self.distinct()
All folders the given user can do something with.
def get_work_item_by_id(self, wi_id): ''' Retrieves a single work item based off of the supplied ID :param wi_id: The work item ID number :return: Workitem or None ''' work_items = self.get_work_items(id=wi_id) if work_items is not None: return work_i...
Retrieves a single work item based off of the supplied ID :param wi_id: The work item ID number :return: Workitem or None
def remove(self, label): """Remove a label. Args: label (gkeepapi.node.Label): The Label object. """ if label.id in self._labels: self._labels[label.id] = None self._dirty = True
Remove a label. Args: label (gkeepapi.node.Label): The Label object.
def get_range(self, ignore_blank_lines=True): """ Gets the fold region range (start and end line). .. note:: Start line do no encompass the trigger line. :param ignore_blank_lines: True to ignore blank lines at the end of the scope (the method will rewind to find that last ...
Gets the fold region range (start and end line). .. note:: Start line do no encompass the trigger line. :param ignore_blank_lines: True to ignore blank lines at the end of the scope (the method will rewind to find that last meaningful block that is part of the fold scope). ...
def add_sender(self, partition=None, operation=None, send_timeout=60, keep_alive=30, auto_reconnect=True): """ Add a sender to the client to EventData object to an EventHub. :param partition: Optionally specify a particular partition to send to. If omitted, the events will be distribut...
Add a sender to the client to EventData object to an EventHub. :param partition: Optionally specify a particular partition to send to. If omitted, the events will be distributed to available partitions via round-robin. :type parition: str :operation: An optional operation to b...
def event_params(segments, params, band=None, n_fft=None, slopes=None, prep=None, parent=None): """Compute event parameters. Parameters ---------- segments : instance of wonambi.trans.select.Segments list of segments, with time series and metadata params : dict of bool...
Compute event parameters. Parameters ---------- segments : instance of wonambi.trans.select.Segments list of segments, with time series and metadata params : dict of bool, or str 'dur', 'minamp', 'maxamp', 'ptp', 'rms', 'power', 'peakf', 'energy', 'peakef'. If 'all', a dict...
def remove_builder(cls, builder_name: str): """Remove a registered builder `builder_name`. No reason to use this except for tests. """ cls.builders.pop(builder_name, None) for hook_spec in cls.hooks.values(): hook_spec.pop(builder_name, None)
Remove a registered builder `builder_name`. No reason to use this except for tests.
def return_hdr(self): """Return the header for further use. Returns ------- subj_id : str subject identification code start_time : datetime start time of the dataset s_freq : float sampling frequency chan_name : list of str ...
Return the header for further use. Returns ------- subj_id : str subject identification code start_time : datetime start time of the dataset s_freq : float sampling frequency chan_name : list of str list of all the channels...
def makeDigraph(automaton, inputAsString=repr, outputAsString=repr, stateAsString=repr): """ Produce a L{graphviz.Digraph} object from an automaton. """ digraph = graphviz.Digraph(graph_attr={'pack': 'true', 'dpi': '100'}, ...
Produce a L{graphviz.Digraph} object from an automaton.
def transpose_note(note, transpose, scale="C"): """ Transpose a note :param str note: note to transpose :type transpose: int :param str scale: key scale :rtype: str :return: transposed note """ val = note_to_val(note) val += transpose return val_to_note(val, scale)
Transpose a note :param str note: note to transpose :type transpose: int :param str scale: key scale :rtype: str :return: transposed note
def app_routes(app): """ list of route of an app """ _routes = [] for rule in app.url_map.iter_rules(): _routes.append({ 'path': rule.rule, 'name': rule.endpoint, 'methods': list(rule.methods) }) return jsonify({'routes': _routes})
list of route of an app
def forward_ad(node, wrt, preserve_result=False, check_dims=True): """Perform forward-mode AD on an AST. This function analyses the AST to determine which variables are active and proceeds by taking the naive derivative. Before returning the primal and adjoint it annotates push and pop statements as such. A...
Perform forward-mode AD on an AST. This function analyses the AST to determine which variables are active and proceeds by taking the naive derivative. Before returning the primal and adjoint it annotates push and pop statements as such. Args: node: A `FunctionDef` AST node. wrt: A tuple of argument in...
def parse(self, target): """ Parse nested rulesets and save it in cache. """ if isinstance(target, ContentNode): if target.name: self.parent = target self.name.parse(self) self.name += target.name target.ruleset....
Parse nested rulesets and save it in cache.
def delete_category(category_id): """Delete a Category with id = category_id. :param category_id: PYBOSSA Category ID :type category_id: integer :returns: True -- the response status code """ try: res = _pybossa_req('delete', 'category', category_id) if type(res).__name__ == 'b...
Delete a Category with id = category_id. :param category_id: PYBOSSA Category ID :type category_id: integer :returns: True -- the response status code
def update_virtual_meta(self): """Will read back the virtual column etc, written by :func:`DataFrame.write_virtual_meta`. This will be done when opening a DataFrame.""" import astropy.units try: path = os.path.join(self.get_private_dir(create=False), "virtual_meta.yaml") ...
Will read back the virtual column etc, written by :func:`DataFrame.write_virtual_meta`. This will be done when opening a DataFrame.
def install_handler(self, event_type, handler, user_handle=None): """Installs handlers for event callbacks in this resource. :param event_type: Logical event identifier. :param handler: Interpreted as a valid reference to a handler to be installed by a client application. :param user_ha...
Installs handlers for event callbacks in this resource. :param event_type: Logical event identifier. :param handler: Interpreted as a valid reference to a handler to be installed by a client application. :param user_handle: A value specified by an application that can be used for identifying ha...
def linewidth(self, linewidth=None): """Returns or sets (if a value is provided) the width of the series' line. :param Number linewidth: If given, the series' linewidth will be set to\ this. :rtype: ``Number``""" if linewidth is None: return self._linewidth ...
Returns or sets (if a value is provided) the width of the series' line. :param Number linewidth: If given, the series' linewidth will be set to\ this. :rtype: ``Number``
def declare(self, queue='', virtual_host='/', passive=False, durable=False, auto_delete=False, arguments=None): """Declare a Queue. :param str queue: Queue name :param str virtual_host: Virtual host name :param bool passive: Do not create :param bool durable: Dur...
Declare a Queue. :param str queue: Queue name :param str virtual_host: Virtual host name :param bool passive: Do not create :param bool durable: Durable queue :param bool auto_delete: Automatically delete when not in use :param dict|None arguments: Queue key/value argume...
def run(self): """Build extensions in build directory, then copy if --inplace""" old_inplace, self.inplace = self.inplace, 0 _build_ext.run(self) self.inplace = old_inplace if old_inplace: self.copy_extensions_to_source()
Build extensions in build directory, then copy if --inplace
def updateData(self, state_data, action_data, reward_data): """ Updates the data used by the renderer. """ # self.dataLock.acquire() self.state_data[:, self.updates] = state_data self.action_data[:, self.updates] = action_data self.reward_data[0, self.updates] = reward_da...
Updates the data used by the renderer.
def file_key_retire( blockchain_id, file_key, config_path=CONFIG_PATH, wallet_keys=None ): """ Retire the given key. Move it to the head of the old key bundle list @file_key should be data returned by file_key_lookup Return {'status': True} on success Return {'error': ...} on error """ con...
Retire the given key. Move it to the head of the old key bundle list @file_key should be data returned by file_key_lookup Return {'status': True} on success Return {'error': ...} on error
def sum_sp_values(self): """ return system level values (spa + spb) input: "values": { "spa": 385, "spb": 505 }, return: "values": { "0": 890 }, """ if self.values is None: ret = IdValues() ...
return system level values (spa + spb) input: "values": { "spa": 385, "spb": 505 }, return: "values": { "0": 890 },
def prepare_data(data_dir, fileroot, block_pct_tokens_thresh=0.1): """ Prepare data for a single HTML + gold standard blocks example, uniquely identified by ``fileroot``. Args: data_dir (str) fileroot (str) block_pct_tokens_thresh (float): must be in [0.0, 1.0] Returns: ...
Prepare data for a single HTML + gold standard blocks example, uniquely identified by ``fileroot``. Args: data_dir (str) fileroot (str) block_pct_tokens_thresh (float): must be in [0.0, 1.0] Returns: Tuple[str, Tuple[np.array[int], np.array[int], List[str]], Tuple[np.array[...
def req_withdraw(self, address, amount, currency, fee=0, addr_tag="", _async=False): """ 申请提现虚拟币 :param address: :param amount: :param currency:btc, ltc, bcc, eth, etc ...(火币Pro支持的币种) :param fee: :param addr_tag: :return: { "status": "ok"...
申请提现虚拟币 :param address: :param amount: :param currency:btc, ltc, bcc, eth, etc ...(火币Pro支持的币种) :param fee: :param addr_tag: :return: { "status": "ok", "data": 700 }
def Liu(Tb, Tc, Pc): r'''Calculates enthalpy of vaporization at the normal boiling point using the Liu [1]_ correlation, and a chemical's critical temperature, pressure and boiling point. The enthalpy of vaporization is given by: .. math:: \Delta H_{vap} = RT_b \left[ \frac{T_b}{220}\right...
r'''Calculates enthalpy of vaporization at the normal boiling point using the Liu [1]_ correlation, and a chemical's critical temperature, pressure and boiling point. The enthalpy of vaporization is given by: .. math:: \Delta H_{vap} = RT_b \left[ \frac{T_b}{220}\right]^{0.0627} \frac{ ...
def get_argument_starttime(self): """ Helper function to get starttime argument. Raises exception if argument is missing. Returns the starttime argument. """ try: starttime = self.get_argument(constants.PARAM_STARTTIME) return starttime except tornado.web.MissingArgumentError as ...
Helper function to get starttime argument. Raises exception if argument is missing. Returns the starttime argument.
def _parse_q2r(self, f): """Parse q2r output file The format of q2r output is described at the mailing list below: http://www.democritos.it/pipermail/pw_forum/2005-April/002408.html http://www.democritos.it/pipermail/pw_forum/2008-September/010099.html http://www.democritos.it/p...
Parse q2r output file The format of q2r output is described at the mailing list below: http://www.democritos.it/pipermail/pw_forum/2005-April/002408.html http://www.democritos.it/pipermail/pw_forum/2008-September/010099.html http://www.democritos.it/pipermail/pw_forum/2009-August/013613...
def remove_namespace(self, ns_uri): """Removes the indicated namespace from this set.""" if not self.contains_namespace(ns_uri): return ni = self.__ns_uri_map.pop(ns_uri) for prefix in ni.prefixes: del self.__prefix_map[prefix]
Removes the indicated namespace from this set.
def add_arguments(parser, default_level=logging.INFO): """ Add arguments to an ArgumentParser or OptionParser for purposes of grabbing a logging level. """ adder = ( getattr(parser, 'add_argument', None) or getattr(parser, 'add_option') ) adder( '-l', '--log-level', default=default_level, type=lo...
Add arguments to an ArgumentParser or OptionParser for purposes of grabbing a logging level.
def _parse_arguments(): """Return a parser context result.""" parser = argparse.ArgumentParser(description="CMake AST Dumper") parser.add_argument("filename", nargs=1, metavar=("FILE"), help="read FILE") return parser.parse_args()
Return a parser context result.
def score_x_of_a_kind_yatzy(dice: List[int], min_same_faces: int) -> int: """Similar to yahtzee, but only return the sum of the dice that satisfy min_same_faces """ for die, count in Counter(dice).most_common(1): if count >= min_same_faces: return die * min_same_faces return 0
Similar to yahtzee, but only return the sum of the dice that satisfy min_same_faces
def do_mkdir(self, line): """mkdir DIRECTORY... Creates one or more directories. """ args = self.line_to_args(line) for filename in args: filename = resolve_path(filename) if not mkdir(filename): print_err('Unable to create %s' % filena...
mkdir DIRECTORY... Creates one or more directories.
def handle_http_error(self, response, custom_messages=None, raise_for_status=False): """Converts service errors to Python exceptions Parameters ---------- response : requests.Response A service response. custom_messages : dict, optional ...
Converts service errors to Python exceptions Parameters ---------- response : requests.Response A service response. custom_messages : dict, optional A mapping of custom exception messages to HTTP status codes. raise_for_status : bool, optional ...
def from_point(cls, point, network=BitcoinMainNet, **kwargs): """Create a PublicKey from a point on the SECP256k1 curve. :param point: A point on the SECP256k1 curve. :type point: SECP256k1.point """ verifying_key = VerifyingKey.from_public_point(point, curve=SECP256k1) ...
Create a PublicKey from a point on the SECP256k1 curve. :param point: A point on the SECP256k1 curve. :type point: SECP256k1.point
def _split_index(self, key): """ Partitions key into key and deep dimension groups. If only key indices are supplied, the data is indexed with an empty tuple. Keys with indices than there are dimensions will be padded. """ if not isinstance(key, tuple): key = ...
Partitions key into key and deep dimension groups. If only key indices are supplied, the data is indexed with an empty tuple. Keys with indices than there are dimensions will be padded.
def is_bday(date, bday=None): """ Return true iff the given date is a business day. Parameters ---------- date : :class:`pandas.Timestamp` Any value that can be converted to a pandas Timestamp--e.g., '2012-05-01', dt.datetime(2012, 5, 1, 3) bday : :class:`pandas.tseries.offsets...
Return true iff the given date is a business day. Parameters ---------- date : :class:`pandas.Timestamp` Any value that can be converted to a pandas Timestamp--e.g., '2012-05-01', dt.datetime(2012, 5, 1, 3) bday : :class:`pandas.tseries.offsets.CustomBusinessDay` Defaults to `C...
def delete(self, *args, **kwargs): """ Deletes the video from youtube Raises: OperationError """ api = Api() # Authentication is required for deletion api.authenticate() # Send API request, raises OperationError on unsuccessful deletion ...
Deletes the video from youtube Raises: OperationError
def mount(nbd, root=None): ''' Pass in the nbd connection device location, mount all partitions and return a dict of mount points CLI Example: .. code-block:: bash salt '*' qemu_nbd.mount /dev/nbd0 ''' __salt__['cmd.run']( 'partprobe {0}'.format(nbd), pytho...
Pass in the nbd connection device location, mount all partitions and return a dict of mount points CLI Example: .. code-block:: bash salt '*' qemu_nbd.mount /dev/nbd0
def where(self, inplace=False, **kwargs): """Return indices over every dimension that met the conditions. Condition syntax: *attribute* = value Return indices that satisfy the condition where the attribute is equal to the value e.g. ty...
Return indices over every dimension that met the conditions. Condition syntax: *attribute* = value Return indices that satisfy the condition where the attribute is equal to the value e.g. type_array = 'H' *attribute* = list(va...
def parse(cls, expression): """ Parse the given console command definition into a dict. :param expression: The expression to parse :type expression: str :rtype: dict """ parsed = {"name": None, "arguments": [], "options": []} if not expression.strip(): ...
Parse the given console command definition into a dict. :param expression: The expression to parse :type expression: str :rtype: dict
def generate(self, id_or_uri): """ Generates and returns a random range. Args: id_or_uri: ID or URI of range. Returns: dict: A dict containing a list with IDs. """ uri = self._client.build_uri(id_or_uri) + "/generate" retu...
Generates and returns a random range. Args: id_or_uri: ID or URI of range. Returns: dict: A dict containing a list with IDs.
def parser(key = "default"): """Returns the parser for the given key, (e.g. 'ssh')""" #Make sure we have a parser for that key. If we don't, then set #one up if we know what parameters to use; otherwise return the #default parser. if key not in _parsers: if key == "ssh": _parsers...
Returns the parser for the given key, (e.g. 'ssh')
def _reads_per_position(bam_in, loci_file, out_dir): """ Create input for compute entropy """ data = Counter() a = pybedtools.BedTool(bam_in) b = pybedtools.BedTool(loci_file) c = a.intersect(b, s=True, bed=True, wo=True) for line in c: end = int(line[1]) + 1 + int(line[2]) if li...
Create input for compute entropy
def _parse_sentencetree(self, tree, parent_node_id=None, ignore_traces=True): """parse a sentence Tree into this document graph""" def get_nodelabel(node): if isinstance(node, nltk.tree.Tree): return node.label() elif isinstance(node, unicode): ret...
parse a sentence Tree into this document graph
def add_annotation( self, subj: URIRef, pred: URIRef, obj: Union[Literal, URIRef], a_p: URIRef , a_o: Union[Literal, URIRef], ) -> BNode: """ Adds annotation to rdflib graph. The annotation axiom will filled in if this is a...
Adds annotation to rdflib graph. The annotation axiom will filled in if this is a new annotation for the triple. Args: subj: Entity subject to be annotated pref: Entities Predicate Anchor to be annotated obj: Entities Object Anchor to be annotated a_p: A...
def current_changed(self, index): """Stack index has changed""" # count = self.get_stack_count() # for btn in (self.filelist_btn, self.previous_btn, self.next_btn): # btn.setEnabled(count > 1) editor = self.get_current_editor() if editor.lsp_ready and not editor....
Stack index has changed
def calibrate_signal(signal, resp, fs, frange): """Given original signal and recording, spits out a calibrated signal""" # remove dc offset from recorded response (synthesized orignal shouldn't have one) dc = np.mean(resp) resp = resp - dc npts = len(signal) f0 = np.ceil(frange[0] / (float(fs) ...
Given original signal and recording, spits out a calibrated signal
def set_latency(self, latency): """Set client latency.""" self._client['config']['latency'] = latency yield from self._server.client_latency(self.identifier, latency)
Set client latency.
def backup(file_name, jail=None, chroot=None, root=None): ''' Export installed packages into yaml+mtree file CLI Example: .. code-block:: bash salt '*' pkg.backup /tmp/pkg jail Backup packages from the specified jail. Note that this will run the command within the jail, a...
Export installed packages into yaml+mtree file CLI Example: .. code-block:: bash salt '*' pkg.backup /tmp/pkg jail Backup packages from the specified jail. Note that this will run the command within the jail, and so the path to the backup file will be relative to the root...
def has_role(item): """A :func:`.check` that is added that checks if the member invoking the command has the role specified via the name or ID specified. If a string is specified, you must give the exact name of the role, including caps and spelling. If an integer is specified, you must give the e...
A :func:`.check` that is added that checks if the member invoking the command has the role specified via the name or ID specified. If a string is specified, you must give the exact name of the role, including caps and spelling. If an integer is specified, you must give the exact snowflake ID of the ro...
def certify_date(value, required=True): """ Certifier for datetime.date values. :param value: The value to be certified. :param bool required: Whether the value can be `None` Defaults to True. :raises CertifierTypeError: The type is invalid """ if certify_required( ...
Certifier for datetime.date values. :param value: The value to be certified. :param bool required: Whether the value can be `None` Defaults to True. :raises CertifierTypeError: The type is invalid
def _header_string(basis_dict): '''Creates a header with information about a basis set Information includes description, revision, etc, but not references ''' tw = textwrap.TextWrapper(initial_indent='', subsequent_indent=' ' * 20) header = '-' * 70 + '\n' header += ' Basis Set Exchange\n' ...
Creates a header with information about a basis set Information includes description, revision, etc, but not references
def dumps(self, obj, salt=None): """Returns a signed string serialized with the internal serializer. The return value can be either a byte or unicode string depending on the format of the internal serializer. """ payload = want_bytes(self.dump_payload(obj)) rv = self.make...
Returns a signed string serialized with the internal serializer. The return value can be either a byte or unicode string depending on the format of the internal serializer.
def prepare_request_body(self, private_key=None, subject=None, issuer=None, audience=None, expires_at=None, issued_at=None, ...
Create and add a JWT assertion to the request body. :param private_key: Private key used for signing and encrypting. Must be given as a string. :param subject: (sub) The principal that is the subject of the JWT, i.e. which user is the token requeste...
def _cache_key_select_daterange(method, self, field_id, field_title, style=None): """ This function returns the key used to decide if method select_daterange has to be recomputed """ key = update_timer(), field_id, field_title, style return key
This function returns the key used to decide if method select_daterange has to be recomputed
def get_plugin_conf(self, phase, name): """ Return the configuration for a plugin. Raises KeyError if there are no plugins of that type. Raises IndexError if the named plugin is not listed. """ match = [x for x in self.template[phase] if x.get('name') == name] re...
Return the configuration for a plugin. Raises KeyError if there are no plugins of that type. Raises IndexError if the named plugin is not listed.
def filter_exclude_downhole(self, threshold, filt=True): """ Exclude all points down-hole (after) the first excluded data. Parameters ---------- threhold : int The minimum number of contiguous excluded data points that must exist before downhole exclusion...
Exclude all points down-hole (after) the first excluded data. Parameters ---------- threhold : int The minimum number of contiguous excluded data points that must exist before downhole exclusion occurs. file : valid filter string or bool Which filter ...
def populate_observable(self, time, kind, dataset, **kwargs): """ TODO: add documentation """ if kind in ['mesh', 'orb']: return if time==self.time and dataset in self.populated_at_time and 'pblum' not in kind: # then we've already computed the needed co...
TODO: add documentation
def _find_valid_index(self, how): """ Retrieves the index of the first valid value. Parameters ---------- how : {'first', 'last'} Use this parameter to change between the first or last valid index. Returns ------- idx_first_valid : type of in...
Retrieves the index of the first valid value. Parameters ---------- how : {'first', 'last'} Use this parameter to change between the first or last valid index. Returns ------- idx_first_valid : type of index
def load_neurons(neurons, neuron_loader=load_neuron, name=None, population_class=Population, ignored_exceptions=()): '''Create a population object from all morphologies in a directory\ of from morphologies in a list of file names Param...
Create a population object from all morphologies in a directory\ of from morphologies in a list of file names Parameters: neurons: directory path or list of neuron file paths neuron_loader: function taking a filename and returning a neuron population_class: class representing popula...
def potential_cloud_pixels(self): """Determine potential cloud pixels (PCPs) Combine basic spectral testsr to get a premliminary cloud mask First pass, section 3.1.1 in Zhu and Woodcock 2012 Equation 6 (Zhu and Woodcock, 2012) Parameters ---------- ndvi: ndarray ...
Determine potential cloud pixels (PCPs) Combine basic spectral testsr to get a premliminary cloud mask First pass, section 3.1.1 in Zhu and Woodcock 2012 Equation 6 (Zhu and Woodcock, 2012) Parameters ---------- ndvi: ndarray ndsi: ndarray blue: ndarray ...
def parse_fn(fn): """ This parses the file name and returns the coordinates of the tile Parameters ----------- fn : str Filename of a GEOTIFF Returns -------- coords = [LLC.lat, LLC.lon, URC.lat, URC.lon] """ try: parts = os.path.splitext(os.path.split(fn)[-1])[0].r...
This parses the file name and returns the coordinates of the tile Parameters ----------- fn : str Filename of a GEOTIFF Returns -------- coords = [LLC.lat, LLC.lon, URC.lat, URC.lon]
def select_valid_methods_P(self, T, P): r'''Method to obtain a sorted list methods which are valid at `T` according to `test_method_validity`. Considers either only user methods if forced is True, or all methods. User methods are first tested according to their listed order, and unless f...
r'''Method to obtain a sorted list methods which are valid at `T` according to `test_method_validity`. Considers either only user methods if forced is True, or all methods. User methods are first tested according to their listed order, and unless forced is True, then all methods are test...
def ResetConsoleColor() -> bool: """ Reset to the default text color on console window. Return bool, True if succeed otherwise False. """ if sys.stdout: sys.stdout.flush() bool(ctypes.windll.kernel32.SetConsoleTextAttribute(_ConsoleOutputHandle, _DefaultConsoleColor))
Reset to the default text color on console window. Return bool, True if succeed otherwise False.
def random(key: str, index: Index, index_map: IndexMap=None) -> pd.Series: """Produces an indexed `pandas.Series` of uniformly distributed random numbers. The index passed in typically corresponds to a subset of rows in a `pandas.DataFrame` for which a probabilistic draw needs to be made. Parameters ...
Produces an indexed `pandas.Series` of uniformly distributed random numbers. The index passed in typically corresponds to a subset of rows in a `pandas.DataFrame` for which a probabilistic draw needs to be made. Parameters ---------- key : A string used to create a seed for the random numb...
def instance(self, counter=None, pipeline_counter=None): """Returns all the information regarding a specific stage run See the `Go stage instance documentation`__ for examples. .. __: http://api.go.cd/current/#get-stage-instance Args: counter (int): The stage instance to fet...
Returns all the information regarding a specific stage run See the `Go stage instance documentation`__ for examples. .. __: http://api.go.cd/current/#get-stage-instance Args: counter (int): The stage instance to fetch. If falsey returns the latest stage instance from :me...
def raw_search(self, *args, **kwargs): """ Find the a set of emails matching each regular expression passed in against the (RFC822) content. Args: *args: list of regular expressions. Kwargs: limit (int) - Limit to how many of the most resent emails to search thr...
Find the a set of emails matching each regular expression passed in against the (RFC822) content. Args: *args: list of regular expressions. Kwargs: limit (int) - Limit to how many of the most resent emails to search through. date (datetime) - If specified, it will f...
def scheme_chunker(text, getreffs): """ This is the scheme chunker which will resolve the reference giving a callback (getreffs) and a text object with its metadata :param text: Text Object representing either an edition or a translation :type text: MyCapytains.resources.inventory.Text :param getreffs:...
This is the scheme chunker which will resolve the reference giving a callback (getreffs) and a text object with its metadata :param text: Text Object representing either an edition or a translation :type text: MyCapytains.resources.inventory.Text :param getreffs: callback function which retrieves a list of...
def xml_replace(filename, **replacements): """Read the content of an XML template file (XMLT), apply the given `replacements` to its substitution markers, and write the result into an XML file with the same name but ending with `xml` instead of `xmlt`. First, we write an XMLT file, containing a regula...
Read the content of an XML template file (XMLT), apply the given `replacements` to its substitution markers, and write the result into an XML file with the same name but ending with `xml` instead of `xmlt`. First, we write an XMLT file, containing a regular HTML comment, a readily defined element `e1`...
def _check_repo_sign_utils_support(name): ''' Check for specified command name in search path ''' if salt.utils.path.which(name): return True else: raise CommandExecutionError( 'utility \'{0}\' needs to be installed or made available in search path'.format(name) )
Check for specified command name in search path
def geturl(environ, query=True, path=True, use_server_name=False): """Rebuilds a request URL (from PEP 333). You may want to chose to use the environment variables server_name and server_port instead of http_host in some case. The parameter use_server_name allows you to chose. :param query: Is QUER...
Rebuilds a request URL (from PEP 333). You may want to chose to use the environment variables server_name and server_port instead of http_host in some case. The parameter use_server_name allows you to chose. :param query: Is QUERY_STRING included in URI (default: True) :param path: Is path included...
def _load(self): """ Function load. :return: Response content :raises: NotFoundError """ try: get = requests.get(self._ref, verify=self.http_verify, auth=self.auth, ti...
Function load. :return: Response content :raises: NotFoundError
def store_magic_envelope_doc(self, payload): """Get the Magic Envelope, trying JSON first.""" try: json_payload = json.loads(decode_if_bytes(payload)) except ValueError: # XML payload xml = unquote(decode_if_bytes(payload)) xml = xml.lstrip().encod...
Get the Magic Envelope, trying JSON first.
def all_subclasses(cls): """Generator yielding all subclasses of `cls` recursively""" for subcls in cls.__subclasses__(): yield subcls for subsubcls in all_subclasses(subcls): yield subsubcls
Generator yielding all subclasses of `cls` recursively
def get_interfaces(self): """Return interfaces details.""" result = {} interfaces = junos_views.junos_iface_table(self.device) interfaces.get() interfaces_logical = junos_views.junos_logical_iface_table(self.device) interfaces_logical.get() # convert all the tup...
Return interfaces details.
def _prm_store_from_dict(self, fullname, store_dict, hdf5_group, store_flags, kwargs): """Stores a `store_dict`""" for key, data_to_store in store_dict.items(): # self._logger.log(1, 'SUB-Storing %s [%s]', key, str(store_dict[key])) original_hdf5_group = None flag = ...
Stores a `store_dict`
def cart_to_polar(arr_c): """Return cartesian vectors in their polar representation. Parameters ---------- arr_c: array, shape (a1, a2, ..., d) Cartesian vectors, with last axis indexing the dimension. Returns ------- arr_p: array, shape of arr_c Polar vectors, using (radiu...
Return cartesian vectors in their polar representation. Parameters ---------- arr_c: array, shape (a1, a2, ..., d) Cartesian vectors, with last axis indexing the dimension. Returns ------- arr_p: array, shape of arr_c Polar vectors, using (radius, inclination, azimuth) conventi...
def add_property(self, name, value): # type: (str, object) -> bool """ Adds a property to the framework **if it is not yet set**. If the property already exists (same name), then nothing is done. Properties can't be updated. :param name: The property name :param...
Adds a property to the framework **if it is not yet set**. If the property already exists (same name), then nothing is done. Properties can't be updated. :param name: The property name :param value: The value to set :return: True if the property was stored, else False
def delete_connection(self, name, reason=None): """ Closes an individual connection. Give an optional reason :param name: The connection name :type name: str :param reason: An option reason why the connection was deleted :type reason: str """ headers = {...
Closes an individual connection. Give an optional reason :param name: The connection name :type name: str :param reason: An option reason why the connection was deleted :type reason: str
def _update_mean_in_window(self): """ Compute mean in window the slow way. useful for first step. Considers all values in window See Also -------- _add_observation_to_means : fast update of mean for single observation addition _remove_observation_from_means : fa...
Compute mean in window the slow way. useful for first step. Considers all values in window See Also -------- _add_observation_to_means : fast update of mean for single observation addition _remove_observation_from_means : fast update of mean for single observation removal
def delete(self, *args): """Remove the key from the request cache and from memcache.""" cache = get_cache() key = self.get_cache_key(*args) if key in cache: del cache[key]
Remove the key from the request cache and from memcache.
def R_op(self, inputs, eval_points): """Apply the adjoint of the Jacobian at ``inputs`` to ``eval_points``. This is the symbolic counterpart of ODL's :: op.derivative(x).adjoint(v) See `grad` for its usage. Parameters ---------- inputs : 1-element list of ...
Apply the adjoint of the Jacobian at ``inputs`` to ``eval_points``. This is the symbolic counterpart of ODL's :: op.derivative(x).adjoint(v) See `grad` for its usage. Parameters ---------- inputs : 1-element list of `theano.tensor.var.TensorVariable` S...
def convert_surrogate_pair(match): """ Convert a surrogate pair to the single codepoint it represents. This implements the formula described at: http://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates """ pair = match.group(0) codept = 0x10000 + (ord(pair[0]) - 0xd800) * ...
Convert a surrogate pair to the single codepoint it represents. This implements the formula described at: http://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates
def parse(args): """ Define the available arguments """ from tzlocal import get_localzone try: timezone = get_localzone() if isinstance(timezone, pytz.BaseTzInfo): timezone = timezone.zone except Exception: # pragma: no cover timezone = 'UTC' if timezone...
Define the available arguments
def uintersect1d(arr1, arr2, assume_unique=False): """Find the sorted unique elements of the two input arrays. A wrapper around numpy.intersect1d that preserves units. All input arrays must have the same units. See the documentation of numpy.intersect1d for full details. Examples -------- ...
Find the sorted unique elements of the two input arrays. A wrapper around numpy.intersect1d that preserves units. All input arrays must have the same units. See the documentation of numpy.intersect1d for full details. Examples -------- >>> from unyt import cm >>> A = [1, 2, 3]*cm >>>...
def is_blackout(self) -> bool: """Does this alert match a blackout period?""" if not current_app.config['NOTIFICATION_BLACKOUT']: if self.severity in current_app.config['BLACKOUT_ACCEPT']: return False return db.is_blackout_period(self)
Does this alert match a blackout period?
def file_ops(staticfied, args): """Write to stdout or a file""" destination = args.o or args.output if destination: with open(destination, 'w') as file: file.write(staticfied) else: print(staticfied)
Write to stdout or a file
def to_dict(self): """ Encode the name, the status of all checks, and the current overall status. """ # evaluate checks checks = { key: HealthResult.evaluate(func, self.graph) for key, func in self.checks.items() } dct = dict( ...
Encode the name, the status of all checks, and the current overall status.
def __restrictIndex(self, i): """Provides list-like handling of a record index with a clearer error message if the index is out of bounds.""" if self.numRecords: rmax = self.numRecords - 1 if abs(i) > rmax: raise IndexError("Shape or Record index out...
Provides list-like handling of a record index with a clearer error message if the index is out of bounds.
def _removecleaner(self, cleaner): """ Remove the cleaner from the list if it already exists. Returns True if the cleaner was removed. """ oldlen = len(self._old_cleaners) self._old_cleaners = [ oldc for oldc in self._old_cleaners if not oldc.issam...
Remove the cleaner from the list if it already exists. Returns True if the cleaner was removed.
def insert_from_segwizard(self, fileobj, instruments, name, version = None, comment = None): """ Parse the contents of the file object fileobj as a segwizard-format segment list, and insert the result as a new list of "active" segments into this LigolwSegments object. A new entry will be created in the segme...
Parse the contents of the file object fileobj as a segwizard-format segment list, and insert the result as a new list of "active" segments into this LigolwSegments object. A new entry will be created in the segment_definer table for the segment list, and instruments, name and comment are used to populate the...
def share(self, base=None, keys=None, by=None, **kwargs): """ Share the formatoptions of one plotter with all the others This method shares specified formatoptions from `base` with all the plotters in this instance. Parameters ---------- base: None, Plotter, xar...
Share the formatoptions of one plotter with all the others This method shares specified formatoptions from `base` with all the plotters in this instance. Parameters ---------- base: None, Plotter, xarray.DataArray, InteractiveList, or list of them The source of the ...
def childgroup(self, field): """ Return a list of fields stored by row regarding the configured grid :param field: The original field this widget is attached to """ grid = getattr(self, "grid", None) named_grid = getattr(self, "named_grid", None) if grid is not ...
Return a list of fields stored by row regarding the configured grid :param field: The original field this widget is attached to
def md_to_pdf(input_name, output_name): """ Converts an input MarkDown file to a PDF of the given output name. Parameters ========== input_name : String Relative file location of the input file to where this function is being called. output_name : String Relative file location of the o...
Converts an input MarkDown file to a PDF of the given output name. Parameters ========== input_name : String Relative file location of the input file to where this function is being called. output_name : String Relative file location of the output file to where this function is being called. N...
def search_seqs(self, seqrec, in_seq, locus, run=0, partial_ann=None): """ search_seqs - method for annotating a BioPython sequence without alignment :param seqrec: The reference sequence :type seqrec: SeqRecord :param locus: The gene locus associated with the sequence. ...
search_seqs - method for annotating a BioPython sequence without alignment :param seqrec: The reference sequence :type seqrec: SeqRecord :param locus: The gene locus associated with the sequence. :type locus: str :param in_seq: The input sequence :type in_seq: SeqRecord ...