code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def start_segment_address(cs, ip): """Return Start Segment Address Record. @param cs 16-bit value for CS register. @param ip 16-bit value for IP register. @return String representation of Intel Hex SSA record. """ b = [4, 0, 0, 0x03, (cs>>8)&0x0FF, cs...
Return Start Segment Address Record. @param cs 16-bit value for CS register. @param ip 16-bit value for IP register. @return String representation of Intel Hex SSA record.
async def fetch_token(self): """Fetch new session token from api.""" url = '{}/login'.format(API_URL) payload = 'email={}&password={}'.format(self._email, self._password) reg = await self.api_post(url, None, payload) if reg is None: _LOGGER.error('Unable to authentic...
Fetch new session token from api.
def update_config(config_new, config_default): ''' Updates the loaded method configuration with default values. ''' if any([isinstance(v, dict) for v in list(config_new.values())]): for k,v in list(config_new.items()): if isinstance(v,dict) and k in config_default: u...
Updates the loaded method configuration with default values.
def _set_shared_instances(self): """Sets attributes from the shared instances.""" self.inqueue = self.em.get_inqueue() self.outqueue = self.em.get_outqueue() self.namespace = self.em.get_namespace()
Sets attributes from the shared instances.
def _vmf_normalize(kappa, dim): """Compute normalization constant using built-in numpy/scipy Bessel approximations. Works well on small kappa and mu. """ num = np.power(kappa, dim / 2. - 1.) if dim / 2. - 1. < 1e-15: denom = np.power(2. * np.pi, dim / 2.) * i0(kappa) else: ...
Compute normalization constant using built-in numpy/scipy Bessel approximations. Works well on small kappa and mu.
def parse(station: str, txt: str) -> TafData: """ Returns TafData and Units dataclasses with parsed data and their associated units """ core.valid_station(station) while len(txt) > 3 and txt[:4] in ('TAF ', 'AMD ', 'COR '): txt = txt[4:] _, station, time = core.get_station_and_time(txt[:...
Returns TafData and Units dataclasses with parsed data and their associated units
def _get_layout(self): """ Get the outputs layout from xrandr and try to detect the currently active layout as best as we can on start. """ connected = list() active_layout = list() disconnected = list() layout = OrderedDict( {"connected": Orde...
Get the outputs layout from xrandr and try to detect the currently active layout as best as we can on start.
def _show(self, message, indent=0, enable_verbose=True): # pragma: no cover """Message printer. """ if enable_verbose: print(" " * indent + message)
Message printer.
def mime(self): """ Returns the finalised mime object, after applying the internal headers. Usually this is not to be overriden. """ mime = self.mime_object() self.headers.prepare(mime) return mime
Returns the finalised mime object, after applying the internal headers. Usually this is not to be overriden.
def render(self, target, data): """Render the table.""" rows = self.get_rows(target, data) rows = self._filter_rows(rows) renderer = getattr(self, "_render_%s" % target.name, None) if renderer is None: raise ValueError( "Cannot render %r for %s." % (se...
Render the table.
def points_on_circle(radius, points): """ returns a set of uniform points around a circle :param radius: radius of the circle :param points: number of points on the circle :return: """ angle = np.linspace(0, 2*np.pi, points) x_coord = np.cos(angle)*radius y_coord = np.sin(angle)*radi...
returns a set of uniform points around a circle :param radius: radius of the circle :param points: number of points on the circle :return:
async def count(self, query, clear_limit=False): """Perform *COUNT* aggregated query asynchronously. :return: number of objects in ``select()`` query """ query = self._swap_database(query) return (await count(query, clear_limit=clear_limit))
Perform *COUNT* aggregated query asynchronously. :return: number of objects in ``select()`` query
def ostree_compose(self, release): """Compose the OSTree in the mock container""" start = datetime.utcnow() treefile = os.path.join(release['git_dir'], 'treefile.json') cmd = release['ostree_compose'] % treefile with file(treefile, 'w') as tree: json.dump(release['tre...
Compose the OSTree in the mock container
def _prepend_name(self, prefix, dict_): '''changes the keys of the dictionary prepending them with "name."''' return dict(['.'.join([prefix, name]), msg] for name, msg in dict_.iteritems())
changes the keys of the dictionary prepending them with "name."
def _words_by_score(words, score, least_to_most, n=None): """ Order a vector of `words` by a `score`, either `least_to_most` or reverse. Optionally return only the top `n` results. """ if words.shape != score.shape: raise ValueError('`words` and `score` must have the same shape') if n i...
Order a vector of `words` by a `score`, either `least_to_most` or reverse. Optionally return only the top `n` results.
async def create_student_container(self, job_id, parent_container_id, sockets_path, student_path, systemfiles_path, course_common_student_path, socket_id, environment_name, memory_limit, time_limit, hard_time_limit, share_network, write_stre...
Creates a new student container. :param write_stream: stream on which to write the return value of the container (with a correctly formatted msgpack message)
def _finalize(self): """Reset the status and tell the database to finalize the traces.""" if self.status in ['running', 'halt']: if self.verbose > 0: print_('\nSampling finished normally.') self.status = 'ready' self.save_state() self.db._finalize...
Reset the status and tell the database to finalize the traces.
def overlap_cplx(vec1, vec2, psd=None, low_frequency_cutoff=None, high_frequency_cutoff=None, normalized=True): """Return the complex overlap between the two TimeSeries or FrequencySeries. Parameters ---------- vec1 : TimeSeries or FrequencySeries The input vector containing a wavefor...
Return the complex overlap between the two TimeSeries or FrequencySeries. Parameters ---------- vec1 : TimeSeries or FrequencySeries The input vector containing a waveform. vec2 : TimeSeries or FrequencySeries The input vector containing a waveform. psd : Frequency Series A ...
def get_notmuch_setting(self, section, key, fallback=None): """ look up config values from notmuch's config :param section: key is in :type section: str :param key: key to look up :type key: str :param fallback: fallback returned if key is not present :ty...
look up config values from notmuch's config :param section: key is in :type section: str :param key: key to look up :type key: str :param fallback: fallback returned if key is not present :type fallback: str :returns: config value with type as specified in the sp...
def statistical_axes(fit, **kw): """ Hyperbolic error using a statistical process (either sampling or noise errors) Integrates covariance with error level and degrees of freedom for plotting confidence intervals. Degrees of freedom is set to 2, which is the relevant number of independe...
Hyperbolic error using a statistical process (either sampling or noise errors) Integrates covariance with error level and degrees of freedom for plotting confidence intervals. Degrees of freedom is set to 2, which is the relevant number of independent dimensions to planar fitting of *a pri...
def assumes(*args): '''Stores a function's assumptions as an attribute.''' args = tuple(args) def decorator(func): func.assumptions = args return func return decorator
Stores a function's assumptions as an attribute.
def getProductUIDs(self): """ return the uids of the products referenced by order items """ uids = [] for orderitem in self.objectValues('XupplyOrderItem'): product = orderitem.getProduct() if product is not None: uids.append(orderitem.getProduct()...
return the uids of the products referenced by order items
def p_theory(self, p): """theory : LBRACKET superclauses_sum RBRACKET | LBRACKET superclauses_sum RBRACKET literal_list""" if len(p) == 4: p[0] = Theory(p[2]) else: p[0] = Theory(p[2], literals=p[4])
theory : LBRACKET superclauses_sum RBRACKET | LBRACKET superclauses_sum RBRACKET literal_list
def object_data(self): '''Process the archival export and return a buffer with foxml content for ingest into the destination repository. :returns: :class:`io.BytesIO` for ingest, with references to uploaded datastream content or content location urls ''' self.foxml_b...
Process the archival export and return a buffer with foxml content for ingest into the destination repository. :returns: :class:`io.BytesIO` for ingest, with references to uploaded datastream content or content location urls
def _init_metadata(self): """stub""" self._provenance_metadata = { 'element_id': Id(self.my_osid_object_form._authority, self.my_osid_object_form._namespace, 'provenanceId'), 'element_label': 'provenanceId', 'i...
stub
def get_aggregations(self, query, group_by, stats_field, percents=(50, 95, 99, 99.9), size=100): """ Returns aggregations (rows count + percentile stats) for a given query This is basically the same as the following pseudo-SQL query: SELECT PERCENTILE(stats_field, 75) FROM query GROUP B...
Returns aggregations (rows count + percentile stats) for a given query This is basically the same as the following pseudo-SQL query: SELECT PERCENTILE(stats_field, 75) FROM query GROUP BY group_by LIMIT size https://www.elastic.co/guide/en/elasticsearch/reference/5.5/search-aggregations-bucket...
def tex_parse(string): """ Renders some basic TeX math to HTML. """ string = string.replace('{', '').replace('}', '') def tex_replace(match): return \ sub(r'\^(\w)', r'<sup>\1</sup>', sub(r'\^\{(.*?)\}', r'<sup>\1</sup>', sub(r'\_(\w)', r'<sub>\1</sub>', sub(r'\_\{(.*?)\}', r'<sub>\1</sub>', sub(...
Renders some basic TeX math to HTML.
def to_dict(self) -> Dict[str, Any]: """Message format according to monitoring service spec""" return { 'type': self.__class__.__name__, 'channel_identifier': self.channel_identifier, 'token_network_address': to_normalized_address(self.token_network_address), ...
Message format according to monitoring service spec
def json_dumps(obj): """A safe JSON dump function that provides correct diverging numbers for a ECMAscript consumer. """ try: return json.dumps(obj, indent=2, sort_keys=True, allow_nan=False) except ValueError: pass # we don't want to call do_map on the original object since i...
A safe JSON dump function that provides correct diverging numbers for a ECMAscript consumer.
def _generate_current_command(self): ''' Returns a constructed GCode string that contains this driver's axis-current settings, plus a small delay to wait for those settings to take effect. ''' values = ['{}{}'.format(axis, value) for axis, value in sorte...
Returns a constructed GCode string that contains this driver's axis-current settings, plus a small delay to wait for those settings to take effect.
def __updateJobResultsPeriodic(self): """ Periodic check to see if this is the best model. This should only have an effect if this is the *first* model to report its progress """ if self._isBestModelStored and not self._isBestModel: return while True: jobResultsStr = self._jobsDAO.j...
Periodic check to see if this is the best model. This should only have an effect if this is the *first* model to report its progress
def randomize_molecule_low(molecule, manipulations): """Return a randomized copy of the molecule, without the nonbond check.""" manipulations = copy.copy(manipulations) shuffle(manipulations) coordinates = molecule.coordinates.copy() for manipulation in manipulations: manipulation.apply(coo...
Return a randomized copy of the molecule, without the nonbond check.
def from_dataset(cls, dataset, constraints = (), **kwargs): """Construct a optimized inverse model from an existing dataset. A LWLR forward model is constructed by default. """ fm = LWLRForwardModel(dataset.dim_x, dataset.dim_y, **kwargs) fm.dataset = dataset im = cls.fro...
Construct a optimized inverse model from an existing dataset. A LWLR forward model is constructed by default.
def main(argv=None): """Validate text parsed with FSM or validate an FSM via command line.""" if argv is None: argv = sys.argv try: opts, args = getopt.getopt(argv[1:], 'h', ['help']) except getopt.error as msg: raise Usage(msg) for opt, _ in opts: if opt in ('-h', '--help'): print(__...
Validate text parsed with FSM or validate an FSM via command line.
def allreduce_ring(xs, devices, reduction_fn_string="SUM"): """Compute the reduction of all Tensors and put the result everywhere. Performance-optimized for a ring of devices. Args: xs: a list of n tf.Tensors devices: a list of strings reduction_fn_string: "SUM" or "MAX" Returns: a list of n ...
Compute the reduction of all Tensors and put the result everywhere. Performance-optimized for a ring of devices. Args: xs: a list of n tf.Tensors devices: a list of strings reduction_fn_string: "SUM" or "MAX" Returns: a list of n Tensors Raises: ValueError: if devices is not a list of n s...
def results(self, dataset_name, index_by, timeframe): """ Retrieve results from a Cached Dataset. Read key must be set. """ url = "{0}/{1}/results".format(self._cached_datasets_url, dataset_name) index_by = index_by if isinstance(index_by, str) else json.dumps(index_by) timefram...
Retrieve results from a Cached Dataset. Read key must be set.
def is_valid_address (s): """ returns True if address is a valid Bluetooth address valid address are always strings of the form XX:XX:XX:XX:XX:XX where X is a hexadecimal character. For example, 01:23:45:67:89:AB is a valid address, but IN:VA:LI:DA:DD:RE is not """ try: ...
returns True if address is a valid Bluetooth address valid address are always strings of the form XX:XX:XX:XX:XX:XX where X is a hexadecimal character. For example, 01:23:45:67:89:AB is a valid address, but IN:VA:LI:DA:DD:RE is not
def input(self, _in, out, **kw): """Input filtering.""" args = [self.binary or 'cleancss'] + self.rebase_opt if self.extra_args: args.extend(self.extra_args) self.subprocess(args, out, _in)
Input filtering.
def defocusThroughDepth(u, uf, f, fn, k=2.355): ''' return the defocus (mm std) through DOF u -> scene point (depth value) uf -> in-focus position (the distance at which the scene point should be placed in order to be focused) f -> focal length k -> camera dependent constant (transfe...
return the defocus (mm std) through DOF u -> scene point (depth value) uf -> in-focus position (the distance at which the scene point should be placed in order to be focused) f -> focal length k -> camera dependent constant (transferring blur circle to PSF), 2.335 would be FHWD of 2dgaussian ...
def get_parent(self): """Return tile from previous zoom level.""" return None if self.zoom == 0 else self.tile_pyramid.tile( self.zoom - 1, self.row // 2, self.col // 2 )
Return tile from previous zoom level.
def register(self, name, func): """ Register a new callback.\ When the name/id is not found\ a new hook is created under its name,\ meaning the hook is usually created by\ the first registered callback :param str name: Hook name :param callable func: A fu...
Register a new callback.\ When the name/id is not found\ a new hook is created under its name,\ meaning the hook is usually created by\ the first registered callback :param str name: Hook name :param callable func: A func reference (callback)
def process_from_web(): """Return a TrrustProcessor based on the online interaction table. Returns ------- TrrustProcessor A TrrustProcessor object that has a list of INDRA Statements in its statements attribute. """ logger.info('Downloading table from %s' % trrust_human_url) ...
Return a TrrustProcessor based on the online interaction table. Returns ------- TrrustProcessor A TrrustProcessor object that has a list of INDRA Statements in its statements attribute.
def remove_item(self, val): """ Removes given item from the list. Args: val: Item Returns: Cache backend response. """ return cache.lrem(self.key, json.dumps(val))
Removes given item from the list. Args: val: Item Returns: Cache backend response.
def unregister_message_callback(self, type_, from_): """ Unregister a callback previously registered with :meth:`register_message_callback`. :param type_: Message type to listen for. :type type_: :class:`~.MessageType` or :data:`None` :param from_: Sender JID to listen f...
Unregister a callback previously registered with :meth:`register_message_callback`. :param type_: Message type to listen for. :type type_: :class:`~.MessageType` or :data:`None` :param from_: Sender JID to listen for. :type from_: :class:`~aioxmpp.JID` or :data:`None` :r...
def datetimes(self): """Return datetimes for this collection as a tuple.""" if self._datetimes is None: self._datetimes = tuple(self.header.analysis_period.datetimes) return self._datetimes
Return datetimes for this collection as a tuple.
def get_available_modes(self): """Return a list of available mode objects for an Arlo user.""" resource = "modes" resource_event = self.publish_and_get_event(resource) if resource_event: properties = resource_event.get("properties") return properties.get("modes") ...
Return a list of available mode objects for an Arlo user.
def clone(cls, model, use_json=True, use_lp=False): """ Make a copy of a model. The model being copied can be of the same type or belong to a different solver interface. This is the preferred way of copying models. Example ---------- >>> new_model = Model.clone(old_model...
Make a copy of a model. The model being copied can be of the same type or belong to a different solver interface. This is the preferred way of copying models. Example ---------- >>> new_model = Model.clone(old_model)
def get_uri_template(urlname, args=None, prefix=""): ''' Utility function to return an URI Template from a named URL in django Copied from django-digitalpaper. Restrictions: - Only supports named urls! i.e. url(... name="toto") - Only support one namespace level - Only returns the first URL...
Utility function to return an URI Template from a named URL in django Copied from django-digitalpaper. Restrictions: - Only supports named urls! i.e. url(... name="toto") - Only support one namespace level - Only returns the first URL possibility. - Supports multiple pattern possibilities (i.e....
def _vector_size(v): """ Returns the size of the vector. >>> _vector_size([1., 2., 3.]) 3 >>> _vector_size((1., 2., 3.)) 3 >>> _vector_size(array.array('d', [1., 2., 3.])) 3 >>> _vector_size(np.zeros(3)) 3 >>> _vector_size(np.zeros((3, 1))) 3 >>> _vector_size(np.zero...
Returns the size of the vector. >>> _vector_size([1., 2., 3.]) 3 >>> _vector_size((1., 2., 3.)) 3 >>> _vector_size(array.array('d', [1., 2., 3.])) 3 >>> _vector_size(np.zeros(3)) 3 >>> _vector_size(np.zeros((3, 1))) 3 >>> _vector_size(np.zeros((1, 3))) Traceback (most re...
def NewDefaultAgency(self, **kwargs): """Create a new Agency object and make it the default agency for this Schedule""" agency = self._gtfs_factory.Agency(**kwargs) if not agency.agency_id: agency.agency_id = util.FindUniqueId(self._agencies) self._default_agency = agency self.SetDefaultAgency...
Create a new Agency object and make it the default agency for this Schedule
def convex_conj(self): """The conjugate functional of IndicatorLpUnitBall. The convex conjugate functional of an ``Lp`` norm, ``p < infty`` is the indicator function on the unit ball defined by the corresponding dual norm ``q``, given by ``1/p + 1/q = 1`` and where ``q = infty`` if ...
The conjugate functional of IndicatorLpUnitBall. The convex conjugate functional of an ``Lp`` norm, ``p < infty`` is the indicator function on the unit ball defined by the corresponding dual norm ``q``, given by ``1/p + 1/q = 1`` and where ``q = infty`` if ``p = 1`` [Roc1970]. By the Fe...
def validate_json_schema(self): """Validate the JSON schema. Return list of errors.""" errors = [] for work in self: for task in work: if not task.get_results().validate_json_schema(): errors.append(task) if not work.get_results().vali...
Validate the JSON schema. Return list of errors.
def to_xdr_object(self): """Creates an XDR Memo object for a transaction with MEMO_HASH.""" return Xdr.types.Memo(type=Xdr.const.MEMO_HASH, hash=self.memo_hash)
Creates an XDR Memo object for a transaction with MEMO_HASH.
def scan_uow_candidates(self): """ method performs two actions: - enlist stale or invalid units of work into reprocessing queue - cancel UOWs that are older than 2 days and have been submitted more than 1 hour ago """ try: since = settings.settings['synergy_start_time...
method performs two actions: - enlist stale or invalid units of work into reprocessing queue - cancel UOWs that are older than 2 days and have been submitted more than 1 hour ago
def read_cf1_config(self): """Read a flash page from the specified target""" target = self._cload.targets[0xFF] config_page = target.flash_pages - 1 return self._cload.read_flash(addr=0xFF, page=config_page)
Read a flash page from the specified target
def _validate_zooms(zooms): """ Return a list of zoom levels. Following inputs are converted: - int --> [int] - dict{min, max} --> range(min, max + 1) - [int] --> [int] - [int, int] --> range(smaller int, bigger int + 1) """ if isinstance(zooms, dict): if any([a not in zooms...
Return a list of zoom levels. Following inputs are converted: - int --> [int] - dict{min, max} --> range(min, max + 1) - [int] --> [int] - [int, int] --> range(smaller int, bigger int + 1)
def get_url_parameters(self): """Create a dictionary of parameters used in URLs for this model.""" url_fields = {} for field in self.url_fields: url_fields[field] = getattr(self, field) return url_fields
Create a dictionary of parameters used in URLs for this model.
def remove_all_cts_records_by(self, crypto_idfp): """ Remove all CTS records from the specified player :param crypto_idfp: :return: """ regex = re.compile('(.+)/cts100record/crypto_idfp(\d+)') to_remove = [] for k, v in self.filter(regex, is_regex=True): ...
Remove all CTS records from the specified player :param crypto_idfp: :return:
def ctrl_transfer(self, bmRequestType, bRequest, wValue=0, wIndex=0, data_or_wLength = None, timeout = None): r"""Do a control transfer on the endpoint 0. This method is used to issue a control transfer over the endpoint 0 (endpoint 0 is required to always be a control endpoint). ...
r"""Do a control transfer on the endpoint 0. This method is used to issue a control transfer over the endpoint 0 (endpoint 0 is required to always be a control endpoint). The parameters bmRequestType, bRequest, wValue and wIndex are the same of the USB Standard Control Request format. ...
def find_lemma(self, verb): """ Returns the base form of the given inflected verb, using a rule-based approach. """ v = verb.lower() # Common prefixes: be-finden and emp-finden probably inflect like finden. if not (v.startswith("ge") and v.endswith("t")): # Probably gerund. ...
Returns the base form of the given inflected verb, using a rule-based approach.
def do_selection_reduction_to_one_parent(selection): """ Find and reduce selection to one parent state. :param selection: :return: state model which is parent of selection or None if root state """ all_models_selected = selection.get_all() # check if all elements select...
Find and reduce selection to one parent state. :param selection: :return: state model which is parent of selection or None if root state
def get_stdev(self, col, row): """ Returns the standard deviation at this location (if valid location). :param col: the 0-based column index :type col: int :param row: the 0-based row index :type row: int :return: the standard deviation :rtype: float ...
Returns the standard deviation at this location (if valid location). :param col: the 0-based column index :type col: int :param row: the 0-based row index :type row: int :return: the standard deviation :rtype: float
def process(self, plugin, context, instance=None, action=None): """Transmit a `process` request to host Arguments: plugin (PluginProxy): Plug-in to process context (ContextProxy): Filtered context instance (InstanceProxy, optional): Instance to process ac...
Transmit a `process` request to host Arguments: plugin (PluginProxy): Plug-in to process context (ContextProxy): Filtered context instance (InstanceProxy, optional): Instance to process action (str, optional): Action to process
def generate_value_label(self, byteorder, encoding): """ Parameters ---------- byteorder : str Byte order of the output encoding : str File encoding Returns ------- value_label : bytes Bytes containing the formatted val...
Parameters ---------- byteorder : str Byte order of the output encoding : str File encoding Returns ------- value_label : bytes Bytes containing the formatted value label
def convert_p(element, text): """ Adds 2 newlines to the end of text """ depth = -1 while element: if (not element.name == '[document]' and not element.parent.get('id') == '__RESTRUCTIFY_WRAPPER__'): depth += 1 element = element.parent if text: ...
Adds 2 newlines to the end of text
def _is_locked(self): ''' Checks to see if we are already pulling items from the queue ''' if os.path.isfile(self._lck): try: import psutil except ImportError: return True #Lock file exists and no psutil #If psutil is im...
Checks to see if we are already pulling items from the queue
def lower_key(fn): """ :param fn: a key function :return: a function that wraps around the supplied key function to ensure the returned key is in lowercase. """ def lower(key): try: return key.lower() except AttributeError: return key retu...
:param fn: a key function :return: a function that wraps around the supplied key function to ensure the returned key is in lowercase.
def get_assessments_by_query(self, assessment_query): """Gets a list of ``Assessments`` matching the given assessment query. arg: assessment_query (osid.assessment.AssessmentQuery): the assessment query return: (osid.assessment.AssessmentList) - the returned `...
Gets a list of ``Assessments`` matching the given assessment query. arg: assessment_query (osid.assessment.AssessmentQuery): the assessment query return: (osid.assessment.AssessmentList) - the returned ``AssessmentList`` raise: NullArgument - ``assessment_que...
def get_data_by_slug(model, slug, kind='', **kwargs): """Get instance data by slug and kind. Raise 404 Not Found if there is no data. This function requires model has a `slug` column. :param model: a string, model name in rio.models :param slug: a string used to query by `slug`. This requires there is...
Get instance data by slug and kind. Raise 404 Not Found if there is no data. This function requires model has a `slug` column. :param model: a string, model name in rio.models :param slug: a string used to query by `slug`. This requires there is a slug field in model definition. :para...
def get_lines(handle, line): """ Get zero-indexed line from an open file-like. """ for i, l in enumerate(handle): if i == line: return l
Get zero-indexed line from an open file-like.
def flip_coded(self): """Flips the coding of the alleles.""" self.genotypes = 2 - self.genotypes self.reference, self.coded = self.coded, self.reference
Flips the coding of the alleles.
def instantiate_components(self, context): """ Instantiate the defined components .. note:: This method requires the iPOPO core service to be registered. This means that the ``pelix.ipopo.core`` must have been declared in the list of bundles (or installed and st...
Instantiate the defined components .. note:: This method requires the iPOPO core service to be registered. This means that the ``pelix.ipopo.core`` must have been declared in the list of bundles (or installed and started programmatically). :param context: A :class:`~pe...
def refresh_db(**kwargs): ''' Update ports with ``port selfupdate`` CLI Example: .. code-block:: bash salt mac pkg.refresh_db ''' # Remove rtag file to keep multiple refreshes from happening in pkg states salt.utils.pkg.clear_rtag(__opts__) cmd = ['port', 'selfupdate'] ret...
Update ports with ``port selfupdate`` CLI Example: .. code-block:: bash salt mac pkg.refresh_db
def _tryMatch(self, textToMatchObject): """Try to find themselves in the text. Returns (count, matchedRule) or (None, None) if doesn't match """ for rule in self.context.rules: ruleTryMatchResult = rule.tryMatch(textToMatchObject) if ruleTryMatchResult is not None...
Try to find themselves in the text. Returns (count, matchedRule) or (None, None) if doesn't match
def nonterminal(n): """ Create a PEG function to match a nonterminal. """ def match_nonterminal(s, grm=None, pos=0): if grm is None: grm = {} expr = grm[n] return expr(s, grm, pos) return match_nonterminal
Create a PEG function to match a nonterminal.
def get_image_path(definition): """Helper to get path of image from a definition in resource directory. :param definition: A definition (hazard, exposure). :type definition: dict :returns: The definition's image path. :rtype: str """ path = resources_path( 'img', 'wizard', 'keyword...
Helper to get path of image from a definition in resource directory. :param definition: A definition (hazard, exposure). :type definition: dict :returns: The definition's image path. :rtype: str
def get_anki_phrases(lang='english', limit=None): """ Retrieve as many anki paired-statement corpora as you can for the requested language If `ankis` (requested languages) is more than one, then get the english texts associated with those languages. TODO: improve modularity: def function that takes a sing...
Retrieve as many anki paired-statement corpora as you can for the requested language If `ankis` (requested languages) is more than one, then get the english texts associated with those languages. TODO: improve modularity: def function that takes a single language and call it recursively if necessary >>> g...
def is_bool_dtype(arr_or_dtype): """ Check whether the provided array or dtype is of a boolean dtype. Parameters ---------- arr_or_dtype : array-like The array or dtype to check. Returns ------- boolean Whether or not the array or dtype is of a boolean dtype. Notes...
Check whether the provided array or dtype is of a boolean dtype. Parameters ---------- arr_or_dtype : array-like The array or dtype to check. Returns ------- boolean Whether or not the array or dtype is of a boolean dtype. Notes ----- An ExtensionArray is considere...
def send_method_request(self, method: str, method_params: dict) -> dict: """ Sends user-defined method and method params """ url = '/'.join((self.METHOD_URL, method)) method_params['v'] = self.API_VERSION if self._access_token: method_params['access_token'] = ...
Sends user-defined method and method params
def export_chat_invite_link( self, chat_id: Union[int, str] ) -> str: """Use this method to generate a new invite link for a chat; any previously generated link is revoked. You must be an administrator in the chat for this to work and have the appropriate admin rights. Args...
Use this method to generate a new invite link for a chat; any previously generated link is revoked. You must be an administrator in the chat for this to work and have the appropriate admin rights. Args: chat_id (``int`` | ``str``): Unique identifier for the target chat or u...
def _decodeAddressField(byteIter, smscField=False, log=False): """ Decodes the address field at the current position of the bytearray iterator :param byteIter: Iterator over bytearray :type byteIter: iter(bytearray) :return: Tuple containing the address value and amount of bytes read (value i...
Decodes the address field at the current position of the bytearray iterator :param byteIter: Iterator over bytearray :type byteIter: iter(bytearray) :return: Tuple containing the address value and amount of bytes read (value is or None if it is empty (zero-length)) :rtype: tuple
def tobytes(self): """Return the bitstring as bytes, padding with zero bits if needed. Up to seven zero bits will be added at the end to byte align. """ d = offsetcopy(self._datastore, 0).rawbytes # Need to ensure that unused bits at end are set to zero unusedbits = 8 -...
Return the bitstring as bytes, padding with zero bits if needed. Up to seven zero bits will be added at the end to byte align.
def check_extension(conn, extension: str) -> bool: """Check to see if an extension is installed.""" query = 'SELECT installed_version FROM pg_available_extensions WHERE name=%s;' with conn.cursor() as cursor: cursor.execute(query, (extension,)) result = cursor.fetchone() if result is ...
Check to see if an extension is installed.
def get_git_branch(git_path='git'): """Returns the name of the current git branch """ branch_match = call((git_path, 'rev-parse', '--symbolic-full-name', 'HEAD')) if branch_match == "HEAD": return None else: return os.path.basename(branch_match)
Returns the name of the current git branch
def encode_notifications(tokens, notifications): """ Returns the encoded bytes of tokens and notifications tokens a list of tokens or a string of only one token notifications a list of notifications or a dictionary of only one """ fmt = "!BH32sH%ds" structify = lambda t, p: stru...
Returns the encoded bytes of tokens and notifications tokens a list of tokens or a string of only one token notifications a list of notifications or a dictionary of only one
def _from_dict(cls, _dict): """Initialize a UnalignedElement object from a json dictionary.""" args = {} if 'document_label' in _dict: args['document_label'] = _dict.get('document_label') if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('lo...
Initialize a UnalignedElement object from a json dictionary.
def read_input_data(filename): """Helper function to get training data""" logging.info('Opening file %s for reading input', filename) input_file = open(filename, 'r') data = [] labels = [] for line in input_file: tokens = line.split(',', 1) labels.append(tokens[0].strip()) ...
Helper function to get training data
def visit_snippet(self, node): """ HTML document generator visit handler """ lang = self.highlightlang linenos = node.rawsource.count('\n') >= self.highlightlinenothreshold - 1 fname = node['filename'] highlight_args = node.get('highlight_args', {}) if 'language' in node: # code-...
HTML document generator visit handler
def sub(x, y, context=None): """ Return ``x`` - ``y``. """ return _apply_function_in_current_context( BigFloat, mpfr.mpfr_sub, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
Return ``x`` - ``y``.
def check_geophysical_vars_fill_value(self, ds): ''' Check that geophysical variables contain fill values. :param netCDF4.Dataset ds: An open netCDF dataset ''' results = [] for geo_var in get_geophysical_variables(ds): results.append( self._h...
Check that geophysical variables contain fill values. :param netCDF4.Dataset ds: An open netCDF dataset
def make_request(self, session, url, **kwargs): """Make a HTTP POST request. :param url: The URL to post to. :param data: The data to post. :returns: The response to the request. :rtype: requests.Response """ log.debug('Making request: POST %s %s' % (url, kwargs)...
Make a HTTP POST request. :param url: The URL to post to. :param data: The data to post. :returns: The response to the request. :rtype: requests.Response
def _perp_eigendecompose(matrix: np.ndarray, rtol: float = 1e-5, atol: float = 1e-8, ) -> Tuple[np.array, List[np.ndarray]]: """An eigendecomposition that ensures eigenvectors are perpendicular. numpy.linalg.eig doesn't guarantee that e...
An eigendecomposition that ensures eigenvectors are perpendicular. numpy.linalg.eig doesn't guarantee that eigenvectors from the same eigenspace will be perpendicular. This method uses Gram-Schmidt to recover a perpendicular set. It further checks that all eigenvectors are perpendicular and raises an A...
def _diff_cache_cluster(current, desired): ''' If you need to enhance what modify_cache_cluster() considers when deciding what is to be (or can be) updated, add it to 'modifiable' below. It's a dict mapping the param as used in modify_cache_cluster() to that in describe_cache_clusters(). Any data fidd...
If you need to enhance what modify_cache_cluster() considers when deciding what is to be (or can be) updated, add it to 'modifiable' below. It's a dict mapping the param as used in modify_cache_cluster() to that in describe_cache_clusters(). Any data fiddlery that needs to be done to make the mappings mea...
def _make_order(field_path, direction): """Helper for :meth:`order_by`.""" return query_pb2.StructuredQuery.Order( field=query_pb2.StructuredQuery.FieldReference(field_path=field_path), direction=_enum_from_direction(direction), )
Helper for :meth:`order_by`.
def _create_state_data(self, context, resp_args, relay_state): """ Adds the frontend idp entity id to state See super class satosa.frontends.saml2.SAMLFrontend#save_state :type context: satosa.context.Context :type resp_args: dict[str, str | saml2.samlp.NameIDPolicy] :ty...
Adds the frontend idp entity id to state See super class satosa.frontends.saml2.SAMLFrontend#save_state :type context: satosa.context.Context :type resp_args: dict[str, str | saml2.samlp.NameIDPolicy] :type relay_state: str :rtype: dict[str, dict[str, str] | str]
def send_command_w_enter(self, *args, **kwargs): """ For 'show run-config' Cisco WLC adds a 'Press Enter to continue...' message Even though pagination is disabled show run-config also has excessive delays in the output which requires special handling. Arguments are the s...
For 'show run-config' Cisco WLC adds a 'Press Enter to continue...' message Even though pagination is disabled show run-config also has excessive delays in the output which requires special handling. Arguments are the same as send_command_timing() method
def interactive(f): """Decorator for making functions appear as interactively defined. This results in the function being linked to the user_ns as globals() instead of the module globals(). """ # build new FunctionType, so it can have the right globals # interactive functions never have closure...
Decorator for making functions appear as interactively defined. This results in the function being linked to the user_ns as globals() instead of the module globals().
def sanitizer(name, replacements=[(':','_'), ('/','_'), ('\\','_')]): """ String sanitizer to avoid problematic characters in filenames. """ for old,new in replacements: name = name.replace(old,new) return name
String sanitizer to avoid problematic characters in filenames.
def settings_module(self): """Gets SETTINGS_MODULE variable""" settings_module = parse_conf_data( os.environ.get( self.ENVVAR_FOR_DYNACONF, self.SETTINGS_FILE_FOR_DYNACONF ), tomlfy=True, ) if settings_module != getattr(self, "SETTINGS_...
Gets SETTINGS_MODULE variable
def cupy_wrapper(func): """A wrapper function that converts numpy ndarray arguments to cupy arrays, and convert any cupy arrays returned by the wrapped function into numpy ndarrays. """ @functools.wraps(func) def wrapped(*args, **kwargs): args = list(args) for n, a in enumerate(...
A wrapper function that converts numpy ndarray arguments to cupy arrays, and convert any cupy arrays returned by the wrapped function into numpy ndarrays.