positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def get_queryset(self, request): ''' Restrict the listed courses for the current user.''' qs = super(CourseAdmin, self).get_queryset(request) if request.user.is_superuser: return qs else: return qs.filter(Q(tutors__pk=request.user.pk) | Q(owner=request.user)).distinct()
Restrict the listed courses for the current user.
def get(self, key: str, default: Any = DEFAULT): """ Performs the functionality associated with dict.get(key) but also checks for returned dicts and returns a Params object in their place with an updated history. """ if default is self.DEFAULT: try: value = self.params.get(key) except KeyError: raise ConfigurationError("key \"{}\" is required at location \"{}\"".format(key, self.history)) else: value = self.params.get(key, default) return self._check_is_dict(key, value)
Performs the functionality associated with dict.get(key) but also checks for returned dicts and returns a Params object in their place with an updated history.
def run(self, funcs): """Run a set of functions in parallel, returning their results. Make sure any function you pass exits with a reasonable timeout. If it doesn't return within the timeout or the result is ignored due an exception in a separate thread it will continue to stick around until it finishes, including blocking process exit. Args: funcs: An iterable of functions or iterable of args to functools.partial. Returns: A list of return values with the values matching the order in funcs. Raises: Propagates the first exception encountered in one of the functions. """ funcs = [f if callable(f) else functools.partial(*f) for f in funcs] if len(funcs) == 1: # Ignore threads if it's not needed. return [funcs[0]()] if len(funcs) > self._workers: # Lazy init and grow as needed. self.shutdown() self._workers = len(funcs) self._executor = futures.ThreadPoolExecutor(self._workers) futs = [self._executor.submit(f) for f in funcs] done, not_done = futures.wait(futs, self._timeout, futures.FIRST_EXCEPTION) # Make sure to propagate any exceptions. for f in done: if not f.cancelled() and f.exception() is not None: if not_done: # If there are some calls that haven't finished, cancel and recreate # the thread pool. Otherwise we may have a thread running forever # blocking parallel calls. for nd in not_done: nd.cancel() self.shutdown(False) # Don't wait, they may be deadlocked. raise f.exception() # Either done or timed out, so don't wait again. return [f.result(timeout=0) for f in futs]
Run a set of functions in parallel, returning their results. Make sure any function you pass exits with a reasonable timeout. If it doesn't return within the timeout or the result is ignored due an exception in a separate thread it will continue to stick around until it finishes, including blocking process exit. Args: funcs: An iterable of functions or iterable of args to functools.partial. Returns: A list of return values with the values matching the order in funcs. Raises: Propagates the first exception encountered in one of the functions.
def _credentials_found_in_envars(): """Check for credentials in envars. Returns: bool: ``True`` if at least one is found, otherwise ``False``. """ return any([os.getenv('PAN_ACCESS_TOKEN'), os.getenv('PAN_CLIENT_ID'), os.getenv('PAN_CLIENT_SECRET'), os.getenv('PAN_REFRESH_TOKEN')])
Check for credentials in envars. Returns: bool: ``True`` if at least one is found, otherwise ``False``.
def check_username_uniqueness(self, username): """ Checks if the given username is available for registration. Results are returned in the on_username_uniqueness_received() callback :param username: The username to check for its existence """ log.info("[+] Checking for Uniqueness of username '{}'".format(username)) return self._send_xmpp_element(sign_up.CheckUsernameUniquenessRequest(username))
Checks if the given username is available for registration. Results are returned in the on_username_uniqueness_received() callback :param username: The username to check for its existence
def get_form_kwargs(self): """ Returns the keyword arguments to provide tp the associated form. """ kwargs = super(ModelFormMixin, self).get_form_kwargs() kwargs['poll'] = self.object return kwargs
Returns the keyword arguments to provide tp the associated form.
def importobject(module_name, object_name): """ Imports the object with the given name from the inputted module. :param module_name | <str> object_name | <str> :usage |>>> import projex |>>> modname = 'projex.envmanager' |>>> attr = 'EnvManager' |>>> EnvManager = projex.importobject(modname, attr) :return <object> || None """ if module_name not in sys.modules: try: __import__(module_name) except ImportError: logger.debug(traceback.print_exc()) logger.error('Could not import module: %s', module_name) return None module = sys.modules.get(module_name) if not module: logger.warning('No module %s found.' % module_name) return None if not hasattr(module, object_name): logger.warning('No object %s in %s.' % (object_name, module_name)) return None return getattr(module, object_name)
Imports the object with the given name from the inputted module. :param module_name | <str> object_name | <str> :usage |>>> import projex |>>> modname = 'projex.envmanager' |>>> attr = 'EnvManager' |>>> EnvManager = projex.importobject(modname, attr) :return <object> || None
def coordinate_system(self, coordsys): """Sets instrument coordinate system. Accepts an int or string.""" if coordsys.upper() == "ENU": ncs = 0 elif coordsys.upper() == "XYZ": ncs = 1 elif coordsys.upper() == "BEAM": ncs = 2 elif coordsys in [0, 1, 2]: ncs = coordsys else: raise ValueError("Invalid coordinate system selection") self.pdx.CoordinateSystem = ncs
Sets instrument coordinate system. Accepts an int or string.
def lpc(blk, order=None): """ Find the Linear Predictive Coding (LPC) coefficients as a ZFilter object, the analysis whitening filter. This implementation uses the autocorrelation method, using numpy.linalg.pinv as a linear system solver. Parameters ---------- blk : An iterable with well-defined length. Don't use this function with Stream objects! order : The order of the resulting ZFilter object. Defaults to ``len(blk) - 1``. Returns ------- A FIR filter, as a ZFilter object. The mean squared error over the given block is in its "error" attribute. Hint ---- See ``lpc.kautocor`` example, which should apply equally for this strategy. See Also -------- lpc.autocor: LPC coefficients by using one of the autocorrelation method strategies. lpc.kautocor: LPC coefficients obtained with Levinson-Durbin algorithm. """ from numpy import matrix from numpy.linalg import pinv acdata = acorr(blk, order) coeffs = pinv(toeplitz(acdata[:-1])) * -matrix(acdata[1:]).T coeffs = coeffs.T.tolist()[0] filt = 1 + sum(ai * z ** -i for i, ai in enumerate(coeffs, 1)) filt.error = acdata[0] + sum(a * c for a, c in xzip(acdata[1:], coeffs)) return filt
Find the Linear Predictive Coding (LPC) coefficients as a ZFilter object, the analysis whitening filter. This implementation uses the autocorrelation method, using numpy.linalg.pinv as a linear system solver. Parameters ---------- blk : An iterable with well-defined length. Don't use this function with Stream objects! order : The order of the resulting ZFilter object. Defaults to ``len(blk) - 1``. Returns ------- A FIR filter, as a ZFilter object. The mean squared error over the given block is in its "error" attribute. Hint ---- See ``lpc.kautocor`` example, which should apply equally for this strategy. See Also -------- lpc.autocor: LPC coefficients by using one of the autocorrelation method strategies. lpc.kautocor: LPC coefficients obtained with Levinson-Durbin algorithm.
def check_ratelimit_budget(self, seconds_waited): """ If we have a ratelimit_budget, ensure it is not exceeded. """ if self.ratelimit_budget is not None: self.ratelimit_budget -= seconds_waited if self.ratelimit_budget < 1: raise RatelimitBudgetExceeded("Rate limit budget exceeded!")
If we have a ratelimit_budget, ensure it is not exceeded.
def generate_data_key(key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Generate a secure data key. CLI example:: salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = {} try: data_key = conn.generate_data_key( key_id, encryption_context=encryption_context, number_of_bytes=number_of_bytes, key_spec=key_spec, grant_tokens=grant_tokens ) r['data_key'] = data_key except boto.exception.BotoServerError as e: r['error'] = __utils__['boto.get_error'](e) return r
Generate a secure data key. CLI example:: salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128
def verbose(self, msg, *args, **kw): """Log a message with level :data:`VERBOSE`. The arguments are interpreted as for :func:`logging.debug()`.""" if self.isEnabledFor(VERBOSE): self._log(VERBOSE, msg, args, **kw)
Log a message with level :data:`VERBOSE`. The arguments are interpreted as for :func:`logging.debug()`.
def respond_via_request(self, task): """ Handle response after 55 second. :param task: :return: """ warn(f"Detected slow response into webhook. " f"(Greater than {RESPONSE_TIMEOUT} seconds)\n" f"Recommended to use 'async_task' decorator from Dispatcher for handler with long timeouts.", TimeoutWarning) dispatcher = self.get_dispatcher() loop = dispatcher.loop try: results = task.result() except Exception as e: loop.create_task( dispatcher.errors_handlers.notify(dispatcher, types.Update.get_current(), e)) else: response = self.get_response(results) if response is not None: asyncio.ensure_future(response.execute_response(dispatcher.bot), loop=loop)
Handle response after 55 second. :param task: :return:
def wait_for(self, predicate, timeout=None): """Like :meth:`wait` but additionally for *predicate* to be true. The *predicate* argument must be a callable that takes no arguments. Its result is interpreted as a boolean value. """ if not is_locked(self._lock): raise RuntimeError('lock is not locked') hub = get_hub() try: with switch_back(timeout, lock=thread_lock(self._lock)) as switcher: handle = add_callback(self, switcher, predicate) # See the comment in Lock.acquire() why it is OK to release the # lock here before calling hub.switch(). # Also if this is a reentrant lock make sure it is fully released. state = release_save(self._lock) hub.switch() except BaseException as e: with self._lock: remove_callback(self, handle) if e is switcher.timeout: return False raise finally: acquire_restore(self._lock, state) return True
Like :meth:`wait` but additionally for *predicate* to be true. The *predicate* argument must be a callable that takes no arguments. Its result is interpreted as a boolean value.
def authority_issuer_serial(self): """ :return: None or a byte string of the SHA-256 hash of the isser from the authority key identifier extension concatenated with the ascii character ":", concatenated with the serial number from the authority key identifier extension as an ascii string """ if self._authority_issuer_serial is False: akiv = self.authority_key_identifier_value if akiv and akiv['authority_cert_issuer'].native: issuer = self.authority_key_identifier_value['authority_cert_issuer'][0].chosen # We untag the element since it is tagged via being a choice from GeneralName issuer = issuer.untag() authority_serial = self.authority_key_identifier_value['authority_cert_serial_number'].native self._authority_issuer_serial = issuer.sha256 + b':' + str_cls(authority_serial).encode('ascii') else: self._authority_issuer_serial = None return self._authority_issuer_serial
:return: None or a byte string of the SHA-256 hash of the isser from the authority key identifier extension concatenated with the ascii character ":", concatenated with the serial number from the authority key identifier extension as an ascii string
def ddtodms(self, dd): """Take in dd string and convert to dms""" negative = dd < 0 dd = abs(dd) minutes,seconds = divmod(dd*3600,60) degrees,minutes = divmod(minutes,60) if negative: if degrees > 0: degrees = -degrees elif minutes > 0: minutes = -minutes else: seconds = -seconds return (degrees,minutes,seconds)
Take in dd string and convert to dms
def compare(self, other, base=None): """ comparison, will return the first difference """ if self.__class__ != other.__class__: return False, '' names = self._field_names_ def cmp_func(name, s, o): # special case for string types if isinstance(s, six.string_types) and isinstance(o, six.string_types): return s == o, name if s.__class__ != o.__class__: return False, name if isinstance(s, BaseObj): if not isinstance(s, weakref.ProxyTypes): return s.compare(o, name) elif isinstance(s, list): for i, v in zip(range(len(s)), s): same, n = cmp_func(jp_compose(str(i), name), v, o[i]) if not same: return same, n elif isinstance(s, dict): # compare if any key diff diff = list(set(s.keys()) - set(o.keys())) if diff: return False, jp_compose(str(diff[0]), name) diff = list(set(o.keys()) - set(s.keys())) if diff: return False, jp_compose(str(diff[0]), name) for k, v in six.iteritems(s): same, n = cmp_func(jp_compose(k, name), v, o[k]) if not same: return same, n else: return s == o, name return True, name for n in names: same, n = cmp_func(jp_compose(n, base), getattr(self, n), getattr(other, n)) if not same: return same, n return True, ''
comparison, will return the first difference
def dnld_goa(self, species, ext='gaf', item=None, fileout=None): """Download GOA source file name on EMBL-EBI ftp server.""" basename = self.get_basename(species, ext, item) src = os.path.join(self.ftp_src_goa, species.upper(), "{F}.gz".format(F=basename)) dst = os.path.join(os.getcwd(), basename) if fileout is None else fileout dnld_file(src, dst, prt=sys.stdout, loading_bar=None) return dst
Download GOA source file name on EMBL-EBI ftp server.
def get_scenenode(self, nodes): """Get the scenenode in the given nodes There should only be one scenenode in nodes! :param nodes: :type nodes: :returns: None :rtype: None :raises: AssertionError """ scenenodes = cmds.ls(nodes, type='jb_sceneNode') assert scenenodes, "Found no scene nodes!" return sorted(scenenodes)[0]
Get the scenenode in the given nodes There should only be one scenenode in nodes! :param nodes: :type nodes: :returns: None :rtype: None :raises: AssertionError
def get_content(self): """performs es search and gets content objects """ if "query" in self.query: q = self.query["query"] else: q = self.query search = custom_search_model(Content, q, field_map={ "feature-type": "feature_type.slug", "tag": "tags.slug", "content-type": "_type", }) return search
performs es search and gets content objects
def unpersist(self, blocking=False): """Marks the :class:`DataFrame` as non-persistent, and remove all blocks for it from memory and disk. .. note:: `blocking` default has changed to False to match Scala in 2.0. """ self.is_cached = False self._jdf.unpersist(blocking) return self
Marks the :class:`DataFrame` as non-persistent, and remove all blocks for it from memory and disk. .. note:: `blocking` default has changed to False to match Scala in 2.0.
def parse_pictures(self, picture_page): """Parses the DOM and returns character pictures attributes. :type picture_page: :class:`bs4.BeautifulSoup` :param picture_page: MAL character pictures page's DOM :rtype: dict :return: character pictures attributes. """ character_info = self.parse_sidebar(picture_page) second_col = picture_page.find(u'div', {'id': 'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1] try: picture_table = second_col.find(u'table', recursive=False) character_info[u'pictures'] = [] if picture_table: character_info[u'pictures'] = map(lambda img: img.get(u'src').decode('utf-8'), picture_table.find_all(u'img')) except: if not self.session.suppress_parse_exceptions: raise return character_info
Parses the DOM and returns character pictures attributes. :type picture_page: :class:`bs4.BeautifulSoup` :param picture_page: MAL character pictures page's DOM :rtype: dict :return: character pictures attributes.
def neighbour_and_arc_simplices(self): """ Get indices of neighbour simplices for each simplex and arc indices. Identical to get_neighbour_simplices() but also returns an array of indices that reside on boundary hull, -1 denotes no neighbour. """ nt, ltri, lct, ierr = _tripack.trlist(self.lst, self.lptr, self.lend, nrow=9) if ierr != 0: raise ValueError('ierr={} in trlist\n{}'.format(ierr, _ier_codes[ierr])) ltri = ltri.T[:nt] - 1 return ltri[:,3:6], ltri[:,6:]
Get indices of neighbour simplices for each simplex and arc indices. Identical to get_neighbour_simplices() but also returns an array of indices that reside on boundary hull, -1 denotes no neighbour.
def get_msms_annotations(self, outdir, force_rerun=False): """Run MSMS on this structure and store the residue depths/ca depths in the corresponding ChainProp SeqRecords """ # Now can run on Biopython Model objects exclusively thanks to Biopython updates # if self.file_type != 'pdb': # raise ValueError('{}: unable to run MSMS with "{}" file type. Please change file type to "pdb"'.format(self.id, # self.file_type)) if self.structure: parsed = self.structure else: parsed = self.parse_structure() if not parsed: log.error('{}: unable to open structure to run MSMS'.format(self.id)) return log.debug('{}: running MSMS'.format(self.id)) # PDB ID is currently set to the structure file so the output name is the same with _msms.df appended to it msms_results = ssbio.protein.structure.properties.msms.get_msms_df(model=parsed.first_model, pdb_id=self.structure_path, outdir=outdir, force_rerun=force_rerun) if msms_results.empty: log.error('{}: unable to run MSMS'.format(self.id)) return chains = msms_results.chain.unique() for chain in chains: res_depths = msms_results[msms_results.chain == chain].res_depth.tolist() ca_depths = msms_results[msms_results.chain == chain].ca_depth.tolist() chain_prop = self.chains.get_by_id(chain) chain_seq = chain_prop.seq_record # Making sure the X's are filled in res_depths = ssbio.protein.structure.properties.residues.match_structure_sequence(orig_seq=chain_seq, new_seq=res_depths, fill_with=float('Inf')) ca_depths = ssbio.protein.structure.properties.residues.match_structure_sequence(orig_seq=chain_seq, new_seq=ca_depths, fill_with=float('Inf')) chain_prop.seq_record.letter_annotations['RES_DEPTH-msms'] = res_depths chain_prop.seq_record.letter_annotations['CA_DEPTH-msms'] = ca_depths log.debug('{}: stored residue depths in chain seq_record letter_annotations'.format(chain))
Run MSMS on this structure and store the residue depths/ca depths in the corresponding ChainProp SeqRecords
def execute(self, command): """ Execute (or simulate) a command. Add to our log. @param command: Either a C{str} command (which will be passed to the shell) or a C{list} of command arguments (including the executable name), in which case the shell is not used. @return: A C{CompletedProcess} instance. This has attributes such as C{returncode}, C{stdout}, and C{stderr}. See pydoc subprocess. """ if isinstance(command, six.string_types): # Can't have newlines in a command given to the shell. strCommand = command = command.replace('\n', ' ').strip() shell = True else: strCommand = ' '.join(command) shell = False if self._dryRun: self.log.append('$ ' + strCommand) return start = time() self.log.extend([ '# Start command (shell=%s) at %s' % (shell, ctime(start)), '$ ' + strCommand, ]) if six.PY3: try: result = run(command, check=True, stdout=PIPE, stderr=PIPE, shell=shell, universal_newlines=True) except CalledProcessError as e: from sys import stderr print('CalledProcessError:', e, file=stderr) print('STDOUT:\n%s' % e.stdout, file=stderr) print('STDERR:\n%s' % e.stderr, file=stderr) raise else: try: result = check_call(command, stdout=PIPE, stderr=PIPE, shell=shell, universal_newlines=True) except CalledProcessError as e: from sys import stderr print('CalledProcessError:', e, file=stderr) print('Return code: %s' % e.returncode, file=stderr) print('Output:\n%s' % e.output, file=stderr) raise stop = time() elapsed = (stop - start) self.log.extend([ '# Stop command at %s' % ctime(stop), '# Elapsed = %f seconds' % elapsed, ]) return result
Execute (or simulate) a command. Add to our log. @param command: Either a C{str} command (which will be passed to the shell) or a C{list} of command arguments (including the executable name), in which case the shell is not used. @return: A C{CompletedProcess} instance. This has attributes such as C{returncode}, C{stdout}, and C{stderr}. See pydoc subprocess.
def convert_noun_phrases(self, id_run, pos_run): """ Converts any identified phrases in the run into phrase_ids. The dictionary provides all acceptable phrases :param id_run: a run of token ids :param dictionary: a dictionary of acceptable phrases described as there component token ids :return: a run of token and phrase ids. """ i = 0 rv = [] while i < len(id_run): phrase_id, offset = PhraseDictionary.return_max_phrase(id_run, i, self) if phrase_id: if pos_run[i] in ('JJ', 'JJR', 'JJS', 'NN', 'NNS', 'NNP', 'NNPS', 'SYM', 'CD', 'VBG', 'FW', 'NP'): print "MERGED", pos_run[i], self.get_phrase(phrase_id) rv.append((phrase_id,'NP')) i = offset else: print "SKIPPED", pos_run[i], self.get_phrase(phrase_id) rv.append((id_run[i], pos_run[i])) i += 1 else: rv.append((id_run[i], pos_run[i])) i += 1 return rv
Converts any identified phrases in the run into phrase_ids. The dictionary provides all acceptable phrases :param id_run: a run of token ids :param dictionary: a dictionary of acceptable phrases described as there component token ids :return: a run of token and phrase ids.
def your_tips_on_tip_submission_form(context): """ A template tag to display the most recent and popular tip on the tip submission form. :param context: takes context """ context = copy(context) site_main = context['request'].site.root_page most_recent_tip = (YourTipsArticlePage.objects .descendant_of(site_main) .order_by('-latest_revision_created_at') .first()) most_popular_tip = (YourTipsArticlePage.objects .descendant_of(site_main) .filter(votes__gte=1) .order_by('-total_upvotes') .first()) context.update({ 'most_popular_tip': most_popular_tip, 'most_recent_tip': most_recent_tip, 'your_tip_page_slug': get_your_tip(context).slug }) return context
A template tag to display the most recent and popular tip on the tip submission form. :param context: takes context
def load_truetype_font( path: str, tile_width: int, tile_height: int ) -> Tileset: """Return a new Tileset from a `.ttf` or `.otf` file. Same as :any:`set_truetype_font`, but returns a :any:`Tileset` instead. You can send this Tileset to :any:`set_default`. This function is provisional. The API may change. """ if not os.path.exists(path): raise RuntimeError("File not found:\n\t%s" % (os.path.realpath(path),)) return Tileset._claim( lib.TCOD_load_truetype_font_(path.encode(), tile_width, tile_height) )
Return a new Tileset from a `.ttf` or `.otf` file. Same as :any:`set_truetype_font`, but returns a :any:`Tileset` instead. You can send this Tileset to :any:`set_default`. This function is provisional. The API may change.
def generate_output_events(self, source, key, val, line='2', hr=True, show_name=False, colorize=True): """ The function for generating CLI output RDAP events results. Args: source (:obj:`str`): The parent key 'network' or 'objects' (required). key (:obj:`str`): The event key 'events' or 'events_actor' (required). val (:obj:`dict`): The event dictionary (required). line (:obj:`str`): The line number (0-4). Determines indentation. Defaults to '0'. hr (:obj:`bool`): Enable human readable key translations. Defaults to True. show_name (:obj:`bool`): Show human readable name (default is to only show short). Defaults to False. colorize (:obj:`bool`): Colorize the console output with ANSI colors. Defaults to True. Returns: str: The generated output. """ output = generate_output( line=line, short=HR_RDAP[source][key]['_short'] if hr else key, name=HR_RDAP[source][key]['_name'] if (hr and show_name) else None, is_parent=False if (val is None or len(val) == 0) else True, value='None' if (val is None or len(val) == 0) else None, colorize=colorize ) if val is not None: count = 0 for item in val: try: action = item['action'] except KeyError: action = None try: timestamp = item['timestamp'] except KeyError: timestamp = None try: actor = item['actor'] except KeyError: actor = None if count > 0: output += generate_output( line=str(int(line)+1), is_parent=True, colorize=colorize ) output += generate_output( line=str(int(line)+1), short=HR_RDAP_COMMON[key]['action'][ '_short'] if hr else 'action', name=HR_RDAP_COMMON[key]['action'][ '_name'] if (hr and show_name) else None, value=action, colorize=colorize ) output += generate_output( line=str(int(line)+1), short=HR_RDAP_COMMON[key]['timestamp'][ '_short'] if hr else 'timestamp', name=HR_RDAP_COMMON[key]['timestamp'][ '_name'] if (hr and show_name) else None, value=timestamp, colorize=colorize ) output += generate_output( line=str(int(line)+1), short=HR_RDAP_COMMON[key]['actor'][ '_short'] if hr else 'actor', name=HR_RDAP_COMMON[key]['actor'][ '_name'] if (hr and show_name) else None, value=actor, colorize=colorize ) count += 1 return output
The function for generating CLI output RDAP events results. Args: source (:obj:`str`): The parent key 'network' or 'objects' (required). key (:obj:`str`): The event key 'events' or 'events_actor' (required). val (:obj:`dict`): The event dictionary (required). line (:obj:`str`): The line number (0-4). Determines indentation. Defaults to '0'. hr (:obj:`bool`): Enable human readable key translations. Defaults to True. show_name (:obj:`bool`): Show human readable name (default is to only show short). Defaults to False. colorize (:obj:`bool`): Colorize the console output with ANSI colors. Defaults to True. Returns: str: The generated output.
def config(self, name, suffix): "Return config variable value, defaulting to environment" var = '%s_%s' % (name, suffix) var = var.upper().replace('-', '_') if var in self._config: return self._config[var] return os.environ[var]
Return config variable value, defaulting to environment
def _parse_datetime_value(value): """Deserialize a DateTime object from its proper ISO-8601 representation.""" if value.endswith('Z'): # Arrow doesn't support the "Z" literal to denote UTC time. # Strip the "Z" and add an explicit time zone instead. value = value[:-1] + '+00:00' return arrow.get(value, 'YYYY-MM-DDTHH:mm:ssZ').datetime
Deserialize a DateTime object from its proper ISO-8601 representation.
def plural_verb(self, text, count=None): """ Return the plural of text, where text is a verb. If count supplied, then return text if count is one of: 1, a, an, one, each, every, this, that otherwise return the plural. Whitespace at the start and end is preserved. """ pre, word, post = self.partition_word(text) if not word: return text plural = self.postprocess( word, self._pl_special_verb(word, count) or self._pl_general_verb(word, count), ) return "{}{}{}".format(pre, plural, post)
Return the plural of text, where text is a verb. If count supplied, then return text if count is one of: 1, a, an, one, each, every, this, that otherwise return the plural. Whitespace at the start and end is preserved.
def convtable2dict(convtable, locale, update=None): """ Convert a list of conversion dict to a dict for a certain locale. >>> sorted(convtable2dict([{'zh-hk': '列斯', 'zh-hans': '利兹', 'zh': '利兹', 'zh-tw': '里茲'}, {':uni': '巨集', 'zh-cn': '宏'}], 'zh-cn').items()) [('列斯', '利兹'), ('利兹', '利兹'), ('巨集', '宏'), ('里茲', '利兹')] """ rdict = update.copy() if update else {} for r in convtable: if ':uni' in r: if locale in r: rdict[r[':uni']] = r[locale] elif locale[:-1] == 'zh-han': if locale in r: for word in r.values(): rdict[word] = r[locale] else: v = fallback(locale, r) for word in r.values(): rdict[word] = v return rdict
Convert a list of conversion dict to a dict for a certain locale. >>> sorted(convtable2dict([{'zh-hk': '列斯', 'zh-hans': '利兹', 'zh': '利兹', 'zh-tw': '里茲'}, {':uni': '巨集', 'zh-cn': '宏'}], 'zh-cn').items()) [('列斯', '利兹'), ('利兹', '利兹'), ('巨集', '宏'), ('里茲', '利兹')]
def collectData(reads1, reads2, square, matchAmbiguous): """ Get pairwise matching statistics for two sets of reads. @param reads1: An C{OrderedDict} of C{str} read ids whose values are C{Read} instances. These will be the rows of the table. @param reads2: An C{OrderedDict} of C{str} read ids whose values are C{Read} instances. These will be the columns of the table. @param square: If C{True} we are making a square table of a set of sequences against themselves (in which case we show nothing on the diagonal). @param matchAmbiguous: If C{True}, count ambiguous nucleotides that are possibly correct as actually being correct. Otherwise, we are strict and insist that only non-ambiguous nucleotides can contribute to the matching nucleotide count. """ result = defaultdict(dict) for id1, read1 in reads1.items(): for id2, read2 in reads2.items(): if id1 != id2 or not square: match = compareDNAReads( read1, read2, matchAmbiguous=matchAmbiguous)['match'] if not matchAmbiguous: assert match['ambiguousMatchCount'] == 0 result[id1][id2] = result[id2][id1] = match return result
Get pairwise matching statistics for two sets of reads. @param reads1: An C{OrderedDict} of C{str} read ids whose values are C{Read} instances. These will be the rows of the table. @param reads2: An C{OrderedDict} of C{str} read ids whose values are C{Read} instances. These will be the columns of the table. @param square: If C{True} we are making a square table of a set of sequences against themselves (in which case we show nothing on the diagonal). @param matchAmbiguous: If C{True}, count ambiguous nucleotides that are possibly correct as actually being correct. Otherwise, we are strict and insist that only non-ambiguous nucleotides can contribute to the matching nucleotide count.
def set_pointer0d(subseqs): """Set_pointer function for 0-dimensional link sequences.""" print(' . set_pointer0d') lines = Lines() lines.add(1, 'cpdef inline set_pointer0d' '(self, str name, pointerutils.PDouble value):') for seq in subseqs: lines.add(2, 'if name == "%s":' % seq.name) lines.add(3, 'self.%s = value.p_value' % seq.name) return lines
Set_pointer function for 0-dimensional link sequences.
def onThemeColor(self, color, item): """pass theme colors to bottom panel""" bconf = self.panel_bot.conf if item == 'grid': bconf.set_gridcolor(color) elif item == 'bg': bconf.set_bgcolor(color) elif item == 'frame': bconf.set_framecolor(color) elif item == 'text': bconf.set_textcolor(color) bconf.canvas.draw()
pass theme colors to bottom panel
def from_file(pkg_file): """ Return a |PackageReader| instance loaded with contents of *pkg_file*. """ phys_reader = PhysPkgReader(pkg_file) content_types = _ContentTypeMap.from_xml(phys_reader.content_types_xml) pkg_srels = PackageReader._srels_for(phys_reader, PACKAGE_URI) sparts = PackageReader._load_serialized_parts( phys_reader, pkg_srels, content_types ) phys_reader.close() return PackageReader(content_types, pkg_srels, sparts)
Return a |PackageReader| instance loaded with contents of *pkg_file*.
def slow_highlight(img1, img2, opts): """Try to find similar areas between two images. Produces two masks for img1 and img2. The algorithm works by comparing every possible alignment of the images, smoothing it a bit to reduce spurious matches in areas that are perceptibly different (e.g. text), and then taking the point-wise minimum of all those difference maps. This way if you insert a few pixel rows/columns into an image, similar areas should match even if different areas need to be aligned with different shifts. As you can imagine, this brute-force approach can be pretty slow, if there are many possible alignments. The closer the images are in size, the faster this will work. If would work better if it could compare alignments that go beyond the outer boundaries of the images, in case some pixels got shifted closer to an edge. """ w1, h1 = img1.size w2, h2 = img2.size W, H = max(w1, w2), max(h1, h2) pimg1 = Image.new('RGB', (W, H), opts.bgcolor) pimg2 = Image.new('RGB', (W, H), opts.bgcolor) pimg1.paste(img1, (0, 0)) pimg2.paste(img2, (0, 0)) diff = Image.new('L', (W, H), 255) # It is not a good idea to keep one diff image; it should track the # relative positions of the two images. I think that's what explains # the fuzz I see near the edges of the different areas. xr = abs(w1 - w2) + 1 yr = abs(h1 - h2) + 1 try: p = Progress(xr * yr, timeout=opts.timeout) for x in range(xr): for y in range(yr): p.next() this = ImageChops.difference(pimg1, pimg2).convert('L') this = this.filter(ImageFilter.MaxFilter(7)) diff = ImageChops.darker(diff, this) if h1 > h2: pimg2 = ImageChops.offset(pimg2, 0, 1) else: pimg1 = ImageChops.offset(pimg1, 0, 1) if h1 > h2: pimg2 = ImageChops.offset(pimg2, 0, -yr) else: pimg1 = ImageChops.offset(pimg1, 0, -yr) if w1 > w2: pimg2 = ImageChops.offset(pimg2, 1, 0) else: pimg1 = ImageChops.offset(pimg1, 1, 0) except KeyboardInterrupt: return None, None diff = diff.filter(ImageFilter.MaxFilter(5)) diff1 = diff.crop((0, 0, w1, h1)) diff2 = diff.crop((0, 0, w2, h2)) mask1 = tweak_diff(diff1, opts.opacity) mask2 = tweak_diff(diff2, opts.opacity) return mask1, mask2
Try to find similar areas between two images. Produces two masks for img1 and img2. The algorithm works by comparing every possible alignment of the images, smoothing it a bit to reduce spurious matches in areas that are perceptibly different (e.g. text), and then taking the point-wise minimum of all those difference maps. This way if you insert a few pixel rows/columns into an image, similar areas should match even if different areas need to be aligned with different shifts. As you can imagine, this brute-force approach can be pretty slow, if there are many possible alignments. The closer the images are in size, the faster this will work. If would work better if it could compare alignments that go beyond the outer boundaries of the images, in case some pixels got shifted closer to an edge.
def add_parameter(self, parameter, overload=False): ''' Adds a `Parameter` object to the instance. If a `Parameter` with the same name or alias has already been added and `overload` is False (the default), a `ValueError` is thrown. If a class member or method with the same name or alias is already defined, a `ValueError` is thrown, regardless of the value of overload. ''' if not isinstance(parameter, Parameter): raise TypeError('`parameter` must be an instance of `Parameter`') if hasattr(self, parameter.name): item = getattr(self, parameter.name) if not isinstance(item, Parameter): raise ValueError('"{}" is already a class member or method.' ''.format(parameter.name)) elif not overload: raise ValueError('Parameter "{}" has already been added' ' and overload is False.' ''.format(parameter.name)) if parameter.name in self._parameters and not overload: raise ValueError('Parameter "{}" has already been added' ' and overload is False.' ''.format(parameter.name)) for alias in parameter.aliases: if alias in self._aliases and not overload: raise ValueError('Alias "{}" has already been added' ' and overload is False.' ''.format(parameter.name)) self._add_parameter(parameter)
Adds a `Parameter` object to the instance. If a `Parameter` with the same name or alias has already been added and `overload` is False (the default), a `ValueError` is thrown. If a class member or method with the same name or alias is already defined, a `ValueError` is thrown, regardless of the value of overload.
def ParsePartitionsTable( self, parser_mediator, database=None, table=None, **unused_kwargs): """Parses the Partitions table. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. database (Optional[pyesedb.file]): ESE database. table (Optional[pyesedb.table]): table. Raises: ValueError: if the database or table value is missing. """ if database is None: raise ValueError('Missing database value.') if table is None: raise ValueError('Missing table value.') for esedb_record in table.records: if parser_mediator.abort: break record_values = self._GetRecordValues( parser_mediator, table.name, esedb_record) event_data = MsieWebCachePartitionsEventData() event_data.directory = record_values.get('Directory', None) event_data.partition_identifier = record_values.get('PartitionId', None) event_data.partition_type = record_values.get('PartitionType', None) event_data.table_identifier = record_values.get('TableId', None) timestamp = record_values.get('LastScavengeTime', None) if timestamp: date_time = dfdatetime_filetime.Filetime(timestamp=timestamp) event = time_events.DateTimeValuesEvent( date_time, 'Last Scavenge Time') parser_mediator.ProduceEventWithEventData(event, event_data)
Parses the Partitions table. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. database (Optional[pyesedb.file]): ESE database. table (Optional[pyesedb.table]): table. Raises: ValueError: if the database or table value is missing.
def require(self, key: str) -> str: """ Returns a configuration value by its given key. If it doesn't exist, an error is thrown. :param str key: The requested configuration key. :return: The configuration key's value. :rtype: str :raises ConfigMissingError: The configuration value did not exist. """ v = self.get(key) if v is None: raise ConfigMissingError(self.full_key(key)) return v
Returns a configuration value by its given key. If it doesn't exist, an error is thrown. :param str key: The requested configuration key. :return: The configuration key's value. :rtype: str :raises ConfigMissingError: The configuration value did not exist.
def unload_plug_in(self, name): """Unloads a DBGF plug-in. in name of type str The plug-in name or DLL. Special name 'all' unloads all plug-ins. """ if not isinstance(name, basestring): raise TypeError("name can only be an instance of type basestring") self._call("unloadPlugIn", in_p=[name])
Unloads a DBGF plug-in. in name of type str The plug-in name or DLL. Special name 'all' unloads all plug-ins.
def get_last_line_number(node): """Estimate last line number of the given AST node. The estimate is based on the line number of the last descendant of `node` that has a lineno attribute. Therefore, it underestimates the size of code ending with, e.g., multiline strings and comments. When traversing the tree, we may see a mix of nodes with line numbers and nodes without line numbers. We therefore, store the maximum line number seen so far and report it at the end. A more accurate (but also slower to compute) estimate would traverse all children, instead of just the last one, since choosing the last one may lead to a path that ends with a node without line number. """ max_lineno = node.lineno while True: last_child = _get_last_child_with_lineno(node) if last_child is None: return max_lineno else: try: max_lineno = max(max_lineno, last_child.lineno) except AttributeError: pass node = last_child
Estimate last line number of the given AST node. The estimate is based on the line number of the last descendant of `node` that has a lineno attribute. Therefore, it underestimates the size of code ending with, e.g., multiline strings and comments. When traversing the tree, we may see a mix of nodes with line numbers and nodes without line numbers. We therefore, store the maximum line number seen so far and report it at the end. A more accurate (but also slower to compute) estimate would traverse all children, instead of just the last one, since choosing the last one may lead to a path that ends with a node without line number.
def clean(self): """ Cleans/checks user has entered all required attributes. This might save some queries from being sent to server if they are totally wrong. """ if not all([self._type, self._requested, self._value, self._action]): raise MalFormattedSource( "<type, requested, value, action> fields are required." )
Cleans/checks user has entered all required attributes. This might save some queries from being sent to server if they are totally wrong.
def _generic_search(cls, name, search_string, metadata={}, ignore=''): """ Searches for a specific string given three types of regex search types. Also auto-checks for camel casing. :param name: str, name of object in question :param search_string: str, string to find and insert into the search regexes :param metadata: dict, metadata to add to the result if we find a match :param ignore: str, ignore specific string for the search :return: dict, dictionary of search results """ patterns = [cls.REGEX_ABBR_SEOS, cls.REGEX_ABBR_ISLAND, cls.REGEX_ABBR_CAMEL] if not search_string[0].isupper(): patterns.remove(cls.REGEX_ABBR_CAMEL) for pattern in patterns: search_result = cls._get_regex_search(name, pattern.format(ABBR=search_string, SEP=cls.REGEX_SEPARATORS), metadata=metadata, match_index=0, ignore=ignore) if search_result is not None: if cls.is_valid_camel(search_result.get('match_full'), strcmp=search_result.get('match')): return search_result return None
Searches for a specific string given three types of regex search types. Also auto-checks for camel casing. :param name: str, name of object in question :param search_string: str, string to find and insert into the search regexes :param metadata: dict, metadata to add to the result if we find a match :param ignore: str, ignore specific string for the search :return: dict, dictionary of search results
def update_device(self, device_id=None, uuid=None, major=None, minor=None, comment=None): """ 更新设备信息 详情请参考 http://mp.weixin.qq.com/wiki/15/b9e012f917e3484b7ed02771156411f3.html :param device_id: 设备编号,若填了UUID、major、minor,则可不填设备编号,若二者都填,则以设备编号为优先 :param uuid: UUID :param major: major :param minor: minor :param comment: 设备的备注信息,不超过15个汉字或30个英文字母。 :return: 返回的 JSON 数据包 """ data = optionaldict() data['comment'] = comment data['device_identifier'] = { 'device_id': device_id, 'uuid': uuid, 'major': major, 'minor': minor } return self._post( 'shakearound/device/update', data=data )
更新设备信息 详情请参考 http://mp.weixin.qq.com/wiki/15/b9e012f917e3484b7ed02771156411f3.html :param device_id: 设备编号,若填了UUID、major、minor,则可不填设备编号,若二者都填,则以设备编号为优先 :param uuid: UUID :param major: major :param minor: minor :param comment: 设备的备注信息,不超过15个汉字或30个英文字母。 :return: 返回的 JSON 数据包
def to_json(value, **kwargs): """Convert array to JSON list nan values are converted to string 'nan', inf values to 'inf'. """ def _recurse_list(val): if val and isinstance(val[0], list): return [_recurse_list(v) for v in val] return [str(v) if np.isnan(v) or np.isinf(v) else v for v in val] return _recurse_list(value.tolist())
Convert array to JSON list nan values are converted to string 'nan', inf values to 'inf'.
def add_place(self, **kwargs): """Adds a place to the Google Places database. On a successful request, this method will return a dict containing the the new Place's place_id and id in keys 'place_id' and 'id' respectively. keyword arguments: name -- The full text name of the Place. Limited to 255 characters. lat_lng -- A dict containing the following keys: lat, lng. accuracy -- The accuracy of the location signal on which this request is based, expressed in meters. types -- The category in which this Place belongs. Only one type can currently be specified for a Place. A string or single element list may be passed in. language -- The language in which the Place's name is being reported. (defaults 'en'). sensor -- Boolean flag denoting if the location came from a device using its location sensor (default False). """ required_kwargs = {'name': [str], 'lat_lng': [dict], 'accuracy': [int], 'types': [str, list]} request_params = {} for key in required_kwargs: if key not in kwargs or kwargs[key] is None: raise ValueError('The %s argument is required.' % key) expected_types = required_kwargs[key] type_is_valid = False for expected_type in expected_types: if isinstance(kwargs[key], expected_type): type_is_valid = True break if not type_is_valid: raise ValueError('Invalid value for %s' % key) if key is not 'lat_lng': request_params[key] = kwargs[key] if len(kwargs['name']) > 255: raise ValueError('The place name must not exceed 255 characters ' + 'in length.') try: kwargs['lat_lng']['lat'] kwargs['lat_lng']['lng'] request_params['location'] = kwargs['lat_lng'] except KeyError: raise ValueError('Invalid keys for lat_lng.') request_params['language'] = (kwargs.get('language') if kwargs.get('language') is not None else lang.ENGLISH) sensor = (kwargs.get('sensor') if kwargs.get('sensor') is not None else False) # At some point Google might support multiple types, so this supports # strings and lists. if isinstance(kwargs['types'], str): request_params['types'] = [kwargs['types']] else: request_params['types'] = kwargs['types'] url, add_response = _fetch_remote_json( GooglePlaces.ADD_API_URL % (str(sensor).lower(), self.api_key), json.dumps(request_params), use_http_post=True) _validate_response(url, add_response) return {'place_id': add_response['place_id'], 'id': add_response['id']}
Adds a place to the Google Places database. On a successful request, this method will return a dict containing the the new Place's place_id and id in keys 'place_id' and 'id' respectively. keyword arguments: name -- The full text name of the Place. Limited to 255 characters. lat_lng -- A dict containing the following keys: lat, lng. accuracy -- The accuracy of the location signal on which this request is based, expressed in meters. types -- The category in which this Place belongs. Only one type can currently be specified for a Place. A string or single element list may be passed in. language -- The language in which the Place's name is being reported. (defaults 'en'). sensor -- Boolean flag denoting if the location came from a device using its location sensor (default False).
def set_user_loc(self, master_or_instance, value): """Set the user location of a Glyphs master or instance.""" if hasattr(master_or_instance, "instanceInterpolations"): # The following code is only valid for instances. # Masters also the keys `weight` and `width` but they should not be # used, they are deprecated and should only be used to store # (parts of) the master's name, but not its location. # Try to set the key if possible, i.e. if there is a key, and # if there exists a code that can represent the given value, e.g. # for "weight": 600 can be represented by SemiBold so we use that, # but for 550 there is no code so we will have to set the custom # parameter as well. if self.user_loc_key is not None and hasattr( master_or_instance, self.user_loc_key ): code = user_loc_value_to_instance_string(self.tag, value) value_for_code = user_loc_string_to_value(self.tag, code) setattr(master_or_instance, self.user_loc_key, code) if self.user_loc_param is not None and value != value_for_code: try: class_ = user_loc_value_to_class(self.tag, value) master_or_instance.customParameters[ self.user_loc_param ] = class_ except NotImplementedError: # user_loc_value_to_class only works for weight & width pass return # For masters, set directly the custom parameter (old way) # and also the Axis Location (new way). # Only masters can have an 'Axis Location' parameter. if self.user_loc_param is not None: try: class_ = user_loc_value_to_class(self.tag, value) master_or_instance.customParameters[self.user_loc_param] = class_ except NotImplementedError: pass loc_param = master_or_instance.customParameters["Axis Location"] if loc_param is None: loc_param = [] master_or_instance.customParameters["Axis Location"] = loc_param location = None for loc in loc_param: if loc.get("Axis") == self.name: location = loc if location is None: loc_param.append({"Axis": self.name, "Location": value}) else: location["Location"] = value
Set the user location of a Glyphs master or instance.
def get_daemon_stats(self, details=False): """Increase the stats provided by the Daemon base class :return: stats dictionary :rtype: dict """ # Call the base Daemon one res = super(Receiver, self).get_daemon_stats(details=details) res.update({'name': self.name, 'type': self.type}) counters = res['counters'] counters['external-commands'] = len(self.external_commands) counters['external-commands-unprocessed'] = len(self.unprocessed_external_commands) return res
Increase the stats provided by the Daemon base class :return: stats dictionary :rtype: dict
def totals(iter, keyfunc, sumfunc): """groups items by field described in keyfunc and counts totals using value from sumfunc """ data = sorted(iter, key=keyfunc) res = {} for k, group in groupby(data, keyfunc): res[k] = sum([sumfunc(entry) for entry in group]) return res
groups items by field described in keyfunc and counts totals using value from sumfunc
def _writeString(self, obj, use_reference=True): """ Appends a string to the serialization stream :param obj: String to serialize :param use_reference: If True, allow writing a reference """ # TODO: Convert to "modified UTF-8" # http://docs.oracle.com/javase/7/docs/api/java/io/DataInput.html#modified-utf-8 string = to_bytes(obj, "utf-8") if use_reference and isinstance(obj, JavaString): try: idx = self.references.index(obj) except ValueError: # First appearance of the string self.references.append(obj) logging.debug( "*** Adding ref 0x%X for string: %s", len(self.references) - 1 + self.BASE_REFERENCE_IDX, obj, ) self._writeStruct(">H", 2, (len(string),)) self.object_stream.write(string) else: # Write a reference to the previous type logging.debug( "*** Reusing ref 0x%X for string: %s", idx + self.BASE_REFERENCE_IDX, obj, ) self.write_reference(idx) else: self._writeStruct(">H", 2, (len(string),)) self.object_stream.write(string)
Appends a string to the serialization stream :param obj: String to serialize :param use_reference: If True, allow writing a reference
def get_private_file(self): """ Return all relevant data in a single object, so this is easy to extend and server implementations can pick what they need. """ return PrivateFile( request=self.request, storage=self.get_storage(), relative_name=self.get_path() )
Return all relevant data in a single object, so this is easy to extend and server implementations can pick what they need.
def setCurrentSchemaColumn(self, column): """ Sets the current item based on the inputed column. :param column | <orb.Column> || None """ if column == self._column: self.treeWidget().setCurrentItem(self) return True for c in range(self.childCount()): if self.child(c).setCurrentSchemaColumn(column): self.setExpanded(True) return True return None
Sets the current item based on the inputed column. :param column | <orb.Column> || None
def markov_blanket(y, mean, scale, shape, skewness): """ Markov blanket for the Exponential distribution Parameters ---------- y : np.ndarray univariate time series mean : np.ndarray array of location parameters for the Exponential distribution scale : float scale parameter for the Exponential distribution shape : float tail thickness parameter for the Exponential distribution skewness : float skewness parameter for the Exponential distribution Returns ---------- - Markov blanket of the Exponential family """ return ss.expon.logpdf(x=y, scale=1/mean)
Markov blanket for the Exponential distribution Parameters ---------- y : np.ndarray univariate time series mean : np.ndarray array of location parameters for the Exponential distribution scale : float scale parameter for the Exponential distribution shape : float tail thickness parameter for the Exponential distribution skewness : float skewness parameter for the Exponential distribution Returns ---------- - Markov blanket of the Exponential family
def add_account_alias(self, account, alias): """ :param account: an account object to be used as a selector :param alias: email alias address :returns: None (the API itself returns nothing) """ self.request('AddAccountAlias', { 'id': self._get_or_fetch_id(account, self.get_account), 'alias': alias, })
:param account: an account object to be used as a selector :param alias: email alias address :returns: None (the API itself returns nothing)
def Serialize(self, writer): """ Serialize full object. Args: writer (neo.IO.BinaryWriter): """ super(Block, self).Serialize(writer) writer.WriteSerializableArray(self.Transactions)
Serialize full object. Args: writer (neo.IO.BinaryWriter):
def get_groupname(taskfileinfo): """Return a suitable name for a groupname for the given taskfileinfo. :param taskfileinfo: the taskfile info for the file that needs a group when importing/referencing :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: None :rtype: None :raises: None """ element = taskfileinfo.task.element name = element.name return name + "_grp"
Return a suitable name for a groupname for the given taskfileinfo. :param taskfileinfo: the taskfile info for the file that needs a group when importing/referencing :type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo` :returns: None :rtype: None :raises: None
def insertTopLevelItem( self, index, item ): """ Inserts the inputed item at the given index in the tree. :param index | <int> item | <XGanttWidgetItem> """ self.treeWidget().insertTopLevelItem(index, item) if self.updatesEnabled(): try: item.sync(recursive = True) except AttributeError: pass
Inserts the inputed item at the given index in the tree. :param index | <int> item | <XGanttWidgetItem>
def split(self, text): """Split text into a list of cells.""" import re if re.search('\n\n', text): return text.split('\n\n') elif re.search('\r\n\r\n', text): return text.split('\r\n\r\n') else: LOGGER.error("'%s' does not appear to be a 'srt' subtitle file", self.filename) sys.exit(1)
Split text into a list of cells.
def _add_helpingmaterials(config, helping_file, helping_type): """Add helping materials to a project.""" try: project = find_project_by_short_name(config.project['short_name'], config.pbclient, config.all) data = _load_data(helping_file, helping_type) if len(data) == 0: return ("Unknown format for the tasks file. Use json, csv, po or " "properties.") # Show progress bar with click.progressbar(data, label="Adding Helping Materials") as pgbar: for d in pgbar: helping_info, file_path = create_helping_material_info(d) if file_path: # Create first the media object hm = config.pbclient.create_helpingmaterial(project_id=project.id, info=helping_info, file_path=file_path) check_api_error(hm) z = hm.info.copy() z.update(helping_info) hm.info = z response = config.pbclient.update_helping_material(hm) check_api_error(response) else: response = config.pbclient.create_helpingmaterial(project_id=project.id, info=helping_info) check_api_error(response) # Check if for the data we have to auto-throttle task creation sleep, msg = enable_auto_throttling(config, data, endpoint='/api/helpinmaterial') # If true, warn user if sleep: # pragma: no cover click.secho(msg, fg='yellow') # If auto-throttling enabled, sleep for sleep seconds if sleep: # pragma: no cover time.sleep(sleep) return ("%s helping materials added to project: %s" % (len(data), config.project['short_name'])) except exceptions.ConnectionError: return ("Connection Error! The server %s is not responding" % config.server) except (ProjectNotFound, TaskNotFound): raise
Add helping materials to a project.
def categorization(self, domains, labels=False): '''Get the domain status and categorization of a domain or list of domains. 'domains' can be either a single domain, or a list of domains. Setting 'labels' to True will give back categorizations in human-readable form. For more detail, see https://investigate.umbrella.com/docs/api#categorization ''' if type(domains) is str: return self._get_categorization(domains, labels) elif type(domains) is list: return self._post_categorization(domains, labels) else: raise Investigate.DOMAIN_ERR
Get the domain status and categorization of a domain or list of domains. 'domains' can be either a single domain, or a list of domains. Setting 'labels' to True will give back categorizations in human-readable form. For more detail, see https://investigate.umbrella.com/docs/api#categorization
def tokenize(s): # type: (str) -> List[Token] """Translate a type comment into a list of tokens.""" original = s tokens = [] # type: List[Token] while True: if not s: tokens.append(End()) return tokens elif s[0] == ' ': s = s[1:] elif s[0] in '()[],*': tokens.append(Separator(s[0])) s = s[1:] elif s[:2] == '->': tokens.append(Separator('->')) s = s[2:] else: m = re.match(r'[-\w]+(\s*(\.|:)\s*[-/\w]*)*', s) if not m: raise ParseError(original) fullname = m.group(0) fullname = fullname.replace(' ', '') if fullname in TYPE_FIXUPS: fullname = TYPE_FIXUPS[fullname] # pytz creates classes with the name of the timezone being used: # https://github.com/stub42/pytz/blob/f55399cddbef67c56db1b83e0939ecc1e276cf42/src/pytz/tzfile.py#L120-L123 # This causes pyannotates to crash as it's invalid to have a class # name with a `/` in it (e.g. "pytz.tzfile.America/Los_Angeles") if fullname.startswith('pytz.tzfile.'): fullname = 'datetime.tzinfo' if '-' in fullname or '/' in fullname: # Not a valid Python name; there are many places that # generate these, so we just substitute Any rather # than crashing. fullname = 'Any' tokens.append(DottedName(fullname)) s = s[len(m.group(0)):]
Translate a type comment into a list of tokens.
def _scheme_propagation(self, scheme, definitions): """ Will updated a scheme based on inheritance. This is defined in a scheme objects with ``'inherit': '$definition'``. Will also updated parent objects for nested inheritance. Usage:: >>> SCHEME = { >>> 'thing1': { >>> 'inherit': '$thing2' >>> }, >>> '_': { >>> 'thing2': { >>> 'this_is': 'thing2 is a definition' >>> } >>> } >>> } >>> scheme = SCHEME.get('thing1') >>> if 'inherit' in scheme: >>> scheme = self._scheme_propagation(scheme, SCHEME.get('_')) >>> >>> scheme.get('some_data') :param scheme: A dict, should be a scheme defining validation. :param definitions: A dict, should be defined in the scheme using '_'. :rtype: A :dict: will return a updated copy of the scheme. """ if not isinstance(scheme, dict): raise TypeError('scheme must be a dict to propagate.') inherit_from = scheme.get('inherit') if isinstance(inherit_from, six.string_types): if not inherit_from.startswith('$'): raise AttributeError('When inheriting from an object it must start with a $.') if inherit_from.count('$') > 1: raise AttributeError('When inheriting an object it can only have one $.') if not isinstance(definitions, dict): raise AttributeError("Must define definitions in the root of the SCHEME. " "It is done so with '_': { objs }.") name = inherit_from[1:] definition = definitions.copy().get(name) if not definition: raise LookupError( 'Was unable to find {0} in definitions. The follow are available: {1}.'.format(name, definitions) ) else: raise AttributeError('inherit must be defined in your scheme and be a string value. format: $variable.') updated_scheme = {key: value for key, value in six.iteritems(scheme) if key not in definition} nested_scheme = None for key, value in six.iteritems(definition): if key in scheme: updated_scheme[key] = scheme[key] else: updated_scheme[key] = value if key == 'inherit': nested_scheme = self._scheme_propagation(definition, definitions) # remove inherit key if 'inherit' in updated_scheme: del updated_scheme['inherit'] if nested_scheme is not None: updated_scheme.update(nested_scheme) return updated_scheme
Will updated a scheme based on inheritance. This is defined in a scheme objects with ``'inherit': '$definition'``. Will also updated parent objects for nested inheritance. Usage:: >>> SCHEME = { >>> 'thing1': { >>> 'inherit': '$thing2' >>> }, >>> '_': { >>> 'thing2': { >>> 'this_is': 'thing2 is a definition' >>> } >>> } >>> } >>> scheme = SCHEME.get('thing1') >>> if 'inherit' in scheme: >>> scheme = self._scheme_propagation(scheme, SCHEME.get('_')) >>> >>> scheme.get('some_data') :param scheme: A dict, should be a scheme defining validation. :param definitions: A dict, should be defined in the scheme using '_'. :rtype: A :dict: will return a updated copy of the scheme.
def prefetchDeclarativeIds(self, Declarative, count) -> DelcarativeIdGen: """ Prefetch Declarative IDs This function prefetches a chunk of IDs from a database sequence. Doing this allows us to preallocate the IDs before an insert, which significantly speeds up : * Orm inserts, especially those using inheritance * When we need the ID to assign it to a related object that we're also inserting. :param Declarative: The SQLAlchemy declarative class. (The class that inherits from DeclarativeBase) :param count: The number of IDs to prefetch :return: An iterable that dispenses the new IDs """ return _commonPrefetchDeclarativeIds( self.dbEngine, self._sequenceMutex, Declarative, count )
Prefetch Declarative IDs This function prefetches a chunk of IDs from a database sequence. Doing this allows us to preallocate the IDs before an insert, which significantly speeds up : * Orm inserts, especially those using inheritance * When we need the ID to assign it to a related object that we're also inserting. :param Declarative: The SQLAlchemy declarative class. (The class that inherits from DeclarativeBase) :param count: The number of IDs to prefetch :return: An iterable that dispenses the new IDs
def getblockhash(self, index: int) -> str: '''Returns the hash of the block at ; index 0 is the genesis block.''' return cast(str, self.api_fetch('getblockhash?index=' + str(index)))
Returns the hash of the block at ; index 0 is the genesis block.
def _canonicalize_name(prefix, qvm_type, noisy): """Take the output of _parse_name to create a canonical name. """ if noisy: noise_suffix = '-noisy' else: noise_suffix = '' if qvm_type is None: qvm_suffix = '' elif qvm_type == 'qvm': qvm_suffix = '-qvm' elif qvm_type == 'pyqvm': qvm_suffix = '-pyqvm' else: raise ValueError(f"Unknown qvm_type {qvm_type}") name = f'{prefix}{noise_suffix}{qvm_suffix}' return name
Take the output of _parse_name to create a canonical name.
def course_unregister_user(self, course, username=None): """ Unregister a user to the course :param course: a Course object :param username: The username of the user that we want to unregister. If None, uses self.session_username() """ if username is None: username = self.session_username() # Needed if user belongs to a group self._database.aggregations.find_one_and_update( {"courseid": course.get_id(), "groups.students": username}, {"$pull": {"groups.$.students": username, "students": username}}) # If user doesn't belong to a group, will ensure correct deletion self._database.aggregations.find_one_and_update( {"courseid": course.get_id(), "students": username}, {"$pull": {"students": username}}) self._logger.info("User %s unregistered from course %s", username, course.get_id())
Unregister a user to the course :param course: a Course object :param username: The username of the user that we want to unregister. If None, uses self.session_username()
def refund_reward(self, agreement_id, amount, account): """ Refund reaward condition. :param agreement_id: id of the agreement, hex str :param amount: Amount of tokens, int :param account: Account :return: """ return self.release_reward(agreement_id, amount, account)
Refund reaward condition. :param agreement_id: id of the agreement, hex str :param amount: Amount of tokens, int :param account: Account :return:
def DeleteGRRUser(self, username, cursor=None): """Deletes the user and all related metadata with the given username.""" cursor.execute("DELETE FROM grr_users WHERE username_hash = %s", (mysql_utils.Hash(username),)) if cursor.rowcount == 0: raise db.UnknownGRRUserError(username)
Deletes the user and all related metadata with the given username.
def get_vert_connectivity(mesh_v, mesh_f): """Returns a sparse matrix (of size #verts x #verts) where each nonzero element indicates a neighborhood relation. For example, if there is a nonzero element in position (15,12), that means vertex 15 is connected by an edge to vertex 12.""" vpv = sp.csc_matrix((len(mesh_v),len(mesh_v))) # for each column in the faces... for i in range(3): IS = mesh_f[:,i] JS = mesh_f[:,(i+1)%3] data = np.ones(len(IS)) ij = np.vstack((row(IS.flatten()), row(JS.flatten()))) mtx = sp.csc_matrix((data, ij), shape=vpv.shape) vpv = vpv + mtx + mtx.T return vpv
Returns a sparse matrix (of size #verts x #verts) where each nonzero element indicates a neighborhood relation. For example, if there is a nonzero element in position (15,12), that means vertex 15 is connected by an edge to vertex 12.
def get_new_profile_template(self): """ Retrieves the profile template for a given server profile. Returns: dict: Server profile template. """ uri = '{}/new-profile-template'.format(self.data["uri"]) return self._helper.do_get(uri)
Retrieves the profile template for a given server profile. Returns: dict: Server profile template.
def _parse_reports_by_type(self): """ Returns a data dictionary Goes through logs and parses them based on 'No errors found', VERBOSE or SUMMARY type. """ data = dict() for file_meta in self.find_log_files('picard/sam_file_validation', filehandles=True): sample = file_meta['s_name'] if sample in data: log.debug("Duplicate sample name found! Overwriting: {}".format(sample)) filehandle = file_meta['f'] first_line = filehandle.readline().rstrip() filehandle.seek(0) # Rewind reading of the file if 'No errors found' in first_line: sample_data = _parse_no_error_report() elif first_line.startswith('ERROR') or first_line.startswith('WARNING'): sample_data = _parse_verbose_report(filehandle) else: sample_data = _parse_summary_report(filehandle) data[sample] = sample_data return data
Returns a data dictionary Goes through logs and parses them based on 'No errors found', VERBOSE or SUMMARY type.
def read_phase(ph_file): """ Read hypoDD phase files into Obspy catalog class. :type ph_file: str :param ph_file: Phase file to read event info from. :returns: Catalog of events from file. :rtype: :class:`obspy.core.event.Catalog` >>> from obspy.core.event.catalog import Catalog >>> # Get the path to the test data >>> import eqcorrscan >>> import os >>> TEST_PATH = os.path.dirname(eqcorrscan.__file__) + '/tests/test_data' >>> catalog = read_phase(TEST_PATH + '/tunnel.phase') >>> isinstance(catalog, Catalog) True """ ph_catalog = Catalog() f = open(ph_file, 'r') # Topline of each event is marked by # in position 0 for line in f: if line[0] == '#': if 'event_text' not in locals(): event_text = {'header': line.rstrip(), 'picks': []} else: ph_catalog.append(_phase_to_event(event_text)) event_text = {'header': line.rstrip(), 'picks': []} else: event_text['picks'].append(line.rstrip()) ph_catalog.append(_phase_to_event(event_text)) return ph_catalog
Read hypoDD phase files into Obspy catalog class. :type ph_file: str :param ph_file: Phase file to read event info from. :returns: Catalog of events from file. :rtype: :class:`obspy.core.event.Catalog` >>> from obspy.core.event.catalog import Catalog >>> # Get the path to the test data >>> import eqcorrscan >>> import os >>> TEST_PATH = os.path.dirname(eqcorrscan.__file__) + '/tests/test_data' >>> catalog = read_phase(TEST_PATH + '/tunnel.phase') >>> isinstance(catalog, Catalog) True
def delete_alarm(name, region=None, key=None, keyid=None, profile=None): ''' Delete a cloudwatch alarm CLI example to delete a queue:: salt myminion boto_cloudwatch.delete_alarm myalarm region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.delete_alarms([name]) log.info('Deleted alarm %s', name) return True
Delete a cloudwatch alarm CLI example to delete a queue:: salt myminion boto_cloudwatch.delete_alarm myalarm region=us-east-1
def _subtask_error(self, idx, error): """Receive an error from a single subtask.""" self.set_exception(error) self.errbacks.clear()
Receive an error from a single subtask.
def add_user(uid, password, desc=None): """ Adds user to the DCOS Enterprise. If not description is provided the uid will be used for the description. :param uid: user id :type uid: str :param password: password :type password: str :param desc: description of user :type desc: str """ try: desc = uid if desc is None else desc user_object = {"description": desc, "password": password} acl_url = urljoin(_acl_url(), 'users/{}'.format(uid)) r = http.put(acl_url, json=user_object) assert r.status_code == 201 except DCOSHTTPException as e: # already exists if e.response.status_code != 409: raise
Adds user to the DCOS Enterprise. If not description is provided the uid will be used for the description. :param uid: user id :type uid: str :param password: password :type password: str :param desc: description of user :type desc: str
def _build_session(self, name, start_info, end_info): """Builds a session object.""" assert start_info is not None result = api_pb2.Session( name=name, start_time_secs=start_info.start_time_secs, model_uri=start_info.model_uri, metric_values=self._build_session_metric_values(name), monitor_url=start_info.monitor_url) if end_info is not None: result.status = end_info.status result.end_time_secs = end_info.end_time_secs return result
Builds a session object.
def Update(self,name,description=None,location=None): """Updates the attributes of a given Network via PUT. https://www.ctl.io/api-docs/v2/#networks-update-network { "name": "VLAN for Development Servers", "description": "Development Servers on 11.22.33.0/24" } Returns a 204 and no content """ if not location: location = clc.v2.Account.GetLocation(session=self.session) payload = {'name': name} payload['description'] = description if description else self.description r = clc.v2.API.Call('PUT','/v2-experimental/networks/%s/%s/%s' % (self.alias, location, self.id), payload, session=self.session) self.name = self.data['name'] = name if description: self.data['description'] = description
Updates the attributes of a given Network via PUT. https://www.ctl.io/api-docs/v2/#networks-update-network { "name": "VLAN for Development Servers", "description": "Development Servers on 11.22.33.0/24" } Returns a 204 and no content
def _listen(sockets): """Main server loop. Listens for incoming events and dispatches them to appropriate chatroom""" while True: (i , o, e) = select.select(sockets.keys(),[],[],1) for socket in i: if isinstance(sockets[socket], Chatroom): data_len = sockets[socket].client.Process(1) if data_len is None or data_len == 0: raise Exception('Disconnected from server') #elif sockets[socket] == 'stdio': # msg = sys.stdin.readline().rstrip('\r\n') # logger.info('stdin: [%s]' % (msg,)) else: raise Exception("Unknown socket type: %s" % repr(sockets[socket]))
Main server loop. Listens for incoming events and dispatches them to appropriate chatroom
def report(self, simulation, state): """Generate a report. Parameters ---------- simulation : Simulation The Simulation to generate a report for state : State The current state of the simulation """ if not self._initialized: self._initialized = True self._steps[0] += self.interval positions = state.getPositions() # Serialize self._out.write(b''.join([b'\nSTARTOFCHUNK\n', pickle.dumps([self._steps[0], positions._value]), b'\nENDOFCHUNK\n'])) if hasattr(self._out, 'flush'): self._out.flush()
Generate a report. Parameters ---------- simulation : Simulation The Simulation to generate a report for state : State The current state of the simulation
def remove_system(self, system): ''' Removes system from world and kills system ''' if system in self._systems: self._systems.remove(system) else: raise UnmanagedSystemError(system)
Removes system from world and kills system
def doeigs_s(tau, Vdirs): """ get elements of s from eigenvaulues - note that this is very unstable Input: tau,V: tau is an list of eigenvalues in decreasing order: [t1,t2,t3] V is an list of the eigenvector directions [[V1_dec,V1_inc],[V2_dec,V2_inc],[V3_dec,V3_inc]] Output: The six tensor elements as a list: s=[x11,x22,x33,x12,x23,x13] """ t = np.zeros((3, 3,), 'f') # initialize the tau diagonal matrix V = [] for j in range(3): t[j][j] = tau[j] # diagonalize tau for k in range(3): V.append(dir2cart([Vdirs[k][0], Vdirs[k][1], 1.0])) V = np.transpose(V) tmp = np.dot(V, t) chi = np.dot(tmp, np.transpose(V)) return a2s(chi)
get elements of s from eigenvaulues - note that this is very unstable Input: tau,V: tau is an list of eigenvalues in decreasing order: [t1,t2,t3] V is an list of the eigenvector directions [[V1_dec,V1_inc],[V2_dec,V2_inc],[V3_dec,V3_inc]] Output: The six tensor elements as a list: s=[x11,x22,x33,x12,x23,x13]
def set_day_time(self, hour): """Queue up a change day time command. It will be applied when `tick` or `step` is called next. By the next tick, the lighting and the skysphere will be updated with the new hour. If there is no skysphere or directional light in the world, the command will not function properly but will not cause a crash. Args: hour (int): The hour in military time, between 0 and 23 inclusive. """ self._should_write_to_command_buffer = True command_to_send = DayTimeCommand(hour % 24) self._commands.add_command(command_to_send)
Queue up a change day time command. It will be applied when `tick` or `step` is called next. By the next tick, the lighting and the skysphere will be updated with the new hour. If there is no skysphere or directional light in the world, the command will not function properly but will not cause a crash. Args: hour (int): The hour in military time, between 0 and 23 inclusive.
def buildMask(dqarr, bitvalue): """ Builds a bit-mask from an input DQ array and a bitvalue flag """ return bitfield_to_boolean_mask(dqarr, bitvalue, good_mask_value=1, dtype=np.uint8)
Builds a bit-mask from an input DQ array and a bitvalue flag
def _load_version(cls, state, version): """ A function to load a previously saved NearestNeighborClassifier model. Parameters ---------- unpickler : GLUnpickler A GLUnpickler file handler. version : int Version number maintained by the class writer. """ assert(version == cls._PYTHON_NN_CLASSIFIER_MODEL_VERSION) knn_model = _tc.nearest_neighbors.NearestNeighborsModel(state['knn_model']) del state['knn_model'] state['_target_type'] = eval(state['_target_type']) return cls(knn_model, state)
A function to load a previously saved NearestNeighborClassifier model. Parameters ---------- unpickler : GLUnpickler A GLUnpickler file handler. version : int Version number maintained by the class writer.
def age(self, as_at_date=None): """ Compute the person's age """ if self.date_of_death != None or self.is_deceased == True: return None as_at_date = date.today() if as_at_date == None else as_at_date if self.date_of_birth != None: if (as_at_date.month >= self.date_of_birth.month) and (as_at_date.day >= self.date_of_birth.day): return (as_at_date.year - self.date_of_birth.year) else: return ((as_at_date.year - self.date_of_birth.year) -1) else: return None
Compute the person's age
def write_hier_all(self, out=sys.stdout, len_dash=1, max_depth=None, num_child=None, short_prt=False): """Write hierarchy for all GO Terms in obo file.""" # Print: [biological_process, molecular_function, and cellular_component] for go_id in ['GO:0008150', 'GO:0003674', 'GO:0005575']: self.write_hier(go_id, out, len_dash, max_depth, num_child, short_prt, None)
Write hierarchy for all GO Terms in obo file.
def joined(self, a, b): """ Returns True if a and b are members of the same set. """ mapping = self._mapping try: return mapping[a] is mapping[b] except KeyError: return False
Returns True if a and b are members of the same set.
def modify(self, monitor_id, options): """Create a monitor using passed configuration.""" if not self._state: raise InvalidState("State was not properly obtained from the app") monitors = self.list() # Get the latest set of monitors obj = None for monitor in monitors: if monitor_id != monitor['monitor_id']: continue obj = monitor if not monitor_id: raise MonitorNotFound("No monitor was found with that term.") options['action'] = 'MODIFY' options.update(obj) payload = self._build_payload(obj['term'], options) url = self.ALERTS_MODIFY_URL.format(requestX=self._state[3]) self._log.debug("Modifying alert using: %s" % url) params = json.dumps(payload, separators=(',', ':')) data = {'params': params} response = self._session.post(url, data=data, headers=self.HEADERS) if response.status_code != 200: raise ActionError("Failed to create monitor: %s" % response.content) return self.list()
Create a monitor using passed configuration.
def find_matching_symlink(path, source): """Find a symlink under `path` that points at `source`. If source is relative, it is considered relative to `path`. Returns: str: Name of symlink found, or None. """ def to_abs(target): if os.path.isabs(target): return target else: return os.path.normpath(os.path.join(path, target)) abs_source = to_abs(source) for name in os.listdir(path): linkpath = os.path.join(path, name) if os.path.islink: source_ = os.readlink(linkpath) if to_abs(source_) == abs_source: return name return None
Find a symlink under `path` that points at `source`. If source is relative, it is considered relative to `path`. Returns: str: Name of symlink found, or None.
def get_model(self): """ Get a model if the formula was previously satisfied. """ if self.minisat and self.status == True: model = pysolvers.minisat22_model(self.minisat) return model if model != None else []
Get a model if the formula was previously satisfied.
def parse_selinux(parts): """ Parse part of an ls output line that is selinux. Args: parts (list): A four element list of strings representing the initial parts of an ls line after the permission bits. The parts are owner group, selinux info, and the path. Returns: A dict containing owner, group, se_user, se_role, se_type, se_mls, and name. If the raw name was a symbolic link, link is always included. """ owner, group = parts[:2] selinux = parts[2].split(":") lsel = len(selinux) path, link = parse_path(parts[-1]) result = { "owner": owner, "group": group, "se_user": selinux[0], "se_role": selinux[1] if lsel > 1 else None, "se_type": selinux[2] if lsel > 2 else None, "se_mls": selinux[3] if lsel > 3 else None, "name": path } if link: result["link"] = link return result
Parse part of an ls output line that is selinux. Args: parts (list): A four element list of strings representing the initial parts of an ls line after the permission bits. The parts are owner group, selinux info, and the path. Returns: A dict containing owner, group, se_user, se_role, se_type, se_mls, and name. If the raw name was a symbolic link, link is always included.
def collect(self): """ Collect and publish S.M.A.R.T. attributes """ devices = re.compile(self.config['devices']) for device in os.listdir('/dev'): if devices.match(device): command = [self.config['bin'], "-A", os.path.join('/dev', device)] if str_to_bool(self.config['use_sudo']): command.insert(0, self.config['sudo_cmd']) attributes = subprocess.Popen( command, stdout=subprocess.PIPE ).communicate()[0].strip().splitlines() metrics = {} start_line = self.find_attr_start_line(attributes) for attr in attributes[start_line:]: attribute = attr.split() if attribute[1] != "Unknown_Attribute": metric = "%s.%s" % (device, attribute[1]) else: metric = "%s.%s" % (device, attribute[0]) # 234 Thermal_Throttle (...) 0/0 if '/' in attribute[9]: expanded = attribute[9].split('/') for i, subattribute in enumerate(expanded): submetric = '%s_%d' % (metric, i) if submetric not in metrics: metrics[submetric] = subattribute elif metrics[submetric] == 0 and subattribute > 0: metrics[submetric] = subattribute else: # New metric? Store it if metric not in metrics: metrics[metric] = attribute[9] # Duplicate metric? Only store if it has a larger value # This happens semi-often with the Temperature_Celsius # attribute You will have a PASS/FAIL after the real # temp, so only overwrite if The earlier one was a # PASS/FAIL (0/1) elif metrics[metric] == 0 and attribute[9] > 0: metrics[metric] = attribute[9] else: continue for metric in metrics.keys(): self.publish(metric, metrics[metric])
Collect and publish S.M.A.R.T. attributes
def convert_coord(coord_from,matrix_file,base_to_aligned=True): '''Takes an XYZ array (in DICOM coordinates) and uses the matrix file produced by 3dAllineate to transform it. By default, the 3dAllineate matrix transforms from base to aligned space; to get the inverse transform set ``base_to_aligned`` to ``False``''' with open(matrix_file) as f: try: values = [float(y) for y in ' '.join([x for x in f.readlines() if x.strip()[0]!='#']).strip().split()] except: nl.notify('Error reading values from matrix file %s' % matrix_file, level=nl.level.error) return False if len(values)!=12: nl.notify('Error: found %d values in matrix file %s (expecting 12)' % (len(values),matrix_file), level=nl.level.error) return False matrix = np.vstack((np.array(values).reshape((3,-1)),[0,0,0,1])) if not base_to_aligned: matrix = np.linalg.inv(matrix) return np.dot(matrix,list(coord_from) + [1])[:3]
Takes an XYZ array (in DICOM coordinates) and uses the matrix file produced by 3dAllineate to transform it. By default, the 3dAllineate matrix transforms from base to aligned space; to get the inverse transform set ``base_to_aligned`` to ``False``
def read(self, filename): """Reads the file specified by filename This method will load the eapi.conf file specified by filename into the instance object. It will also add the default connection localhost if it was not defined in the eapi.conf file Args: filename (str): The full path to the file to load """ try: SafeConfigParser.read(self, filename) except SafeConfigParserError as exc: # Ignore file and syslog a message on SafeConfigParser errors msg = ("%s: parsing error in eapi conf file: %s" % (type(exc).__name__, filename)) debug(msg) self._add_default_connection() for name in self.sections(): if name.startswith('connection:') and \ 'host' not in dict(self.items(name)): self.set(name, 'host', name.split(':')[1]) self.generate_tags()
Reads the file specified by filename This method will load the eapi.conf file specified by filename into the instance object. It will also add the default connection localhost if it was not defined in the eapi.conf file Args: filename (str): The full path to the file to load
def make_image_cache(img_cache): """ Initiates the image cache if it does not exist """ log.info('Initiating the image cache at {0}'.format(img_cache)) if not os.path.isdir(img_cache): utils.mkdir_p(img_cache) utils.mkdir_p(os.path.join(img_cache, '10.1371')) utils.mkdir_p(os.path.join(img_cache, '10.3389'))
Initiates the image cache if it does not exist
def wrap_method( func, default_retry=None, default_timeout=None, client_info=client_info.DEFAULT_CLIENT_INFO, ): """Wrap an RPC method with common behavior. This applies common error wrapping, retry, and timeout behavior a function. The wrapped function will take optional ``retry`` and ``timeout`` arguments. For example:: import google.api_core.gapic_v1.method from google.api_core import retry from google.api_core import timeout # The original RPC method. def get_topic(name, timeout=None): request = publisher_v2.GetTopicRequest(name=name) return publisher_stub.GetTopic(request, timeout=timeout) default_retry = retry.Retry(deadline=60) default_timeout = timeout.Timeout(deadline=60) wrapped_get_topic = google.api_core.gapic_v1.method.wrap_method( get_topic, default_retry) # Execute get_topic with default retry and timeout: response = wrapped_get_topic() # Execute get_topic without doing any retying but with the default # timeout: response = wrapped_get_topic(retry=None) # Execute get_topic but only retry on 5xx errors: my_retry = retry.Retry(retry.if_exception_type( exceptions.InternalServerError)) response = wrapped_get_topic(retry=my_retry) The way this works is by late-wrapping the given function with the retry and timeout decorators. Essentially, when ``wrapped_get_topic()`` is called: * ``get_topic()`` is first wrapped with the ``timeout`` into ``get_topic_with_timeout``. * ``get_topic_with_timeout`` is wrapped with the ``retry`` into ``get_topic_with_timeout_and_retry()``. * The final ``get_topic_with_timeout_and_retry`` is called passing through the ``args`` and ``kwargs``. The callstack is therefore:: method.__call__() -> Retry.__call__() -> Timeout.__call__() -> wrap_errors() -> get_topic() Note that if ``timeout`` or ``retry`` is ``None``, then they are not applied to the function. For example, ``wrapped_get_topic(timeout=None, retry=None)`` is more or less equivalent to just calling ``get_topic`` but with error re-mapping. Args: func (Callable[Any]): The function to wrap. It should accept an optional ``timeout`` argument. If ``metadata`` is not ``None``, it should accept a ``metadata`` argument. default_retry (Optional[google.api_core.Retry]): The default retry strategy. If ``None``, the method will not retry by default. default_timeout (Optional[google.api_core.Timeout]): The default timeout strategy. Can also be specified as an int or float. If ``None``, the method will not have timeout specified by default. client_info (Optional[google.api_core.gapic_v1.client_info.ClientInfo]): Client information used to create a user-agent string that's passed as gRPC metadata to the method. If unspecified, then a sane default will be used. If ``None``, then no user agent metadata will be provided to the RPC method. Returns: Callable: A new callable that takes optional ``retry`` and ``timeout`` arguments and applies the common error mapping, retry, timeout, and metadata behavior to the low-level RPC method. """ func = grpc_helpers.wrap_errors(func) if client_info is not None: user_agent_metadata = [client_info.to_grpc_metadata()] else: user_agent_metadata = None return general_helpers.wraps(func)( _GapicCallable( func, default_retry, default_timeout, metadata=user_agent_metadata ) )
Wrap an RPC method with common behavior. This applies common error wrapping, retry, and timeout behavior a function. The wrapped function will take optional ``retry`` and ``timeout`` arguments. For example:: import google.api_core.gapic_v1.method from google.api_core import retry from google.api_core import timeout # The original RPC method. def get_topic(name, timeout=None): request = publisher_v2.GetTopicRequest(name=name) return publisher_stub.GetTopic(request, timeout=timeout) default_retry = retry.Retry(deadline=60) default_timeout = timeout.Timeout(deadline=60) wrapped_get_topic = google.api_core.gapic_v1.method.wrap_method( get_topic, default_retry) # Execute get_topic with default retry and timeout: response = wrapped_get_topic() # Execute get_topic without doing any retying but with the default # timeout: response = wrapped_get_topic(retry=None) # Execute get_topic but only retry on 5xx errors: my_retry = retry.Retry(retry.if_exception_type( exceptions.InternalServerError)) response = wrapped_get_topic(retry=my_retry) The way this works is by late-wrapping the given function with the retry and timeout decorators. Essentially, when ``wrapped_get_topic()`` is called: * ``get_topic()`` is first wrapped with the ``timeout`` into ``get_topic_with_timeout``. * ``get_topic_with_timeout`` is wrapped with the ``retry`` into ``get_topic_with_timeout_and_retry()``. * The final ``get_topic_with_timeout_and_retry`` is called passing through the ``args`` and ``kwargs``. The callstack is therefore:: method.__call__() -> Retry.__call__() -> Timeout.__call__() -> wrap_errors() -> get_topic() Note that if ``timeout`` or ``retry`` is ``None``, then they are not applied to the function. For example, ``wrapped_get_topic(timeout=None, retry=None)`` is more or less equivalent to just calling ``get_topic`` but with error re-mapping. Args: func (Callable[Any]): The function to wrap. It should accept an optional ``timeout`` argument. If ``metadata`` is not ``None``, it should accept a ``metadata`` argument. default_retry (Optional[google.api_core.Retry]): The default retry strategy. If ``None``, the method will not retry by default. default_timeout (Optional[google.api_core.Timeout]): The default timeout strategy. Can also be specified as an int or float. If ``None``, the method will not have timeout specified by default. client_info (Optional[google.api_core.gapic_v1.client_info.ClientInfo]): Client information used to create a user-agent string that's passed as gRPC metadata to the method. If unspecified, then a sane default will be used. If ``None``, then no user agent metadata will be provided to the RPC method. Returns: Callable: A new callable that takes optional ``retry`` and ``timeout`` arguments and applies the common error mapping, retry, timeout, and metadata behavior to the low-level RPC method.
def clone(self): """Return a new Scope object that has the curr_scope pinned at the current one :returns: A new scope object """ self._dlog("cloning the stack") # TODO is this really necessary to create a brand new one? # I think it is... need to think about it more. # or... are we going to need ref counters and a global # scope object that allows a view into (or a snapshot of) # a specific scope stack? res = Scope(self._log) res._scope_stack = self._scope_stack res._curr_scope = self._curr_scope return res
Return a new Scope object that has the curr_scope pinned at the current one :returns: A new scope object
def visit_and_update(self, visitor_fn): """Create an updated version (if needed) of BinaryComposition via the visitor pattern.""" new_left = self.left.visit_and_update(visitor_fn) new_right = self.right.visit_and_update(visitor_fn) if new_left is not self.left or new_right is not self.right: return visitor_fn(BinaryComposition(self.operator, new_left, new_right)) else: return visitor_fn(self)
Create an updated version (if needed) of BinaryComposition via the visitor pattern.