code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def get_global_register_objects(self, do_sort=None, reverse=False, **kwargs): """Generate register objects (list) from register name list Usage: get_global_register_objects(name = ["Amp2Vbn", "GateHitOr", "DisableColumnCnfg"], address = [2, 3]) Receives: keyword lists of register names, add...
Generate register objects (list) from register name list Usage: get_global_register_objects(name = ["Amp2Vbn", "GateHitOr", "DisableColumnCnfg"], address = [2, 3]) Receives: keyword lists of register names, addresses,... for making cuts Returns: list of register objects
def _write_fuzzmanagerconf(self, path): """ Write fuzzmanager config file for selected build @type path: basestring @param path: A string representation of the fuzzmanager config path """ output = configparser.RawConfigParser() output.add_section('Main') ...
Write fuzzmanager config file for selected build @type path: basestring @param path: A string representation of the fuzzmanager config path
def add_node(self, node): """Add a node and connect it to the center.""" nodes = self.nodes() if len(nodes) > 1: first_node = min(nodes, key=attrgetter("creation_time")) first_node.connect(direction="both", whom=node)
Add a node and connect it to the center.
def region_interface_areas(regions, areas, voxel_size=1, strel=None): r""" Calculates the interfacial area between all pairs of adjecent regions Parameters ---------- regions : ND-array An image of the pore space partitioned into individual pore regions. Note that zeros in the image...
r""" Calculates the interfacial area between all pairs of adjecent regions Parameters ---------- regions : ND-array An image of the pore space partitioned into individual pore regions. Note that zeros in the image will not be considered for area calculation. areas : array_li...
def encode_max_apdu_length_accepted(arg): """Return the encoding of the highest encodable value less than the value of the arg.""" for i in range(5, -1, -1): if (arg >= _max_apdu_length_encoding[i]): return i raise ValueError("invalid max APDU length accepted: %r" % (arg,))
Return the encoding of the highest encodable value less than the value of the arg.
def score_leaves(self) -> Set[BaseEntity]: """Calculate the score for all leaves. :return: The set of leaf nodes that were scored """ leaves = set(self.iter_leaves()) if not leaves: log.warning('no leaves.') return set() for leaf in leaves: ...
Calculate the score for all leaves. :return: The set of leaf nodes that were scored
def join_mwp(tags: List[str]) -> List[str]: """ Join multi-word predicates to a single predicate ('V') token. """ ret = [] verb_flag = False for tag in tags: if "V" in tag: # Create a continuous 'V' BIO span prefix, _ = tag.split("-") if verb_flag:...
Join multi-word predicates to a single predicate ('V') token.
def get_accounts(cls, soco=None): """Get all accounts known to the Sonos system. Args: soco (`SoCo`, optional): a `SoCo` instance to query. If `None`, a random instance is used. Defaults to `None`. Returns: dict: A dict containing account instances. Each...
Get all accounts known to the Sonos system. Args: soco (`SoCo`, optional): a `SoCo` instance to query. If `None`, a random instance is used. Defaults to `None`. Returns: dict: A dict containing account instances. Each key is the account's serial numb...
def do_reload(bot, target, cmdargs, server_send=None): """The reloading magic. - First, reload handler.py. - Then make copies of all the handler data we want to keep. - Create a new handler and restore all the data. """ def send(msg): if server_send is not None: server_sen...
The reloading magic. - First, reload handler.py. - Then make copies of all the handler data we want to keep. - Create a new handler and restore all the data.
def _push_cm_exit(self, cm, cm_exit): """Helper to correctly register callbacks to __exit__ methods.""" _exit_wrapper = self._create_exit_wrapper(cm, cm_exit) self._push_exit_callback(_exit_wrapper, True)
Helper to correctly register callbacks to __exit__ methods.
def run_from_command_line(): """ Run Firenado's management commands from a command line """ for commands_conf in firenado.conf.management['commands']: logger.debug("Loading %s commands from %s." % ( commands_conf['name'], commands_conf['module'] )) exec('impor...
Run Firenado's management commands from a command line
def get_options(server): """Retrieve the available HTTP verbs""" try: response = requests.options( server, allow_redirects=False, verify=False, timeout=5) except (requests.exceptions.ConnectionError, requests.exceptions.MissingSchema): return "Server {} is not availab...
Retrieve the available HTTP verbs
def get_key(self, key_id): """ Returns a restclients.Key object for the given key ID. If the key ID isn't found, or if there is an error communicating with the KWS, a DataFailureException will be thrown. """ url = ENCRYPTION_KEY_URL.format(key_id) return self._ke...
Returns a restclients.Key object for the given key ID. If the key ID isn't found, or if there is an error communicating with the KWS, a DataFailureException will be thrown.
def regular(u): ''' Equation matrix generation for the regular (cubic) lattice. The order of constants is as follows: .. math:: C_{11}, C_{12}, C_{44} :param u: vector of deformations: [ :math:`u_{xx}, u_{yy}, u_{zz}, u_{yz}, u_{xz}, u_{xy}` ] :returns: Symmetry defined stress-...
Equation matrix generation for the regular (cubic) lattice. The order of constants is as follows: .. math:: C_{11}, C_{12}, C_{44} :param u: vector of deformations: [ :math:`u_{xx}, u_{yy}, u_{zz}, u_{yz}, u_{xz}, u_{xy}` ] :returns: Symmetry defined stress-strain equation matrix
def _update_mtime(self): """ Updates modif time """ try: self._mtime = os.path.getmtime(self.editor.file.path) except OSError: # file_path does not exists. self._mtime = 0 self._timer.stop() except (TypeError, AttributeError): #...
Updates modif time
def crop(self, lat, lon, var): """ Crop a subset of the dataset for each var Given doy, depth, lat and lon, it returns the smallest subset that still contains the requested coordinates inside it. It handels special cases like a region around greenwich and the ...
Crop a subset of the dataset for each var Given doy, depth, lat and lon, it returns the smallest subset that still contains the requested coordinates inside it. It handels special cases like a region around greenwich and the international date line. Accep...
def is_reseller(self): """is the user a reseller""" return self.role == self.roles.reseller.value and self.state == State.approved
is the user a reseller
def pydict2xmlstring(metadata_dict, **kwargs): """Create an XML string from a metadata dictionary.""" ordering = kwargs.get('ordering', UNTL_XML_ORDER) root_label = kwargs.get('root_label', 'metadata') root_namespace = kwargs.get('root_namespace', None) elements_namespace = kwargs.get('elements_name...
Create an XML string from a metadata dictionary.
def scroll_deck_x(self, decknum, scroll_x): """Move a deck left or right.""" if decknum >= len(self.decks): raise IndexError("I have no deck at {}".format(decknum)) if decknum >= len(self.deck_x_hint_offsets): self.deck_x_hint_offsets = list(self.deck_x_hint_offsets) + [0...
Move a deck left or right.
def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'): """ Similar to smart_bytes, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ if isinstance(s, memoryview): ...
Similar to smart_bytes, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects.
def extract_symbols(self, raw_data_directory: str, destination_directory: str): """ Extracts the symbols from the raw XML documents and matching images of the Audiveris OMR dataset into individual symbols :param raw_data_directory: The directory, that contains the xml-files and matching...
Extracts the symbols from the raw XML documents and matching images of the Audiveris OMR dataset into individual symbols :param raw_data_directory: The directory, that contains the xml-files and matching images :param destination_directory: The directory, in which the symbols should be generate...
def dependents_of_addresses(self, addresses): """Given an iterable of addresses, yield all of those addresses dependents.""" seen = OrderedSet(addresses) for address in addresses: seen.update(self._dependent_address_map[address]) seen.update(self._implicit_dependent_address_map[address]) ret...
Given an iterable of addresses, yield all of those addresses dependents.
def dump(self): '''Print the entire contents of this to debug log messages. This is really only intended for debugging. It could produce a lot of data. ''' with self.registry.lock(identifier=self.worker_id) as session: for work_spec_name in self.registry.pull(NICE_...
Print the entire contents of this to debug log messages. This is really only intended for debugging. It could produce a lot of data.
def remove_hairs_from_tags(dom): """ Use :func:`.remove_hairs` to some of the tags: - mods:title - mods:placeTerm """ transform_content( dom.match("mods:mods", "mods:titleInfo", "mods:title"), lambda x: remove_hairs(x.getContent()) ) transform_content( do...
Use :func:`.remove_hairs` to some of the tags: - mods:title - mods:placeTerm
def start_hq(output_dir, config, topic, is_master=True, **kwargs): """Start a HQ """ HightQuarter = get_hq_class(config.get('hq_class')) hq = HightQuarter(output_dir, config, topic, **kwargs) hq.setup() if is_master: hq.wait_turrets(config.get("min_turrets", 1)) hq.run() hq.tear_...
Start a HQ
def __deserialize_model(self, data, klass): """ Deserializes list or dict to model. :param data: dict, list. :param klass: class literal. :return: model object. """ instance = klass() if not instance.swagger_types: return data for at...
Deserializes list or dict to model. :param data: dict, list. :param klass: class literal. :return: model object.
def phase_to_color_wheel(complex_number): """Map a phase of a complexnumber to a color in (r,g,b). complex_number is phase is first mapped to angle in the range [0, 2pi] and then to a color wheel with blue at zero phase. """ angles = np.angle(complex_number) angle_round = int(((angles + 2 * np....
Map a phase of a complexnumber to a color in (r,g,b). complex_number is phase is first mapped to angle in the range [0, 2pi] and then to a color wheel with blue at zero phase.
def _parse_coroutine(self): """ Parser state machine. Every 'yield' expression returns the next byte. """ while True: d = yield if d == int2byte(0): pass # NOP # Go to state escaped. elif d == IAC: ...
Parser state machine. Every 'yield' expression returns the next byte.
def apply_tasks_to_issue(self, tasks, issue_number, issue_body): """Applies task numbers to an issue.""" issue_body = issue_body task_numbers = format_task_numbers_with_links(tasks) if task_numbers: new_body = ASANA_SECTION_RE.sub('', issue_body) new_body = new_bo...
Applies task numbers to an issue.
def overloaded_build(type_, add_name=None): """Factory for constant transformers that apply to a given build instruction. Parameters ---------- type_ : type The object type to overload the construction of. This must be one of "buildable" types, or types with a "BUILD_*" instruction....
Factory for constant transformers that apply to a given build instruction. Parameters ---------- type_ : type The object type to overload the construction of. This must be one of "buildable" types, or types with a "BUILD_*" instruction. add_name : str, optional The suffix of...
def add_apt_key(filename=None, url=None, keyid=None, keyserver='subkeys.pgp.net', update=False): """ Trust packages signed with this public key. Example:: import burlap # Varnish signing key from URL and verify fingerprint) burlap.deb.add_apt_key(keyid='C4DEFFEB', url='http://repo...
Trust packages signed with this public key. Example:: import burlap # Varnish signing key from URL and verify fingerprint) burlap.deb.add_apt_key(keyid='C4DEFFEB', url='http://repo.varnish-cache.org/debian/GPG-key.txt') # Nginx signing key from default key server (subkeys.pgp.net...
def get_flashed_messages( with_categories: bool=False, category_filter: List[str]=[], ) -> Union[List[str], List[Tuple[str, str]]]: """Retrieve the flashed messages stored in the session. This is mostly useful in templates where it is exposed as a global function, for example .. code-b...
Retrieve the flashed messages stored in the session. This is mostly useful in templates where it is exposed as a global function, for example .. code-block:: html+jinja <ul> {% for message in get_flashed_messages() %} <li>{{ message }}</li> {% endfor %} </ul> ...
def authenticate(self, request): """Authenticate the user, requiring a logged-in account and CSRF. This is exactly the same as the `SessionAuthentication` implementation, with the `user.is_active` check removed. Args: request (HttpRequest) Returns: Tupl...
Authenticate the user, requiring a logged-in account and CSRF. This is exactly the same as the `SessionAuthentication` implementation, with the `user.is_active` check removed. Args: request (HttpRequest) Returns: Tuple of `(user, token)` Raises: ...
def _compute_quantile(data, dims, cutoffs): """Helper method for stretch_linear. Dask delayed functions need to be non-internal functions (created inside a function) to be serializable on a multi-process scheduler. Quantile requires the data to be loaded since it not supported on ...
Helper method for stretch_linear. Dask delayed functions need to be non-internal functions (created inside a function) to be serializable on a multi-process scheduler. Quantile requires the data to be loaded since it not supported on dask arrays yet.
def stop_and_persist(self, symbol=' ', text=None): """Stops the spinner and persists the final frame to be shown. Parameters ---------- symbol : str, optional Symbol to be shown in final frame text: str, optional Text to be shown in final frame Re...
Stops the spinner and persists the final frame to be shown. Parameters ---------- symbol : str, optional Symbol to be shown in final frame text: str, optional Text to be shown in final frame Returns ------- self
def evaluate(self, system_id=1, rouge_args=None): """ Run ROUGE to evaluate the system summaries in system_dir against the model summaries in model_dir. The summaries are assumed to be in the one-sentence-per-line HTML format ROUGE understands. system_id: Optional system ID...
Run ROUGE to evaluate the system summaries in system_dir against the model summaries in model_dir. The summaries are assumed to be in the one-sentence-per-line HTML format ROUGE understands. system_id: Optional system ID which will be printed in ROUGE's output. ...
def join(self, other, how='left', lsuffix='', rsuffix=''): """ Join items with other Panel either on major and minor axes column. Parameters ---------- other : Panel or list of Panels Index should be similar to one of the columns in this one how : {'left', 'r...
Join items with other Panel either on major and minor axes column. Parameters ---------- other : Panel or list of Panels Index should be similar to one of the columns in this one how : {'left', 'right', 'outer', 'inner'} How to handle indexes of the two objects. ...
def parse(cls, fptr, offset, length): """Parse JPEG 2000 color specification box. Parameters ---------- fptr : file Open file object. offset : int Start position of box in bytes. length : int Length of the box in bytes. Return...
Parse JPEG 2000 color specification box. Parameters ---------- fptr : file Open file object. offset : int Start position of box in bytes. length : int Length of the box in bytes. Returns ------- ColourSpecificationBox ...
def read_folder(folder, ext='*', uppercase=False, replace_dot='.', parent=''): """ This will read all of the files in the folder with the extension equal to ext :param folder: str of the folder name :param ext: str of the extension :param uppercase: bool if True will uppercase all the fi...
This will read all of the files in the folder with the extension equal to ext :param folder: str of the folder name :param ext: str of the extension :param uppercase: bool if True will uppercase all the file names :param replace_dot: str will replace "." in the filename :param parent: str of...
def stderr_output(cmd): """Wraps the execution of check_output in a way that ignores stderr when not in debug mode""" handle, gpg_stderr = stderr_handle() try: output = subprocess.check_output(cmd, stderr=gpg_stderr) # nosec if handle: handle.close() return str(pol...
Wraps the execution of check_output in a way that ignores stderr when not in debug mode
def _apply_worksheet_template_reference_analyses(self, wst, type='all'): """ Add reference analyses to worksheet according to the worksheet template layout passed in. Does not overwrite slots that are already filled. :param wst: worksheet template used as the layout """ i...
Add reference analyses to worksheet according to the worksheet template layout passed in. Does not overwrite slots that are already filled. :param wst: worksheet template used as the layout
def _adb(self, commands): """Call the adb executable from the SDK, passing the given commands as arguments.""" ctx = self.ctx ctx.prepare_build_environment(user_sdk_dir=self.sdk_dir, user_ndk_dir=self.ndk_dir, us...
Call the adb executable from the SDK, passing the given commands as arguments.
def hrmint(xvals, yvals, x): """ Evaluate a Hermite interpolating polynomial at a specified abscissa value. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/hrmint_c.html :param xvals: Abscissa values. :type xvals: Array of floats :param yvals: Ordinate and derivative value...
Evaluate a Hermite interpolating polynomial at a specified abscissa value. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/hrmint_c.html :param xvals: Abscissa values. :type xvals: Array of floats :param yvals: Ordinate and derivative values. :type yvals: Array of floats :...
def min_time(self): """ Get the `~astropy.time.Time` time of the tmoc first observation Returns ------- min_time : `astropy.time.Time` time of the first observation """ min_time = Time(self._interval_set.min / TimeMOC.DAY_MICRO_SEC, format='jd', sca...
Get the `~astropy.time.Time` time of the tmoc first observation Returns ------- min_time : `astropy.time.Time` time of the first observation
def master_primary_name(self) -> Optional[str]: """ Return the name of the primary node of the master instance """ master_primary_name = self.master_replica.primaryName if master_primary_name: return self.master_replica.getNodeName(master_primary_name) return...
Return the name of the primary node of the master instance
def get_callproc_signature(self, name, param_types): """Returns a procedure's signature from the name and list of types. :name: the name of the procedure :params: can be either strings, or 2-tuples. 2-tuples must be of the form (name, db_type). :return: the procedure's signature """ if isinstan...
Returns a procedure's signature from the name and list of types. :name: the name of the procedure :params: can be either strings, or 2-tuples. 2-tuples must be of the form (name, db_type). :return: the procedure's signature
def main(argv=None): """to install and/or test from the command line use:: python cma.py [options | func dim sig0 [optkey optval][optkey optval]...] with options being ``--test`` (or ``-t``) to run the doctest, ``--test -v`` to get (much) verbosity. ``install`` to install cma.py (uses setup ...
to install and/or test from the command line use:: python cma.py [options | func dim sig0 [optkey optval][optkey optval]...] with options being ``--test`` (or ``-t``) to run the doctest, ``--test -v`` to get (much) verbosity. ``install`` to install cma.py (uses setup from distutils.core). `...
def mv(hdfs_src, hdfs_dst): """Move a file on hdfs :param hdfs_src: Source (str) :param hdfs_dst: Destination (str) :raises: IOError: If unsuccessful """ cmd = "hadoop fs -mv %s %s" % (hdfs_src, hdfs_dst) rcode, stdout, stderr = _checked_hadoop_fs_command(cmd)
Move a file on hdfs :param hdfs_src: Source (str) :param hdfs_dst: Destination (str) :raises: IOError: If unsuccessful
def _generate_initial_score(self): """Runs the evaluation function for the initial pose.""" self.current_energy = self.eval_fn(self.polypeptide, *self.eval_args) self.best_energy = copy.deepcopy(self.current_energy) self.best_model = copy.deepcopy(self.polypeptide) return
Runs the evaluation function for the initial pose.
def filename(self): """Filename of the attachment, without the full 'attachment' path.""" if self.value and 'value' in self._json_data and self._json_data['value']: return self._json_data['value'].split('/')[-1] return None
Filename of the attachment, without the full 'attachment' path.
def _check_auth(self, must_admin, redir_login=True): """ check if a user is autheticated and, optionnaly an administrator if user not authenticated -> redirect to login page (with escaped URL of the originaly requested page (redirection after login) if user authenticated, not admin a...
check if a user is autheticated and, optionnaly an administrator if user not authenticated -> redirect to login page (with escaped URL of the originaly requested page (redirection after login) if user authenticated, not admin and must_admin enabled -> 403 error @boolean must_admin: f...
def _get_simple(self, name): """ Query the stack for a non-dotted name. """ for item in reversed(self._stack): result = _get_value(item, name) if result is not _NOT_FOUND: return result raise KeyNotFoundError(name, "part missing")
Query the stack for a non-dotted name.
def get_next_non_summer_term(term): """ Return the Term object for the quarter after as the given term (skip the summer quarter) """ next_term = get_term_after(term) if next_term.is_summer_quarter(): return get_next_autumn_term(next_term) return next_term
Return the Term object for the quarter after as the given term (skip the summer quarter)
def list_(): ''' Get a list of automatically running programs CLI Example: .. code-block:: bash salt '*' autoruns.list ''' autoruns = {} # Find autoruns in registry keys = ['HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Run', 'HKLM\\Software\\Microsoft\\Windows\...
Get a list of automatically running programs CLI Example: .. code-block:: bash salt '*' autoruns.list
def accuracy(self): """ Calculates the accuracy of the tree by comparing the model predictions to the dataset (TP + TN) / (TP + TN + FP + FN) == (T / (T + F)) """ sub_observed = np.array([self.observed.metadata[i] for i in self.observed.arr]) return float((self.mo...
Calculates the accuracy of the tree by comparing the model predictions to the dataset (TP + TN) / (TP + TN + FP + FN) == (T / (T + F))
def _invalid_frame(fobj): """Select valid stack frame to process.""" fin = fobj.f_code.co_filename invalid_module = any([fin.endswith(item) for item in _INVALID_MODULES_LIST]) return invalid_module or (not os.path.isfile(fin))
Select valid stack frame to process.
def get_gravatar(email, size=80, default='identicon'): """ Get's a Gravatar for a email address. :param size: The size in pixels of one side of the Gravatar's square image. Optional, if not supplied will default to ``80``. :param default: Defines what should be displayed if no imag...
Get's a Gravatar for a email address. :param size: The size in pixels of one side of the Gravatar's square image. Optional, if not supplied will default to ``80``. :param default: Defines what should be displayed if no image is found for this user. Optional argument which defau...
def get_main_version(version): "Returns main version (X.Y[.Z]) from VERSION." parts = 2 if version[2] == 0 else 3 return '.'.join(str(x) for x in version[:parts])
Returns main version (X.Y[.Z]) from VERSION.
def sequence_id_factory(value, datatype_cls, validation_level=None): """ Creates a :class:`SI <hl7apy.base_datatypes.SI>` object The value in input can be a string representing an integer number or an ``int``. (i.e. a string valid for ``int()`` ). If it's not, a :exc:`ValueError` is raised Als...
Creates a :class:`SI <hl7apy.base_datatypes.SI>` object The value in input can be a string representing an integer number or an ``int``. (i.e. a string valid for ``int()`` ). If it's not, a :exc:`ValueError` is raised Also an empty string or ``None`` are allowed :type value: ``str`` or ``None`` ...
def add_report_data(list_all=[], module_name="TestModule", **kwargs): ''' add report data to a list @param list_all: a list which save the report data @param module_name: test set name or test module name @param kwargs: such as case_name: testcase name ...
add report data to a list @param list_all: a list which save the report data @param module_name: test set name or test module name @param kwargs: such as case_name: testcase name status: test result, Pass or Fail resp_teste...
def set_values(self, choice_ids): """assume choice_ids is a list of choiceIds, like ["57978959cdfc5c42eefb36d1", "57978959cdfc5c42eefb36d0", "57978959cdfc5c42eefb36cf", "57978959cdfc5c42eefb36ce"] """ # if not self.my_osid_object._my_map['choices']: # raise IllegalSta...
assume choice_ids is a list of choiceIds, like ["57978959cdfc5c42eefb36d1", "57978959cdfc5c42eefb36d0", "57978959cdfc5c42eefb36cf", "57978959cdfc5c42eefb36ce"]
def kill_all(self): """kill all slaves and reap the monitor """ for pid in self.children: try: os.kill(pid, signal.SIGTRAP) except OSError: continue self.join()
kill all slaves and reap the monitor
def clear_data(self): """Removes the content data. raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ if (self.get_data_metadata().is_read_only() or ...
Removes the content data. raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.*
def iter_components(self): """Iterate over all defined components yielding IOTile objects.""" names = self.list_components() for name in names: yield self.get_component(name)
Iterate over all defined components yielding IOTile objects.
def channels_rename(self, room_id, name, **kwargs): """Changes the name of the channel.""" return self.__call_api_post('channels.rename', roomId=room_id, name=name, kwargs=kwargs)
Changes the name of the channel.
def place(vertices_resources, nets, machine, constraints, random=default_random): """A random placer. This algorithm performs uniform-random placement of vertices (completely ignoring connectivty) and thus in the general case is likely to produce very poor quality placements. It exists primar...
A random placer. This algorithm performs uniform-random placement of vertices (completely ignoring connectivty) and thus in the general case is likely to produce very poor quality placements. It exists primarily as a baseline comparison for placement quality and is probably of little value to most user...
def _sra_download_worker(*args): """A worker to download SRA files. To be used with multiprocessing. """ gsm = args[0][0] email = args[0][1] dirpath = args[0][2] kwargs = args[0][3] return (gsm.get_accession(), gsm.download_SRA(email, dirpath, **kwargs))
A worker to download SRA files. To be used with multiprocessing.
def load_config(): """ Load settings from default config and optionally overwrite with config file and commandline parameters (in that order). """ # We start with the default config config = flatten(default_config.DEFAULT_CONFIG) # Read commandline arguments cli_config = flatten(par...
Load settings from default config and optionally overwrite with config file and commandline parameters (in that order).
def webhooks(self): """ Access the webhooks :returns: twilio.rest.messaging.v1.session.webhook.WebhookList :rtype: twilio.rest.messaging.v1.session.webhook.WebhookList """ if self._webhooks is None: self._webhooks = WebhookList(self._version, session_sid=self...
Access the webhooks :returns: twilio.rest.messaging.v1.session.webhook.WebhookList :rtype: twilio.rest.messaging.v1.session.webhook.WebhookList
def getrdfdata(): """Downloads Project Gutenberg RDF catalog. Yields: xml.etree.ElementTree.Element: An etext meta-data definition. """ if not os.path.exists(RDFFILES): _, _ = urllib.urlretrieve(RDFURL, RDFFILES) with tarfile.open(RDFFILES) as archive: for tarinfo in archive: yield ElementTree.parse(archi...
Downloads Project Gutenberg RDF catalog. Yields: xml.etree.ElementTree.Element: An etext meta-data definition.
def get_instance(self, contract_name: str) -> None: """ Fetches a contract instance belonging to deployment after validating contract name. """ self._validate_name_and_references(contract_name) # Use a deployment's "contract_type" to lookup contract factory # in c...
Fetches a contract instance belonging to deployment after validating contract name.
def load(self, prof_name): """ Load the profile with the given name. :param str prof_name: Profile name. :rtype: ProfileStub :return: An stub to loaded profile. """ prof_dir = self.__profile_dir(prof_name) prof_ini_path = self.__profile_ini_path(prof_dir) if not os.path.exists(p...
Load the profile with the given name. :param str prof_name: Profile name. :rtype: ProfileStub :return: An stub to loaded profile.
def replace(self, src): "Given some source html substitute and annotated as applicable" for html in self.substitutions.keys(): if src == html: annotation = self.annotation % self.substitutions[src][1] return annotation + self.substitutions[src][0] retu...
Given some source html substitute and annotated as applicable
def get_user(self, user_id=None, username=None, email=None): """ Returns the user specified by either ID, username or email. Since more than user can have the same email address, searching by that term will return a list of 1 or more User objects. Searching by username or ID wil...
Returns the user specified by either ID, username or email. Since more than user can have the same email address, searching by that term will return a list of 1 or more User objects. Searching by username or ID will return a single User. If a user_id that doesn't belong to the current ...
def assertFileExists(self, filename, msg=None): '''Fail if ``filename`` does not exist as determined by ``os.path.isfile(filename)``. Parameters ---------- filename : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittes...
Fail if ``filename`` does not exist as determined by ``os.path.isfile(filename)``. Parameters ---------- filename : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used.
def _load_yaml_config(path=None): """Open and return the yaml contents.""" furious_yaml_path = path or find_furious_yaml() if furious_yaml_path is None: logging.debug("furious.yaml not found.") return None with open(furious_yaml_path) as yaml_file: return yaml_file.read()
Open and return the yaml contents.
def load_obo_file(self, obo_file, optional_attrs, load_obsolete, prt): """Read obo file. Store results.""" reader = OBOReader(obo_file, optional_attrs) # Save alt_ids and their corresponding main GO ID. Add to GODag after populating GO Terms alt2rec = {} for rec in reader: ...
Read obo file. Store results.
def _load_zp_mappings(self, file): """ Given a file that defines the mapping between ZFIN-specific EQ definitions and the automatically derived ZP ids, create a mapping here. This may be deprecated in the future :return: """ zp_map = {} LOG.info("...
Given a file that defines the mapping between ZFIN-specific EQ definitions and the automatically derived ZP ids, create a mapping here. This may be deprecated in the future :return:
def _step(self, theme, direction): """ Traverse the list in the given direction and return the next theme """ if not self.themes: self.reload() # Try to find the starting index key = (theme.source, theme.name) for i, val in enumerate(self.themes): ...
Traverse the list in the given direction and return the next theme
def p_try_statement_1(self, p): """try_statement : TRY block catch""" p[0] = ast.Try(statements=p[2], catch=p[3])
try_statement : TRY block catch
def refresh_balance(self): """ Recalculate self.balance and self.depth based on child node values. """ left_depth = self.left_node.depth if self.left_node else 0 right_depth = self.right_node.depth if self.right_node else 0 self.depth = 1 + max(left_depth, right_depth) ...
Recalculate self.balance and self.depth based on child node values.
def activate_right(self, token): """Make a copy of the received token and call `_activate_right`.""" watchers.MATCHER.debug( "Node <%s> activated right with token %r", self, token) return self._activate_right(token.copy())
Make a copy of the received token and call `_activate_right`.
def _validate_plan(plan): """Validate if given plan is valid based on kafka-cluster-assignment protocols. Validate following parameters: - Correct format of plan - Partition-list should be unique - Every partition of a topic should have same replication-factor - Replicas of a partition should h...
Validate if given plan is valid based on kafka-cluster-assignment protocols. Validate following parameters: - Correct format of plan - Partition-list should be unique - Every partition of a topic should have same replication-factor - Replicas of a partition should have unique broker-set
def _config_from_url(self): """ Manage block configuration from requests.args (url params) """ config = { "name": self._blk.name, "options": {} } for key, value in six.iteritems(request.args): if isinstance(value, list) and len(value) == 1: ...
Manage block configuration from requests.args (url params)
def set_attributes(self, doc, fields, parent_type=None): """ Fields are specified as a list so that order is preserved for display purposes only. (Might be used for certain serialization formats...) :param str doc: Description of type. :param list(Field) fields: Ordered list of ...
Fields are specified as a list so that order is preserved for display purposes only. (Might be used for certain serialization formats...) :param str doc: Description of type. :param list(Field) fields: Ordered list of fields for type. :param Optional[Composite] parent_type: The type thi...
def get_package_data(filename, mode='rb'): '''Return the contents of a real file or a zip file.''' if os.path.exists(filename): with open(filename, mode=mode) as in_file: return in_file.read() else: parts = os.path.normpath(filename).split(os.sep) for part, index in zip(...
Return the contents of a real file or a zip file.
def render( self, tag, single, between, kwargs ): """Append the actual tags to content.""" out = "<%s" % tag for key, value in list( kwargs.items( ) ): if value is not None: # when value is None that means stuff like <... checked> key = key.strip('_') ...
Append the actual tags to content.
def _get_hd(self, hdr_info): """Open the file, read and get the basic file header info and set the mda dictionary """ hdr_map, variable_length_headers, text_headers = hdr_info with open(self.filename) as fp: total_header_length = 16 while fp.tell() < ...
Open the file, read and get the basic file header info and set the mda dictionary
def warp_vrt(directory, delete_extra=False, use_band_map=False, overwrite=False, remove_bqa=True, return_profile=False): """ Read in image geometry, resample subsequent images to same grid. The purpose of this function is to snap many Landsat images to one geometry. Use Landsat578 to download ...
Read in image geometry, resample subsequent images to same grid. The purpose of this function is to snap many Landsat images to one geometry. Use Landsat578 to download and unzip them, then run them through this to get identical geometries for analysis. Files :param use_band_map: :param delete_extr...
def to_fp32(learn:Learner): "Put `learn` back to FP32 precision mode." learn.data.remove_tfm(batch_to_half) for cb in learn.callbacks: if isinstance(cb, MixedPrecision): learn.callbacks.remove(cb) learn.model = learn.model.float() return learn
Put `learn` back to FP32 precision mode.
def _setTaskParsObj(self, theTask): """ Overridden version for ConfigObj. theTask can be either a .cfg file name or a ConfigObjPars object. """ # Create the ConfigObjPars obj self._taskParsObj = cfgpars.getObjectFromTaskArg(theTask, self._strict, F...
Overridden version for ConfigObj. theTask can be either a .cfg file name or a ConfigObjPars object.
def main_help_text(self, commands_only=False): """ Returns the script's main help text, as a string. """ if commands_only: usage = sorted(get_commands().keys()) else: usage = [ "", "Type '%s help <subcommand>' for help on a ...
Returns the script's main help text, as a string.
def sendfrom(self, user_id, dest_address, amount, minconf=1): """ Send coins from user's account. Args: user_id (str): this user's unique identifier dest_address (str): address which is to receive coins amount (str or Decimal): amount to send (eight decimal points)...
Send coins from user's account. Args: user_id (str): this user's unique identifier dest_address (str): address which is to receive coins amount (str or Decimal): amount to send (eight decimal points) minconf (int): ensure the account has a valid balance using this ...
def _has_name(soup_obj): """checks if soup_obj is really a soup object or just a string If it has a name it is a soup object""" try: name = soup_obj.name if name == None: return False return True except AttributeError: return False
checks if soup_obj is really a soup object or just a string If it has a name it is a soup object
def do_init_fields(self, flist): """ Initialize each fields of the fields_desc dict """ for f in flist: self.default_fields[f.name] = copy.deepcopy(f.default) self.fieldtype[f.name] = f if f.holds_packets: self.packetfields.append(f)
Initialize each fields of the fields_desc dict
def get_rank(): """ Gets distributed rank or returns zero if distributed is not initialized. """ if torch.distributed.is_available() and torch.distributed.is_initialized(): rank = torch.distributed.get_rank() else: rank = 0 return rank
Gets distributed rank or returns zero if distributed is not initialized.
def make_child_of(self, chunk): """ Link one YAML chunk to another. Used when inserting a chunk of YAML into another chunk. """ if self.is_mapping(): for key, value in self.contents.items(): self.key(key, key).pointer.make_child_of(chunk.pointer) ...
Link one YAML chunk to another. Used when inserting a chunk of YAML into another chunk.
def _FormatSubjectOrProcessToken(self, token_data): """Formats a subject or process token as a dictionary of values. Args: token_data (bsm_token_data_subject32|bsm_token_data_subject64): AUT_SUBJECT32, AUT_PROCESS32, AUT_SUBJECT64 or AUT_PROCESS64 token data. Returns: dict[...
Formats a subject or process token as a dictionary of values. Args: token_data (bsm_token_data_subject32|bsm_token_data_subject64): AUT_SUBJECT32, AUT_PROCESS32, AUT_SUBJECT64 or AUT_PROCESS64 token data. Returns: dict[str, str]: token values.
def get_agent_queue(self, queue_id, project=None, action_filter=None): """GetAgentQueue. [Preview API] Get information about an agent queue. :param int queue_id: The agent queue to get information about :param str project: Project ID or project name :param str action_filter: Filt...
GetAgentQueue. [Preview API] Get information about an agent queue. :param int queue_id: The agent queue to get information about :param str project: Project ID or project name :param str action_filter: Filter by whether the calling user has use or manage permissions :rtype: :clas...
def sort_index( self, axis=0, level=None, ascending=True, inplace=False, kind="quicksort", na_position="last", sort_remaining=True, by=None, ): """Sort a DataFrame by one of the indices (columns or index). Args: ...
Sort a DataFrame by one of the indices (columns or index). Args: axis: The axis to sort over. level: The MultiIndex level to sort over. ascending: Ascending or descending inplace: Whether or not to update this DataFrame inplace. kind: How to pe...