Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
365,900
def full_name(first_name, last_name, username, **extra): name = " ".join(n for n in [first_name, last_name] if n) if not name: return username return name
Return full name or username.
365,901
def _are_scopes_sufficient(authorized_scopes, sufficient_scopes): for sufficient_scope_set in sufficient_scopes: if sufficient_scope_set.issubset(authorized_scopes): return True return False
Check if a list of authorized scopes satisfies any set of sufficient scopes. Args: authorized_scopes: a list of strings, return value from oauth.get_authorized_scopes sufficient_scopes: a set of sets of strings, return value from _process_scopes
365,902
def targeted_conjugate_about(tensor: np.ndarray, target: np.ndarray, indices: Sequence[int], conj_indices: Sequence[int] = None, buffer: Optional[np.ndarray] = None, out: Opti...
r"""Conjugates the given tensor about the target tensor. This method computes a target tensor conjugated by another tensor. Here conjugate is used in the sense of conjugating by a matrix, i.a. A conjugated about B is $A B A^\dagger$ where $\dagger$ represents the conjugate transpose. Abstractly th...
365,903
def extract_author_keywords(skw_db, ckw_db, fulltext): akw = {} for k, v in get_author_keywords(skw_db, ckw_db, fulltext).items(): akw[KeywordToken(k, type=)] = v return akw
Find out human defined keywords in a text string. Searches for the string "Keywords:" and its declinations and matches the following words. :param skw_db: list single kw object :param ckw_db: list of composite kw objects :param fulltext: utf-8 string :return: dictionary of matches in a formt {...
365,904
def recommend_from_interactions( self, observed_items, k=10, exclude=None, items=None, new_user_data=None, new_item_data=None, exclude_known=True, diversity=0, random_seed=None, verbose=True): column_types = self._get_data_schema() user_id = self...
Recommend the ``k`` highest scored items based on the interactions given in `observed_items.` Parameters ---------- observed_items : SArray, SFrame, or list A list/SArray of items to use to make recommendations, or an SFrame of items and optionally ratings and/or...
365,905
def boolean(self): try: return self._boolean except AttributeError: nbits = len(self.bits) boolean = numpy.zeros((self.size, nbits), dtype=bool) for i, sample in enumerate(self.value): boolean[i, :] = [int(sample) >> j & 1 for j in...
A mapping of this `StateVector` to a 2-D array containing all binary bits as booleans, for each time point.
365,906
def get(cls, rkey): if rkey in cls._cached: logger.info( % rkey) return cls._cached[rkey] if rkey in cls._stock: img = cls._load_image(rkey) return img else: raise StockImageException( % rkey)
Get image previously registered with key rkey. If key not exist, raise StockImageException
365,907
def limit(self, keys): if not isinstance(keys, list) and not isinstance(keys, tuple): keys = [keys] remove_keys = [k for k in self.keys() if k not in keys] for k in remove_keys: self.pop(k)
Remove all keys other than the keys specified.
365,908
def extractUserStore(userAccount, extractionDestination, legacySiteAuthoritative=True): if legacySiteAuthoritative: userAccount.migrateDown() av = userAccount.avatars av.open().close() def _(): ...
Move the SubStore for the given user account out of the given site store completely. Place the user store's database directory into the given destination directory. @type userAccount: C{LoginAccount} @type extractionDestination: C{FilePath} @type legacySiteAuthoritative: C{bool} @param legac...
365,909
def thickness_hydrostatic_from_relative_humidity(pressure, temperature, relative_humidity, **kwargs): r bottom = kwargs.pop(, None) depth = kwargs.pop(, None) mixing = mixing_ratio_from_relative_humidity(relative_humidity, temperature, pressure) retu...
r"""Calculate the thickness of a layer given pressure, temperature and relative humidity. Similar to ``thickness_hydrostatic``, this thickness calculation uses the pressure, temperature, and relative humidity profiles via the hypsometric equation with virtual temperature adjustment. .. math:: Z_2 - Z_...
365,910
def tamper_file(filepath, mode=, proba=0.03, block_proba=None, blocksize=65535, burst_length=None, header=None): if header and header > 0: blocksize = header tamper_count = 0 total_size = 0 with open(filepath, "r+b") as fh: buf = fh.read(blocksize) for i in xran...
Randomly tamper a file's content
365,911
def _permission_trees(permissions): treecache = PermissionTreeCache() cached = treecache.get() if not cached: tree = PermissionTreeBuilder() for permission in permissions: tree.insert(permission) result = tree.serialize() t...
Get the cached permission tree, or build a new one if necessary.
365,912
def parse_response(self, response): parser, unmarshaller = self.getparser() parser.feed(response.text.encode()) parser.close() return unmarshaller.close()
Parse XMLRPC response
365,913
def update(self, state, tnow): self.state = state self.update_time = tnow
update the threat state
365,914
def get_maxsing(self,eigthresh=1.0e-5): sthresh = self.s.x.flatten()/self.s.x[0] ising = 0 for i,st in enumerate(sthresh): if st > eigthresh: ising += 1 else: break return max(1,ising)
Get the number of singular components with a singular value ratio greater than or equal to eigthresh Parameters ---------- eigthresh : float the ratio of the largest to smallest singular value Returns ------- int : int number of singular ...
365,915
def _check_params(self, *args, **kwargs): terms = kwargs.get() if not terms: raise crawler.CrawlerParamsError() if not isinstance(terms, list): terms = [terms] if len(terms) != len(self.base[]): log.debug(.format(len(terms), len(...
检查参数信息是否匹配
365,916
def map_template(category, template_list): if isinstance(template_list, str): template_list = [template_list] for template in template_list: path = os.path.normpath(category) while path is not None: for extension in [, , , , ]: candidate = os.path.join(...
Given a file path and an acceptable list of templates, return the best-matching template's path relative to the configured template directory. Arguments: category -- The path to map template_list -- A template to look up (as a string), or a list of templates.
365,917
def update(self, key, value): if not is_string(key): raise Exception("Key must be string") if not is_string(value): raise Exception("Value must be string") self.root_node = self._update_and_delete_storage( self.r...
:param key: a string :value: a string
365,918
def build_search(self): s = self.search() s = self.query(s, self._query) s = self.filter(s) if self.fields: s = self.highlight(s) s = self.sort(s) self.aggregate(s) return s
Construct the ``Search`` object.
365,919
def _map_xpath_flags_to_re(expr: str, xpath_flags: str) -> Tuple[int, str]: python_flags: int = 0 modified_expr = expr if xpath_flags is None: xpath_flags = "" if in xpath_flags: python_flags |= re.DOTALL if in xpath_flags: python_flags |= re.MULTILINE if in xpat...
Map `5.6.2 Flags <https://www.w3.org/TR/xpath-functions-31/#flags>`_ to python :param expr: match pattern :param xpath_flags: xpath flags :returns: python flags / modified match pattern
365,920
def request(self, source, target): node = new_ele("copy-config") node.append(util.datastore_or_url("target", target, self._assert)) try: node.append(util.datastore_or_url("source", source, self._assert)) except Exception: node.a...
Create or replace an entire configuration datastore with the contents of another complete configuration datastore. *source* is the name of the configuration datastore to use as the source of the copy operation or `config` element containing the configuration subtree to copy *target* is the nam...
365,921
def getAllNodes(self): ret = TagCollection() for rootNode in self.getRootNodes(): ret.append(rootNode) ret += rootNode.getAllChildNodes() return ret
getAllNodes - Get every element @return TagCollection<AdvancedTag>
365,922
def copy_subtree(ret, element, msg): sub_element = ModelDiff.process_attrib(deepcopy(element), msg) ret.append(sub_element) return sub_element
copy_subtree High-level api: Copy element as a subtree and put it as a child of ret. Parameters ---------- element : `Element` A node in a model tree. msg : `str` Message to be added. ret : `Element` A node in self.tree. R...
365,923
def error(self): warnings.warn("Database.error() is deprecated", DeprecationWarning, stacklevel=2) error = self.command("getlasterror") error_msg = error.get("err", "") if error_msg is None: return None if error_msg.startswith("not mast...
**DEPRECATED**: Get the error if one occurred on the last operation. This method is obsolete: all MongoDB write operations (insert, update, remove, and so on) use the write concern ``w=1`` and report their errors by default. .. versionchanged:: 2.8 Deprecated.
365,924
def install(self, release_id, upgrade=False): release_path = os.path.join(self._releases, release_id) if not self._runner.exists(release_path): self._runner.run("{0} ".format(self._venv_path, release_path)) cmd = [os.path.join(release_path, , ), ] if upgrade: ...
Install target packages into a virtual environment. If the virtual environment for the given release ID does not exist on the remote system, it will be created. The virtual environment will be created according to the standard Tunic directory structure (see :doc:`design`). If `...
365,925
def load_obsdata(self, idx: int) -> None: if self._obs_ramflag: self.obs[0] = self._obs_array[idx] elif self._obs_diskflag: raw = self._obs_file.read(8) self.obs[0] = struct.unpack(, raw)
Load the next obs sequence value (of the given index).
365,926
def unwrap_aliases(data_type): unwrapped_alias = False while is_alias(data_type): unwrapped_alias = True data_type = data_type.data_type return data_type, unwrapped_alias
Convenience method to unwrap all Alias(es) from around a DataType. Args: data_type (DataType): The target to unwrap. Return: Tuple[DataType, bool]: The underlying data type and a bool indicating whether the input type had at least one alias layer.
365,927
def find_closing_braces(self, query): if query[0] != : raise Exception("Trying to find closing braces for no opening braces") num_open_braces = 0 for i in range(len(query)): c = query[i] if c == : num_open_braces += 1 elif c == : num_open_braces -= 1 if num...
Find the index of the closing braces for the opening braces at the start of the query string. Note that first character of input string must be an opening braces.
365,928
def p_unitary_op_3(self, program): program[0] = node.CustomUnitary([program[1], program[4]]) self.verify_as_gate(program[1], program[4]) self.verify_reg_list(program[4], ) self.verify_distinct([program[4]])
unitary_op : id '(' ')' primary_list
365,929
def get_default_org(self): for org in self.list_orgs(): org_config = self.get_org(org) if org_config.default: return org, org_config return None, None
retrieve the name and configuration of the default org
365,930
def describe_api_key(apiKey, region=None, key=None, keyid=None, profile=None): try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) response = conn.get_api_key(apiKey=apiKey) return {: _convert_datetime_str(response)} except ClientError as e: return {:...
Gets info about the given api key CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_key apigw_api_key
365,931
def get_all_compiler_versions(): versions=[] if is_windows: if is_win64: keyname = else: keyname = try: k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, keyname) except SCons.Util.WinErro...
Returns a sorted list of strings, like "70" or "80" or "9.0" with most recent compiler version first.
365,932
def create_window(self): self.undocked_window = window = PluginWindow(self) window.setAttribute(Qt.WA_DeleteOnClose) icon = self.get_plugin_icon() if is_text_string(icon): icon = self.get_icon(icon) window.setWindowIcon(icon) window.setWindowTitle(sel...
Create a QMainWindow instance containing this plugin.
365,933
def BSearchFloor(a, x, lo=0, hi=None): if len(a) == 0: return -1 hi = hi if hi is not None else len(a) pos = bisect_left(a, x, lo, hi) return pos - 1 if pos >= hi \ else (pos if x == a[pos] else (pos - 1 if pos > lo else -1))
Returns highest i such as a[i] <= x, or -1 if x < all elements in a So, if x is in between two elements in a, this function will return the index of the lower element, hence "Floor". Arguments: a -- ordered numeric sequence x -- element to search within a lo -- lowest index to co...
365,934
def distance(args): from jcvi.utils.iter import pairwise p = OptionParser(distance.__doc__) p.add_option("--distmode", default="ss", choices=("ss", "ee"), help="Distance mode between paired reads. ss is outer distance, " \ "ee is inner distance [default: %default]") op...
%prog distance bedfile Calculate distance between bed features. The output file is a list of distances, which can be used to plot histogram, etc.
365,935
def addSpatialNoise(self, sequence, amount): newSequence = [] for pattern in sequence: if pattern is not None: pattern = self.patternMachine.addNoise(pattern, amount) newSequence.append(pattern) return newSequence
Add spatial noise to each pattern in the sequence. @param sequence (list) Sequence @param amount (float) Amount of spatial noise @return (list) Sequence with spatial noise
365,936
def get_md_header(header_text_line: str, header_duplicate_counter: dict, keep_header_levels: int = 3, parser: str = , no_links: bool = False) -> dict: r result = get_atx_heading(header_text_line, keep_header_levels, parser, ...
r"""Build a data structure with the elements needed to create a TOC line. :parameter header_text_line: a single markdown line that needs to be transformed into a TOC line. :parameter header_duplicate_counter: a data structure that contains the number of occurrencies of each header anchor link...
365,937
def get_fields(schema, exclude_dump_only=False): if hasattr(schema, "fields"): fields = schema.fields elif hasattr(schema, "_declared_fields"): fields = copy.deepcopy(schema._declared_fields) else: raise ValueError( "{!r} doesn't have either `fields` or `_declared_fi...
Return fields from schema :param Schema schema: A marshmallow Schema instance or a class object :param bool exclude_dump_only: whether to filter fields in Meta.dump_only :rtype: dict, of field name field object pairs
365,938
def wrap_call(self, call_cmd): if isinstance(call_cmd, basestring): call_cmd = [call_cmd] return [self._trickle_cmd, "-s"] + self._settings.to_argument_list() + list(call_cmd)
"wraps" the call_cmd so it can be executed by subprocess.call (and related flavors) as "args" argument :param call_cmd: original args like argument (string or sequence) :return: a sequence with the original command "executed" under trickle
365,939
def do_label(self): outputdict = self.outputdict xlabel_options = self.kwargs.get("xlabel_options", {}) self.subplot.set_xlabel( self.kwargs.get("xlabel", "").format(**outputdict), **xlabel_options) ylabel_options = self.kwargs.get("ylabel_options", {}) ...
Create label for x and y axis, title and suptitle
365,940
def hybrid_forward(self, F, a, b): tilde_a = self.f(a) tilde_b = self.f(b) e = F.batch_dot(tilde_a, tilde_b, transpose_b=True) beta = F.batch_dot(e.softmax(), tilde_b) alpha = F.batch_dot(e.transpose([0, ...
Forward of Decomposable Attention layer
365,941
def main(): arg_parser = argparse.ArgumentParser() arg_parser.add_argument(, , required=True, action=, help=) arg_parser.add_argument(, , required=True, action=, help=) arg_parser.add_argument(, , required=True, action=, help=) arg_p...
Main routine.
365,942
def process_request_params( self, params: Sequence[ExtensionParameter], accepted_extensions: Sequence[Extension], ) -> Tuple[List[ExtensionParameter], Extension]:
Process request parameters received from the client. ``params`` is a list of (name, value) pairs. ``accepted_extensions`` is a list of previously accepted extensions. To accept the offer, return a 2-uple containing: - response parameters: a list of (name, value) pairs - an ex...
365,943
def fix_geometry(self, isophote): self.sample.geometry.eps = isophote.sample.geometry.eps self.sample.geometry.pa = isophote.sample.geometry.pa self.sample.geometry.x0 = isophote.sample.geometry.x0 self.sample.geometry.y0 = isophote.sample.geometry.y0
Fix the geometry of a problematic isophote to be identical to the input isophote. This method should be called when the fitting goes berserk and delivers an isophote with bad geometry, such as ellipticity > 1 or another meaningless situation. This is not a problem in itself when...
365,944
def main(args=None): if args is None: args = sys.argv[1:] parser = argparse.ArgumentParser( description=) parser.add_argument(, , type=str, help="csv file to import") parser.add_argument(, , type=str, help="reformats results by module...
The main routine.
365,945
def check_arguments(args, parser): if args.asm_block not in [, ]: try: args.asm_block = int(args.asm_block) except ValueError: parser.error() if not args.unit: if in args.pmodel or in args.pmodel: args.unit = else: arg...
Check arguments passed by user that are not checked by argparse itself.
365,946
def get_chart(self, relation=None, index=0, limit=10, **kwargs): return self.get_object( "chart", object_id="0", relation=relation, parent="chart", **kwargs )
Get chart :returns: a list of :class:`~deezer.resources.Resource` objects.
365,947
def density_2d(self, x, y, Rs, rho0, r_core, center_x=0, center_y=0): x_ = x - center_x y_ = y - center_y R = np.sqrt(x_ ** 2 + y_ ** 2) b = r_core * Rs ** -1 x = R * Rs ** -1 Fx = self._F(x, b) return 2 * rho0 * Rs * Fx
projected two dimenstional NFW profile (kappa*Sigma_crit) :param R: radius of interest :type R: float/numpy array :param Rs: scale radius :type Rs: float :param rho0: density normalization (characteristic density) :type rho0: float :param r200: radius of (sub)hal...
365,948
def merged(self, other): children = [c for c in itertools.chain(self.children, other.children) if len(c) > 0] return ParseNode(self.node_type, children=children, consumed=self.consumed + other.consumed, ignored=self.ignored)
Returns a new ParseNode whose type is this node's type, and whose children are all the children from this node and the other whose length is not 0.
365,949
def last_bed_temp(self): try: bedtemps = self.intervals[1][][] except KeyError: return None tmp = 0 num_temps = len(bedtemps) if num_temps == 0: return None for temp in bedtemps: tmp += temp[1] bedtemp = t...
Return avg bed temperature for last session.
365,950
def toggle_plain_text(self, checked): if checked: self.docstring = checked self.switch_to_plain_text() self.force_refresh() self.set_option(, not checked)
Toggle plain text docstring
365,951
def _outputMessages(self, warnings, node): if not warnings: return for warning in warnings: linenum, offset, msgidInPyCodeStyle, text = warning if text.startswith(msgidInPyCodeStyle): text = text[len(msgidInPyCod...
Map pycodestyle results to messages in pylint, then output them. @param warnings: it should be a list of tuple including line number and message id
365,952
def init_states(batch_size, num_lstm_layer, num_hidden): init_c = [( % l, (batch_size, num_hidden)) for l in range(num_lstm_layer)] init_h = [( % l, (batch_size, num_hidden)) for l in range(num_lstm_layer)] return init_c + init_h
Returns name and shape of init states of LSTM network Parameters ---------- batch_size: list of tuple of str and tuple of int and int num_lstm_layer: int num_hidden: int Returns ------- list of tuple of str and tuple of int and int
365,953
def authenticate_external(self, auth_params): if not isinstance(auth_params, list): raise TypeError("auth_params can only be an instance of type list") for a in auth_params[:10]: if not isinstance(a, basestring): raise TypeError( "...
Verify credentials using the external auth library. in auth_params of type str The auth parameters, credentials, etc. out result of type str The authentification result.
365,954
def download(ctx): user, project_name = get_project_or_local(ctx.obj.get()) try: PolyaxonClient().project.download_repo(user, project_name) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error(.format(project_name)) Printer.print...
Download code of the current project.
365,955
def ProcessHuntFlowLog(flow_obj, log_msg): if not hunt.IsLegacyHunt(flow_obj.parent_hunt_id): return hunt_urn = rdfvalue.RDFURN("hunts").Add(flow_obj.parent_hunt_id) flow_urn = hunt_urn.Add(flow_obj.flow_id) log_entry = rdf_flows.FlowLog( client_id=flow_obj.client_id, urn=flow_urn, fl...
Processes log message from a given hunt-induced flow.
365,956
def to_api(in_dict, int_keys=None, date_keys=None, bool_keys=None): if int_keys: for in_key in int_keys: if (in_key in in_dict) and (in_dict.get(in_key, None) is not None): in_dict[in_key] = int(in_dict[in_key]) if date_keys: for in_key in date_keys: ...
Extends a given object for API Production.
365,957
def organizations(self, organization, include=None): return self._query_zendesk(self.endpoint.organizations, , id=organization, include=include)
Retrieve the tickets for this organization. :param include: list of objects to sideload. `Side-loading API Docs <https://developer.zendesk.com/rest_api/docs/core/side_loading>`__. :param organization: Organization object or id
365,958
def derive_fields(self): if self.fields: return list(self.fields) else: fields = [] for field in self.object._meta.fields: fields.append(field.name) exclude = self.derive_exclude() fields = ...
Derives our fields. We first default to using our 'fields' variable if available, otherwise we figure it out from our object.
365,959
def _batched_op_msg_compressed( operation, command, docs, check_keys, ack, opts, ctx): data, to_send = _encode_batched_op_msg( operation, command, docs, check_keys, ack, opts, ctx) request_id, msg = _compress( 2013, data, ctx.sock_info.compression_context) retur...
Create the next batched insert, update, or delete operation with OP_MSG, compressed.
365,960
def diff_texts(left, right, diff_options=None, formatter=None): return _diff(etree.fromstring, left, right, diff_options=diff_options, formatter=formatter)
Takes two Unicode strings containing XML
365,961
def copy(self, copyPrimaryKey=False, copyValues=False): cpy = self.__class__(**self.asDict(copyPrimaryKey, forStorage=False)) if copyValues is True: for fieldName in cpy.FIELDS: setattr(cpy, fieldName, copy.deepcopy(getattr(cpy, fieldName))) return cpy
copy - Copies this object. @param copyPrimaryKey <bool> default False - If True, any changes to the copy will save over-top the existing entry in Redis. If False, only the data is copied, and nothing is saved. @param copyValues <bool> default False - If True, every fi...
365,962
def getLibs(self, explicit_only=False): libbinsource if in self.description: return {os.path.normpath(self.description[]): self.getName()} elif not in self.description and not explicit_only: return {: self.getName()} else: return {}
Return a dictionary of libraries to compile: {"dirname":"libname"}, this is used when automatically generating CMakeLists. If explicit_only is not set, then in the absence of both 'lib' and 'bin' sections in the module.json file, the "source" directory will be returned. ...
365,963
def object_from_json(self, object_type, object_json, parent=None): if not isinstance(object_json, dict): return object_json obj = self.instantiate_object(object_type, parent) for key, value in object_json.items(): if key not in self.skip_attrs: ke...
Given a blob of JSON representing a Zenpy object, recursively deserialize it and any nested objects it contains. This method also adds the deserialized object to the relevant cache if applicable.
365,964
def add_hydrogen(self, num): self.H_count = num if num > 0 and self.symbol in ("N", "O"): self.H_donor = 1 else: self.H_donor = 0
Adds hydrogens Args: num (int): number of hydrogens
365,965
def at(self, root): leafs = root.strip(" ").split() for leaf in leafs: if leaf: self._json_data = self.__get_value_from_data(leaf, self._json_data) return self
Set root where PyJsonq start to prepare :@param root :@type root: string :@return self :@throws KeyError
365,966
def allow_cors(func): def wrapper(*args, **kwargs): response.headers[] = response.headers[] = \ response.headers[] = \ return func(*args, **kwargs) return wrapper
This is a decorator which enable CORS for the specified endpoint.
365,967
def set_daily(self, interval, **kwargs): self._clear_pattern() self.__interval = interval self.set_range(**kwargs)
Set to repeat every x no. of days :param int interval: no. of days to repeat at :keyword date start: Start date of repetition (kwargs) :keyword date end: End date of repetition (kwargs) :keyword int occurrences: no of occurrences (kwargs)
365,968
def copy_current_websocket_context(func: Callable) -> Callable: if not has_websocket_context(): raise RuntimeError() websocket_context = _websocket_ctx_stack.top.copy() @wraps(func) async def wrapper(*args: Any, **kwargs: Any) -> Any: async with websocket_context: retu...
Share the current websocket context with the function decorated. The websocket context is local per task and hence will not be available in any other task. This decorator can be used to make the context available, .. code-block:: python @copy_current_websocket_context async def within...
365,969
def bgsave(host=None, port=None, db=None, password=None): * server = _connect(host, port, db, password) return server.bgsave()
Asynchronously save the dataset to disk CLI Example: .. code-block:: bash salt '*' redis.bgsave
365,970
def live_processes(self): result = [] for process_type, process_infos in self.all_processes.items(): for process_info in process_infos: if process_info.process.poll() is None: result.append((process_type, process_info.process)) return resu...
Return a list of the live processes. Returns: A list of the live processes.
365,971
def basename(path, extension_marker="."): result = os.path.basename(path or "") if extension_marker: pre, _, post = result.rpartition(extension_marker) return pre or post return result
:param str|None path: Path to consider :param str|None extension_marker: Trim file extension based on specified character :return str: Basename part of path, without extension (if 'extension_marker' provided)
365,972
def register_presence_callback(self, type_, from_, cb): type_ = self._coerce_enum(type_, structs.PresenceType) warnings.warn( "register_presence_callback is deprecated; use " "aioxmpp.dispatcher.SimplePresenceDispatcher or " "aioxmpp.PresenceClient instead", ...
Register a callback to be called when a presence stanza is received. :param type_: Presence type to listen for. :type type_: :class:`~.PresenceType` :param from_: Sender JID to listen for, or :data:`None` for a wildcard match. :type from_: :class:`~aioxmpp.JID` or ...
365,973
def com_google_fonts_check_metadata_valid_name_values(style, font_metadata, font_familynames, typographic_familynames): from fontbakery.constants import ...
METADATA.pb font.name field contains font name in right format?
365,974
def default(self, obj): if isinstance(obj, UUID): return obj.hex elif isinstance(obj, datetime.datetime): return obj.isoformat() return super().default(obj)
Encode more types.
365,975
def post_run(self, outline=False, dump=False, *args, **kwargs): hooks = self.context.config.post_build handle_hooks( "post_build", hooks, self.provider, self.context, dump, outline )
Any steps that need to be taken after running the action.
365,976
def list_instances_json(self, application=None, show_only_destroyed=False): q_filter = {: , : , : , : , : } if not show_only_destroyed: q_filter[] = else: q_filter[] = q_filter[] = q_filt...
Get list of instances in json format converted to list
365,977
def list_domains(self): domains = [] for cookie in iter(self): if cookie.domain not in domains: domains.append(cookie.domain) return domains
Utility method to list all the domains in the jar.
365,978
def unpack_from(self, data, offset=0): return {info.name: v for info, v in self.unpack_from_any(data, offset)}
See :func:`~bitstruct.unpack_from_dict()`.
365,979
def setMinimumPixmapSize(self, size): self._minimumPixmapSize = size position = self.position() self._position = None self.setPosition(position)
Sets the minimum pixmap size that will be displayed to the user for the dock widget. :param size | <int>
365,980
def parse_end_date(self, request, start_date): if request.GET.get(): try: return djtz.parse( % request.GET.get()) except ValueError: pass days_to_show = self.default_days_to_show or \ appsettings.DEFAULT_DAYS_TO_SHOW if...
Return period in days after the start date to show event occurrences, which is one of the following in order of priority: - `end_date` GET parameter value, if given and valid. The filtering will be *inclusive* of the end date: until end-of-day of this date - `days_to_show` GET param...
365,981
def CreateKey(self, prikey=None): account = super(UserWallet, self).CreateKey(private_key=prikey) self.OnCreateAccount(account) contract = WalletContract.CreateSignatureContract(account.PublicKey) self.AddContract(contract) return account
Create a KeyPair and store it encrypted in the database. Args: private_key (iterable_of_ints): (optional) 32 byte private key. Returns: KeyPair: a KeyPair instance.
365,982
def read_magic_file(self, path, sort_by_this_name, sort_by_file_type=False): DATA = {} with open(path, ) as fin: lines = list(fin.readlines()) first_line = lines[0] if not first_line: return False, None, if first_line[0] == "s" or first_line[1] =...
read a magic-formatted tab-delimited file. return a dictionary of dictionaries, with this format: {'Z35.5a': {'specimen_weight': '1.000e-03', 'er_citation_names': 'This study', 'specimen_volume': '', 'er_location_name': '', 'er_site_name': 'Z35.', 'er_sample_name': 'Z35.5', 'specimen_class': '', 'er_spe...
365,983
def _calc_rms(mol1, mol2, clabel1, clabel2): obmol1 = BabelMolAdaptor(mol1).openbabel_mol obmol2 = BabelMolAdaptor(mol2).openbabel_mol cmol1 = ob.OBMol() for i in clabel1: oa1 = obmol1.GetAtom(i) a1 = cmol1.NewAtom() a1.SetAtomicNum(oa1.GetAt...
Calculate the RMSD. Args: mol1: The first molecule. OpenBabel OBMol or pymatgen Molecule object mol2: The second molecule. OpenBabel OBMol or pymatgen Molecule object clabel1: The atom indices that can reorder the first molecule to ...
365,984
async def dump_tuple(self, elem, elem_type, params=None, obj=None): if len(elem) != len(elem_type.f_specs()): raise ValueError( % len(elem_type.f_specs())) elem_fields = params[0] if params else None if elem_fields is None: elem_fields = elem_type.f_specs() ...
Dumps tuple of elements to the writer. :param elem: :param elem_type: :param params: :param obj: :return:
365,985
def cross_entropy_loss(logits, one_hot_labels, label_smoothing=0, weight=1.0, scope=None): logits.get_shape().assert_is_compatible_with(one_hot_labels.get_shape()) with tf.name_scope(scope, , [logits, one_hot_labels]): num_classes = one_hot_labels.get_shape()[-1].value one_hot_labe...
Define a Cross Entropy loss using softmax_cross_entropy_with_logits. It can scale the loss by weight factor, and smooth the labels. Args: logits: [batch_size, num_classes] logits outputs of the network . one_hot_labels: [batch_size, num_classes] target one_hot_encoded labels. label_smoothing: if great...
365,986
def getSimpleFileData(self, fileInfo, data): result = fileInfo[fileInfo.find(data + "</td>"):] result = result[:result.find("</A></td>")] result = result[result.rfind(">") + 1:] return result
Function to initialize the simple data for file info
365,987
def transform_to_matrices(transform): components = [ [j.strip() for j in i.strip().split() if len(j) > 0] for i in transform.lower().split() if len(i) > 0] matrices = [] for line in components: if len(line) == 0: continue elif len(line) != 2: ...
Convert an SVG transform string to an array of matrices. > transform = "rotate(-10 50 100) translate(-36 45.5) skewX(40) scale(1 0.5)" Parameters ----------- transform : str Contains transformation information in SVG form Returns ...
365,988
def rpc(self, address, rpc_id): if address in self.mock_rpcs and rpc_id in self.mock_rpcs[address]: value = self.mock_rpcs[address][rpc_id] return value result = self._call_rpc(address, rpc_id, bytes()) if len(result) != 4: self.warn(u"RPC...
Call an RPC and receive the result as an integer. If the RPC does not properly return a 32 bit integer, raise a warning unless it cannot be converted into an integer at all, in which case a HardwareError is thrown. Args: address (int): The address of the tile we want to cal...
365,989
def build(self, grad_list, get_opt_fn): assert len(grad_list) == len(self.towers) DataParallelBuilder._check_grad_list(grad_list) if self._scale_gradient and len(self.towers) > 1: gradproc = ScaleGradient((, 1.0 / len(self.towers)), verbose=False) ...
Args: grad_list ([[(grad, var), ...], ...]): #GPU lists to be reduced. Each is the gradients computed on each GPU. get_opt_fn (-> tf.train.Optimizer): callable which returns an optimizer Returns: tf.Operation: the training op
365,990
def check_valid_temperature(var, units): r check_valid(var, , ) check_valid(var, , units) assert_daily(var)
r"""Check that variable is air temperature.
365,991
def VerifyStructure(self, parser_mediator, line): self._last_month = 0 self._year_use = parser_mediator.GetEstimatedYear() try: structure = self.FIREWALL_LINE.parseString(line) except pyparsing.ParseException as exception: logger.debug(( ).format(exception)) ...
Verify that this file is a Mac AppFirewall log file. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. line (str): line from a text file. Returns: bool: True if the line is in the expected format, False if...
365,992
def to_text(self, filename=None, overwrite=True): table = self.standardized if filename == None: filename = .format(self.name) self.speak(.format(filename)) table.write(filename, format=, overwrite=overwrite)
Write this catalog out to a text file.
365,993
def _get_args(self, executable, *args): args = list(args) args.insert(0, executable) if self.username: args.append("--username={}".format(self.username)) if self.host: args.append("--host={}".format(self.host)) if self.port: args.appen...
compile all the executable and the arguments, combining with common arguments to create a full batch of command args
365,994
def generate(self): ts=self.generate_tobs() noise=self.generate_noise(ts) rvs=[] for t,n in zip(ts, noise): rvs.append(n + np.sum(rv.rv_model(t, self.params), axis=0)) return ts,rvs
Returns (ts, rvs), where ts is a list of arrays of observation times (one array for each observatory), and rvs is a corresponding list of total radial velocity measurements.
365,995
def GetServices(self,filename): objlist=[] for sobj in self.services: if sobj.KnowsFile(filename) : objlist.append(sobj) if len(objlist)==0: return None return objlist
Returns a list of service objects handling this file type
365,996
def GetPathInfo(self, timestamp=None): path_info_timestamp = self._LastEntryTimestamp(self._path_infos, timestamp) try: result = self._path_infos[path_info_timestamp].Copy() except KeyError: result = rdf_objects.PathInfo( path_type=self._path_type, components=self._components) ...
Generates a summary about the path record. Args: timestamp: A point in time from which the data should be retrieved. Returns: A `rdf_objects.PathInfo` instance.
365,997
def asynloop(self, auto_connect=False, timeout=10, detached_delay=0.2): if auto_connect: self.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT)) try: self.listening = True start = int(time.time()) while True: asynco...
Non-blocking event loop consuming messages until connection is lost, or shutdown is requested. :param int timeout: number of secs for asyncore timeout :param float detached_delay: float secs to sleep when exiting asyncore loop and execution detached queue callbacks
365,998
def system_types(): * ret = {} for line in __salt__[]().splitlines(): if not line: continue if line.startswith(): continue comps = line.strip().split() ret[comps[0]] = comps[1] return ret
List the system types that are supported by the installed version of sfdisk CLI Example: .. code-block:: bash salt '*' partition.system_types
365,999
def _to_numpy(Z): if Z is None: return Z elif issparse(Z): return Z.toarray() elif isinstance(Z, np.ndarray): return Z elif isinstance(Z, list): return np.array(Z) elif isinstance(Z, torch.Tensor): return Z.cpu(...
Converts a None, list, np.ndarray, or torch.Tensor to np.ndarray; also handles converting sparse input to dense.