Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
19,400
def get_primary_contributors(self, permitted=True): primary_credits = [] credits = self.credits.exclude(role=None).order_by() if credits: primary_role = credits[0].role for credit in credits: if credit.role == primary_role: pri...
Returns a list of primary contributors, with primary being defined as those contributors that have the highest role assigned(in terms of priority). When permitted is set to True only permitted contributors are returned.
19,401
def merge(move, output_dir, sources): jsons = [] for s in sources: filename = "%s.json" % os.path.split(s)[1] jsons += [os.path.join(s, filename)] reference_config = TinyDB(jsons[0]).table() for j in jsons[1:]: for i, j in zip(reference_config.all(), TinyDB(j).tab...
Merge multiple results folder into one, by copying the results over to a new folder. For a faster operation (which on the other hand destroys the campaign data if interrupted), the move option can be used to directly move results to the new folder.
19,402
def process_request(self, request): global _urlconf_pages page_list = list( Page.objects.exclude(glitter_app_name=).values_list(, ).order_by() ) with _urlconf_lock: if page_list != _urlconf_pages: glitter_urls = if glitt...
Reloads glitter URL patterns if page URLs change. Avoids having to restart the server to recreate the glitter URLs being used by Django.
19,403
def popitem(self, dict_name, priority_min=, priority_max=): if self._session_lock_identifier is None: raise ProgrammerError() conn = redis.Redis(connection_pool=self.pool) script = conn.register_script() dict_name = self._namespace(dict_name) key_value = scri...
Select an item and remove it. The item comes from `dict_name`, and has the lowest score at least `priority_min` and at most `priority_max`. If some item is found, remove it from `dict_name` and return it. This runs as a single atomic operation but still requires a session lock...
19,404
def get (self, feature): if type(feature) == type([]): feature = feature[0] if not isinstance(feature, b2.build.feature.Feature): feature = b2.build.feature.get(feature) assert isinstance(feature, b2.build.feature.Feature) if self.feature_map_ is None: ...
Returns all values of 'feature'.
19,405
def get_stp_mst_detail_output_msti_port_interface_id(self, **kwargs): config = ET.Element("config") get_stp_mst_detail = ET.Element("get_stp_mst_detail") config = get_stp_mst_detail output = ET.SubElement(get_stp_mst_detail, "output") msti = ET.SubElement(output, "msti")...
Auto Generated Code
19,406
def format_signed(feature, formatter=None, **kwargs ): txt = if feature[] > 0 else name = feature[] if formatter is not None: name = formatter(name, **kwargs) return .format(txt, name)
Format unhashed feature with sign. >>> format_signed({'name': 'foo', 'sign': 1}) 'foo' >>> format_signed({'name': 'foo', 'sign': -1}) '(-)foo' >>> format_signed({'name': ' foo', 'sign': -1}, lambda x: '"{}"'.format(x)) '(-)" foo"'
19,407
def _releaseModifiers(self, modifiers, globally=False): modifiers.reverse() modFlags = self._pressModifiers(modifiers, pressed=False, globally=globally) return modFlags
Release given modifiers (provided in list form). Parameters: modifiers list Returns: None
19,408
def default_config(): kernel:Linux if salt.utils.systemd.booted(__context__) \ and salt.utils.systemd.version(__context__) >= 207: return return
Linux hosts using systemd 207 or later ignore ``/etc/sysctl.conf`` and only load from ``/etc/sysctl.d/*.conf``. This function will do the proper checks and return a default config file which will be valid for the Minion. Hosts running systemd >= 207 will use ``/etc/sysctl.d/99-salt.conf``. CLI Example:...
19,409
def post(self): alllastfirstformat data = request.get_json() options, sql_raw = data.get(), data.get() if options == : sql_formmated = sqlparse.format(sql_raw, keyword_case=, reindent=True) return build_response(dict(data=sql_formmated, code=200)) ...
return executed sql result to client. post data format: {"options": ['all', 'last', 'first', 'format'], "sql_raw": "raw sql ..."} Returns: sql result.
19,410
def exclude_samples(in_file, out_file, to_exclude, ref_file, config, filters=None): include, exclude = _get_exclude_samples(in_file, to_exclude) if len(exclude) == 0: out_file = in_file elif not utils.file_exists(out_file): with file_transaction(config, out_file) as tx_out_file: ...
Exclude specific samples from an input VCF file.
19,411
def ocr(img, mrz_mode=True, extra_cmdline_params=): input_file_name = % _tempnam() output_file_name_base = % _tempnam() output_file_name = "%s.txt" % output_file_name_base try: if str(img.dtype).startswith() and np.nanmin(img) >= 0 and np.nanmax(img) <= 1: img = img.a...
Runs Tesseract on a given image. Writes an intermediate tempfile and then runs the tesseract command on the image. This is a simplified modification of image_to_string from PyTesseract, which is adapted to SKImage rather than PIL. In principle we could have reimplemented it just as well - there are some appar...
19,412
def timer(logger=None, level=logging.INFO, fmt="function %(function_name)s execution time: %(execution_time).3f", *func_or_func_args, **timer_kwargs): } if logger: logger.log( level, fmt % context, ...
Function decorator displaying the function execution time All kwargs are the arguments taken by the Timer class constructor.
19,413
def write_id (self): self.writeln(u"<tr>") self.writeln(u % self.part("id")) self.write(u"<td>%d</td></tr>" % self.stats.number)
Write ID for current URL.
19,414
def load(json_src, save=False): if isinstance(json_src, six.string_types): json_src = json_lib.loads(json_src) if isinstance(json_src, list): return [getattr(objects, obj[]).load(obj, save) for obj in json_src] return getattr(objects, json_src[]).load(json_src, save)
Load any json serialized cinderlib object.
19,415
def _reduce_logsumexp(input_tensor, axis=None, keepdims=False, name=None): try: return scipy_special.logsumexp( input_tensor, axis=_astuple(axis), keepdims=keepdims) except NotImplementedError: m = _max_mask_non_finite(input_tensor, axis=axis, keepdims=True) y = input_tensor - m ...
Computes `log(sum(exp(input_tensor))) along the specified axis.
19,416
def comic_archive_compress(args): try: filename, old_format, settings, nag_about_gifs = args Settings.update(settings) tmp_dir = _get_archive_tmp_dir(filename) new_filename = files.replace_ext(filename, _NEW_ARCHIVE_SUFFIX) _comic_archive_write_zipfile(new_fil...
Called back by every optimization inside a comic archive. When they're all done it creates the new archive and cleans up.
19,417
def remove_defaults(self, *args): for arg in args: if arg not in self.defaults: raise KeyError(.format(arg)) return self.discard_defaults(*args)
cplan.remove_defaults(a, b...) yields a new caclulation plan identical to cplan except without default values for any of the given parameter names. An exception is raised if any default value given is not found in cplan.
19,418
def _parse_http_header(h): values = [] if not in h: for value in h.split(): parts = value.split() values.append((parts[0].strip(), {})) for attr in parts[1:]: name, value = attr.split(, 1) values[-1][1][name.strip()] = value.str...
Parses a typical multi-valued and parametrised HTTP header (e.g. Accept headers) and returns a list of values and parameters. For non-standard or broken input, this implementation may return partial results. :param h: A header string (e.g. ``text/html,text/plain;q=0.9,*/*;q=0.8``) :return: List of (valu...
19,419
def convert_float_to_two_registers(floatValue): myList = list() s = bytearray(struct.pack(, floatValue) ) myList.append(s[0] | (s[1]<<8)) myList.append(s[2] | (s[3]<<8)) return myList
Convert 32 Bit real Value to two 16 Bit Value to send as Modbus Registers floatValue: Value to be converted return: 16 Bit Register values int[]
19,420
def rollup(self, freq, **kwargs): return self.ret_rels().resample(freq, **kwargs).prod() - 1.0
Downsample `self` through geometric linking. Parameters ---------- freq : {'D', 'W', 'M', 'Q', 'A'} The frequency of the result. **kwargs Passed to `self.resample()`. Returns ------- TSeries Example ------- # Deri...
19,421
def get_task_ops(task_type=TaskType.ALG_CTRL): try: return LearnToExecuteState.TASK_TYPE_OPS[task_type] except KeyError: raise KeyError("Bad task_type , check config." % task_type)
Returns an operations list based on the specified task index. Args: task_type: indicates the task type used. Returns: List of the eligible ops.
19,422
def player_stats(game_id): box_score = mlbgame.data.get_box_score(game_id) box_score_tree = etree.parse(box_score).getroot() pitching = box_score_tree.findall() batting = box_score_tree.findall() pitching_info = __player_stats_info(pitching, ) batting_info = __player_stats_in...
Return dictionary of individual stats of a game with matching id. The additional pitching/batting is mostly the same stats, except it contains some useful stats such as groundouts/flyouts per pitcher (go/ao). MLB decided to have two box score files, thus we return the data from both.
19,423
def load_from_stream(self, group): self._unpack_attrs(group.atts) self.name = group.name for dim in group.dims: new_dim = Dimension(self, dim.name) self.dimensions[dim.name] = new_dim new_dim.load_from_stream(dim) for var in group.vars: ...
Load a Group from an NCStream object.
19,424
def require(self, entity_type, attribute_name=None): if not attribute_name: attribute_name = entity_type self.requires += [(entity_type, attribute_name)] return self
The intent parser should require an entity of the provided type. Args: entity_type(str): an entity type attribute_name(str): the name of the attribute on the parsed intent. Defaults to match entity_type. Returns: self: to continue modifications.
19,425
def rpc_get_all_names( self, offset, count, **con_info ): if not check_offset(offset): return {: , : 400} if not check_count(count, 100): return {: , : 400} db = get_db_state(self.working_dir) num_domains = db.get_num_names() if num_domains > of...
Get all unexpired names, paginated Return {'status': true, 'names': [...]} on success Return {'error': ...} on error
19,426
def _add_unitary_two(self, gate, qubit0, qubit1): gate_tensor = np.reshape(np.array(gate, dtype=complex), 4 * [2]) indexes = einsum_matmul_index([qubit0, qubit1], self._number_of_qubits) self._unitary = np.einsum(indexes, gate_tensor, self._unitary, ...
Apply a two-qubit unitary matrix. Args: gate (matrix_like): a the two-qubit gate matrix qubit0 (int): gate qubit-0 qubit1 (int): gate qubit-1
19,427
def output_influx(data): for contract in data: yesterday_data = data[contract][] del data[contract][] out = "pyhydroquebec,contract=" + contract + " " for index, key in enumerate(data[contract]): if index != 0: out = out + "," ...
Print data using influxDB format.
19,428
def getSubjectObjectsByPredicate(self, predicate): return sorted( set( [ (str(s), str(o)) for s, o in self.subject_objects(rdflib.term.URIRef(predicate)) ] ) )
Args: predicate : str Predicate for which to return subject, object tuples. Returns: list of subject, object tuples: All subject/objects with ``predicate``. Notes: Equivalent SPARQL: .. highlight: sql :: SELECT DISTINCT ?s ?o WHERE {{ ?s {0} ...
19,429
def to_nnf(self): node = self.node.to_nnf() if node is self.node: return self else: return _expr(node)
Return an equivalent expression is negation normal form.
19,430
def fit( self, df, duration_col, event_col=None, ancillary_df=None, show_progress=False, timeline=None, weights_col=None, robust=False, initial_point=None, entry_col=None, ): self.duration_col = duration_col ...
Fit the accelerated failure time model to a right-censored dataset. Parameters ---------- df: DataFrame a Pandas DataFrame with necessary columns `duration_col` and `event_col` (see below), covariates columns, and special columns (weights). `duration_col` ref...
19,431
def _validate_inputs(self, inputdict): try: parameters = inputdict.pop(self.get_linkname()) except KeyError: raise InputValidationError("No parameters specified for this " "calculation") if not isinstance(parameters...
Validate input links.
19,432
def matchToString(aaMatch, read1, read2, indent=, offsets=None): match = aaMatch[] matchCount = match[] gapMismatchCount = match[] gapGapMismatchCount = match[] nonGapMismatchCount = match[] if offsets: len1 = len2 = len(offsets) else: len1, len2 = map(len, (read1, read...
Format amino acid sequence match as a string. @param aaMatch: A C{dict} returned by C{compareAaReads}. @param read1: A C{Read} instance or an instance of one of its subclasses. @param read2: A C{Read} instance or an instance of one of its subclasses. @param indent: A C{str} to indent all returned lines...
19,433
def get_parameter(name, withdecryption=False, resp_json=False, region=None, key=None, keyid=None, profile=None): conn = __utils__[](, region=region, key=key, keyid=keyid, profile=profile) try: resp = conn.get_parameter(Name=name, WithDecryption=withdecryption) except conn.exceptions.ParameterNo...
Retrives a parameter from SSM Parameter Store .. versionadded:: Neon .. code-block:: text salt-call boto_ssm.get_parameter test-param withdescription=True
19,434
def eigh_robust(a, b=None, eigvals=None, eigvals_only=False, overwrite_a=False, overwrite_b=False, turbo=True, check_finite=True): kwargs = dict(eigvals=eigvals, eigvals_only=eigvals_only, turbo=turbo, check_finite=check_finite, overwrite_a=ov...
Robustly solve the Hermitian generalized eigenvalue problem This function robustly solves the Hermetian generalized eigenvalue problem ``A v = lambda B v`` in the case that B is not strictly positive definite. When B is strictly positive-definite, the result is equivalent to scipy.linalg.eigh() within ...
19,435
def get_tile_info(tile, time, aws_index=None, all_tiles=False): start_date, end_date = parse_time_interval(time) candidates = [] for tile_info in search_iter(start_date=start_date, end_date=end_date): path_props = tile_info[][].split() this_tile = .join(path_props[1: 4]) this_a...
Get basic information about image tile :param tile: tile name (e.g. ``'T10UEV'``) :type tile: str :param time: A single date or a time interval, times have to be in ISO 8601 string :type time: str or (str, str) :param aws_index: index of tile on AWS :type aws_index: int or None :param all_t...
19,436
def authenticated_user(self, auth): response = self.get("/user", auth=auth) return GogsUser.from_json(response.json())
Returns the user authenticated by ``auth`` :param auth.Authentication auth: authentication for user to retrieve :return: user authenticated by the provided authentication :rtype: GogsUser :raises NetworkFailure: if there is an error communicating with the server :raises ApiFail...
19,437
def _add_raster_layer(self, raster_layer, layer_name, save_style=False): if not self.is_writable(): return False, output = QFileInfo(self.uri.filePath(layer_name + )) source = QFileInfo(raster_layer.source()) if source.exists() and source.suffix() in [, ]: ...
Add a raster layer to the folder. :param raster_layer: The layer to add. :type raster_layer: QgsRasterLayer :param layer_name: The name of the layer in the datastore. :type layer_name: str :param save_style: If we have to save a QML too. Default to False. :type save_st...
19,438
def show_args(): * mapping = {: {}, : {}} for flag, arg in option_toggles.items(): mapping[][flag] = arg for option, arg in option_flags.items(): mapping[][option] = arg return mapping
Show which arguments map to which flags and options. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' logadm.show_args
19,439
def update(self, instance, oldValue, newValue): self.__set__(instance, self.__get__(instance, None) + newValue - (oldValue or 0))
Updates the aggregate based on a change in the child value.
19,440
async def create( cls, node: Union[Node, str], cache_device: Union[BlockDevice, Partition]): params = {} if isinstance(node, str): params[] = node elif isinstance(node, Node): params[] = node.system_id else: raise TypeE...
Create a BcacheCacheSet on a Node. :param node: Node to create the interface on. :type node: `Node` or `str` :param cache_device: Block device or partition to create the cache set on. :type cache_device: `BlockDevice` or `Partition`
19,441
def _set_history_control_entry(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("history_control_index",history_control_entry.history_control_entry, yang_name="history-control-entry", rest_name="history", parent=self, is_container=, user_o...
Setter method for history_control_entry, mapped from YANG variable /interface/fortygigabitethernet/rmon/collection/history_control_entry (list) If this variable is read-only (config: false) in the source YANG file, then _set_history_control_entry is considered as a private method. Backends looking to popula...
19,442
def setData(self, index, value, role=Qt.EditRole): if role != Qt.CheckStateRole and role != Qt.EditRole: return False treeItem = self.getItem(index, altItem=self.invisibleRootItem) try: result = self.setItemData(treeItem, index.column(), value, role=role) ...
Sets the role data for the item at index to value. Returns true if successful; otherwise returns false. The dataChanged and sigItemChanged signals will be emitted if the data was successfully set. Descendants should typically override setItemData function instead of set...
19,443
def remove_prefix(self, prefix): if prefix not in self.__prefix_map: return ni = self.__lookup_prefix(prefix) ni.prefixes.discard(prefix) del self.__prefix_map[prefix] if ni.preferred_prefix == prefix: ni.preferred_prefix = next(iter(ni...
Removes prefix from this set. This is a no-op if the prefix doesn't exist in it.
19,444
def otp(scope, password, seed, seqs): return [crypt.otp(password[0], seed[0], int(seq)) for seq in seqs]
Calculates a one-time password hash using the given password, seed, and sequence number and returns it. Uses the md4/sixword algorithm as supported by TACACS+ servers. :type password: string :param password: A password. :type seed: string :param seed: A username. :type seqs: int :par...
19,445
def from_xml(xml): parsed = xml if not isinstance(xml, MARCXMLRecord): parsed = MARCXMLRecord(str(xml)) if "DEL" in parsed.datafields: raise DocumentNotFoundException("Document was deleted.") return EPeriodical( ur...
Convert :class:`.MARCXMLRecord` object to :class:`.EPublication` namedtuple. Args: xml (str/MARCXMLRecord): MARC XML which will be converted to EPublication. In case of str, ``<record>`` tag is required. Returns: structure: :class:`.EPublication` namedtu...
19,446
def get_method_analysis(self, method): class_analysis = self.get_class_analysis(method.get_class_name()) if class_analysis: return class_analysis.get_method_analysis(method) return None
Returns the crossreferencing object for a given Method. Beware: the similar named function :meth:`~get_method()` will return a :class:`MethodAnalysis` object, while this function returns a :class:`MethodClassAnalysis` object! This Method will only work after a run of :meth:`~create_xref()` ...
19,447
def getInterval(self): items = ( ("", _(u"Not set")), ("1", _(u"daily")), ("7", _(u"weekly")), ("30", _(u"monthly")), ("90", _(u"quarterly")), ("180", _(u"biannually")), ("365", _(u"yearly")), ) return D...
Vocabulary of date intervals to calculate the "To" field date based from the "From" field date.
19,448
def startLogin(): flask.session["state"] = oic.oauth2.rndstr(SECRET_KEY_LENGTH) flask.session["nonce"] = oic.oauth2.rndstr(SECRET_KEY_LENGTH) args = { "client_id": app.oidcClient.client_id, "response_type": "code", "scope": ["openid", "profile"], "nonce": flask.session["...
If we are not logged in, this generates the redirect URL to the OIDC provider and returns the redirect response :return: A redirect response to the OIDC provider
19,449
def shakespeare(chunk_size): file_name = maybe_download(, ) with open(file_name) as f: shakespeare_full = f.read() length = (len(shakespeare_full) // chunk_size) * chunk_size if length < len(shakespeare_full): shakespeare_full = shakespeare_full[:length] arr = np.ar...
Downloads Shakespeare, converts it into ASCII codes and chunks it. Args: chunk_size: The dataset is broken down so that it is shaped into batches x chunk_size. Returns: A numpy array of ASCII codes shaped into batches x chunk_size.
19,450
def get_needed_fieldnames(arr, names): fieldnames = set([]) names = list(parsed_names & (set(dir(arr)) | set(arr.fieldnames))) for name in names: if name in arr.fieldnames: fieldnames.update([name]) else: t...
Given a FieldArray-like array and a list of names, determines what fields are needed from the array so that using the names does not result in an error. Parameters ---------- arr : instance of a FieldArray or similar The array from which to determine what fields to get. names : (list of...
19,451
def input_file(filename): if excluded(filename) or not filename_match(filename): return {} if options.verbose: message( + filename) options.counters[] = options.counters.get(, 0) + 1 errors = Checker(filename).check_all() if options.testsuite and not errors: message("%s:...
Run all checks on a Python source file.
19,452
def extract(dump_files, extractors=ALL_EXTRACTORS): def process_dump(dump, path): for page in dump: if page.namespace != 0: continue else: for cite in extract_cite_history(page, extractors): yield cite return mwxml.map(process_d...
Extracts cites from a set of `dump_files`. :Parameters: dump_files : str | `file` A set of files MediaWiki XML dump files (expects: pages-meta-history) extractors : `list`(`extractor`) A list of extractors to apply to the text :Returns: `iterable` --...
19,453
def handle_aliases_in_calls(name, import_alias_mapping): for key, val in import_alias_mapping.items(): if name == key or \ name.startswith(key + ): return name.replace(key, val) return None
Returns either None or the handled alias. Used in add_module.
19,454
def on_timer(self): try: self.flush() except Exception as e: log.exception(, e) self._set_timer()
Executes flush(). Ignores any errors to make sure one exception doesn't halt the whole flushing process.
19,455
def map_val(dest, src, key, default=None, src_key=None): if not src_key: src_key = key if src_key in src: dest[key] = src[src_key] else: if default is not None: dest[key] = default
Will ensure a dict has values sourced from either another dict or based on the provided default
19,456
def logout_service_description(self): label = + self.name if (self.auth_type): label = label + + self.auth_type + return({"@id": self.logout_uri, "profile": self.profile_base + , "label": label})
Logout service description.
19,457
def rar3_s2k(psw, salt): if not isinstance(psw, unicode): psw = psw.decode() seed = bytearray(psw.encode() + salt) h = Rar3Sha1(rarbug=True) iv = EMPTY for i in range(16): for j in range(0x4000): cnt = S_LONG.pack(i * 0x4000 + j) h.update(seed) ...
String-to-key hash for RAR3.
19,458
def to_string(cls, error_code): if error_code == cls.ILLEGAL_COMMAND: return return super(JLinkEraseErrors, cls).to_string(error_code)
Returns the string message for the given ``error_code``. Args: cls (JLinkEraseErrors): the ``JLinkEraseErrors`` class error_code (int): error code to convert Returns: An error string corresponding to the error code. Raises: ValueError: if the error code...
19,459
def verify_directory(verbose=True, max_size_mb=50): ok = True mb_to_bytes = 1000 * 1000 expected_files = ["config.txt", "experiment.py"] for f in expected_files: if os.path.exists(f): log("✓ {} is PRESENT".format(f), chevrons=False, verbose=verbose) else: ...
Ensure that the current directory looks like a Dallinger experiment, and does not appear to have unintended contents that will be copied on deployment.
19,460
def add_key_val(keyname, keyval, keytype, filename, extnum): funtype = {: int, : float, : str, : bool} if keytype not in funtype: raise ValueError(, keytype) with fits.open(filename, "update") as hdulist: hdulist[extnum].header[keyname] = funtype[keytype](keyval) print( + keyna...
Add/replace FITS key Add/replace the key keyname with value keyval of type keytype in filename. Parameters: ---------- keyname : str FITS Keyword name. keyval : str FITS keyword value. keytype: str FITS keyword type: int, float, str or bool. filaname : str F...
19,461
def present(name, password, permission): ret = {: name, : True, : {}, : } users = __salt__[]() if __opts__[]: if name in users: ret[] = .format(name) else: ret[] = .format(name) ret[] = {name: } return ret ...
Ensure the user exists on the Dell DRAC name: The users username password The password used to authenticate permission The permissions that should be assigned to a user
19,462
def confirm_authorization_request(self): server = self.server uri, http_method, body, headers = extract_params() try: realms, credentials = server.get_realms_and_credentials( uri, http_method=http_method, body=body, headers=headers ) ...
When consumer confirm the authrozation.
19,463
def merge(self, other): if not other: return Recipe(self.recipe) if isinstance(other, basestring): return self.merge(Recipe(other)) if not other.recipe: return Recipe(self.recipe) if not self.recipe: ...
Merge two recipes together, returning a single recipe containing all nodes. Note: This does NOT yet return a minimal recipe. :param other: A Recipe object that should be merged with the current Recipe object. :return: A new Recipe object containing information from ...
19,464
def _ppf(self, q, left, right, cache): if isinstance(left, Dist) and left in cache: left = cache[left] if isinstance(right, Dist) and right in cache: right = cache[right] if isinstance(left, Dist): if isinstance(right, Dist): raise St...
Point percentile function. Example: >>> print(chaospy.Uniform().inv([0.1, 0.2, 0.9])) [0.1 0.2 0.9] >>> print(chaospy.Trunc(chaospy.Uniform(), 0.4).inv([0.1, 0.2, 0.9])) [0.04 0.08 0.36] >>> print(chaospy.Trunc(0.6, chaospy.Uniform()).inv([0.1, 0.2, 0...
19,465
def resample_waveforms(Y_dict): for key in Y_dict.keys(): Y_dict[key] = signal.decimate(Y_dict[key], 4, ftype=) metadata = {} metadata["fs"] = 4096. metadata["T"] = 1. metadata["source distance"] = 10. return Y_dict, metadata
INPUT: - Dictionary of waveforms loaded from text file - ALSO, Dictionary of timeseries indexed by name OUTPUT: - Y_dict: resampled, normalized waveforms, ready for FFT - new parameters: + fs = 4096 + time durati...
19,466
def substitute_infinitives_as_subjects(sent_str): sent_doc = textacy.Doc(sent_str, lang=) inf_pattern = r infinitives = textacy.extract.pos_regex_matches(sent_doc, inf_pattern) inf_subjs = [] for inf in infinitives: if inf[0].text.lower() != : continue if ( no...
If an infinitive is used as a subject, substitute the gerund.
19,467
def print_help(self, script_name: str): textWidth = max(60, shutil.get_terminal_size((80, 20)).columns) if len(script_name) > 20: print(f) print( ) else: print( f ) print( ...
print a help message from the script
19,468
def run_nose(self, params): thread.set_index(params.thread_index) log.debug("[%s] Starting nose iterations: %s", params.worker_index, params) assert isinstance(params.tests, list) end_time = self.params.ramp_up + self.params.hold_for end_time += time.time() if ...
:type params: Params
19,469
def modify_no_rollback(self, dn: str, mod_list: dict): _debug("modify_no_rollback", self, dn, mod_list) result = self._do_with_retry(lambda obj: obj.modify_s(dn, mod_list)) _debug("--") return result
Modify a DN in the LDAP database; See ldap module. Doesn't return a result if transactions enabled.
19,470
def windowed_df(pos, ac1, ac2, size=None, start=None, stop=None, step=None, windows=None, is_accessible=None, fill=np.nan): pos = SortedIndex(pos, copy=False) is_accessible = asarray_ndim(is_accessible, 1, allow_none=True) loc_df = locate_fixed_differences(ac1, ac2) ...
Calculate the density of fixed differences between two populations in windows over a single chromosome/contig. Parameters ---------- pos : array_like, int, shape (n_items,) Variant positions, using 1-based coordinates, in ascending order. ac1 : array_like, int, shape (n_variants, n_alleles...
19,471
def get_data_matches(text, delim_pos, dxproj, folderpath, classname=None, typespec=None, visibility=None): unescaped_text = text[delim_pos + 1:] if visibility is None: if text != and delim_pos != len(text) - 1: visibility = "either" else: ...
:param text: String to be tab-completed; still in escaped form :type text: string :param delim_pos: index of last unescaped "/" or ":" in text :type delim_pos: int :param dxproj: DXProject handler to use :type dxproj: DXProject :param folderpath: Unescaped path in which to search for data object...
19,472
def sample_id(self, lon): if self.grid == : sample = np.rint(float(self.SAMPLE_PROJECTION_OFFSET) + 1.0 + (lon * np.pi / 180.0 - float(self.CENTER_LONGITUDE)) * self.A_AXIS_RADIUS * np.cos(self.CENTER_LAT...
Return the corresponding sample Args: lon (int): longidute in degree Returns: Correponding sample
19,473
def csi(self, capname, *args): value = curses.tigetstr(capname) if value is None: return b else: return curses.tparm(value, *args)
Return the escape sequence for the selected Control Sequence.
19,474
def find_best_question(X, y, criterion): measure_impurity = gini_impurity if criterion == "gini" else entropy current_impurity = measure_impurity(y) best_info_gain = 0 best_question = None for feature_n in range(X.shape[1]): for value in set(X[:, feature_n]): q = Ques...
Find the best question to ask by iterating over every feature / value and calculating the information gain.
19,475
def get_cpu_props(cls, family, arch=): cpus = cls.get_cpus_by_arch(arch) try: return cpus.xpath(.format(family))[0] except IndexError: raise LagoException(.format(family))
Get CPU info XML Args: family(str): CPU family arch(str): CPU arch Returns: lxml.etree.Element: CPU xml Raises: :exc:`~LagoException`: If no such CPU family exists
19,476
def wetdays(pr, thresh=, freq=): r thresh = utils.convert_units_to(thresh, pr, ) wd = (pr >= thresh) * 1 return wd.resample(time=freq).sum(dim=)
r"""Wet days Return the total number of days during period with precipitation over threshold. Parameters ---------- pr : xarray.DataArray Daily precipitation [mm] thresh : str Precipitation value over which a day is considered wet. Default: '1 mm/day'. freq : str, optional Re...
19,477
def from_connection_string(cls, conn_str, *, loop=None, **kwargs): address, policy, key, _ = parse_conn_str(conn_str) parsed_namespace = urlparse(address) namespace, _, base = parsed_namespace.hostname.partition() return cls( service_namespace=namespace, ...
Create a Service Bus client from a connection string. :param conn_str: The connection string. :type conn_str: str Example: .. literalinclude:: ../examples/async_examples/test_examples_async.py :start-after: [START create_async_servicebus_client_connstr] ...
19,478
def ensure_benchmark_data(symbol, first_date, last_date, now, trading_day, environ=None): filename = get_benchmark_filename(symbol) data = _load_cached_data(filename, first_date, last_date, now, , environ) if data is not None: return data ...
Ensure we have benchmark data for `symbol` from `first_date` to `last_date` Parameters ---------- symbol : str The symbol for the benchmark to load. first_date : pd.Timestamp First required date for the cache. last_date : pd.Timestamp Last required date for the cache. no...
19,479
def remove_observing_method(self, prop_names, method): for prop_name in prop_names: if prop_name in self.__PROP_TO_METHS: self.__PROP_TO_METHS[prop_name].remove(method) del self.__PAT_METH_TO_KWARGS[(prop_name, method)] elif metho...
Remove dynamic notifications. *method* a callable that was registered with :meth:`observe`. *prop_names* a sequence of strings. This need not correspond to any one `observe` call. .. note:: This can revert even the effects of decorator `observe` at runtime. Don'...
19,480
def send_message(msg: ) -> Optional[]: global middlewares, master, slaves if msg is None: return for i in middlewares: m = i.process_message(msg) if m is None: return None assert m is not None msg = m msg.verify() if msg.deli...
Deliver a message to the destination channel. Args: msg (EFBMsg): The message Returns: The message sent by the destination channel, includes the updated message ID from there. Returns ``None`` if the message is not sent.
19,481
def load_key(self, key_path, password): try: return paramiko.RSAKey.from_private_key_file(key_path) except PasswordRequiredException as ex: return paramiko.RSAKey.from_private_key_file(key_path, password=password)
Creates paramiko rsa key :type key_path: str :param key_path: path to rsa key :type password: str :param password: password to try if rsa key is encrypted
19,482
def makeRequests(callable_, args_list, callback=None, exc_callback=_handle_thread_exception): requests = [] for item in args_list: if isinstance(item, tuple): requests.append( WorkRequest(callable_, item[0], item[1], callback=callback, ...
Create several work requests for same callable with different arguments. Convenience function for creating several work requests for the same callable where each invocation of the callable receives different values for its arguments. ``args_list`` contains the parameters for each invocation of callabl...
19,483
def set_cookie(response, key, value, max_age): expires = datetime.strftime( datetime.utcnow() + timedelta(seconds=max_age), "%a, %d-%b-%Y %H:%M:%S GMT" ) response.set_cookie( key, value, max_age=max_age, expires=expires, domain=settings.SESSION_CO...
Set the cookie ``key`` on ``response`` with value ``value`` valid for ``max_age`` secondes :param django.http.HttpResponse response: a django response where to set the cookie :param unicode key: the cookie key :param unicode value: the cookie value :param int max_age: the maximum validi...
19,484
def animate(func: types.AnyFunction = None, *, animation: types.AnimationGenerator = _default_animation(), step: float = 0.1) -> types.AnyFunction: if callable(func): return _animate_no_kwargs(func, animation, step) elif func is None: return _animate_with...
Wrapper function for the _Animate wrapper class. Args: func: A function to run while animation is showing. animation: An AnimationGenerator that yields animation frames. step: Approximate timestep (in seconds) between frames. Returns: An animated version of func if func is n...
19,485
def parse(cls, filepath, filecontent, parser): try: objects = parser.parse(filepath, filecontent) except Exception as e: raise MappingError(.format(filepath, e)) objects_by_name = {} for obj in objects: if not Serializable.is_serializable(obj): raise UnaddressableObjectErr...
Parses a source for addressable Serializable objects. No matter the parser used, the parsed and mapped addressable objects are all 'thin'; ie: any objects they point to in other namespaces or even in the same namespace but from a seperate source are left as unresolved pointers. :param string filepath:...
19,486
def set_creation_date(self, p_date=date.today()): self.fields[] = p_date self.src = re.sub( r, lambda m: u"{}{} {}".format(m.group(1) or , p_date.isoformat(), m.group(3)), self.src)
Sets the creation date of a todo. Should be passed a date object.
19,487
def stepper_request_library_version(self): data = [self.STEPPER_LIBRARY_VERSION] self._command_handler.send_sysex(self._command_handler.STEPPER_DATA, data)
Request the stepper library version from the Arduino. To retrieve the version after this command is called, call get_stepper_version
19,488
def help_text(cls): docs = [cmd_func.__doc__ for cmd_func in cls.commands.values()]
Return a slack-formatted list of commands with their usage.
19,489
def mols_from_file(path, no_halt=True, assign_descriptors=True): with open(path, ) as f: fd = (tx.decode(line) for line in f) for c in mol_supplier(fd, no_halt, assign_descriptors): yield c
Compound supplier from CTAB text file (.mol, .sdf)
19,490
def decode_consumermetadata_response(cls, data): (correlation_id, error_code, node_id), cur = \ relative_unpack(, data, 0) host, cur = read_short_ascii(data, cur) (port,), cur = relative_unpack(, data, cur) return ConsumerMetadataResponse( error_code, no...
Decode bytes to a ConsumerMetadataResponse :param bytes data: bytes to decode
19,491
def bbox(self): from itertools import chain knots = [ (knot.anchor[1], knot.anchor[0]) for knot in chain.from_iterable(self.paths) ] if len(knots) == 0: return (0., 0., 1., 1.) x, y = zip(*knots) return (min(x), min(y), max(x),...
Bounding box tuple (left, top, right, bottom) in relative coordinates, where top-left corner is (0., 0.) and bottom-right corner is (1., 1.). :return: `tuple`
19,492
def cmap_center_adjust(cmap, center_ratio): if not (0. < center_ratio) & (center_ratio < 1.): return cmap a = math.log(center_ratio) / math.log(0.5) return cmap_powerlaw_adjust(cmap, a)
Returns a new colormap based on the one given but adjusted so that the old center point higher (>0.5) or lower (<0.5) :param cmap: colormap instance (e.g., cm.jet) :param center_ratio:
19,493
def _break_reads(self, contig, position, fout, min_read_length=250): sam_reader = pysam.Samfile(self.bam, "rb") for read in sam_reader.fetch(contig): seqs = [] if read.pos < position < read.reference_end - 1: split_point = position - read.pos ...
Get all reads from contig, but breaks them all at given position (0-based) in the reference. Writes to fout. Currently pproximate where it breaks (ignores indels in the alignment)
19,494
def parse_conference_address(address_string): geo_elements = address_string.split() city = geo_elements[0] country_name = geo_elements[-1].upper().replace(, ).strip() us_state = None state = None country_code = None country_code = match_country_name_to_its_code(country_name, city...
Parse a conference address. This is a pretty dummy address parser. It only extracts country and state (for US) and should be replaced with something better, like Google Geocoding.
19,495
def get_appliance_stats_by_location(self, location_id, start, end, granularity=None, per_page=None, page=None, min_power=None): url = "https://api.neur.io/v1/appliances/stats" headers = self.__gen_headers() headers["Content-Type"] = "application/json" params ...
Get appliance usage data for a given location within a given time range. Stats are generated by fetching appliance events that match the supplied criteria and then aggregating them together based on the granularity specified with the request. Note: This endpoint uses the location's time zone when...
19,496
def load_data(self, df): stmt = ddl.LoadData(self._qualified_name, df) return self._execute(stmt)
Wraps the LOAD DATA DDL statement. Loads data into an MapD table from pandas.DataFrame or pyarrow.Table Parameters ---------- df: pandas.DataFrame or pyarrow.Table Returns ------- query : MapDQuery
19,497
def dest_fpath(self, source_fpath: str) -> str: relative_fpath = os.path.join(*source_fpath.split(os.sep)[1:]) relative_dirpath = os.path.dirname(relative_fpath) source_fname = relative_fpath.split(os.sep)[-1] base_fname = source_fname.split()[0] dest_fname = f ...
Calculates full path for end json-api file from source file full path.
19,498
def append(self, obj): if isinstance(obj, dict) and self._col_names: obj = [obj.get(col, None) for col in self._col_names] assert isinstance(obj, list), \ "obj appended to ReprListList needs to be a list or dict" self._original.append(obj)
If it is a list it will append the obj, if it is a dictionary it will convert it to a list and append :param obj: dict or list of the object to append :return: None
19,499
def scalar(name, data, step=None, description=None): summary_metadata = metadata.create_summary_metadata( display_name=None, description=description) summary_scope = ( getattr(tf.summary.experimental, , None) or tf.summary.summary_scope) with summary_scope( name, , values=[data, step...
Write a scalar summary. Arguments: name: A name for this summary. The summary tag used for TensorBoard will be this name prefixed by any active name scopes. data: A real numeric scalar value, convertible to a `float32` Tensor. step: Explicit `int64`-castable monotonic step value for this summary. I...