Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
341,400
def ensure_dir(self, *path_parts): path = self.getpath(*path_parts) ensure_directory(path) return path
Ensures a subdirectory of the working directory. Parameters ---------- path_parts : iterable[str] The parts of the path after the working directory.
341,401
def deep_compare(self, other, settings): if not self._is_compatible_with(other): return False first, middle, last = self._compare_components(other, settings) return first and middle and last
Compares each field of the name one at a time to see if they match. Each name field has context-specific comparison logic. :param Name other: other Name for comparison :return bool: whether the two names are compatible
341,402
def truth(val, context): try: 0 + val except TypeError: lower_val = val.lower() if lower_val in TRUE: return True elif lower_val in FALSE: return False else: raise FilterError("Bad boolean value %r in %r (expected one of , or )" %...
Convert truth value in "val" to a boolean.
341,403
def run(items, run_parallel): to_process = [] extras = [] for batch, cur_items in _group_by_batches(items).items(): if _ready_for_het_analysis(cur_items): to_process.append((batch, cur_items)) else: for data in cur_items: extras.append([data]) ...
Top level entry point for calculating heterogeneity, handles organization and job distribution.
341,404
def validate(cls, mapper_spec): super(RawDatastoreInputReader, cls).validate(mapper_spec) params = _get_params(mapper_spec) entity_kind = params[cls.ENTITY_KIND_PARAM] if "." in entity_kind: logging.warning( ". detected in entity kind %s specified for reader %s." "Assuming...
Inherit docs.
341,405
def _normalize_angle(angle, range, step): while angle <= range[0]: angle += step while angle >= range[1]: angle -= step return angle
Finds an angle that matches the given one modulo step. Increments and decrements the given value with a given step. Args: range: a 2-tuple of min and max target values. step: tuning step. Returns: Normalized value within a given range.
341,406
def batch_augment(x, func, device=): with tf.device(device): return tf.map_fn(func, x)
Apply dataset augmentation to a batch of exmaples. :param x: Tensor representing a batch of examples. :param func: Callable implementing dataset augmentation, operating on a single image. :param device: String specifying which device to use.
341,407
def on_post_save(sender, **kwargs): if not invalidate: return if kwargs.get("raw", False): return if sender is MigrationRecorder.Migration: return if issubclass(sender, Model): obj = kwargs["instance"] if isinstance(obj, Model): try: ...
Expire ultracache cache keys affected by this object
341,408
def variable_length_to_fixed_length_categorical( self, left_edge=4, right_edge=4, max_length=15): cache_key = ( "fixed_length_categorical", left_edge, right_edge, max_length) if cache_key not in self.encoding_cache: fixed...
Encode variable-length sequences using a fixed-length encoding designed for preserving the anchor positions of class I peptides. The sequences must be of length at least left_edge + right_edge, and at most max_length. Parameters ---------- left_edge : in...
341,409
def db_temp_from_wb_rh(wet_bulb, rel_humid, b_press=101325): assert rel_humid == 0 or rel_humid == 100, \ humidity_ratio = humid_ratio_from_db_rh(wet_bulb, rel_humid, b_press) hr_saturation = humid_ratio_from_db_rh(wet_bulb, 100, b_press) db_temp = wet_bulb + (((hr_saturation - humidity_r...
Dry Bulb Temperature (C) and humidity_ratio at at wet_bulb (C), rel_humid (%) and Pressure b_press (Pa). Formula is only valid for rel_humid == 0 or rel_humid == 100.
341,410
def gsea_edb_parser(results_path, index=0): from bs4 import BeautifulSoup soup = BeautifulSoup(open(results_path), features=) tag = soup.findAll() term = dict(tag[index].attrs) enrich_term = term.get().split(" es_profile = term.get().split(" ") hit_ind =term.get().s...
Parse results.edb file stored under **edb** file folder. :param results_path: the .results file located inside edb folder. :param index: gene_set index of gmt database, used for iterating items. :return: enrichment_term, hit_index,nes, pval, fdr.
341,411
def compileMatchList(self): self.matchList = [] numChar = len(self.toReplace) if numChar == 0: return stop = 0 text = self.qteWidget.text() while True: start = text.find(self.toReplace, stop) if sta...
Compile the list of spans of every match.
341,412
def fit(self, x, y): train = np.vstack((np.array([self.featurize_row(row.iloc[0], row.iloc[1]) for idx, row in x.iterrows()]), np.array([self.featurize_row(row.iloc[1], ...
Train the model. Args: x_tr (pd.DataFrame): CEPC format dataframe containing the pairs y_tr (pd.DataFrame or np.ndarray): labels associated to the pairs
341,413
def discrete_gaussian_curvature_measure(mesh, points, radius): points = np.asanyarray(points, dtype=np.float64) if not util.is_shape(points, (-1, 3)): raise ValueError() nearest = mesh.kdtree.query_ball_point(points, radius) gauss_curv = [mesh.vertex_defects[vertices].sum() for vertices i...
Return the discrete gaussian curvature measure of a sphere centered at a point as detailed in 'Restricted Delaunay triangulations and normal cycle', Cohen-Steiner and Morvan. Parameters ---------- points : (n,3) float, list of points in space radius : float, the sphere radius Returns -...
341,414
def get_style_ranges(self, **kwargs): style_bits = self.get_style_bits(**kwargs) matches = (self.style & style_bits) == style_bits return self.bool_to_ranges(matches)
Return a list of start, end pairs that match the specified style
341,415
def set_qword_at_offset(self, offset, qword): return self.set_bytes_at_offset(offset, self.get_data_from_qword(qword))
Set the quad-word value at the given file offset.
341,416
def values(self): self.expired() values = [] for key in self._dict.keys(): try: value = self._dict[key].get() values.append(value) except: continue return values
Will only return the current values
341,417
def get_logger(name, level=None, fmt=): if name not in Logger.loggers: if Logger.level is None and level is None: Logger.level = level = logging.ERROR elif Logger.level is None: Logger.level = level elif level is None: ...
Return a logger. Args: name (str): name to pass to the logging module. level (int): level of logging. fmt (str): format string. Returns: logging.Logger: logger from ``logging.getLogger``.
341,418
def merge(args): p = OptionParser(merge.__doc__) opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) binfiles = args[:-1] mergedbin = args[-1] if op.exists(mergedbin): logging.error("`{0}` file exists. Remove before proceed."\ .fo...
%prog merge *.bin merged.bin Merge several count arrays into one. Overflows will be capped at uint8_max (255).
341,419
def collection_list(self, resource_id, resource_type="collection"): ret = [] cursor = self.db.cursor() if resource_type == "collection": cursor.execute( "SELECT resourceComponentId FROM ResourcesComponents WHERE parentResourceComponentId IS NULL AND resource...
Fetches a list of all resource and component IDs within the specified resource. :param long resource_id: The ID of the resource to fetch children from. :param string resource_type: Specifies whether the resource to fetch is a collection or a child element. Defaults to 'collection'. ...
341,420
def file(filename): m = hashlib.md5() with open(filename, ) as f: m.update(f.read()) result = m.hexdigest() return result
获取一个文件的 MD5 值 :param: * filename: (string) 需要进行 hash 的文件名 :return: * result: (string) 32位小写 MD5 值
341,421
def wind(self): content = self._cached_boat.get() return Wind( Bearing(content.get()), content.get(), Bearing(content.get()) )
Return the direction of the wind in degrees. :returns: wind object containing direction bearing and speed :rtype: Wind
341,422
def require_user(wa, email): cache_key = try: data = userCache[cache_key] except KeyError: data = wa.users.loadUsers() userCache[cache_key] = data return AssertUser([x for x in data if x.username == email])
Require that the user has an account
341,423
def new_mountpoint(self, name): url = posixpath.join(self.path, name) r = self._jfs.post(url, extra_headers={: }) return r
Create a new mountpoint
341,424
def materialize(self, node=None, bounds=None, callback=None, out_format=, **kwargs): kwargs.update({ "node": node, "bounds": bounds, "callback": callback, "out_format": out_format }) return self.rda._materialize(**kwargs)
Materializes images into gbdx user buckets in s3. Note: This method is only available to RDA based image classes. Args: node (str): the node in the graph to materialize bounds (list): optional bbox for cropping what gets materialized in s3 out_format (str): VECT...
341,425
def _return_result(self, done): chain_future(done, self._running_future) self.current_future = done self.current_index = self._unfinished.pop(done)
Called set the returned future's state that of the future we yielded, and set the current future for the iterator.
341,426
def _apply_BCs(self): r if in self.keys(): ind = np.isfinite(self[]) self.b[ind] = self[][ind] if in self.keys(): f = np.abs(self.A.data).mean() ind = np.isfinite(self[]) self.b[ind] = self[][ind] * f ...
r""" Applies all the boundary conditions that have been specified, by adding values to the *A* and *b* matrices.
341,427
def opHaltStatus(symbol=None, token=, version=): _raiseIfNotStr(symbol) if symbol: return _getJson( + symbol, token, version) return _getJson(, token, version)
The Exchange may suspend trading of one or more securities on IEX for operational reasons and indicates such operational halt using the Operational halt status message. IEX disseminates a full pre-market spin of Operational halt status messages indicating the operational halt status of all securities. In the s...
341,428
def checks_logs(self, log_path, url): local = "" filename = url.split("/")[-1] server = FileSize(url).server() if os.path.isfile(log_path + filename): local = FileSize(log_path + filename).local() if server != local: return True return Fal...
Checks ChangeLog.txt for changes
341,429
def _calc_entropy(data, size=None): if not data: return 0 entropy = 0 if size is None: size = len(data) data = bytes(pyvex.ffi.buffer(data, size)) for x in range(0, 256): p_x = float(data.count(x)) / size if p_x > 0: ...
Calculate the entropy of a piece of data :param data: The target data to calculate entropy on :param size: Size of the data, Optional. :return: A float
341,430
def _update_offset(self, last_message): self.request.offset_id = last_message.id if self.reverse: self.request.offset_id += 1 if isinstance(self.request, functions.messages.SearchRequest): self.req...
After making the request, update its offset with the last message.
341,431
def text(self, encoding=None, errors=): r if encoding is None: f = self.open(_textmode) try: return f.read() finally: f.close() else: f = codecs.open(self, , encoding, errors) ...
r""" Open this file, read it in, return the content as a string. This uses 'U' mode in Python 2.3 and later, so '\r\n' and '\r' are automatically translated to '\n'. Optional arguments: encoding - The Unicode encoding (or character set) of the file. If present, the conten...
341,432
def head_object(self, bucket, object_name): details = self._details( method=b"HEAD", url_context=self._url_context(bucket=bucket, object_name=object_name), ) d = self._submit(self._query_factory(details)) d.addCallback(lambda (response, body): _to_dict(re...
Retrieve object metadata only.
341,433
def get_pro_ac_for_tx_ac(self, tx_ac): rows = self._fetchall(self._queries[], [tx_ac]) try: return rows[0][] except IndexError: return None
Return the (single) associated protein accession for a given transcript accession, or None if not found.
341,434
def reinstall(self): with _LOCK: if not (self.thread.is_alive() and self.thread in _ORIGINAL__ACTIVE): self.thread = self.thread.clone(bind_delay=self.reinstall_delay) if self.should_restart: self.thread.start()
Reinstalls the manhole. Checks if the thread is running. If not, it starts it again.
341,435
def basicConfig(**kw): while len(logging.root.handlers) > 0: logging.root.removeHandler(logging.root.handlers[-1]) logging.basicConfig(**kw)
logging의 로그를 한번 호출하면 basicConfig가 안먹으므로. 기존 핸들러 삭제후 재설정. http://stackoverflow.com/questions/1943747/python-logging-before-you-run-logging-basicconfig ex) basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG) :param filename: Specifies that a FileHandler be created, using the specified filen...
341,436
def node_info(cls_or_slf, node, attrpath, attrpaths, siblings, level, value_dims): opts = None if hasattr(node, ): (lvl, lines) = (level, [(level, cls_or_slf.component_type(node))]) opts = cls_or_slf.option_info(node) elif hasattr(node, ): (lvl, lines...
Given a node, return relevant information.
341,437
def upload_server_cert(cert_name, cert_body, private_key, cert_chain=None, path=None, region=None, key=None, keyid=None, profile=None): exists = get_server_certificate(cert_name, region, key, keyid, profile) if exists: return True conn = _get_conn(region=region, key=key,...
Upload a certificate to Amazon. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_iam.upload_server_cert mycert_name crt priv_key :param cert_name: The name for the server certificate. Do not include the path in this value. :param cert_body: The contents of...
341,438
def query(self): if len(self._cauldron.ingredients()) == 0: raise BadRecipe() if not self.dirty and self._query: return self._query for extension in self.recipe_extensions: extension.add_ingredients() ...
Generates a query using the ingredients supplied by the recipe. :return: A SQLAlchemy query
341,439
def mediatype_delete(mediatypeids, **kwargs): s docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see modules docstring) :return: ID of deleted mediatype, False on failure. CLI Example: .. code-block:: bash salt zabbix.mediatype_delete...
Delete mediatype :param interfaceids: IDs of the mediatypes to delete :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring) :param _...
341,440
async def _get_usage_data(self): raw_res = await self._session.get(USAGE_URL) content = await raw_res.text() soup = BeautifulSoup(content, ) span_list = soup.find_all("span", {"class": "switchDisplay"}) if span_list is None: raise PyEboxErro...
Get data usage.
341,441
def forwards(apps, schema_editor): Movie = apps.get_model(, ) Work = apps.get_model(, ) WorkRole = apps.get_model(, ) WorkSelection = apps.get_model(, ) for m in Movie.objects.all(): work = Work.objects.create( kind=, title=m.title, title_sort=m.tit...
Change all Movie objects into Work objects, and their associated data into WorkRole and WorkSelection models, then delete the Movie.
341,442
def make_category_filter(categories, blank=True): categories = [category.strip() for category in categories] categories.sort() redundant_categories = set() prefix_candidate = None for category in categories: if prefix_candidate != None \ and category.find(prefix_candidate) == 0: redundant_cate...
Generates a dict representing a Factual filter matching any of the categories passed. The resulting filter uses $bw "begins with" operators to return all matching subcategories. Because of this, passing a top level category removes the need to pass any of its subcategories. Conversely, specifying subcategories...
341,443
def get_core(self): if self.maplesat and self.status == False: return pysolvers.maplechrono_core(self.maplesat)
Get an unsatisfiable core if the formula was previously unsatisfied.
341,444
def execute(self, input_data): md5 = input_data[][] response = requests.get(, params={:self.apikey,:md5, :1}) try: vt_output = response.json() except ValueError: return {: } output = {fi...
Execute the VTQuery worker
341,445
def path_compute( p: tcod.path.AStar, ox: int, oy: int, dx: int, dy: int ) -> bool: return bool(lib.TCOD_path_compute(p._path_c, ox, oy, dx, dy))
Find a path from (ox, oy) to (dx, dy). Return True if path is found. Args: p (AStar): An AStar instance. ox (int): Starting x position. oy (int): Starting y position. dx (int): Destination x position. dy (int): Destination y position. Returns: bool: True if a va...
341,446
def getType(self) : if self.type == CONST.COLLECTION_DOCUMENT_TYPE : return "document" elif self.type == CONST.COLLECTION_EDGE_TYPE : return "edge" else : raise ValueError("The collection is of Unknown type %s" % self.type)
returns a word describing the type of the collection (edges or ducments) instead of a number, if you prefer the number it's in self.type
341,447
def sort_by(self, metric, increasing=True): if metric[-1] != : metric += c_values = [list(x) for x in zip(*sorted(eval( + metric + ), key=lambda k_v: k_v[1]))] c_values.insert(1, [self.get_hyperparams(model_id, display=False) for model_id in c_values[0]]) if not increasing: ...
Deprecated since 2016-12-12, use grid.get_grid() instead.
341,448
def _parse_sections(morph_fd): sections = [] token_iter = _get_tokens(morph_fd) for token in token_iter: if token == : section = _parse_section(token_iter) if not _match_section(section, UNWANTED_SECTIONS): sections.append(section) return sections
returns array of all the sections that exist The format is nested lists that correspond to the s-expressions
341,449
def bootstrap_prompt(prompt_kwargs, group): prompt_kwargs = prompt_kwargs or {} defaults = { "history": InMemoryHistory(), "completer": ClickCompleter(group), "message": u"> ", } for key in defaults: default_value = defaults[key] if key not in prompt_kwargs...
Bootstrap prompt_toolkit kwargs or use user defined values. :param prompt_kwargs: The user specified prompt kwargs.
341,450
def mass_3d(self, R, Rs, rho0): Rs = float(Rs) m_3d = 4. * np.pi * rho0 * Rs**3 *(np.log((Rs + R)/Rs) - R/(Rs + R)) return m_3d
mass enclosed a 3d sphere or radius r :param r: :param Ra: :param Rs: :return:
341,451
def dispatch(self, receiver): super(ModelChangedEvent, self).dispatch(receiver) if hasattr(receiver, ): receiver._document_model_changed(self)
Dispatch handling of this event to a receiver. This method will invoke ``receiver._document_model_dhanged`` if it exists.
341,452
def _url_for_email(endpoint, base_url=None, **kw): base_url = base_url or config("MAIL_EXTERNAL_BASE_URL") _external = True if not base_url else False url = url_for(endpoint, _external=_external, **kw) if base_url and not _external: url = "%s/%s" % (base_url.strip("/"), url.lstrip("/")) ...
Create an external url_for by using a custom base_url different from the domain we are on :param endpoint: :param base_url: :param kw: :return:
341,453
def maxId(self): if len(self.model.db) == 0: return 0 return max(map(lambda obj: obj["id"], self.model.db))
int: current max id of objects
341,454
def merge(name, assemblies): assemblies = list(assemblies) merged = assemblies[0].branch(name) allsamples = set(merged.samples.keys()) for iterass in assemblies[1:]: allsamples.update(set(iterass.samples.keys())) merged._hackersonly["max_fragment_length"] =\...
Creates and returns a new Assembly object in which samples from two or more Assembly objects with matching names are 'merged'. Merging does not affect the actual files written on disk, but rather creates new Samples that are linked to multiple data files, and with stats summed.
341,455
def stop(self): for s in self._servers: s.stop() for g in self._server_greenlets: g.kill() logger.info()
Stops services
341,456
def avl_join2(t1, t2): if t1 is None and t2 is None: new_root = None elif t2 is None: new_root = t1 elif t1 is None: new_root = t2 else: new_left, last_node = avl_split_last(t1) debug = 0 if debug: EulerTourTree(root=new_left)._assert_no...
join two trees without any intermediate key Returns: Node: new_root O(log(n) + log(m)) = O(r(t1) + r(t2)) For AVL-Trees the rank r(t1) = height(t1) - 1
341,457
def _handle_unsubscribed(self, dtype, data, ts): self.log.debug("_handle_unsubscribed: %s - %s - %s", dtype, data, ts) channel_id = data.pop() chan_identifier = self.channel_directory.pop(channel_id) self.channel_directory.pop(chan_identifier) self.channel_hand...
Handles responses to unsubscribe() commands. Removes a channel id from the client. :param dtype: :param data: :param ts: :return:
341,458
def parse_args(self, arguments=None): self._args = self.parser.parse_args(arguments) return self.args
parses the arguments from command-line arguments: optional argument list to parse returns: a dictionnary containing the arguments
341,459
def get_parent(brain_or_object): if is_root(brain_or_object): return get_portal() if is_brain(brain_or_object): parent_path = get_parent_path(brain_or_object) return get_object_by_path(parent_path) return brain_or_object.aq_parent
Locate the parent object of the content/catalog brain :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: parent object :rtype: Parent content
341,460
def submit(self, target=None, task=None, args=(), kwargs=None, front=False, dispose_inputs=None): if not self.__running: raise RuntimeError("ThreadPool aincan not provide additional arguments for Jobjob is not pendingexpected Job or callable') job.print_exc = self.print_exc if fron...
Submit a new #Job to the ThreadPool. # Arguments task (function, Job): Either a function that accepts a #Job, *args* and *kwargs* or a #Job object that is in #~Job.PENDING state. target (function): A function object that accepts *args* and *kwargs*. Only if *task* is not specified. args (li...
341,461
def convert_cluster_dict_keys_to_aliases(self, cluster_dict, alias_hash): output_dict = {} directory_to_index_dict = {os.path.split(item["output_path"])[0] : key for key, item in alias_hash.iteritems()} for key, item in cluster_dict.iteritems(): c...
Parameters ---------- cluster_dict : dict dictionary stores information on pre-placement clustering alias_hash : dict Stores information on each input read file given to GraftM, the corresponding reads found within each file, and their taxonomy Return...
341,462
def _link_record(self): action = self._get_lexicon_option() identifier = self._get_lexicon_option() rdtype = self._get_lexicon_option() name = (self._fqdn_name(self._get_lexicon_option()) if self._get_lexicon_option() else None) link = self._get_provider_...
Checks restrictions for use of CNAME lookup and returns a tuple of the fully qualified record name to lookup and a boolean, if a CNAME lookup should be done or not. The fully qualified record name is empty if no record name is specified by this provider.
341,463
def read_uint(self): if self.reader.sysinfo.ProcessorArchitecture == PROCESSOR_ARCHITECTURE.AMD64: return int.from_bytes(self.read(8), byteorder = , signed = False) else: return int.from_bytes(self.read(4), byteorder = , signed = False)
Reads an integer. The size depends on the architecture. Reads a 4 byte small-endian unsinged int on 32 bit arch Reads an 8 byte small-endian unsinged int on 64 bit arch
341,464
def match_files(self, matched, unmatched): this_match = set(self.file_filter(unmatched)) matched |= this_match unmatched -= this_match
Moves all matching files from the set *unmatched* to the set *matched*. Both *matched* and *unmatched* are sets of string, the strings being unqualified file names
341,465
def prep_mlt_arrays(self): par_props = [self.pp_props,self.grid_props, self.zone_props,self.const_props, self.kl_props] par_suffixs = [self.pp_suffix,self.gr_suffix, self.zn_suffix,self.cn_suffix, self.k...
prepare multipler arrays. Copies existing model input arrays and writes generic (ones) multiplier arrays
341,466
def __set_style_sheet(self): frame_width = self.style().pixelMetric(QStyle.PM_DefaultFrameWidth) self.setStyleSheet(QString("QLineEdit {{ padding-left: {0}px; padding-right: {1}px; }}".format( self.__search_active_label.sizeHint().width( ) if self.__search_active_label....
Sets the Widget stylesheet.
341,467
def create_oracle_cx_oracle(username, password, host, port, database, **kwargs): return create_engine( _create_oracle_cx_oracle(username, password, host, port, database), **kwargs )
create an engine connected to a oracle database using cx_oracle.
341,468
def odt_to_ri(f, res, nm): r km = (2 * np.pi * nm) / res ri = nm * np.sqrt(f / km**2 + 1) negrootcoord = np.where(ri.real < 0) ri[negrootcoord] *= -1 return ri
r"""Convert the ODT object function to refractive index In :abbr:`ODT (Optical Diffraction Tomography)`, the object function is defined by the Helmholtz equation .. math:: f(\mathbf{r}) = k_\mathrm{m}^2 \left[ \left( \frac{n(\mathbf{r})}{n_\mathrm{m}} \right)^2 - 1 \righ...
341,469
def _count_files_to_amber(tumor_counts, normal_counts, work_dir, data): amber_dir = utils.safe_makedir(os.path.join(work_dir, "amber")) out_file = os.path.join(amber_dir, "%s.amber.baf" % dd.get_sample_name(data)) if not utils.file_uptodate(out_file, tumor_counts): with file_transaction(data, ...
Converts tumor and normal counts from GATK CollectAllelicCounts into Amber format.
341,470
def get_cursor_position(): it = get_char(u) sequence = consume_escape_sequence(it, next(it)) return tuple(int(x) for x in sequence[2:-1].split(u))
Write an escape sequence to ask for the current cursor position. Since the result is written on the standard input, this function should not be used if you expect that your input has been pasted, because the characters in the buffer would be read before the answer about the cursor.
341,471
def get(self, key, *, encoding=_NOTSET): return self.execute(b, key, encoding=encoding)
Get the value of a key.
341,472
def update_sis_id(self, account_id, sis_account_id): if account_id == self._canvas_account_id: raise Exception("SIS ID cannot be updated for the root account") url = ACCOUNTS_API.format(account_id) body = {"account": {"sis_account_id": sis_account_id}} return Canva...
Updates the SIS ID for the account identified by the passed account ID. https://canvas.instructure.com/doc/api/accounts.html#method.accounts.update
341,473
def write(self, data): return self._with_retry( functools.partial(self._sslobj.write, data), self.gettimeout())
write data to the ssl channel and return the # of bytes transferred
341,474
def get_info(self): return [self.display_name.encode(), self.enabled and b or b, STATE_NAMES[self.state].encode() + b, self.last_printed_line.strip()]
Return a list with all information available about this process
341,475
def right(self): return self.source.directory[self.right_sibling_id] \ if self.right_sibling_id != NOSTREAM else None
Entry is right sibling of current directory entry
341,476
def _get_support_mask(self): check_is_fitted(self, ) n_features = len(self.feature_names) mask = np.zeros(n_features, dtype=bool) mask[np.asarray(self.feat_list_idx)] = True return mask
Get the boolean mask indicating which features are selected Returns ------- support : boolean array of shape [# input features] An element is True iff its corresponding feature is selected for retention.
341,477
def parse_request(cls, jsonrpc_message): try: data = cls.json_loads(jsonrpc_message) except ValueError, err: raise errors.RPCParseError("No valid JSON. (%s)" % str(err)) if not isinstance(data, dict): raise errors.RPCInvalidRPC("No valid RPC-package....
We take apart JSON-RPC-formatted message as a string and decompose it into a dictionary object, emitting errors if parsing detects issues with the format of the message. :Returns: | [method_name, params, id] or [method_name, params] | params is a tuple/list ...
341,478
def gpg_app_get_key( blockchain_id, appname, keyname, immutable=False, key_id=None, key_hash=None, key_version=None, proxy=None, config_dir=None ): assert is_valid_appname(appname) assert is_valid_keyname(keyname) if config_dir is None: config_dir = get_config_dir() fq_key_name = "gpg.%s...
Get an app-specific GPG key. Return {'status': True, 'key_id': ..., 'key': ..., 'app_name': ...} on success return {'error': ...} on error
341,479
def _get_storage_vol(conn, pool, vol): t be found. ' pool_obj = conn.storagePoolLookupByName(pool) return pool_obj.storageVolLookupByName(vol)
Helper function getting a storage volume. Will throw a libvirtError if the pool or the volume couldn't be found.
341,480
def cleanup(self): remove = [] for handle, assoc in self.assocs.iteritems(): if assoc.getExpiresIn() == 0: remove.append(handle) for handle in remove: del self.assocs[handle] return len(remove), len(self.assocs)
Remove expired associations. @return: tuple of (removed associations, remaining associations)
341,481
def draw(self, num_reals=1, par_file = None, obs=False, enforce_bounds=None, cov=None, how="gaussian"): if par_file is not None: self.pst.parrep(par_file) how = how.lower().strip() assert how in ["gaussian","uniform"] if cov is not None: ass...
draw stochastic realizations of parameters and optionally observations, filling MonteCarlo.parensemble and optionally MonteCarlo.obsensemble. Parameters ---------- num_reals : int number of realization to generate par_file : str parameter fi...
341,482
def build_request(self): clientheaders = {} if (self.parent_url and self.parent_url.lower().startswith(HTTP_SCHEMAS)): clientheaders["Referer"] = self.parent_url kwargs = dict( method=, url=self.url, headers=clientheaders, ...
Build a prepared request object.
341,483
def cache_jobs(opts, jid, ret): serial = salt.payload.Serial(opts=opts) fn_ = os.path.join( opts[], , jid, ) jdir = os.path.dirname(fn_) if not os.path.isdir(jdir): os.makedirs(jdir) with salt.utils.files.fopen(fn_, ) as fp_: fp_.write(serial.dum...
Write job information to cache
341,484
def up(context): context.obj.find_repo_type() if context.obj.vc_name == : context.obj.call([, ]) context.obj.call([, , ]) elif context.obj.vc_name == : context.obj.call([, ])
(upload) Synchronise local repo to remote repo
341,485
def vtmlprint(*values, plain=None, strict=None, **options): print(*[vtmlrender(x, plain=plain, strict=strict) for x in values], **options)
Follow normal print() signature but look for vt100 codes for richer output.
341,486
def _flag_is_registered(self, flag_obj): flag_dict = self._flags() name = flag_obj.name if flag_dict.get(name, None) == flag_obj: return True short_name = flag_obj.short_name if (short_name is not None and flag_dict.get(short_name, None) == flag_obj): return True ...
Checks whether a Flag object is registered under long name or short name. Args: flag_obj: Flag, the Flag instance to check for. Returns: bool, True iff flag_obj is registered under long name or short name.
341,487
def token_getter(provider, token=None): session_key = provider + if token is None: token = session.get(session_key) return token
Generic token getter for all the providers
341,488
def _whoami(): username = getuser() try: if onWindows(): get_user_name = ctypes.windll.secur32.GetUserNameExW size = ctypes.pointer(ctypes.c_ulong(0)) get_user_name(3, None, size) name_buffer = ctypes.create_unicode_buffer(size.contents.value)...
Return the current operating system account as (username, fullname).
341,489
def _translate_ldm(self, oprnd1, oprnd2, oprnd3): assert oprnd1.size and oprnd3.size assert oprnd1.size == self._address_size op1_var = self._translate_src_oprnd(oprnd1) op3_var, op3_var_constrs = self._translate_dst_oprnd(oprnd3) exprs = [] for i in reversed(...
Return a formula representation of a LDM instruction.
341,490
def get_descendants(self): if self.is_leaf(): return get_result_class(self.__class__).objects.none() return self.__class__.get_tree(self).exclude(pk=self.pk)
:returns: A queryset of all the node's descendants as DFS, doesn't include the node itself
341,491
def check(ctx, meta_model_file, model_file, ignore_case): debug = ctx.obj[] check_model(meta_model_file, model_file, debug, ignore_case)
Check validity of meta-model and optionally model.
341,492
def build_callbacks(self): filepath = os.path.join(CHECKPOINT_DIR, ) checkpoint = ModelCheckpoint(filepath, monitor=, verbose=1, save_best_only=True, mode=) self.callbacks = [checkpoint]
Eventually, this should be configured, rather than hardcoded
341,493
def _parse_singlefile(self, desired_type: Type[T], file_path: str, encoding: str, logger: Logger, options: Dict[str, Dict[str, Any]]) -> T: first = self._base_parser._parse_singlefile(self._converter.from_type, file_path, encoding, ...
Implementation of AnyParser API
341,494
def score_statement(self, st, extra_evidence=None): if extra_evidence is None: extra_evidence = [] all_evidence = st.evidence + extra_evidence return self.score_evidence_list(all_evidence)
Computes the prior belief probability for an INDRA Statement. The Statement is assumed to be de-duplicated. In other words, the Statement is assumed to have a list of Evidence objects that supports it. The prior probability of the Statement is calculated based on the number of Evidences...
341,495
def site_properties(self): props = {} prop_keys = set() for site in self: prop_keys.update(site.properties.keys()) for k in prop_keys: props[k] = [site.properties.get(k, None) for site in self] return props
Returns the site properties as a dict of sequences. E.g., {"magmom": (5,-5), "charge": (-4,4)}.
341,496
def get_image_dimension(self, url): w_h = (None, None) try: if url.startswith(): url = + url data = requests.get(url).content im = Image.open(BytesIO(data)) w_h = im.size except Exception: logger.warning("Erro...
Return a tuple that contains (width, height) Pass in a url to an image and find out its size without loading the whole file If the image wxh could not be found, the tuple will contain `None` values
341,497
def flushIndexes(cls) : "drops all indexes for a class" con = RabaConnection(cls._raba_namespace) for idx in cls.getIndexes() : con.dropIndexByName(idx[1])
drops all indexes for a class
341,498
def felsensteins(binaryTree, subMatrices, ancestorProbs, leaves, alphabetSize): l = {} def upPass(binaryTree): if binaryTree.internal: i = branchUp(binaryTree.left) j = branchUp(binaryTree.right) k = multiplyWV(i, j, alphabetSize) l[binaryTree.traver...
calculates the un-normalised probabilties of each non-gap residue position
341,499
def get_true_argspec(method): argspec = inspect.getargspec(method) args = argspec[0] if args and args[0] == : return argspec if hasattr(method, ): method = method.__func__ if not hasattr(method, ) or method.__closure__ is None: raise DecoratorCompatibilityError clo...
Drills through layers of decorators attempting to locate the actual argspec for the method.