code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def silenceRemoval(x, fs, st_win, st_step, smoothWindow=0.5, weight=0.5, plot=False): ''' Event Detection (silence removal) ARGUMENTS: - x: the input audio signal - fs: sampling freq - st_win, st_step: window size and step in seconds - smoo...
Event Detection (silence removal) ARGUMENTS: - x: the input audio signal - fs: sampling freq - st_win, st_step: window size and step in seconds - smoothWindow: (optinal) smooth window (in seconds) - weight: (optinal) weight f...
def load_ldap_config(self): # pragma: no cover """Configure LDAP Client settings.""" try: with open('{}/ldap_info.yaml'.format(self.config_dir), 'r') as FILE: config = yaml.load(FILE) self.host = config['server'] self.use...
Configure LDAP Client settings.
def permute(self, idx): """Permutes the columns of the factor matrices inplace """ # Check that input is a true permutation if set(idx) != set(range(self.rank)): raise ValueError('Invalid permutation specified.') # Update factors self.factors = [f[:, idx] fo...
Permutes the columns of the factor matrices inplace
def calc_missingremoterelease_v1(self): """Calculate the portion of the required remote demand that could not be met by the actual discharge release. Required flux sequences: |RequiredRemoteRelease| |ActualRelease| Calculated flux sequence: |MissingRemoteRelease| Basic equation:...
Calculate the portion of the required remote demand that could not be met by the actual discharge release. Required flux sequences: |RequiredRemoteRelease| |ActualRelease| Calculated flux sequence: |MissingRemoteRelease| Basic equation: :math:`MissingRemoteRelease = max( ...
def split_seq(sam_num, n_tile): """ Split the number(sam_num) into numbers by n_tile """ import math print(sam_num) print(n_tile) start_num = sam_num[0::int(math.ceil(len(sam_num) / (n_tile)))] end_num = start_num[1::] end_num.append(len(sam_num)) return [[i, j] for i, j in zip(s...
Split the number(sam_num) into numbers by n_tile
def create_entity(self, name, gl_structure, description=None): """ Create an entity and add it to the model. :param name: The entity name. :param gl_structure: The entity's general ledger structure. :param description: The entity description. :returns: The created entit...
Create an entity and add it to the model. :param name: The entity name. :param gl_structure: The entity's general ledger structure. :param description: The entity description. :returns: The created entity.
def _processDML(self, dataset_name, cols, reader): """Overridden version of create DML for SQLLite""" sql_template = self._generateInsertStatement(dataset_name, cols) # Now insert in batch, reader is a list of rows to insert at this point c = self.conn.cursor() c.executemany(sql...
Overridden version of create DML for SQLLite
def main(args=None): """Roundtrip the .glyphs file given as an argument.""" for arg in args: glyphsLib.dump(load(open(arg, "r", encoding="utf-8")), sys.stdout)
Roundtrip the .glyphs file given as an argument.
def from_dict(cls, pods): """ Returns a new Fragment from a dictionary representation. """ frag = cls() frag.content = pods['content'] frag._resources = [FragmentResource(**d) for d in pods['resources']] # pylint: disable=protected-access frag.js_init_fn = pods['...
Returns a new Fragment from a dictionary representation.
def ufloatDict_nominal(self, ufloat_dict): 'This gives us a dictionary of nominal values from a dictionary of uncertainties' return OrderedDict(izip(ufloat_dict.keys(), map(lambda x: x.nominal_value, ufloat_dict.values())))
This gives us a dictionary of nominal values from a dictionary of uncertainties
def calcRapRperi(self,**kwargs): """ NAME: calcRapRperi PURPOSE: calculate the apocenter and pericenter radii INPUT: OUTPUT: (rperi,rap) HISTORY: 2010-12-01 - Written - Bovy (NYU) """ if hasattr(self,'_rperirap')...
NAME: calcRapRperi PURPOSE: calculate the apocenter and pericenter radii INPUT: OUTPUT: (rperi,rap) HISTORY: 2010-12-01 - Written - Bovy (NYU)
def handleError(self, record): """ Handles any errors raised during the :meth:`emit` method. Will only try to pass exceptions to fallback notifier (if defined) in case the exception is a sub-class of :exc:`~notifiers.exceptions.NotifierException` :param record: :class:`logging.LogRecord...
Handles any errors raised during the :meth:`emit` method. Will only try to pass exceptions to fallback notifier (if defined) in case the exception is a sub-class of :exc:`~notifiers.exceptions.NotifierException` :param record: :class:`logging.LogRecord`
def resume_training(self, train_data, model_path, valid_data=None): """This model resume training of a classifier by reloading the appropriate state_dicts for each model Args: train_data: a tuple of Tensors (X,Y), a Dataset, or a DataLoader of X (data) and Y (labels) for the ...
This model resume training of a classifier by reloading the appropriate state_dicts for each model Args: train_data: a tuple of Tensors (X,Y), a Dataset, or a DataLoader of X (data) and Y (labels) for the train split model_path: the path to the saved checpoint for resumin...
def delete_report(server, report_number, timeout=HQ_DEFAULT_TIMEOUT): """ Delete a specific crash report from the server. :param report_number: Report Number :return: server response """ try: r = requests.post(server + "/reports/delete/%d" % report_number, timeout=timeout) except Exc...
Delete a specific crash report from the server. :param report_number: Report Number :return: server response
def get_vswhere_path(): """ Get the path to vshwere.exe. If vswhere is not already installed as part of Visual Studio, and no alternate path is given using `set_vswhere_path()`, the latest release will be downloaded and stored alongside this script. """ if alternate_path and os.path.exists(...
Get the path to vshwere.exe. If vswhere is not already installed as part of Visual Studio, and no alternate path is given using `set_vswhere_path()`, the latest release will be downloaded and stored alongside this script.
def add_children_gos(self, gos): """Return children of input gos plus input gos.""" lst = [] obo_dag = self.obo_dag get_children = lambda go_obj: list(go_obj.get_all_children()) + [go_obj.id] for go_id in gos: go_obj = obo_dag[go_id] lst.extend(get_childre...
Return children of input gos plus input gos.
def _set_if_type(self, v, load=False): """ Setter method for if_type, mapped from YANG variable /mpls_state/dynamic_bypass/dynamic_bypass_interface/if_type (mpls-if-type) If this variable is read-only (config: false) in the source YANG file, then _set_if_type is considered as a private method. Backe...
Setter method for if_type, mapped from YANG variable /mpls_state/dynamic_bypass/dynamic_bypass_interface/if_type (mpls-if-type) If this variable is read-only (config: false) in the source YANG file, then _set_if_type is considered as a private method. Backends looking to populate this variable should do...
def graph_from_labels(label_image, fg_markers, bg_markers, regional_term = False, boundary_term = False, regional_term_args = False, boundary_term_args = False): """ Cr...
Create a graph-cut ready graph to segment a nD image using the region neighbourhood. Create a `~medpy.graphcut.maxflow.GraphDouble` object for all regions of a nD label image. Every region of the label image is regarded as a node. They are connected to their immediate neighbours by arcs. If to...
async def load_blob(reader, elem_type, params=None, elem=None): """ Loads blob from reader to the element. Returns the loaded blob. :param reader: :param elem_type: :param params: :param elem: :return: """ ivalue = elem_type.SIZE if elem_type.FIX_SIZE else await load_uvarint(reader)...
Loads blob from reader to the element. Returns the loaded blob. :param reader: :param elem_type: :param params: :param elem: :return:
def fold_enrichment(self): """(property) Returns the fold enrichment at the XL-mHG cutoff.""" return self.k / (self.K*(self.cutoff/float(self.N)))
(property) Returns the fold enrichment at the XL-mHG cutoff.
def copy_resource(self, container, resource, local_filename): """ Identical to :meth:`dockermap.client.base.DockerClientWrapper.copy_resource` with additional logging. """ self.push_log("Receiving tarball for resource '{0}:{1}' and storing as {2}".format(container, resource, local_filena...
Identical to :meth:`dockermap.client.base.DockerClientWrapper.copy_resource` with additional logging.
def get_proc_dir(cachedir, **kwargs): ''' Given the cache directory, return the directory that process data is stored in, creating it if it doesn't exist. The following optional Keyword Arguments are handled: mode: which is anything os.makedir would accept as mode. uid: the uid to set, if not ...
Given the cache directory, return the directory that process data is stored in, creating it if it doesn't exist. The following optional Keyword Arguments are handled: mode: which is anything os.makedir would accept as mode. uid: the uid to set, if not set, or it is None or -1 no changes are m...
def get_model_url_name(model_nfo, page, with_namespace=False): """Returns a URL for a given Tree admin page type.""" prefix = '' if with_namespace: prefix = 'admin:' return ('%s%s_%s' % (prefix, '%s_%s' % model_nfo, page)).lower()
Returns a URL for a given Tree admin page type.
def _plot_extension(self, gta, prefix, src, loge_bounds=None, **kwargs): """Utility function for generating diagnostic plots for the extension analysis.""" # format = kwargs.get('format', self.config['plotting']['format']) if loge_bounds is None: loge_bounds = (self.energie...
Utility function for generating diagnostic plots for the extension analysis.
def bz2_decompress_stream(src): """Decompress data from `src`. Args: src (iterable): iterable that yields blocks of compressed data Yields: blocks of uncompressed data """ dec = bz2.BZ2Decompressor() for block in src: decoded = dec.decompress(block) if decoded:...
Decompress data from `src`. Args: src (iterable): iterable that yields blocks of compressed data Yields: blocks of uncompressed data
def error(self, error): """ Defines a simulated exception error that will be raised. Arguments: error (str|Exception): error to raise. Returns: self: current Mock instance. """ self._error = RuntimeError(error) if isinstance(error, str) else erro...
Defines a simulated exception error that will be raised. Arguments: error (str|Exception): error to raise. Returns: self: current Mock instance.
def intersection(self, *others): """Return the intersection of two or more sets as a new set. >>> from ngram import NGram >>> a = NGram(['spam', 'eggs']) >>> b = NGram(['spam', 'ham']) >>> list(a.intersection(b)) ['spam'] """ return self.copy(super(NGram,...
Return the intersection of two or more sets as a new set. >>> from ngram import NGram >>> a = NGram(['spam', 'eggs']) >>> b = NGram(['spam', 'ham']) >>> list(a.intersection(b)) ['spam']
def resolve_frompath(pkgpath, relpath, level=0): """Resolves the path of the module referred to by 'from ..x import y'.""" if level == 0: return relpath parts = pkgpath.split('.') + ['_'] parts = parts[:-level] + (relpath.split('.') if relpath else []) return '.'.join(parts)
Resolves the path of the module referred to by 'from ..x import y'.
def set_condition(self, condition = True): """ Sets a new condition callback for the breakpoint. @see: L{__init__} @type condition: function @param condition: (Optional) Condition callback function. """ if condition is None: self.__condition = True ...
Sets a new condition callback for the breakpoint. @see: L{__init__} @type condition: function @param condition: (Optional) Condition callback function.
def load_cash_balances(self): """ Loads cash balances from GnuCash book and recalculates into the default currency """ from gnucash_portfolio.accounts import AccountsAggregate, AccountAggregate cfg = self.__get_config() cash_root_name = cfg.get(ConfigKeys.cash_root) # Load cash ...
Loads cash balances from GnuCash book and recalculates into the default currency
def encrypt(self, data): ''' encrypt data with AES-CBC and sign it with HMAC-SHA256 ''' aes_key, hmac_key = self.keys pad = self.AES_BLOCK_SIZE - len(data) % self.AES_BLOCK_SIZE if six.PY2: data = data + pad * chr(pad) else: data = data + s...
encrypt data with AES-CBC and sign it with HMAC-SHA256
def this(obj, **kwargs): """Prints series of debugging steps to user. Runs through pipeline of functions and print results of each. """ verbose = kwargs.get("verbose", True) if verbose: print('{:=^30}'.format(" whatis.this? ")) for func in pipeline: s = func(obj, **kwargs) ...
Prints series of debugging steps to user. Runs through pipeline of functions and print results of each.
def remove_action(self, action, sub_menu='Advanced'): """ Removes an action/separator from the editor's context menu. :param action: Action/seprator to remove. :param advanced: True to remove the action from the advanced submenu. """ if sub_menu: try: ...
Removes an action/separator from the editor's context menu. :param action: Action/seprator to remove. :param advanced: True to remove the action from the advanced submenu.
def is_valid_geometry(self): """ It is possible to infer the geometry only if exactly one of sites, sites_csv, hazard_curves_csv, gmfs_csv, region is set. You did set more than one, or nothing. """ has_sites = (self.sites is not None or 'sites' in self.inputs ...
It is possible to infer the geometry only if exactly one of sites, sites_csv, hazard_curves_csv, gmfs_csv, region is set. You did set more than one, or nothing.
def update_kwargs(self, kwargs, count, offset): """ Helper to support handy dictionaries merging on all Python versions. """ kwargs.update({self.count_key: count, self.offset_key: offset}) return kwargs
Helper to support handy dictionaries merging on all Python versions.
def filters_query(filters): """ Turn the tuple of filters into SQL WHERE statements The key (column name) & operator have already been vetted so they can be trusted but the value could still be evil so it MUST be a parameterized input! That is done by creating a param dict wher...
Turn the tuple of filters into SQL WHERE statements The key (column name) & operator have already been vetted so they can be trusted but the value could still be evil so it MUST be a parameterized input! That is done by creating a param dict where they key name & val look like:...
def get_pdf(article, debug=False): """ Download an article PDF from arXiv. :param article: The ADS article to retrieve. :type article: :class:`ads.search.Article` :returns: The binary content of the requested PDF. """ print('Retrieving {0}'.format(article)) i...
Download an article PDF from arXiv. :param article: The ADS article to retrieve. :type article: :class:`ads.search.Article` :returns: The binary content of the requested PDF.
def identify_col_pos(txt): """ assume no delimiter in this file, so guess the best fixed column widths to split by """ res = [] #res.append(0) lines = txt.split('\n') prev_ch = '' for col_pos, ch in enumerate(lines[0]): if _is_white_space(ch) is False and _is_white_space(prev_ch) is True: res.a...
assume no delimiter in this file, so guess the best fixed column widths to split by
def overlap_correlation(wnd, hop): """ Overlap correlation percent for the given overlap hop in samples. """ return sum(wnd * Stream(wnd).skip(hop)) / sum(el ** 2 for el in wnd)
Overlap correlation percent for the given overlap hop in samples.
def is_binary_file(file): """ Returns if given file is a binary file. :param file: File path. :type file: unicode :return: Is file binary. :rtype: bool """ file_handle = open(file, "rb") try: chunk_size = 1024 while True: chunk = file_handle.read(chunk_s...
Returns if given file is a binary file. :param file: File path. :type file: unicode :return: Is file binary. :rtype: bool
def ToDatetime(self): """Converts Timestamp to datetime.""" return datetime.utcfromtimestamp( self.seconds + self.nanos / float(_NANOS_PER_SECOND))
Converts Timestamp to datetime.
def add_coordinate_condition(self, droppable_id, container_id, coordinate, match=True): """stub""" if not isinstance(coordinate, BasicCoordinate): raise InvalidArgument('coordinate is not a BasicCoordinate') self.my_osid_object_form._my_map['coordinateConditions'].append( ...
stub
def _set_es_workers(self, **kwargs): """ Creates index worker instances for each class to index kwargs: ------- idx_only_base[bool]: True will only index the base class """ def make_es_worker(search_conn, es_index, es_doc_type, class_name): """ ...
Creates index worker instances for each class to index kwargs: ------- idx_only_base[bool]: True will only index the base class
def parse(format, string, extra_types=None, evaluate_result=True, case_sensitive=False): '''Using "format" attempt to pull values from "string". The format must match the string contents exactly. If the value you're looking for is instead just a part of the string use search(). If ``evaluate_resul...
Using "format" attempt to pull values from "string". The format must match the string contents exactly. If the value you're looking for is instead just a part of the string use search(). If ``evaluate_result`` is True the return value will be an Result instance with two attributes: .fixed - tupl...
def past_trades(self, symbol='btcusd', limit_trades=50, timestamp=0): """ Send a trade history request, return the response. Arguements: symbol -- currency symbol (default 'btcusd') limit_trades -- maximum number of trades to return (default 50) timestamp -- only return ...
Send a trade history request, return the response. Arguements: symbol -- currency symbol (default 'btcusd') limit_trades -- maximum number of trades to return (default 50) timestamp -- only return trades after this unix timestamp (default 0)
def read_file_header(fd, endian): """Read mat 5 file header of the file fd. Returns a dict with header values. """ fields = [ ('description', 's', 116), ('subsystem_offset', 's', 8), ('version', 'H', 2), ('endian_test', 's', 2) ] hdict = {} for name, fmt, num_...
Read mat 5 file header of the file fd. Returns a dict with header values.
def follow_cf(save, Uspan, target_cf, nup, n_tot=5.0, slsp=None): """Calculates the quasiparticle weight in single site spin hamiltonian under with N degenerate half-filled orbitals """ if slsp == None: slsp = Spinon(slaves=6, orbitals=3, avg_particles=n_tot, hopping=[0.5]...
Calculates the quasiparticle weight in single site spin hamiltonian under with N degenerate half-filled orbitals
def slugify(cls, s): """Return the slug version of the string ``s``""" slug = re.sub("[^0-9a-zA-Z-]", "-", s) return re.sub("-{2,}", "-", slug).strip('-')
Return the slug version of the string ``s``
def map_noreturn(targ, argslist): """ parallel_call_noreturn(targ, argslist) :Parameters: - targ : function - argslist : list of tuples Does [targ(*args) for args in argslist] using the threadpool. """ # Thanks to Anne Archibald's handythread.py for the exception handling # me...
parallel_call_noreturn(targ, argslist) :Parameters: - targ : function - argslist : list of tuples Does [targ(*args) for args in argslist] using the threadpool.
def p_ctx_coords(self, p): """ ctx_coords : multiplicative_path | ctx_coords COLON multiplicative_path""" if len(p) == 2: p[0] = [p[1]] else: p[0] = p[1] + [p[3]]
ctx_coords : multiplicative_path | ctx_coords COLON multiplicative_path
def _GetDirectory(self): """Retrieves a directory. Returns: TARDirectory: a directory or None if not available. """ if self.entry_type != definitions.FILE_ENTRY_TYPE_DIRECTORY: return None return TARDirectory(self._file_system, self.path_spec)
Retrieves a directory. Returns: TARDirectory: a directory or None if not available.
def from_filename(self, filename): ''' Build an IntentSchema from a file path creates a new intent schema if the file does not exist, throws an error if the file exists but cannot be loaded as a JSON ''' if os.path.exists(filename): with open(filename) as fp:...
Build an IntentSchema from a file path creates a new intent schema if the file does not exist, throws an error if the file exists but cannot be loaded as a JSON
def wrap_socket(self, sock, server_side=False, do_handshake_on_connect=True, suppress_ragged_eofs=True, dummy=None): """Wrap an existing Python socket sock and return an ssl.SSLSocket object. """ return ssl.wrap_socket(sock, keyfile=self._keyfile, ...
Wrap an existing Python socket sock and return an ssl.SSLSocket object.
def UpsertUserDefinedFunction(self, collection_link, udf, options=None): """Upserts a user defined function in a collection. :param str collection_link: The link to the collection. :param str udf: :param dict options: The request options for the request. ...
Upserts a user defined function in a collection. :param str collection_link: The link to the collection. :param str udf: :param dict options: The request options for the request. :return: The upserted UDF. :rtype: dict
def put_attachment(self, attachmentid, attachment_update): '''http://bugzilla.readthedocs.org/en/latest/api/core/v1/attachment.html#update-attachment''' assert type(attachment_update) is DotDict if (not 'ids' in attachment_update): attachment_update.ids = [attachmentid] retu...
http://bugzilla.readthedocs.org/en/latest/api/core/v1/attachment.html#update-attachment
def get_result(self, decorated_function, *args, **kwargs): """ Get result from storage for specified function. Will raise an exception (:class:`.WCacheStorage.CacheMissedException`) if there is no cached result. :param decorated_function: called function (original) :param args: args with which function is call...
Get result from storage for specified function. Will raise an exception (:class:`.WCacheStorage.CacheMissedException`) if there is no cached result. :param decorated_function: called function (original) :param args: args with which function is called :param kwargs: kwargs with which function is called :retu...
def get_neighbors(self, site, r, include_index=False, include_image=False): """ Get all neighbors to a site within a sphere of radius r. Excludes the site itself. Args: site (Site): Which is the center of the sphere. r (float): Radius of sphere. incl...
Get all neighbors to a site within a sphere of radius r. Excludes the site itself. Args: site (Site): Which is the center of the sphere. r (float): Radius of sphere. include_index (bool): Whether the non-supercell site index is included in the return...
def sample_counters(mc, system_info): """Sample every router counter in the machine.""" return { (x, y): mc.get_router_diagnostics(x, y) for (x, y) in system_info }
Sample every router counter in the machine.
def hasattrs(object, *names): """ Takes in an object and a variable length amount of named attributes, and checks to see if the object has each property. If any of the attributes are missing, this returns false. :param object: an object that may or may not contain the listed attributes :param n...
Takes in an object and a variable length amount of named attributes, and checks to see if the object has each property. If any of the attributes are missing, this returns false. :param object: an object that may or may not contain the listed attributes :param names: a variable amount of attribute names...
def default_vsan_policy_configured(name, policy): ''' Configures the default VSAN policy on a vCenter. The state assumes there is only one default VSAN policy on a vCenter. policy Dict representation of a policy ''' # TODO Refactor when recurse_differ supports list_differ # It's goi...
Configures the default VSAN policy on a vCenter. The state assumes there is only one default VSAN policy on a vCenter. policy Dict representation of a policy
def _add_token_span_to_document(self, span_element): """ adds an <intro>, <act> or <conclu> token span to the document. """ for token in span_element.text.split(): token_id = self._add_token_to_document(token) if span_element.tag == 'act': # doc can have 0+ acts ...
adds an <intro>, <act> or <conclu> token span to the document.
def file_size(self, name, force_refresh=False): """Returns the size of the file. For efficiency this operation does not use locking, so may return inconsistent data. Use it for informational purposes. """ uname, version = split_name(name) t = time.time() ...
Returns the size of the file. For efficiency this operation does not use locking, so may return inconsistent data. Use it for informational purposes.
def register(self, schema): """Register input schema class. When registering a schema, all inner schemas are registered as well. :param Schema schema: schema to register. :return: old registered schema. :rtype: type """ result = None uuid = schema.uuid ...
Register input schema class. When registering a schema, all inner schemas are registered as well. :param Schema schema: schema to register. :return: old registered schema. :rtype: type
def wrap_and_format(self, width=None, include_params=False, include_return=False, excluded_params=None): """Wrap, format and print this docstring for a specific width. Args: width (int): The number of characters per line. If set to None this will be inferred from the termin...
Wrap, format and print this docstring for a specific width. Args: width (int): The number of characters per line. If set to None this will be inferred from the terminal width and default to 80 if not passed or if passed as None and the terminal width...
def group_callback(self, iocb): """Callback when a child iocb completes.""" if _debug: IOGroup._debug("group_callback %r", iocb) # check all the members for iocb in self.ioMembers: if not iocb.ioComplete.isSet(): if _debug: IOGroup._debug(" - waiting for c...
Callback when a child iocb completes.
def get_emitter(self, name: str) -> Callable[[Event], Event]: """Gets and emitter for a named event. Parameters ---------- name : The name of the event he requested emitter will emit. Users may provide their own named events by requesting an emitter with this fun...
Gets and emitter for a named event. Parameters ---------- name : The name of the event he requested emitter will emit. Users may provide their own named events by requesting an emitter with this function, but should do so with caution as it makes time much mo...
def pipeline_exists(url, pipeline_id, auth, verify_ssl): ''' :param url: (str): the host url in the form 'http://host:port/'. :param pipeline_id: (string) the pipeline identifier :param auth: (tuple) a tuple of username, password :return: (boolean) ''' try: pipeline_status(url, pipel...
:param url: (str): the host url in the form 'http://host:port/'. :param pipeline_id: (string) the pipeline identifier :param auth: (tuple) a tuple of username, password :return: (boolean)
def lnlike(self, model, refactor=False, pos_tol=2.5, neg_tol=50., full_output=False): r""" Return the likelihood of the astrophysical model `model`. Returns the likelihood of `model` marginalized over the PLD model. :param ndarray model: A vector of the same shape as `se...
r""" Return the likelihood of the astrophysical model `model`. Returns the likelihood of `model` marginalized over the PLD model. :param ndarray model: A vector of the same shape as `self.time` \ corresponding to the astrophysical model. :param bool refactor: Re-compute ...
def print_prefixed_lines(lines: List[Tuple[str, Optional[str]]]) -> str: """Print lines specified like this: ["prefix", "string"]""" existing_lines = [line for line in lines if line[1] is not None] pad_len = reduce(lambda pad, line: max(pad, len(line[0])), existing_lines, 0) return "\n".join( ma...
Print lines specified like this: ["prefix", "string"]
def get_page_content(self, page_id, page_info=0): """ PageInfo 0 - Returns only basic page content, without selection markup and binary data objects. This is the standard value to pass. 1 - Returns page content with no selection markup, but with all binary data. 2 - Retur...
PageInfo 0 - Returns only basic page content, without selection markup and binary data objects. This is the standard value to pass. 1 - Returns page content with no selection markup, but with all binary data. 2 - Returns page content with selection markup, but no binary data. 3 -...
def locally_cache_remote_file(href, dir): """ Locally cache a remote resource using a predictable file name and awareness of modification date. Assume that files are "normal" which is to say they have filenames with extensions. """ scheme, host, remote_path, params, query, fragment = urlpars...
Locally cache a remote resource using a predictable file name and awareness of modification date. Assume that files are "normal" which is to say they have filenames with extensions.
def seek(self, offset, whence=SEEK_SET): """Reposition the file pointer.""" if whence == SEEK_SET: self.__sf.seek(offset) elif whence == SEEK_CUR: self.__sf.seek(self.tell() + offset) elif whence == SEEK_END: self.__sf.seek(self.__sf.filesize - offset...
Reposition the file pointer.
def get_title(self, properly_capitalized=False): """Returns the artist or track title.""" if properly_capitalized: self.title = _extract( self._request(self.ws_prefix + ".getInfo", True), "name" ) return self.title
Returns the artist or track title.
def ok_rev_reg_id(token: str, issuer_did: str = None) -> bool: """ Whether input token looks like a valid revocation registry identifier from input issuer DID (default any); i.e., <issuer-did>:4:<issuer-did>:3:CL:<schema-seq-no>:<cred-def-id-tag>:CL_ACCUM:<rev-reg-id-tag> for protocol >= 1.4, or <issuer...
Whether input token looks like a valid revocation registry identifier from input issuer DID (default any); i.e., <issuer-did>:4:<issuer-did>:3:CL:<schema-seq-no>:<cred-def-id-tag>:CL_ACCUM:<rev-reg-id-tag> for protocol >= 1.4, or <issuer-did>:4:<issuer-did>:3:CL:<schema-seq-no>:CL_ACCUM:<rev-reg-id-tag> for pro...
def get_commit_bzs(self, from_revision, to_revision=None): """ Return a list of tuples, one per commit. Each tuple is (sha1, subject, bz_list). bz_list is a (possibly zero-length) list of numbers. """ rng = self.rev_range(from_revision, to_revision) GIT_COMMIT_FIELDS = ['...
Return a list of tuples, one per commit. Each tuple is (sha1, subject, bz_list). bz_list is a (possibly zero-length) list of numbers.
def make_category(self, string, parent=None, order=1): """ Make and save a category object from a string """ cat = Category( name=string.strip(), slug=slugify(SLUG_TRANSLITERATOR(string.strip()))[:49], # arent=parent, order=order ) ...
Make and save a category object from a string
def createTemplate(data): """ Create a new template. Args: `data`: json data required for creating a template Returns: Dictionary containing the details of the template with its ID. """ conn = Qubole.agent() return conn.post(Template.rest_...
Create a new template. Args: `data`: json data required for creating a template Returns: Dictionary containing the details of the template with its ID.
def convex_hull(self): """ The convex hull of the whole scene Returns --------- hull: Trimesh object, convex hull of all meshes in scene """ points = util.vstack_empty([m.vertices for m in self.dump()]) hull = convex.convex_hull(points) return hul...
The convex hull of the whole scene Returns --------- hull: Trimesh object, convex hull of all meshes in scene
def _compile_fragment_ast(schema, current_schema_type, ast, location, context): """Return a list of basic blocks corresponding to the inline fragment at this AST node. Args: schema: GraphQL schema object, obtained from the graphql library current_schema_type: GraphQLType, the schema type at the...
Return a list of basic blocks corresponding to the inline fragment at this AST node. Args: schema: GraphQL schema object, obtained from the graphql library current_schema_type: GraphQLType, the schema type at the current location ast: GraphQL AST node, obtained from the graphql library. ...
def save_yaml_model(model, filename, sort=False, **kwargs): """ Write the cobra model to a file in YAML format. ``kwargs`` are passed on to ``yaml.dump``. Parameters ---------- model : cobra.Model The cobra model to represent. filename : str or file-like File path or descri...
Write the cobra model to a file in YAML format. ``kwargs`` are passed on to ``yaml.dump``. Parameters ---------- model : cobra.Model The cobra model to represent. filename : str or file-like File path or descriptor that the YAML representation should be written to. sort...
def multiply(self, matrix): """ Multiply this matrix by a local dense matrix on the right. :param matrix: a local dense matrix whose number of rows must match the number of columns of this matrix :returns: :py:class:`RowMatrix` >>> rm = RowMatrix(sc.paral...
Multiply this matrix by a local dense matrix on the right. :param matrix: a local dense matrix whose number of rows must match the number of columns of this matrix :returns: :py:class:`RowMatrix` >>> rm = RowMatrix(sc.parallelize([[0, 1], [2, 3]])) >>> rm.multipl...
def verify(path): """Verify that `path` is a zip file with Phasics TIFF files""" valid = False try: zf = zipfile.ZipFile(path) except (zipfile.BadZipfile, IsADirectoryError): pass else: names = sorted(zf.namelist()) names = [nn for ...
Verify that `path` is a zip file with Phasics TIFF files
def get_experiment_kind(root): """Read common properties from root of ReSpecTh XML file. Args: root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file Returns: properties (`dict`): Dictionary with experiment type and apparatus information. """ properties = {} if root...
Read common properties from root of ReSpecTh XML file. Args: root (`~xml.etree.ElementTree.Element`): Root of ReSpecTh XML file Returns: properties (`dict`): Dictionary with experiment type and apparatus information.
def cases(self, env, data): '''Calls each nested handler until one of them returns nonzero result. If any handler returns `None`, it is interpreted as "request does not match, the handler has nothing to do with it and `web.cases` should try to call the next handler".''' for ha...
Calls each nested handler until one of them returns nonzero result. If any handler returns `None`, it is interpreted as "request does not match, the handler has nothing to do with it and `web.cases` should try to call the next handler".
def recursive_apply(inval, func): '''Recursively apply a function to all levels of nested iterables :param inval: the object to run the function on :param func: the function that will be run on the inval ''' if isinstance(inval, dict): return {k: recursive_apply(v, func) for k, v in inval.i...
Recursively apply a function to all levels of nested iterables :param inval: the object to run the function on :param func: the function that will be run on the inval
def filter_bolts(table, header): """ filter to keep bolts """ bolts_info = [] for row in table: if row[0] == 'bolt': bolts_info.append(row) return bolts_info, header
filter to keep bolts
def loadUi(self, filename, baseinstance=None): """ Generate a loader to load the filename. :param filename | <str> baseinstance | <QWidget> :return <QWidget> || None """ try: xui = ElementTree.parse(file...
Generate a loader to load the filename. :param filename | <str> baseinstance | <QWidget> :return <QWidget> || None
def add_subtree(cls, for_node, node, options): """ Recursively build options tree. """ if cls.is_loop_safe(for_node, node): options.append( (node.pk, mark_safe(cls.mk_indent(node.get_depth()) + escape(node)))) for subnode in node.get_children(): ...
Recursively build options tree.
def _shuffle(y, labels, random_state): """Return a shuffled copy of y eventually shuffle among same labels.""" if labels is None: ind = random_state.permutation(len(y)) else: ind = np.arange(len(labels)) for label in np.unique(labels): this_mask = (labels == label) ...
Return a shuffled copy of y eventually shuffle among same labels.
def validate_pair(ob: Any) -> bool: """ Does the object have length 2? """ try: if len(ob) != 2: log.warning("Unexpected result: {!r}", ob) raise ValueError() except ValueError: return False return True
Does the object have length 2?
def reload(self): """ Re-fetches the object from the API, discarding any local changes. Returns without doing anything if the object is new. """ if not self.id: return reloaded_object = self.__class__.find(self.id) self.set_raw( reloaded_o...
Re-fetches the object from the API, discarding any local changes. Returns without doing anything if the object is new.
def get_image(self, image, output='vector'): """ A flexible method for transforming between different representations of image data. Args: image: The input image. Can be a string (filename of image), NiBabel image, N-dimensional array (must have same shape as ...
A flexible method for transforming between different representations of image data. Args: image: The input image. Can be a string (filename of image), NiBabel image, N-dimensional array (must have same shape as self.volume), or vectorized image data (must have...
def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]: """Rate limit a function.""" return util.rate_limited(max_per_hour, *args)
Rate limit a function.
def patcher(args): """ %prog patcher backbone.bed other.bed Given optical map alignment, prepare the patchers. Use --backbone to suggest which assembly is the major one, and the patchers will be extracted from another assembly. """ from jcvi.formats.bed import uniq p = OptionParser(pat...
%prog patcher backbone.bed other.bed Given optical map alignment, prepare the patchers. Use --backbone to suggest which assembly is the major one, and the patchers will be extracted from another assembly.
def RetryUpload(self, job, job_id, error): """Retry the BigQuery upload job. Using the same job id protects us from duplicating data on the server. If we fail all of our retries we raise. Args: job: BigQuery job object job_id: ID string for this upload job error: errors.HttpError obj...
Retry the BigQuery upload job. Using the same job id protects us from duplicating data on the server. If we fail all of our retries we raise. Args: job: BigQuery job object job_id: ID string for this upload job error: errors.HttpError object from the first error Returns: API r...
def list_files(start_path): """tree unix command replacement.""" s = u'\n' for root, dirs, files in os.walk(start_path): level = root.replace(start_path, '').count(os.sep) indent = ' ' * 4 * level s += u'{}{}/\n'.format(indent, os.path.basename(root)) sub_indent = ' ' * 4 * (...
tree unix command replacement.
def translate(args): """ %prog translate cdsfasta Translate CDS to proteins. The tricky thing is that sometimes the CDS represents a partial gene, therefore disrupting the frame of the protein. Check all three frames to get a valid translation. """ transl_tables = [str(x) for x in xrange(1,...
%prog translate cdsfasta Translate CDS to proteins. The tricky thing is that sometimes the CDS represents a partial gene, therefore disrupting the frame of the protein. Check all three frames to get a valid translation.
def trainClassifier(cls, data, numClasses, categoricalFeaturesInfo, numTrees, featureSubsetStrategy="auto", impurity="gini", maxDepth=4, maxBins=32, seed=None): """ Train a random forest model for binary or multiclass classification. :para...
Train a random forest model for binary or multiclass classification. :param data: Training dataset: RDD of LabeledPoint. Labels should take values {0, 1, ..., numClasses-1}. :param numClasses: Number of classes for classification. :param categoricalFeatures...
def parents(self): """return the ancestor nodes""" assert self.parent is not self if self.parent is None: return [] return [self.parent] + self.parent.parents()
return the ancestor nodes
def read_remote(self): '''Send a message back to the server (in contrast to the local user output channel).''' coded_line = self.inout.read_msg() if isinstance(coded_line, bytes): coded_line = coded_line.decode("utf-8") control = coded_line[0] remote_line = co...
Send a message back to the server (in contrast to the local user output channel).