Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
375,600
def add_to_buffer(self, content, read_position): self.read_position = read_position if self.read_buffer is None: self.read_buffer = content else: self.read_buffer = content + self.read_buffer
Add additional bytes content as read from the read_position. Args: content (bytes): data to be added to buffer working BufferWorkSpac. read_position (int): where in the file pointer the data was read from.
375,601
def serve_get(self, path, **params): if path is None: return None matched = self._match_path(path, self.get_registrations) if matched is None: return None else: return matched(path, **params)
Find a GET callback for the given HTTP path, call it and return the results. The callback is called with two arguments, the path used to match it, and params which include the BaseHTTPRequestHandler instance. The callback must return a tuple: (code, content, content_type) ...
375,602
def __stringify_predicate(predicate): funname = getsource(predicate).strip().split()[2].rstrip() params = if not in funname: stack = getouterframes(currentframe()) for frame in range(0, len(stack)): if funname in str(stack[frame]): _, _, _, params = g...
Reflection of function name and parameters of the predicate being used.
375,603
def newPage(doc, pno=-1, width=595, height=842): doc._newPage(pno, width=width, height=height) return doc[pno]
Create and return a new page object.
375,604
def all_casings(input_string): if not input_string: yield "" else: first = input_string[:1] if first.lower() == first.upper(): for sub_casing in all_casings(input_string[1:]): yield first + sub_casing else: for sub_casing in all_casing...
Permute all casings of a given string. A pretty algorithm, via @Amber http://stackoverflow.com/questions/6792803/finding-all-possible-case-permutations-in-python
375,605
def fitness(self, parsimony_coefficient=None): if parsimony_coefficient is None: parsimony_coefficient = self.parsimony_coefficient penalty = parsimony_coefficient * len(self.program) * self.metric.sign return self.raw_fitness_ - penalty
Evaluate the penalized fitness of the program according to X, y. Parameters ---------- parsimony_coefficient : float, optional If automatic parsimony is being used, the computed value according to the population. Otherwise the initialized value is used. Returns ...
375,606
def _request(self, buf, properties, date=None): self.ensure_alive() try: input_format = properties.get("inputFormat", "text") if input_format == "text": ctype = "text/plain; charset=utf-8" elif input_format == "serialized": ct...
Send a request to the CoreNLP server. :param (str | unicode) text: raw text for the CoreNLPServer to parse :param (dict) properties: properties that the server expects :param (str) date: reference date of document, used by server to set docDate - expects YYYY-MM-DD :return: request resu...
375,607
def disable(cls, args): mgr = NAppsManager() if args[]: napps = mgr.get_enabled() else: napps = args[] for napp in napps: mgr.set_napp(*napp) LOG.info(, mgr.napp_id) cls.disable_napp(mgr)
Disable subcommand.
375,608
def _config_profile_list(self): url = self._cfg_profile_list_url payload = {} try: res = self._send_request(, url, payload, ) if res and res.status_code in self._resp_ok: return res.json() except dexc.DfaClientRequestFailed: L...
Get list of supported config profile from DCNM.
375,609
def sample(self, size=1): samples = scipy.stats.bernoulli.rvs(self.p, size=size) if size == 1: return samples[0] return samples
Generate samples of the random variable. Parameters ---------- size : int The number of samples to generate. Returns ------- :obj:`numpy.ndarray` of int or int The samples of the random variable. If `size == 1`, then the returned valu...
375,610
def GammaContrast(gamma=1, per_channel=False, name=None, deterministic=False, random_state=None): params1d = [iap.handle_continuous_param(gamma, "gamma", value_range=None, tuple_to_uniform=True, list_to_choice=True)] func = adjust_contrast_gamma return _Contr...
Adjust contrast by scaling each pixel value to ``255 * ((I_ij/255)**gamma)``. Values in the range ``gamma=(0.5, 2.0)`` seem to be sensible. dtype support:: See :func:`imgaug.augmenters.contrast.adjust_contrast_gamma`. Parameters ---------- gamma : number or tuple of number or list of num...
375,611
def set_value(self, value, timeout): self.value = value self.expiration = time.perf_counter() * 1000 + timeout
Sets a new value and extends its expiration. :param value: a new cached value. :param timeout: a expiration timeout in milliseconds.
375,612
def l2_regularizer(decay, name_filter=): return regularizer( , lambda x: tf.nn.l2_loss(x) * decay, name_filter=name_filter)
Create an l2 regularizer.
375,613
def gen_accept(id_, keysize=2048, force=False): rs previously accepted key will be overwritten. .. code-block:: python >>> wheel.cmd(, []) {: , : } We can now see that the ``foo`` minionkey.listacceptedminionsfoominion1minion2minion3 id_ = clean.id(id_) ret = gen(i...
r''' Generate a key pair then accept the public key. This function returns the key pair in a dict, only the public key is preserved on the master. Returns a dictionary. id\_ The name of the minion for which to generate a key pair. keysize The size of the key pair to generate. The s...
375,614
def parse_valu(text, off=0): _, off = nom(text, off, whites) if nextchar(text, off, ): return parse_list(text, off) if isquote(text, off): return parse_string(text, off) try: valu = int(valu, 0) except ValueError: pass return valu, off
Special syntax for the right side of equals in a macro
375,615
def import_locations(self, data): self._data = data field_names = (, , , , , , , , , , , , , , , , , , ) comma_split = lambda s: s.split() date_parse = lambda s: datetime.date(*map(int, s...
Parse geonames.org country database exports. ``import_locations()`` returns a list of :class:`trigpoints.Trigpoint` objects generated from the data exported by geonames.org_. It expects data files in the following tab separated format:: 2633441 Afon Wyre Afon Wyre River Wayrai,Riv...
375,616
def portdate(port_number, date=None, return_format=None): uri = .format(number=port_number) if date: try: uri = .join([uri, date.strftime("%Y-%m-%d")]) except AttributeError: uri = .join([uri, date]) response = _get(uri, return_format) if in str(response): ...
Information about a particular port at a particular date. If the date is ommited, today's date is used. :param port_number: a string or integer port number :param date: an optional string in 'Y-M-D' format or datetime.date() object
375,617
def _GetTSKPartitionIdentifiers(self, scan_node): if not scan_node or not scan_node.path_spec: raise errors.ScannerError() volume_system = tsk_volume_system.TSKVolumeSystem() volume_system.Open(scan_node.path_spec) volume_identifiers = self._source_scanner.GetVolumeIdentifiers( volu...
Determines the TSK partition identifiers. Args: scan_node (SourceScanNode): scan node. Returns: list[str]: TSK partition identifiers. Raises: ScannerError: if the format of or within the source is not supported or the scan node is invalid or if the volume for a specific identi...
375,618
def vofile(filename, **kwargs): basename = os.path.basename(filename) if os.access(basename, os.R_OK): return open(basename, ) kwargs[] = kwargs.get(, ) return client.open(filename, **kwargs)
Open and return a handle on a VOSpace data connection @param filename: @param kwargs: @return:
375,619
def hybrid_forward(self, F, inputs, token_types, valid_length=None, masked_positions=None): outputs = [] seq_out, attention_out = self._encode_sequence(F, inputs, token_types, valid_length) outputs.append(seq_out) if self.encoder._output_all_encodings: ...
Generate the representation given the inputs. This is used in training or fine-tuning a static (hybridized) BERT model.
375,620
def find_first_fit(unoccupied_columns, row, row_length): for free_col in unoccupied_columns: first_item_x = row[0][0] offset = free_col - first_item_x if check_columns_fit(unoccupied_columns, row, offset, row_length): return offset raise ValueError("Row cannot ...
Finds the first index that the row's items can fit.
375,621
def _to_numeric_float(number, nums_int): index_end = len(number) - nums_int return float(number[:nums_int] + + number[-index_end:])
Transforms a string into a float. The nums_int parameter indicates the number of characters, starting from the left, to be used for the integer value. All the remaining ones will be used for the decimal value. :param number: string with the number :param nums_int: characters, counting from the lef...
375,622
def unmarshal_json( obj, cls, allow_extra_keys=True, ctor=None, ): return unmarshal_dict( obj, cls, allow_extra_keys, ctor=ctor, )
Unmarshal @obj into @cls Args: obj: dict, A JSON object cls: type, The class to unmarshal into allow_extra_keys: bool, False to raise an exception when extra keys are present, True to ignore ctor: None-or-static-method:...
375,623
def tostring(self, fully_qualified=True, pretty_print=True, encoding="UTF-8"): root = self.serialize(fully_qualified=fully_qualified) kwargs = {"pretty_print": pretty_print, "encoding": encoding} if encoding != "unicode": kwargs["xml_declaration"] = True return etree...
Serialize and return a string of this METS document. To write to file, see :meth:`write`. The default encoding is ``UTF-8``. This method will return a unicode string when ``encoding`` is set to ``unicode``. :return: String of this document
375,624
def sigma_filter(filename, region, step_size, box_size, shape, domask, sid): ymin, ymax = region logging.debug(.format(ymin, ymax, strftime("%Y-%m-%d %H:%M:%S", gmtime()))) data_row_min = max(0, ymin - box_size[0]//2) data_row_max = min(shape[0], ymax + box_size[0]//2) NAXIS = fits...
Calculate the background and rms for a sub region of an image. The results are written to shared memory - irms and ibkg. Parameters ---------- filename : string Fits file to open region : list Region within the fits file that is to be processed. (row_min, row_max). step_size :...
375,625
def get_clipboard_text_and_convert(paste_list=False): u txt = GetClipboardText() if txt: if paste_list and u"\t" in txt: array, flag = make_list_of_list(txt) if flag: txt = repr(array) else: txt = u"array(%s)"%repr(array) ...
u"""Get txt from clipboard. if paste_list==True the convert tab separated data to list of lists. Enclose list of list in array() if all elements are numeric
375,626
def image_id_from_registry(image_name): registry, repository, tag = parse(image_name) try: token = auth_token(registry, repository).get("token") if registry == "index.docker.io": registry = "registry-1.docker.io" res = requests.head("https://{}/v2/{}/manifests/{...
Get the docker id from a public or private registry
375,627
def acceptRecord(self, item): record = item.record() self.treePopupWidget().close() self.setCurrentRecord(record)
Closes the tree popup and sets the current record. :param record | <orb.Table>
375,628
def _publish_message(host, amqp_settings, routing_key, data): if host == "stdout": print("Published to %s: %s" % (routing_key, data)) return True try: conn = Connection(**remove_nones( host=host, userid=amqp_settings.get("userid"), password=amqp_...
Publish an AMQP message. Returns: bool: True if message was sent successfully.
375,629
def _add_generic(self, start_node, type_name, group_type_name, args, kwargs, add_prefix=True, check_naming=True): args = list(args) create_new = True name = instance = None constructor = None add_link = type_name == LINK i...
Adds a given item to the tree irrespective of the subtree. Infers the subtree from the arguments. :param start_node: The parental node the adding was initiated from :param type_name: The type of the new instance. Whether it is a parameter, parameter group, config, con...
375,630
def rotate_v1(array, k): array = array[:] n = len(array) for i in range(k): temp = array[n - 1] for j in range(n-1, 0, -1): array[j] = array[j - 1] array[0] = temp return array
Rotate the entire array 'k' times T(n)- O(nk) :type array: List[int] :type k: int :rtype: void Do not return anything, modify array in-place instead.
375,631
def update(self): ret = True fields = self.depopulate(True) q = self.query q.set_fields(fields) pk = self.pk if pk: q.is_field(self.schema.pk.name, pk) else: raise ValueError("You cannot update without a primary key") if...
re-persist the updated field values of this orm that has a primary key
375,632
def generate_monthly(rain_day_threshold, day_end_hour, use_dst, daily_data, monthly_data, process_from): start = monthly_data.before(datetime.max) if start is None: start = datetime.min start = daily_data.after(start + SECOND) if process_from: if start: ...
Generate monthly summaries from daily data.
375,633
def get_lines_from_file(filename, lineno, context_lines, loader=None, module_name=None): lineno = lineno - 1 lower_bound = max(0, lineno - context_lines) upper_bound = lineno + context_lines source = None if loader is not None and hasattr(loader, "get_source"): result = get_source_line...
Returns context_lines before and after lineno from file. Returns (pre_context_lineno, pre_context, context_line, post_context).
375,634
def store(self, database, validate=True, role=None): if validate: self.validate() self._id, self._rev = database.save(self.to_primitive(role=role)) return self
Store the document in the given database. :param database: the `Database` object source for storing the document. :return: an updated instance of `Document` / self.
375,635
def batch_run(self, *commands): original_retries = self.repeat_commands self.repeat_commands = 1 for _ in range(original_retries): for command in commands: cmd = command[0] args = command[1:] cmd(*args) self.repeat_comm...
Run batch of commands in sequence. Input is positional arguments with (function pointer, *args) tuples. This method is useful for executing commands to multiple groups with retries, without having too long delays. For example, - Set group 1 to red and brightness to 10%...
375,636
def _get_schema_loader(self, strict=False): return functools.partial(schema.load_schema, version=self.version, strict=strict)
Gets a closure for schema.load_schema with the correct/current Opsview version
375,637
def readin_rho(filename, rhofile=True, aniso=False): if aniso: a = [[0, 1, 2], [2, 3, 4]] else: a = [0, 2] if rhofile: if filename is None: filename = with open(filename, ) as fid: mag = np.loadtxt(fid, skiprows=1, usecols=(a[0])) else: ...
Read in the values of the resistivity in Ohmm. The format is variable: rho-file or mag-file.
375,638
def sighash(self, sighash_type, index=0, joinsplit=False, script_code=None, anyone_can_pay=False, prevout_value=None): if joinsplit and anyone_can_pay: raise ValueError(t be used with joinsplitsZcashSigHashbb09b876'))
ZIP243 https://github.com/zcash/zips/blob/master/zip-0243.rst
375,639
def _validate_caller_vcf(call_vcf, truth_vcf, callable_bed, svcaller, work_dir, data): stats = _calculate_comparison_stats(truth_vcf) call_vcf = _prep_vcf(call_vcf, callable_bed, dd.get_sample_name(data), dd.get_sample_name(data), stats, work_dir, data) truth_vcf = _prep_vcf(tr...
Validate a caller VCF against truth within callable regions using SURVIVOR. Combines files with SURIVOR merge and counts (https://github.com/fritzsedlazeck/SURVIVOR/)
375,640
def _ValidateDataTypeDefinition(cls, data_type_definition): if not cls._IsIdentifier(data_type_definition.name): raise ValueError( .format( data_type_definition.name)) if keyword.iskeyword(data_type_definition.name): raise ValueError( .format( da...
Validates the data type definition. Args: data_type_definition (DataTypeDefinition): data type definition. Raises: ValueError: if the data type definition is not considered valid.
375,641
def decode_bbox_target(box_predictions, anchors): orig_shape = tf.shape(anchors) box_pred_txtytwth = tf.reshape(box_predictions, (-1, 2, 2)) box_pred_txty, box_pred_twth = tf.split(box_pred_txtytwth, 2, axis=1) anchors_x1y1x2y2 = tf.reshape(anchors, (-1, 2, 2)) anchors_x1y1, anchors_x2y2 =...
Args: box_predictions: (..., 4), logits anchors: (..., 4), floatbox. Must have the same shape Returns: box_decoded: (..., 4), float32. With the same shape.
375,642
async def serve( app: ASGIFramework, config: Config, *, task_status: trio._core._run._TaskStatus = trio.TASK_STATUS_IGNORED, ) -> None: if config.debug: warnings.warn("The config `debug` has no affect when using serve", Warning) if config.workers != 1: warnings.warn("The con...
Serve an ASGI framework app given the config. This allows for a programmatic way to serve an ASGI framework, it can be used via, .. code-block:: python trio.run(partial(serve, app, config)) It is assumed that the event-loop is configured before calling this function, therefore configurat...
375,643
def gene_tree( self, scale_to=None, population_size=1, trim_names=True, ): tree = self.template or self.yule() for leaf in tree._tree.leaf_node_iter(): leaf.num_genes = 1 dfr = tree._tree.seed_node.distance_from_root() ...
Using the current tree object as a species tree, generate a gene tree using the constrained Kingman coalescent process from dendropy. The species tree should probably be a valid, ultrametric tree, generated by some pure birth, birth-death or coalescent process, but no checks are made. Op...
375,644
def get_plugin(self, name): for p in self._plugins: if p.name == name: return p return None
Get a plugin by its name from the plugins loaded for the current namespace :param name: :return:
375,645
def parse_def(self, text): self.__init__() if not is_start_of_function(text): return self.func_indent = get_indent(text) text = text.strip() text = text.replace(, ) text = text.replace(, ) return_type_re = re.search(r, text) ...
Parse the function definition text.
375,646
def draw(self, viewer): cache = self.get_cache(viewer) if not cache.drawn: cache.drawn = True viewer.redraw(whence=2) cpoints = self.get_cpoints(viewer) cr = viewer.renderer.setup_cr(self) if self.linewidth > 0: cr.draw_pol...
General draw method for RGB image types. Note that actual insertion of the image into the output is handled in `draw_image()`
375,647
def make_geohash_tables(table,listofprecisions,**kwargs): return_squares = False sort_by = for key,value in kwargs.iteritems(): if key == : sort_by = value if key == : return_squares = value header = df2list(table)[0] columns = header[10:] originaltable = table if not sort_by == : origi...
sort_by - field to sort by for each group return_squares - boolean arg if true returns a list of squares instead of writing out to table
375,648
def ckf_transform(Xs, Q): m, n = Xs.shape x = sum(Xs, 0)[:, None] / m P = np.zeros((n, n)) xf = x.flatten() for k in range(m): P += np.outer(Xs[k], Xs[k]) - np.outer(xf, xf) P *= 1 / m P += Q return x, P
Compute mean and covariance of array of cubature points. Parameters ---------- Xs : ndarray Cubature points Q : ndarray Noise covariance Returns ------- mean : ndarray mean of the cubature points variance: ndarray covariance matrix of the cubature ...
375,649
def add_team_repo(repo_name, team_name, profile="github", permission=None): pullpushadminmy_repoteam_name team = get_team(team_name, profile=profile) if not team: log.error(, team_name) return False try: client = _get_client(profile) organization = client.get_organization...
Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team mem...
375,650
def PILTowx(pimg): from MAVProxy.modules.lib.wx_loader import wx wimg = wx.EmptyImage(pimg.size[0], pimg.size[1]) try: wimg.SetData(pimg.convert().tobytes()) except NotImplementedError: wimg.SetData(pimg.convert().tostring()) return wimg
convert a PIL Image to a wx image
375,651
def _what_default(self, pronunciation): token_default = self[][][] index_count = 2*len(pronunciation) + 1 predictions = {} for i in range(index_count): index_predictions = {} if i % 2 == 0: index_predictions.update(token_default[]) ...
Provide the default prediction of the what task. This function is used to predict the probability of a given pronunciation being reported for a given token. :param pronunciation: The list or array of confusion probabilities at each index
375,652
def purge_stream(self, stream_id, remove_definition=False, sandbox=None): if sandbox is not None: raise NotImplementedError if stream_id not in self.streams: raise StreamNotFoundError("Stream with id not found".format(stream_id)) stream = self.stream...
Purge the stream :param stream_id: The stream identifier :param remove_definition: Whether to remove the stream definition as well :param sandbox: The sandbox for this stream :return: None :raises: NotImplementedError
375,653
def is_empty(self): return all(isinstance(c, ParseNode) and c.is_empty for c in self.children)
Returns True if this node has no children, or if all of its children are ParseNode instances and are empty.
375,654
def join(chord_root, quality=, extensions=None, bass=): r chord_label = chord_root if quality or extensions: chord_label += ":%s" % quality if extensions: chord_label += "(%s)" % ",".join(extensions) if bass and bass != : chord_label += "/%s" % bass validate_chord_label(c...
r"""Join the parts of a chord into a complete chord label. Parameters ---------- chord_root : str Root pitch class of the chord, e.g. 'C', 'Eb' quality : str Quality of the chord, e.g. 'maj', 'hdim7' (Default value = '') extensions : list Any added or absent scaled d...
375,655
def get_all_alert(self, **kwargs): kwargs[] = True if kwargs.get(): return self.get_all_alert_with_http_info(**kwargs) else: (data) = self.get_all_alert_with_http_info(**kwargs) return data
Get all alerts for a customer # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_all_alert(async_req=True) >>> result = thread.get() :param async_req...
375,656
def remove(self, element, multiplicity=None): _elements = self._elements if element not in _elements: raise KeyError old_multiplicity = _elements.get(element, 0) if multiplicity is None or multiplicity >= old_multiplicity: del _elements[element] ...
Removes an element from the multiset. If no multiplicity is specified, the element is completely removed from the multiset: >>> ms = Multiset('aabbbc') >>> ms.remove('a') 2 >>> sorted(ms) ['b', 'b', 'b', 'c'] If the multiplicity is given, it is subtracted from ...
375,657
def resolve_memory_access(self, tb, x86_mem_operand): size = self.__get_memory_access_size(x86_mem_operand) addr = None if x86_mem_operand.base: addr = ReilRegisterOperand(x86_mem_operand.base, size) if x86_mem_operand.index and x86_mem_operand.scale != 0x0: ...
Return operand memory access translation.
375,658
def change_dir(self, session, path): if path == "-": path = self._previous_path or "." try: previous = os.getcwd() os.chdir(path) except IOError as ex: session.write_line("Error changing directory: {0}", ex) ...
Changes the working directory
375,659
def LogoOverlay(sites, overlayfile, overlay, nperline, sitewidth, rmargin, logoheight, barheight, barspacing, fix_limits={}, fixlongname=False, overlay_cmap=None, underlay=False, scalebar=False): if os.path.splitext(overlayfile)[1] != : raise ValueError("overlayfile must end in .pdf: %s" % overlayfile)...
Makes overlay for *LogoPlot*. This function creates colored bars overlay bars showing up to two properties. The trick of this function is to create the bars the right size so they align when they overlay the logo plot. CALLING VARIABLES: * *sites* : same as the variable of this name used by ...
375,660
def _encode_sequence(self, inputs, token_types, valid_length=None): word_embedding = self.word_embed(inputs) type_embedding = self.token_type_embed(token_types) embedding = word_embedding + type_embedding outputs, additional_outputs = self.encoder(embedding, No...
Generate the representation given the input sequences. This is used for pre-training or fine-tuning a BERT model.
375,661
def clear(self): try: for node in self.__map.itervalues(): del node[:] root = self.__root root[:] = [root, root, None] self.__map.clear() except AttributeError: pass dict.clear(self)
od.clear() -> None. Remove all items from od.
375,662
def well(self, idx) -> Well: if isinstance(idx, int): res = self._wells[idx] elif isinstance(idx, str): res = self.wells_by_index()[idx] else: res = NotImplemented return res
Deprecated---use result of `wells` or `wells_by_index`
375,663
def determine_override_options(selected_options: tuple, override_opts: DictLike, set_of_possible_options: tuple = ()) -> Dict[str, Any]: override_dict: Dict[str, Any] = {} for option in override_opts: if str(option) in list(map(lambda opt: str(opt), selected_options)): ...
Recursively extract the dict described in override_options(). In particular, this searches for selected options in the override_opts dict. It stores only the override options that are selected. Args: selected_options: The options selected for this analysis, in the order defined used wi...
375,664
def broadcast_1d_array(arr, ndim, axis=1): ext_arr = arr for i in range(ndim - 1): ext_arr = np.expand_dims(ext_arr, axis=axis) return ext_arr
Broadcast 1-d array `arr` to `ndim` dimensions on the first axis (`axis`=0) or on the last axis (`axis`=1). Useful for 'outer' calculations involving 1-d arrays that are related to different axes on a multidimensional grid.
375,665
def read_tpld_stats(self): payloads_stats = OrderedDict() for tpld in self.tplds.values(): payloads_stats[tpld] = tpld.read_stats() return payloads_stats
:return: dictionary {tpld index {group name {stat name: value}}}. Sea XenaTpld.stats_captions.
375,666
def format_out_of_country_keeping_alpha_chars(numobj, region_calling_from): num_raw_input = numobj.raw_input if num_raw_input is None or len(num_raw_input) == 0: return format_out_of_country_calling_number(numobj, region_calling_from) country_code = numobj.country_code if not _has...
Formats a phone number for out-of-country dialing purposes. Note that in this version, if the number was entered originally using alpha characters and this version of the number is stored in raw_input, this representation of the number will be used rather than the digit representation. Grouping informa...
375,667
def decrypt(*args, **kwargs): try: return legacy_decrypt(*args, **kwargs) except (NotYetValid, Expired) as e: raise e except (Error, ValueError) as e: return spec_compliant_decrypt(*args, **kwargs)
Decrypts legacy or spec-compliant JOSE token. First attempts to decrypt the token in a legacy mode (https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-19). If it is not a valid legacy token then attempts to decrypt it in a spec-compliant way (http://tools.ietf.org/html/rfc7519)
375,668
def stats(self) -> pd.DataFrame: key = ["icao24", "callsign"] if self.flight_ids is None else "flight_id" return ( self.data.groupby(key)[["timestamp"]] .count() .sort_values("timestamp", ascending=False) .rename(columns={"timestamp": "count"}) ...
Statistics about flights contained in the structure. Useful for a meaningful representation.
375,669
def cross_entropy_reward_loss(logits, actions, rewards, name=None): cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=actions, logits=logits, name=name) return tf.reduce_sum(tf.multiply(cross_entropy, rewards))
Calculate the loss for Policy Gradient Network. Parameters ---------- logits : tensor The network outputs without softmax. This function implements softmax inside. actions : tensor or placeholder The agent actions. rewards : tensor or placeholder The rewards. Returns ...
375,670
def call(self, itemMethod): item = itemMethod.im_self method = itemMethod.im_func.func_name return self.batchController.getProcess().addCallback( CallItemMethod(storepath=item.store.dbdir, storeid=item.storeID, method=met...
Invoke the given bound item method in the batch process. Return a Deferred which fires when the method has been invoked.
375,671
def mark_validation(institute_id, case_name, variant_id): institute_obj, case_obj = institute_and_case(store, institute_id, case_name) variant_obj = store.variant(variant_id) user_obj = store.user(current_user.email) validate_type = request.form[] or None link = url_for(, institute_id=institute...
Mark a variant as sanger validated.
375,672
def _get_variant_effect(cls, variants, ref_sequence): assert len(variants) != 0 var_types = [x.var_type for x in variants] if len(set(var_types)) != 1: return , , var_type = var_types[0] assert set([x.ref_name for x in variants]) == set([ref_sequence.id])...
variants = list of variants in the same codon. returns type of variant (cannot handle more than one indel in the same codon).
375,673
def get_groups(self, username): try: return self.users[username][] except Exception as e: raise UserDoesntExist(username, self.backend_name)
Get a user's groups :param username: 'key' attribute of the user :type username: string :rtype: list of groups
375,674
def submit(self, command, blocksize, job_name="parsl.auto"): if self.provisioned_blocks >= self.max_blocks: logger.warn("[%s] at capacity, cannot add more blocks now", self.label) return None if blocksize < self.nodes_per_block: blocksize ...
Submits the command onto an Local Resource Manager job of blocksize parallel elements. Submit returns an ID that corresponds to the task that was just submitted. If tasks_per_node < 1 : ! This is illegal. tasks_per_node should be integer If tasks_per_node == 1: A single node is p...
375,675
def _init_scratch(self): scratch = np.zeros((self._num_shards, self._shard_size), dtype=np.complex64) scratch_handle = mem_manager.SharedMemManager.create_array( scratch.view(dtype=np.float32)) self._shared_mem_dict[] = scratch_handle
Initializes a scratch pad equal in size to the wavefunction.
375,676
def SetColor(self, color): self.SetFillColor(color) self.SetLineColor(color) self.SetMarkerColor(color)
*color* may be any color understood by ROOT or matplotlib. Set all color attributes with one method call. For full documentation of accepted *color* arguments, see :class:`rootpy.plotting.style.Color`.
375,677
def alias_field(model, field): for part in field.split(LOOKUP_SEP)[:-1]: model = associate_model(model,part) return model.__name__ + "-" + field.split(LOOKUP_SEP)[-1]
Return the prefix name of a field
375,678
def get_contingency_tables(self): return np.array([ContingencyTable(*ct) for ct in self.contingency_tables.values])
Create an Array of ContingencyTable objects for each probability threshold. Returns: Array of ContingencyTable objects
375,679
def driver_name(self): self._driver_name, value = self.get_attr_string(self._driver_name, ) return value
Returns the name of the motor driver that loaded this device. See the list of [supported devices] for a list of drivers.
375,680
def _hash_categorical(c, encoding, hash_key): values = np.asarray(c.categories.values) hashed = hash_array(values, encoding, hash_key, categorize=False) mask = c.isna() if len(hashed): result = hashed.take(c.codes) else: re...
Hash a Categorical by hashing its categories, and then mapping the codes to the hashes Parameters ---------- c : Categorical encoding : string, default 'utf8' hash_key : string key to encode, default to _default_hash_key Returns ------- ndarray of hashed values array, same size as ...
375,681
def _fs_match(pattern, filename, sep, follow, symlinks): matched = False base = None m = pattern.fullmatch(filename) if m: matched = True if not follow: groups = m.groups() last = len(groups) for i, star in enumerate(m.groups()...
Match path against the pattern. Since `globstar` doesn't match symlinks (unless `FOLLOW` is enabled), we must look for symlinks. If we identify a symlink in a `globstar` match, we know this result should not actually match.
375,682
def commit( self, confirm=False, confirm_delay=None, check=False, comment="", and_quit=False, delay_factor=1, ): delay_factor = self.select_delay_factor(delay_factor) if check and (confirm or confirm_delay or comment): rai...
Commit the candidate configuration. Commit the entered configuration. Raise an error and return the failure if the commit fails. Automatically enters configuration mode default: command_string = commit check and (confirm or confirm_dely or comment): Exc...
375,683
def apply_integer_offsets(image2d, offx, offy): if type(offx) != int or type(offy) != int: raise ValueError() naxis2, naxis1 = image2d.shape image2d_shifted = np.zeros((naxis2, naxis1)) non = lambda s: s if s < 0 else None mom = lambda s: max(0,s) image...
Apply global (integer) offsets to image. Parameters ---------- image2d : numpy array Input image offx : int Offset in the X direction (must be integer). offy : int Offset in the Y direction (must be integer). Returns ------- image2d_shifted : numpy array ...
375,684
def wait_and_ignore(condition, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5): ll wait for the condition to become true, but will not error if the condition isn try: return wait_until(condition, timeout, sleep) except: pass
Waits wrapper that'll wait for the condition to become true, but will not error if the condition isn't met. Args: condition (lambda) - Lambda expression to wait for to evaluate to True. Kwargs: timeout (number) : Maximum number of seconds to wait. sleep (number) : Sleep time to wa...
375,685
def visit_Expr(self, node: AST, dfltChaining: bool = True) -> str: return self.visit(node.value)
Return representation of nested expression.
375,686
def _dict_native_ok(d): if len(d) >= 256: return False for k in d: if not isinstance(k, six.string_types): return False return True
This checks if a dictionary can be saved natively as HDF5 groups. If it can't, it will be pickled.
375,687
def wait(self, condition, interval, *args): hid = lambda: + str(uuid.uuid1())[:8] handle = hid() if len(args): element_handle = hid() self.browser.execute_script( .format(element_handle) ) for el in args: ...
:Description: Create an interval in vm.window, will clear interval after condition met. :param condition: Condition in javascript to pass to interval. :example: '$el.innerText == "cheesecake"' :example: '$el[0].disabled && $el[1].disabled' :type condition: string :param interval:...
375,688
def get_class_name(class_key, classification_key): classification = definition(classification_key) for the_class in classification[]: if the_class.get() == class_key: return the_class.get(, class_key) return class_key
Helper to get class name from a class_key of a classification. :param class_key: The key of the class. :type class_key: str :type classification_key: The key of a classification. :param classification_key: str :returns: The name of the class. :rtype: str
375,689
def build_target_areas(entry): target_areas = [] areas = str(entry[]).split() for area in areas: target_areas.append(area.strip()) return target_areas
Cleanup the raw target areas description string
375,690
def uavionix_adsb_out_cfg_encode(self, ICAO, callsign, emitterType, aircraftSize, gpsOffsetLat, gpsOffsetLon, stallSpeed, rfSelect): return MAVLink_uavionix_adsb_out_cfg_message(ICAO, callsign, emitterType, aircraftSize, gpsOffsetLat, gpsOffsetLon, stallSpeed, rfSelect)
Static data to configure the ADS-B transponder (send within 10 sec of a POR and every 10 sec thereafter) ICAO : Vehicle address (24 bit) (uint32_t) callsign : Vehicle identifier (8 characters, null terminated, valid characters are A-...
375,691
def _read_journal(self): root = self._filesystem.inspect_get_roots()[0] inode = self._filesystem.stat()[] with NamedTemporaryFile(buffering=0) as tempfile: self._filesystem.download_inode(root, inode, tempfile.name) journal = usn_journal(tempfile.name) ...
Extracts the USN journal from the disk and parses its content.
375,692
def set(self, subscribed, ignored): sub = {: subscribed, : ignored} json = self._json(self._put(self._api, data=dumps(sub)), 200) self.__init__(json, self._session)
Set the user's subscription for this subscription :param bool subscribed: (required), determines if notifications should be received from this thread. :param bool ignored: (required), determines if notifications should be ignored from this thread.
375,693
def hourly_horizontal_infrared(self): sky_cover = self._sky_condition.hourly_sky_cover db_temp = self._dry_bulb_condition.hourly_values dp_temp = self._humidity_condition.hourly_dew_point_values( self._dry_bulb_condition) horiz_ir = [] for i in xrange(len(sk...
A data collection containing hourly horizontal infrared intensity in W/m2.
375,694
def sign(self): return -1 if self.type in (Account.TYPES.asset, Account.TYPES.expense) else 1
Returns 1 if a credit should increase the value of the account, or -1 if a credit should decrease the value of the account. This is based on the account type as is standard accounting practice. The signs can be derrived from the following expanded form of the accounting equation...
375,695
def dtype(self): mx_dtype = ctypes.c_int() check_call(_LIB.MXNDArrayGetDType( self.handle, ctypes.byref(mx_dtype))) return _DTYPE_MX_TO_NP[mx_dtype.value]
Data-type of the array's elements. Returns ------- numpy.dtype This NDArray's data type. Examples -------- >>> x = mx.nd.zeros((2,3)) >>> x.dtype <type 'numpy.float32'> >>> y = mx.nd.zeros((2,3), dtype='int32') >>> y.dtype ...
375,696
def _gen_ticket(prefix=None, lg=settings.CAS_TICKET_LEN): random_part = u.join( random.choice( string.ascii_letters + string.digits ) for _ in range(lg - len(prefix or "") - 1) ) if prefix is not None: return u % (prefix, random_part) else: return random_...
Generate a ticket with prefix ``prefix`` and length ``lg`` :param unicode prefix: An optional prefix (probably ST, PT, PGT or PGTIOU) :param int lg: The length of the generated ticket (with the prefix) :return: A randomlly generated ticket of length ``lg`` :rtype: unicode
375,697
def block_splitter(data, block_size): buf = [] for i, datum in enumerate(data): buf.append(datum) if len(buf) == block_size: yield buf buf = [] if buf: yield buf
Creates a generator by slicing ``data`` into chunks of ``block_size``. >>> data = range(10) >>> list(block_splitter(data, 2)) [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]] If ``data`` cannot be evenly divided by ``block_size``, the last block will simply be the remainder of the data. Example: >>> ...
375,698
def getmakeidfobject(idf, key, name): idfobject = idf.getobject(key, name) if not idfobject: return idf.newidfobject(key, Name=name) else: return idfobject
get idfobject or make it if it does not exist
375,699
def has_permissions(**perms): def predicate(ctx): ch = ctx.channel permissions = ch.permissions_for(ctx.author) missing = [perm for perm, value in perms.items() if getattr(permissions, perm, None) != value] if not missing: return True raise MissingPermissi...
A :func:`.check` that is added that checks if the member has all of the permissions necessary. The permissions passed in must be exactly like the properties shown under :class:`.discord.Permissions`. This check raises a special exception, :exc:`.MissingPermissions` that is inherited from :exc:`.Ch...