Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
376,100
def silenceRemoval(x, fs, st_win, st_step, smoothWindow=0.5, weight=0.5, plot=False): if weight >= 1: weight = 0.99 if weight <= 0: weight = 0.01 x = audioBasicIO.stereo2mono(x) st_feats, _ = aF.stFeatureExtraction(x, fs, st_win * fs, ...
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...
376,101
def load_ldap_config(self): try: with open(.format(self.config_dir), ) as FILE: config = yaml.load(FILE) self.host = config[] self.user_dn = config[] self.port = config[] self.basedn = co...
Configure LDAP Client settings.
376,102
def permute(self, idx): if set(idx) != set(range(self.rank)): raise ValueError() self.factors = [f[:, idx] for f in self.factors] return self.factors
Permutes the columns of the factor matrices inplace
376,103
def calc_missingremoterelease_v1(self): flu = self.sequences.fluxes.fastaccess flu.missingremoterelease = max( flu.requiredremoterelease-flu.actualrelease, 0.)
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( ...
376,104
def split_seq(sam_num, 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(start_num, end_num)]
Split the number(sam_num) into numbers by n_tile
376,105
def create_entity(self, name, gl_structure, description=None): new_entity = Entity(name, gl_structure, description=description) self.entities.append(new_entity) return new_entity
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.
376,106
def _processDML(self, dataset_name, cols, reader): sql_template = self._generateInsertStatement(dataset_name, cols) c = self.conn.cursor() c.executemany(sql_template, reader) self.conn.commit()
Overridden version of create DML for SQLLite
376,107
def main(args=None): for arg in args: glyphsLib.dump(load(open(arg, "r", encoding="utf-8")), sys.stdout)
Roundtrip the .glyphs file given as an argument.
376,108
def from_dict(cls, pods): frag = cls() frag.content = pods[] frag._resources = [FragmentResource(**d) for d in pods[]] frag.js_init_fn = pods[] frag.js_init_version = pods[] frag.json_init_args = pods[] return frag
Returns a new Fragment from a dictionary representation.
376,109
def ufloatDict_nominal(self, ufloat_dict): 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
376,110
def calcRapRperi(self,**kwargs): if hasattr(self,): return self._rperirap EL= self.calcEL(**kwargs) E, L= EL if self._vR == 0. and m.fabs(self._vT - vcirc(self._pot,self._R,use_physical=False)) < _EPS: rperi= self._R rap = self._R el...
NAME: calcRapRperi PURPOSE: calculate the apocenter and pericenter radii INPUT: OUTPUT: (rperi,rap) HISTORY: 2010-12-01 - Written - Bovy (NYU)
376,111
def handleError(self, record): if logging.raiseExceptions: t, v, tb = sys.exc_info() if issubclass(t, NotifierException) and self.fallback: msg = f"Could not log msg to provider !\n{v}" self.fallback_defaults["message"] = msg self....
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`
376,112
def resume_training(self, train_data, model_path, valid_data=None): restore_state = self.checkpointer.restore(model_path) loss_fn = self._get_loss_fn() self.train() self._train_model( train_data=train_data, loss_fn=loss_fn, valid_data=valid_da...
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...
376,113
def delete_report(server, report_number, timeout=HQ_DEFAULT_TIMEOUT): try: r = requests.post(server + "/reports/delete/%d" % report_number, timeout=timeout) except Exception as e: logging.error(e) return False return r
Delete a specific crash report from the server. :param report_number: Report Number :return: server response
376,114
def get_vswhere_path(): if alternate_path and os.path.exists(alternate_path): return alternate_path if DEFAULT_PATH and os.path.exists(DEFAULT_PATH): return DEFAULT_PATH if os.path.exists(DOWNLOAD_PATH): return DOWNLOAD_PATH _download_vswhere() return DOWNLOAD_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.
376,115
def add_children_gos(self, 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_children(go_obj)) return set(lst)
Return children of input gos plus input gos.
376,116
def _set_if_type(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type="dict_key", restriction_arg={u: {: 7}, u: {: 2}, u: {: 5},...
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...
376,117
def graph_from_labels(label_image, fg_markers, bg_markers, regional_term = False, boundary_term = False, regional_term_args = False, boundary_term_args = False): ...
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...
376,118
async def load_blob(reader, elem_type, params=None, elem=None): ivalue = elem_type.SIZE if elem_type.FIX_SIZE else await load_uvarint(reader) fvalue = bytearray(ivalue) await reader.areadinto(fvalue) if elem is None: return fvalue elif isinstance(elem, BlobType): setattr(ele...
Loads blob from reader to the element. Returns the loaded blob. :param reader: :param elem_type: :param params: :param elem: :return:
376,119
def fold_enrichment(self): return self.k / (self.K*(self.cutoff/float(self.N)))
(property) Returns the fold enrichment at the XL-mHG cutoff.
376,120
def copy_resource(self, container, resource, local_filename): self.push_log("Receiving tarball for resource and storing as {2}".format(container, resource, local_filename)) super(DockerFabricClient, self).copy_resource(container, resource, local_filename)
Identical to :meth:`dockermap.client.base.DockerClientWrapper.copy_resource` with additional logging.
376,121
def get_proc_dir(cachedir, **kwargs): 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 made. Same applies if the directory is already owned by this ...
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...
376,122
def get_model_url_name(model_nfo, page, with_namespace=False): prefix = if with_namespace: prefix = return ( % (prefix, % model_nfo, page)).lower()
Returns a URL for a given Tree admin page type.
376,123
def _plot_extension(self, gta, prefix, src, loge_bounds=None, **kwargs): if loge_bounds is None: loge_bounds = (self.energies[0], self.energies[-1]) name = src[].lower().replace(, ) esuffix = % (loge_bounds[0], loge_bounds[1]) p = ExtensionPlotter(src,...
Utility function for generating diagnostic plots for the extension analysis.
376,124
def bz2_decompress_stream(src): dec = bz2.BZ2Decompressor() for block in src: decoded = dec.decompress(block) if decoded: yield decoded
Decompress data from `src`. Args: src (iterable): iterable that yields blocks of compressed data Yields: blocks of uncompressed data
376,125
def error(self, error): self._error = RuntimeError(error) if isinstance(error, str) else error
Defines a simulated exception error that will be raised. Arguments: error (str|Exception): error to raise. Returns: self: current Mock instance.
376,126
def intersection(self, *others): return self.copy(super(NGram, self).intersection(*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']
376,127
def resolve_frompath(pkgpath, relpath, level=0): 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'.
376,128
def set_condition(self, condition = True): if condition is None: self.__condition = True else: self.__condition = condition
Sets a new condition callback for the breakpoint. @see: L{__init__} @type condition: function @param condition: (Optional) Condition callback function.
376,129
def load_cash_balances(self): from gnucash_portfolio.accounts import AccountsAggregate, AccountAggregate cfg = self.__get_config() cash_root_name = cfg.get(ConfigKeys.cash_root) gc_db = self.config.get(ConfigKeys.gnucash_book_path) with open_book(gc_db, open_if...
Loads cash balances from GnuCash book and recalculates into the default currency
376,130
def encrypt(self, data): 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 + salt.utils.stringutils.to_bytes(pad * chr(pad)) iv_bytes = os.urandom(s...
encrypt data with AES-CBC and sign it with HMAC-SHA256
376,131
def this(obj, **kwargs): verbose = kwargs.get("verbose", True) if verbose: print(.format(" whatis.this? ")) for func in pipeline: s = func(obj, **kwargs) if s is not None: print(s) if verbose: print(.format(" whatis.this? "))
Prints series of debugging steps to user. Runs through pipeline of functions and print results of each.
376,132
def remove_action(self, action, sub_menu=): if sub_menu: try: mnu = self._sub_menus[sub_menu] except KeyError: pass else: mnu.removeAction(action) else: try: self._actions.remove(acti...
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.
376,133
def is_valid_geometry(self): has_sites = (self.sites is not None or in self.inputs or in self.inputs) if not has_sites and not self.ground_motion_fields: return True if ( in self.inputs and not has_sites and not 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.
376,134
def update_kwargs(self, kwargs, count, offset): kwargs.update({self.count_key: count, self.offset_key: offset}) return kwargs
Helper to support handy dictionaries merging on all Python versions.
376,135
def filters_query(filters): def _cast_val(filtr): val = filtr.val if filtr.oper in (, ): val = + filtr.val + elif filtr.oper == : val = + filtr.val elif filtr.oper == : val = filtr.val + ...
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:...
376,136
def get_pdf(article, debug=False): print(.format(article)) identifier = [_ for _ in article.identifier if in _] if identifier: url = .format(identifier[0][9:13], .join(_ for _ in identifier[0][14:] if _.isdigit())) else: params = { : article.bibco...
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.
376,137
def identify_col_pos(txt): res = [] lines = txt.split() 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.append(col_pos) prev_ch = ch res.append(col_pos) return res
assume no delimiter in this file, so guess the best fixed column widths to split by
376,138
def overlap_correlation(wnd, hop): return sum(wnd * Stream(wnd).skip(hop)) / sum(el ** 2 for el in wnd)
Overlap correlation percent for the given overlap hop in samples.
376,139
def is_binary_file(file): file_handle = open(file, "rb") try: chunk_size = 1024 while True: chunk = file_handle.read(chunk_size) if chr(0) in chunk: return True if len(chunk) < chunk_size: break finally: file_h...
Returns if given file is a binary file. :param file: File path. :type file: unicode :return: Is file binary. :rtype: bool
376,140
def ToDatetime(self): return datetime.utcfromtimestamp( self.seconds + self.nanos / float(_NANOS_PER_SECOND))
Converts Timestamp to datetime.
376,141
def add_coordinate_condition(self, droppable_id, container_id, coordinate, match=True): if not isinstance(coordinate, BasicCoordinate): raise InvalidArgument() self.my_osid_object_form._my_map[].append( {: droppable_id, : container_id, : coordinate.get_values(), : match}...
stub
376,142
def _set_es_workers(self, **kwargs): def make_es_worker(search_conn, es_index, es_doc_type, class_name): new_esbase = copy.copy(search_conn) new_esbase.es_index = es_index new_esbase.doc_type = es_doc_type log.info("Indexing into ES index d...
Creates index worker instances for each class to index kwargs: ------- idx_only_base[bool]: True will only index the base class
376,143
def parse(format, string, extra_types=None, evaluate_result=True, case_sensitive=False): 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 - tuple of fixed-position values from the s...
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...
376,144
def past_trades(self, symbol=, limit_trades=50, timestamp=0): request = url = self.base_url + request params = { : request, : self.get_nonce(), : symbol, : limit_trades, : timestamp } return requests.post(url,...
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)
376,145
def read_file_header(fd, endian): fields = [ (, , 116), (, , 8), (, , 2), (, , 2) ] hdict = {} for name, fmt, num_bytes in fields: data = fd.read(num_bytes) hdict[name] = unpack(endian, fmt, data) hdict[] = hdict[].strip() v_major = hdict[] >>...
Read mat 5 file header of the file fd. Returns a dict with header values.
376,146
def follow_cf(save, Uspan, target_cf, nup, n_tot=5.0, slsp=None): if slsp == None: slsp = Spinon(slaves=6, orbitals=3, avg_particles=n_tot, hopping=[0.5]*6, populations = np.asarray([n_tot]*6)/6) zet, lam, mu, mean_f = [], [], [], [] for co in Uspan: print(, co...
Calculates the quasiparticle weight in single site spin hamiltonian under with N degenerate half-filled orbitals
376,147
def slugify(cls, s): slug = re.sub("[^0-9a-zA-Z-]", "-", s) return re.sub("-{2,}", "-", slug).strip()
Return the slug version of the string ``s``
376,148
def map_noreturn(targ, argslist): exceptions = [] n_threads = len(argslist) exc_lock = threading.Lock() done_lock = CountDownLatch(n_threads) def eb(wr, el=exc_lock, ex=exceptions, dl=done_lock): el.acquire() ex.append(sys.exc_info()) el.release() d...
parallel_call_noreturn(targ, argslist) :Parameters: - targ : function - argslist : list of tuples Does [targ(*args) for args in argslist] using the threadpool.
376,149
def p_ctx_coords(self, p): if len(p) == 2: p[0] = [p[1]] else: p[0] = p[1] + [p[3]]
ctx_coords : multiplicative_path | ctx_coords COLON multiplicative_path
376,150
def _GetDirectory(self): 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.
376,151
def from_filename(self, filename): if os.path.exists(filename): with open(filename) as fp: return IntentSchema(json.load(fp, object_pairs_hook=OrderedDict)) else: print () return IntentSchema()
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
376,152
def wrap_socket(self, sock, server_side=False, do_handshake_on_connect=True, suppress_ragged_eofs=True, dummy=None): return ssl.wrap_socket(sock, keyfile=self._keyfile, certfile=self._certfile, server_...
Wrap an existing Python socket sock and return an ssl.SSLSocket object.
376,153
def UpsertUserDefinedFunction(self, collection_link, udf, options=None): if options is None: options = {} collection_id, path, udf = self._GetContainerIdWithPathForUDF(collection_link, udf) return self.Upsert(udf, path, ...
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
376,154
def put_attachment(self, attachmentid, attachment_update): assert type(attachment_update) is DotDict if (not in attachment_update): attachment_update.ids = [attachmentid] return self._put(.format(attachmentid=attachmentid), json.dumps(attachment_update))
http://bugzilla.readthedocs.org/en/latest/api/core/v1/attachment.html#update-attachment
376,155
def get_result(self, decorated_function, *args, **kwargs): cache_entry = self.get_cache(decorated_function, *args, **kwargs) if cache_entry.has_value is False: raise WCacheStorage.CacheMissedException() return cache_entry.cached_value
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...
376,156
def get_neighbors(self, site, r, include_index=False, include_image=False): nn = self.get_sites_in_sphere(site.coords, r, include_index=include_index, include_image=include_image) return [d for d in nn if site != d[0]]
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...
376,157
def sample_counters(mc, system_info): return { (x, y): mc.get_router_diagnostics(x, y) for (x, y) in system_info }
Sample every router counter in the machine.
376,158
def hasattrs(object, *names): for name in names: if not hasattr(object, name): return False return True
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...
376,159
def default_vsan_policy_configured(name, policy): }) return ret
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
376,160
def _add_token_span_to_document(self, span_element): for token in span_element.text.split(): token_id = self._add_token_to_document(token) if span_element.tag == : self._add_spanning_relation(.format(self.act_count), ...
adds an <intro>, <act> or <conclu> token span to the document.
376,161
def file_size(self, name, force_refresh=False): uname, version = split_name(name) t = time.time() logger.debug(, name) try: if not self.remote_store or (version is not None and not force_refresh): try: ...
Returns the size of the file. For efficiency this operation does not use locking, so may return inconsistent data. Use it for informational purposes.
376,162
def register(self, schema): result = None uuid = schema.uuid if uuid in self._schbyuuid: result = self._schbyuuid[uuid] if result != schema: self._schbyuuid[uuid] = schema name = schema.name schemas = self._schbyname.setdefau...
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
376,163
def wrap_and_format(self, width=None, include_params=False, include_return=False, excluded_params=None): if excluded_params is None: excluded_params = [] out = StringIO() if width is None: width, _height = get_terminal_size() for line in self.maindoc: ...
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...
376,164
def group_callback(self, iocb): if _debug: IOGroup._debug("group_callback %r", iocb) for iocb in self.ioMembers: if not iocb.ioComplete.isSet(): if _debug: IOGroup._debug(" - waiting for child: %r", iocb) break else: i...
Callback when a child iocb completes.
376,165
def get_emitter(self, name: str) -> Callable[[Event], Event]: return self._event_manager.get_emitter(name)
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...
376,166
def pipeline_exists(url, pipeline_id, auth, verify_ssl): http://host:port/ try: pipeline_status(url, pipeline_id, auth, verify_ssl)[] return True except requests.HTTPError: return False
: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)
376,167
def lnlike(self, model, refactor=False, pos_tol=2.5, neg_tol=50., full_output=False): r lnl = 0 try: self._ll_info except AttributeError: refactor = True if refactor: t = np.delete(self.time, ...
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 ...
376,168
def print_prefixed_lines(lines: List[Tuple[str, Optional[str]]]) -> str: 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( map( lambda line: line[0].rjust(pad_len) + line[1...
Print lines specified like this: ["prefix", "string"]
376,169
def get_page_content(self, page_id, page_info=0): try: return(self.process.GetPageContent(page_id, "", page_info)) except Exception as e: print(e) print("Could not get Page Content")
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 -...
376,170
def locally_cache_remote_file(href, dir): scheme, host, remote_path, params, query, fragment = urlparse(href) assert scheme in (,), % (scheme,href) head, ext = posixpath.splitext(posixpath.basename(remote_path)) head = sub(r, , head) hash = md5(href).hexdigest()[:8] local_path =...
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.
376,171
def seek(self, offset, whence=SEEK_SET): 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.
376,172
def get_title(self, properly_capitalized=False): if properly_capitalized: self.title = _extract( self._request(self.ws_prefix + ".getInfo", True), "name" ) return self.title
Returns the artist or track title.
376,173
def ok_rev_reg_id(token: str, issuer_did: str = None) -> bool: rr_id_m = re.match( .format(B58), token or ) return bool(rr_id_m) and ((not issuer_did) or (rr_id_m.group(1) == issuer_did and rr_id_m.group(2) == issuer_did))
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...
376,174
def get_commit_bzs(self, from_revision, to_revision=None): rng = self.rev_range(from_revision, to_revision) GIT_COMMIT_FIELDS = [, , ] GIT_LOG_FORMAT = [, , ] GIT_LOG_FORMAT = .join(GIT_LOG_FORMAT) + log_out = self(, % GIT_LOG_FORMAT, rng, log_cm...
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.
376,175
def make_category(self, string, parent=None, order=1): cat = Category( name=string.strip(), slug=slugify(SLUG_TRANSLITERATOR(string.strip()))[:49], order=order ) cat._tree_manager.insert_node(cat, parent, , True) cat.save() ...
Make and save a category object from a string
376,176
def createTemplate(data): conn = Qubole.agent() return conn.post(Template.rest_entity_path, 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.
376,177
def convex_hull(self): points = util.vstack_empty([m.vertices for m in self.dump()]) hull = convex.convex_hull(points) return hull
The convex hull of the whole scene Returns --------- hull: Trimesh object, convex hull of all meshes in scene
376,178
def _compile_fragment_ast(schema, current_schema_type, ast, location, context): query_metadata_table = context[] is_base_type_of_union = ( isinstance(current_schema_type, GraphQLUnionType) and current_schema_type.is_same_type(equivalent_union_type) ) if not (is_same_type...
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. ...
376,179
def save_yaml_model(model, filename, sort=False, **kwargs): obj = model_to_dict(model, sort=sort) obj["version"] = YAML_SPEC if isinstance(filename, string_types): with io.open(filename, "w") as file_handle: yaml.dump(obj, file_handle, **kwargs) else: yaml.dump(obj, file...
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...
376,180
def multiply(self, matrix): if not isinstance(matrix, DenseMatrix): raise ValueError("Only multiplication with DenseMatrix " "is supported.") j_model = self._java_matrix_wrapper.call("multiply", matrix) return RowMatrix(j_model)
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...
376,181
def verify(path): valid = False try: zf = zipfile.ZipFile(path) except (zipfile.BadZipfile, IsADirectoryError): pass else: names = sorted(zf.namelist()) names = [nn for nn in names if nn.endswith(".tif")] names = [nn fo...
Verify that `path` is a zip file with Phasics TIFF files
376,182
def get_experiment_kind(root): properties = {} if root.find().text == : properties[] = else: raise NotImplementedError(root.find().text + ) properties[] = {: , : , : } kind = getattr(root.find(), , False) if not kind: raise MissingElementError() elif kind ...
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.
376,183
def cases(self, env, data): for handler in self.handlers: env._push() data._push() try: result = handler(env, data) finally: env._pop() data._pop() if result is not None: return r...
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".
376,184
def recursive_apply(inval, func): if isinstance(inval, dict): return {k: recursive_apply(v, func) for k, v in inval.items()} elif isinstance(inval, list): return [recursive_apply(v, func) for v in inval] else: return func(inval)
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
376,185
def filter_bolts(table, header): bolts_info = [] for row in table: if row[0] == : bolts_info.append(row) return bolts_info, header
filter to keep bolts
376,186
def loadUi(self, filename, baseinstance=None): try: xui = ElementTree.parse(filename) except xml.parsers.expat.ExpatError: log.exception( % filename) return None loader = UiLoader(baseinstance) xcustomwidge...
Generate a loader to load the filename. :param filename | <str> baseinstance | <QWidget> :return <QWidget> || None
376,187
def add_subtree(cls, for_node, node, options): 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(): cls.add_subtree(for_node...
Recursively build options tree.
376,188
def _shuffle(y, labels, random_state): 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) ind[this_mask] = random_state.permutation(ind[this_mask]) ret...
Return a shuffled copy of y eventually shuffle among same labels.
376,189
def validate_pair(ob: Any) -> bool: 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?
376,190
def reload(self): if not self.id: return reloaded_object = self.__class__.find(self.id) self.set_raw( reloaded_object.raw, reloaded_object.etag )
Re-fetches the object from the API, discarding any local changes. Returns without doing anything if the object is new.
376,191
def get_image(self, image, output=): if isinstance(image, string_types): image = nb.load(image) if type(image).__module__.startswith(): if output == : return image image = image.get_data() if not type(image).__module__.startswith(): ...
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...
376,192
def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]: return util.rate_limited(max_per_hour, *args)
Rate limit a function.
376,193
def patcher(args): from jcvi.formats.bed import uniq p = OptionParser(patcher.__doc__) p.add_option("--backbone", default="OM", help="Prefix of the backbone assembly [default: %default]") p.add_option("--object", default="object", help="New object name [default: %...
%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.
376,194
def RetryUpload(self, job, job_id, error): if self.IsErrorRetryable(error): retry_count = 0 sleep_interval = config.CONFIG["BigQuery.retry_interval"] while retry_count < config.CONFIG["BigQuery.retry_max_attempts"]: time.sleep(sleep_interval.seconds) logging.info("Retrying jo...
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...
376,195
def list_files(start_path): s = u for root, dirs, files in os.walk(start_path): level = root.replace(start_path, ).count(os.sep) indent = * 4 * level s += u.format(indent, os.path.basename(root)) sub_indent = * 4 * (level + 1) for f in files: s += u.for...
tree unix command replacement.
376,196
def translate(args): transl_tables = [str(x) for x in xrange(1,25)] p = OptionParser(translate.__doc__) p.add_option("--ids", default=False, action="store_true", help="Create .ids file with the complete/partial/gaps " "label [default: %default]") p.add_option(...
%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.
376,197
def trainClassifier(cls, data, numClasses, categoricalFeaturesInfo, numTrees, featureSubsetStrategy="auto", impurity="gini", maxDepth=4, maxBins=32, seed=None): return cls._train(data, "classification", numClasses, categoricalFea...
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...
376,198
def parents(self): assert self.parent is not self if self.parent is None: return [] return [self.parent] + self.parent.parents()
return the ancestor nodes
376,199
def read_remote(self): coded_line = self.inout.read_msg() if isinstance(coded_line, bytes): coded_line = coded_line.decode("utf-8") control = coded_line[0] remote_line = coded_line[1:] return (control, remote_line)
Send a message back to the server (in contrast to the local user output channel).