code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def create_cluster_set(self, vcl): """ For a given catalogue and list of cluster IDs this function splits the catalogue into a dictionary containing an individual catalogue of events within each cluster :param numpy.ndarray vcl: Cluster ID list :returns: ...
For a given catalogue and list of cluster IDs this function splits the catalogue into a dictionary containing an individual catalogue of events within each cluster :param numpy.ndarray vcl: Cluster ID list :returns: Dictionary of instances of the :class: ...
def worker_status(obj, filter_queues, details): """ Show the status of all running workers. """ show_colors = obj['show_color'] f_queues = filter_queues.split(',') if filter_queues is not None else None workers = list_workers(config=obj['config'], filter_by_queues=f_queues) if len(workers) == 0: ...
Show the status of all running workers.
def match(self, uri): """ Check to see if this URI is retrievable by this Retriever implementation :param uri: the URI of the resource to be retrieved :type uri: str :return: True if it can be, False if not :rtype: bool """ absolute_uri = self.__absolute__(uri) ...
Check to see if this URI is retrievable by this Retriever implementation :param uri: the URI of the resource to be retrieved :type uri: str :return: True if it can be, False if not :rtype: bool
def blacklistClient(self, clientName: str, reason: str = None, code: int = None): """ Add the client specified by `clientName` to this node's blacklist """ msg = "{} blacklisting client {}".format(self, clientName) if reason: msg += " for reaso...
Add the client specified by `clientName` to this node's blacklist
def _is_ascii_stl(first_bytes): """ Determine if this is an ASCII based data stream, simply by checking the bytes for the word 'solid'. """ is_ascii = False if 'solid' in first_bytes.decode("utf-8").lower(): is_ascii = True return is_ascii
Determine if this is an ASCII based data stream, simply by checking the bytes for the word 'solid'.
def _parse_config(self, config): """ Parses a tensorflow configuration """ self._batch_size = config['batch_size'] self._im_height = config['im_height'] self._im_width = config['im_width'] self._num_channels = config['channels'] self._output_layer = config['out_layer'] ...
Parses a tensorflow configuration
def get_root_nodes(self, project, depth=None): """GetRootNodes. [Preview API] Gets root classification nodes under the project. :param str project: Project ID or project name :param int depth: Depth of children to fetch. :rtype: [WorkItemClassificationNode] """ ro...
GetRootNodes. [Preview API] Gets root classification nodes under the project. :param str project: Project ID or project name :param int depth: Depth of children to fetch. :rtype: [WorkItemClassificationNode]
def new(self, bootstrap_with=None, use_timer=False): """ Actual constructor of the solver. """ if not self.minisat: self.minisat = pysolvers.minisat22_new() if bootstrap_with: for clause in bootstrap_with: self.add_clause(...
Actual constructor of the solver.
def _update_file_frontiers( self, frontier_list, revision, max_csets_proc=30, going_forward=False ): ''' Update the frontier for all given files, up to the given revision. Built for quick continuous _forward_ updating of large ...
Update the frontier for all given files, up to the given revision. Built for quick continuous _forward_ updating of large sets of files of TUIDs. Backward updating should be done through get_tuids(files, revision). If we cannot find a frontier, we will stop looking after max_csets_proc ...
def failure_recovery(self, fail_info): """Failure recovery task. In case of failure in projects, network and VM create/delete, this task goes through all failure cases and try the request. """ # Read failed entries from project database and send request # (create/delete ...
Failure recovery task. In case of failure in projects, network and VM create/delete, this task goes through all failure cases and try the request.
def split_key_string(key): """Splits a key string (of the form, e.g. ``'C# major'``), into a tuple of ``(key, mode)`` where ``key`` is is an integer representing the semitone distance from C. Parameters ---------- key : str String representing a key. Returns ------- key : i...
Splits a key string (of the form, e.g. ``'C# major'``), into a tuple of ``(key, mode)`` where ``key`` is is an integer representing the semitone distance from C. Parameters ---------- key : str String representing a key. Returns ------- key : int Number of semitones abo...
def can_pull(self, initial, scheduled): """ Determines if pull requests should be created :return: bool """ if not initial and self.config.is_valid_schedule(): # if the config has a valid schedule, return True if this is a scheduled run return scheduled ...
Determines if pull requests should be created :return: bool
def domain_name_cleanse(raw_string): '''extract a lower-case, no-slashes domain name from a raw string that might be a URL ''' try: parts = urlparse(raw_string) domain = parts.netloc.split(':')[0] except: domain = '' if not domain: domain = raw_string if not d...
extract a lower-case, no-slashes domain name from a raw string that might be a URL
def _decode_key(self, key): """Decode key using hex_codec to retrieve the original key. Keys are returned as :class:`str` if serialization is enabled. Keys are returned as :class:`bytes` if serialization is disabled. """ bkey = codecs.decode(key.encode(self._keyencoding), 'hex_...
Decode key using hex_codec to retrieve the original key. Keys are returned as :class:`str` if serialization is enabled. Keys are returned as :class:`bytes` if serialization is disabled.
def JC69 (mu=1.0, alphabet="nuc", **kwargs): """ Jukes-Cantor 1969 model. This model assumes equal concentrations of the nucleotides and equal transition rates between nucleotide states. For more info, see: Jukes and Cantor (1969). Evolution of Protein Molecules. New York: Academ...
Jukes-Cantor 1969 model. This model assumes equal concentrations of the nucleotides and equal transition rates between nucleotide states. For more info, see: Jukes and Cantor (1969). Evolution of Protein Molecules. New York: Academic Press. pp. 21–132 Parameters ----------- ...
def dump_certificate_request(type, req): """ Dump the certificate request *req* into a buffer string encoded with the type *type*. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1) :param req: The certificate request to dump :return: The buffer with the dumped certificate request ...
Dump the certificate request *req* into a buffer string encoded with the type *type*. :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1) :param req: The certificate request to dump :return: The buffer with the dumped certificate request in
async def RelationById(self, relation_ids): ''' relation_ids : typing.Sequence[int] Returns -> typing.Sequence[~RelationResult] ''' # map input types to rpc msg _params = dict() msg = dict(type='Uniter', request='RelationById', ...
relation_ids : typing.Sequence[int] Returns -> typing.Sequence[~RelationResult]
def split_before(iterable, pred): """Yield lists of items from *iterable*, where each list starts with an item where callable *pred* returns ``True``: >>> list(split_before('OneTwo', lambda s: s.isupper())) [['O', 'n', 'e'], ['T', 'w', 'o']] >>> list(split_before(range(10), lambda n: n...
Yield lists of items from *iterable*, where each list starts with an item where callable *pred* returns ``True``: >>> list(split_before('OneTwo', lambda s: s.isupper())) [['O', 'n', 'e'], ['T', 'w', 'o']] >>> list(split_before(range(10), lambda n: n % 3 == 0)) [[0, 1, 2], [3, 4, 5]...
def public_key(self): """ Returns the public key associated with this private key. Returns: HDPublicKey: The HDPublicKey object that corresponds to this private key. """ if self._public_key is None: self._public_key = HDPublicKey(x...
Returns the public key associated with this private key. Returns: HDPublicKey: The HDPublicKey object that corresponds to this private key.
def gen_tau(S, K, delta): """The Robust part of the RSD, we precompute an array for speed """ pivot = floor(K/S) return [S/K * 1/d for d in range(1, pivot)] \ + [S/K * log(S/delta)] \ + [0 for d in range(pivot, K)]
The Robust part of the RSD, we precompute an array for speed
def get_authorization(self, request): """ This function extracts the authorization JWT string. It first looks for specified key in header and then looks for the same in body part. Parameters ---------- request: HttpRequest This is the raw request that...
This function extracts the authorization JWT string. It first looks for specified key in header and then looks for the same in body part. Parameters ---------- request: HttpRequest This is the raw request that user has sent. Returns ------- a...
def get_target_service_state(self, service_id: str): """Get the state of a SDP service.""" state = self._get_service_state(service_id) return state.target_state
Get the state of a SDP service.
def get_steps( self, values_only = False, merge_steps=True ): """To get a succinct representation of the StepVector's content, call the 'get_steps' method. It returns an iterator that generates triples of values. Each triple contains one step, giving first the start index of the step, then the s...
To get a succinct representation of the StepVector's content, call the 'get_steps' method. It returns an iterator that generates triples of values. Each triple contains one step, giving first the start index of the step, then the stop index (i.e., one more than the index of the last element), a...
def _sendReset(self, sequenceId=0): """ Sends a reset signal to the network. """ for col in xrange(self.numColumns): self.sensorInputs[col].addResetToQueue(sequenceId) self.externalInputs[col].addResetToQueue(sequenceId) self.network.run(1)
Sends a reset signal to the network.
def sendSync(self, query, *parameters, **options): '''Performs a synchronous query against a q service and returns parsed data. In typical use case, `query` is the name of the function to call and `parameters` are its parameters. When `parameters` list is empty, the q...
Performs a synchronous query against a q service and returns parsed data. In typical use case, `query` is the name of the function to call and `parameters` are its parameters. When `parameters` list is empty, the query can be an arbitrary q expression (e.g. ``0 +/ til 100``)....
def generic_var(self, key, value=None): """ Stores generic variables in the session prepending it with _GENERIC_VAR_KEY_PREFIX. """ return self._get_or_set('{0}{1}'.format(self._GENERIC_VAR_KEY_PREFIX, key), value)
Stores generic variables in the session prepending it with _GENERIC_VAR_KEY_PREFIX.
def distribute(self, func, partitioned_chunks, kwargs): """ Calculates the features in a sequential fashion by pythons map command :param func: the function to send to each worker. :type func: callable :param partitioned_chunks: The list of data chunks - each element is again ...
Calculates the features in a sequential fashion by pythons map command :param func: the function to send to each worker. :type func: callable :param partitioned_chunks: The list of data chunks - each element is again a list of chunks - and should be processed by one worker. ...
def _expand_qname(self, qname): """expand a qualified name's namespace prefix to include the resolved namespace root url""" if type(qname) is not rt.URIRef: raise TypeError("Cannot expand qname of type {}, must be URIRef" .format(type(qname))) for ...
expand a qualified name's namespace prefix to include the resolved namespace root url
def lock(thing_name, lock, key, session=None): """Lock a thing (prevents unauthed dweets for the locked thing) """ return _request('get', '/lock/{0}'.format(thing_name), params={'key': key, 'lock': lock}, session=session)
Lock a thing (prevents unauthed dweets for the locked thing)
def cycle_file(key_arn, source_plaintext_filename, botocore_session=None): """Encrypts and then decrypts a file using a KMS master key provider and a custom static master key provider. Both master key providers are used to encrypt the plaintext file, so either one alone can decrypt it. :param str key_a...
Encrypts and then decrypts a file using a KMS master key provider and a custom static master key provider. Both master key providers are used to encrypt the plaintext file, so either one alone can decrypt it. :param str key_arn: Amazon Resource Name (ARN) of the KMS Customer Master Key (CMK) (http://do...
def _rlimit_min(one_val, nother_val): """Returns the more stringent rlimit value. -1 means no limit.""" if one_val < 0 or nother_val < 0 : return max(one_val, nother_val) else: return min(one_val, nother_val)
Returns the more stringent rlimit value. -1 means no limit.
def center_fit(self, **kwargs): """Write compact xtc that is fitted to the tpr reference structure. See :func:`gromacs.cbook.trj_fitandcenter` for details and description of *kwargs* (including *input*, *input1*, *n* and *n1* for how to supply custom index groups). The most important on...
Write compact xtc that is fitted to the tpr reference structure. See :func:`gromacs.cbook.trj_fitandcenter` for details and description of *kwargs* (including *input*, *input1*, *n* and *n1* for how to supply custom index groups). The most important ones are listed here but in most case...
def acquire_subsamples_gp1(input_data, file_name=None): """ Function invoked for plotting a grid-plot with 3x2 format, showing the differences in ECG signals accordingly to the chosen sampling frequency. Applied in the cell with tag "subsampling_grid_plot_1". ---------- Parameters --------...
Function invoked for plotting a grid-plot with 3x2 format, showing the differences in ECG signals accordingly to the chosen sampling frequency. Applied in the cell with tag "subsampling_grid_plot_1". ---------- Parameters ---------- input_data : dict Dictionary with ECG signal to prese...
def load_earlier_messages_till(self, last): """ Triggers loading of messages till a specific point in time :param last: Datetime object for the last message to be loaded :type last: datetime :return: Nothing :rtype: None """ timestamp = time.mktime(last.t...
Triggers loading of messages till a specific point in time :param last: Datetime object for the last message to be loaded :type last: datetime :return: Nothing :rtype: None
def add_routes(self, routes: Iterable[AbstractRouteDef]) -> None: """Append routes to route table. Parameter should be a sequence of RouteDef objects. """ for route_def in routes: route_def.register(self)
Append routes to route table. Parameter should be a sequence of RouteDef objects.
async def set_active(self): """Set this client as active. While a client is active, no other clients will raise notifications. Call this method whenever there is an indication the user is interacting with this client. This method may be called very frequently, and it will only m...
Set this client as active. While a client is active, no other clients will raise notifications. Call this method whenever there is an indication the user is interacting with this client. This method may be called very frequently, and it will only make a request when necessary.
def __modify(self, preapproval_id, **kwargs): """Call documentation: `/preapproval/modify <https://www.wepay.com/developer/reference/preapproval#modify>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``, with ``ba...
Call documentation: `/preapproval/modify <https://www.wepay.com/developer/reference/preapproval#modify>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``, with ``batch_mode=True`` will set `authorization` param...
def _updateEmissionProbabilities(self): """Sample a new set of emission probabilites from the conditional distribution P(E | S, O) """ observations_by_state = [self.model.collect_observations_in_state(self.observations, state) for state in range(self.model.nstat...
Sample a new set of emission probabilites from the conditional distribution P(E | S, O)
def convert_input_vector(y, index): """ Unite target data type into a Series. If the target is a Series or a DataFrame, we preserve its index. But if the target does not contain index attribute, we use the index from the argument. """ if y is None: return None if isinstance(y, pd.Ser...
Unite target data type into a Series. If the target is a Series or a DataFrame, we preserve its index. But if the target does not contain index attribute, we use the index from the argument.
def _CheckLocation(self, file_entry, search_depth): """Checks the location find specification. Args: file_entry (FileEntry): file entry. search_depth (int): number of location path segments to compare. Returns: bool: True if the file entry matches the find specification, False if not. ...
Checks the location find specification. Args: file_entry (FileEntry): file entry. search_depth (int): number of location path segments to compare. Returns: bool: True if the file entry matches the find specification, False if not.
def tm_header(filename, ppdesc): """ Parse the TM abinit header. Example: Troullier-Martins psp for element Fm Thu Oct 27 17:28:39 EDT 1994 100.00000 14.00000 940714 zatom, zion, pspdat 1 1 3 0 2001 .00000 pspcod,pspxc,lmax,llo...
Parse the TM abinit header. Example: Troullier-Martins psp for element Fm Thu Oct 27 17:28:39 EDT 1994 100.00000 14.00000 940714 zatom, zion, pspdat 1 1 3 0 2001 .00000 pspcod,pspxc,lmax,lloc,mmax,r2well 0 4.085 6.246 0 2.8...
def iter_files(root, exts=None, recursive=False): """ Iterate over file paths within root filtered by specified extensions. :param compat.string_types root: Root folder to start collecting files :param iterable exts: Restrict results to given file extensions :param bool recursive: Wether to walk the...
Iterate over file paths within root filtered by specified extensions. :param compat.string_types root: Root folder to start collecting files :param iterable exts: Restrict results to given file extensions :param bool recursive: Wether to walk the complete directory tree :rtype collections.Iterable[str]:...
def converged(matrix1, matrix2): """ Check for convergence by determining if matrix1 and matrix2 are approximately equal. :param matrix1: The matrix to compare with matrix2 :param matrix2: The matrix to compare with matrix1 :returns: True if matrix1 and matrix2 approximately equal """ ...
Check for convergence by determining if matrix1 and matrix2 are approximately equal. :param matrix1: The matrix to compare with matrix2 :param matrix2: The matrix to compare with matrix1 :returns: True if matrix1 and matrix2 approximately equal
def fallback_findfile(filename): """ :param str filename: :return: try to find the full filename, e.g. in modules, etc :rtype: str|None """ mods = [m for m in sys.modules.values() if m and hasattr(m, "__file__") and filename in m.__file__] if len(mods) == 0: return None alt_fn = ...
:param str filename: :return: try to find the full filename, e.g. in modules, etc :rtype: str|None
def as_png_data_uri(matrix, version, scale=1, border=None, color='#000', background='#fff', compresslevel=9, addad=True): """\ Converts the provided matrix into a PNG data URI. :rtype: str """ buff = io.BytesIO() write_png(matrix, version, buff, scale=scale, border=border, c...
\ Converts the provided matrix into a PNG data URI. :rtype: str
def last(cls, *criterion, **kwargs): """Returns the last instance matching the criterion and/or keyword arguments. Examples: last_male_user = User.last(gender="male") """ kwargs['reverse'] = True return cls.first(*criterion, **kwargs)
Returns the last instance matching the criterion and/or keyword arguments. Examples: last_male_user = User.last(gender="male")
def close_others(self): """ Closes every editors tabs except the current one. """ current_widget = self.currentWidget() self._try_close_dirty_tabs(exept=current_widget) i = 0 while self.count() > 1: widget = self.widget(i) if widget != curr...
Closes every editors tabs except the current one.
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name ...
Return a json dictionary representing this model.
def _pushdate_urls(cls, pushdate, branch, target_platform): """Multiple entries exist per push date. Iterate over all until a working entry is found""" url_base = cls.URL_BASE + '/namespaces/gecko.v2.mozilla-' + branch + '.pushdate.' + pushdate try: base = HTTP_SESSION.post(url_base...
Multiple entries exist per push date. Iterate over all until a working entry is found
def rpc_get_account_at(self, address, block_height, **con_info): """ Get the account's statuses at a particular block height. Returns the sequence of history states on success """ if not check_account_address(address): return {'error': 'Invalid address', 'http_status'...
Get the account's statuses at a particular block height. Returns the sequence of history states on success
def clean(self): """ remove the directory we operated on :return: None """ if self._initialized: logger.info("brace yourselves, removing %r", self.path) shutil.rmtree(self.path)
remove the directory we operated on :return: None
def _register_scatter(): """ Patch `PathCollection` and `scatter` to register their return values. This registration allows us to distinguish `PathCollection`s created by `Axes.scatter`, which should use point-like picking, from others, which should use path-like picking. The former is more common...
Patch `PathCollection` and `scatter` to register their return values. This registration allows us to distinguish `PathCollection`s created by `Axes.scatter`, which should use point-like picking, from others, which should use path-like picking. The former is more common, so we store the latter instead;...
def is_open(location=None, attr=None): """ Returns False if the location is closed, or the OpeningHours object to show the location is currently open. """ obj = utils.is_open(location) if obj is False: return False if attr is not None: return getattr(obj, attr) return obj
Returns False if the location is closed, or the OpeningHours object to show the location is currently open.
def load(self, ioi, ac_ignore_missing=False, **options): """ Load config from a file path or a file / file-like object which 'ioi' refering after some checks. :param ioi: 'anyconfig.globals.IOInfo' namedtuple object provides various info of input object to load d...
Load config from a file path or a file / file-like object which 'ioi' refering after some checks. :param ioi: 'anyconfig.globals.IOInfo' namedtuple object provides various info of input object to load data from :param ac_ignore_missing: Ignore and just retur...
def similar_artists(self, artist_id: str) -> List[NameExternalIDPair]: """ Returns zero or more similar artists (in the form of artist name - external ID pairs) to the one corresponding to the given artist ID. Arguments: artist_id ([str]): The Spotify ID of the artist for wh...
Returns zero or more similar artists (in the form of artist name - external ID pairs) to the one corresponding to the given artist ID. Arguments: artist_id ([str]): The Spotify ID of the artist for whom similar artists are requested. Returns: Zero or more artist name - ...
def rmultinomial(n, p, size=None): """ Random multinomial variates. """ # Leaving size=None as the default means return value is 1d array # if not specified-- nicer. # Single value for p: if len(np.shape(p)) == 1: return np.random.multinomial(n, p, size) # Multiple values for p...
Random multinomial variates.
def get_study_items(results): """Return a list of study items associated with the given results.""" study_items = set() for obj in results: study_items.update(obj.study_items) return study_items
Return a list of study items associated with the given results.
def resolve( self, configurable=None, scope=None, safe=None, besteffort=None ): """Resolve all parameters. :param Configurable configurable: configurable to use for foreign parameter resolution. :param dict scope: variables to use for parameter expression evaluation....
Resolve all parameters. :param Configurable configurable: configurable to use for foreign parameter resolution. :param dict scope: variables to use for parameter expression evaluation. :param bool safe: safe execution (remove builtins functions). :raises: Parameter.Error for...
def remove(self, id_equipamento, id_egrupo): """Remove a associacao de um grupo de equipamento com um equipamento a partir do seu identificador. :param id_egrupo: Identificador do grupo de equipamento. :param id_equipamento: Identificador do equipamento. :return: None :raise E...
Remove a associacao de um grupo de equipamento com um equipamento a partir do seu identificador. :param id_egrupo: Identificador do grupo de equipamento. :param id_equipamento: Identificador do equipamento. :return: None :raise EquipamentoNaoExisteError: Equipamento não cadastrado. ...
def verify_signature_block(certificate_file, content, signature): """ Verifies the 'signature' over the 'content', trusting the 'certificate'. :param certificate_file: the trusted certificate (PEM format) :type certificate_file: str :param content: The signature should match this content :t...
Verifies the 'signature' over the 'content', trusting the 'certificate'. :param certificate_file: the trusted certificate (PEM format) :type certificate_file: str :param content: The signature should match this content :type content: str :param signature: data (DER format) subject to check ...
def review_metadata_csv_multi_user(filedir, metadata, csv_in, n_headers): """ Check validity of metadata for multi user. :param filedir: This field is the filepath of the directory whose csv has to be made. :param metadata: This field is the metadata generated from the load_metadata_csv...
Check validity of metadata for multi user. :param filedir: This field is the filepath of the directory whose csv has to be made. :param metadata: This field is the metadata generated from the load_metadata_csv function. :param csv_in: This field returns a reader object which iterates over t...
def assoc(_d, key, value): """Associate a key with a value in a dictionary :param _d: a dictionary :param key: a key in the dictionary :param value: a value for the key :returns: a new dictionary >>> data = {} >>> new_data = assoc(data, 'name', 'Holy Grail') >>> new_data {'name': '...
Associate a key with a value in a dictionary :param _d: a dictionary :param key: a key in the dictionary :param value: a value for the key :returns: a new dictionary >>> data = {} >>> new_data = assoc(data, 'name', 'Holy Grail') >>> new_data {'name': 'Holy Grail'} >>> data {} ...
def _decode_bytes(data, encoding, str_len): """ Generic decoding with length check. The string is decoded from bytes with the given encoding, then the length of the string is checked. The string is decoded using the "replace" method. :param data: bytes :param enc...
Generic decoding with length check. The string is decoded from bytes with the given encoding, then the length of the string is checked. The string is decoded using the "replace" method. :param data: bytes :param encoding: encoding name ("utf-8" or "utf-16") :param str_le...
def int2ap(num): """Convert integer to A-P string representation.""" val = '' ap = 'ABCDEFGHIJKLMNOP' num = int(abs(num)) while num: num, mod = divmod(num, 16) val += ap[mod:mod + 1] return val
Convert integer to A-P string representation.
def remove(self, arr): """Removes an array from the list Parameters ---------- arr: str or :class:`InteractiveBase` The array name or the data object in this list to remove Raises ------ ValueError If no array with the specified array nam...
Removes an array from the list Parameters ---------- arr: str or :class:`InteractiveBase` The array name or the data object in this list to remove Raises ------ ValueError If no array with the specified array name is in the list
def ReadCronJobRun(self, job_id, run_id, cursor=None): """Reads a single cron job run from the db.""" query = ("SELECT run, UNIX_TIMESTAMP(write_time) FROM cron_job_runs " "WHERE job_id = %s AND run_id = %s") num_runs = cursor.execute( query, [job_id, db_utils.CronJobRunIDToInt(run_id)]...
Reads a single cron job run from the db.
def resolve_remote(self, uri): """ Resolve a remote ``uri``. If called directly, does not check the store first, but after retrieving the document at the specified URI it will be saved in the store if :attr:`cache_remote` is True. .. note:: If the requests_...
Resolve a remote ``uri``. If called directly, does not check the store first, but after retrieving the document at the specified URI it will be saved in the store if :attr:`cache_remote` is True. .. note:: If the requests_ library is present, ``jsonschema`` will use it to ...
def map_routes( feed: "Feed", route_ids: List[str], date: Optional[str] = None, color_palette: List[str] = cs.COLORS_SET2, *, include_stops: bool = True, ): """ Return a Folium map showing the given routes and (optionally) their stops. Parameters ---------- feed : Feed ...
Return a Folium map showing the given routes and (optionally) their stops. Parameters ---------- feed : Feed route_ids : list IDs of routes in ``feed.routes`` date : string YYYYMMDD date string restricting the output to trips active on the date color_palette : list ...
def update(self, buyer_nick, status, session, grade=None, province=None, city=None): '''taobao.crm.memberinfo.update 编辑会员资料 检查一个分组上是否有异步任务,异步任务包括 - 1.将一个分组下的所有用户添加到另外一个分组 - 2.将一个分组下的所有用户移动到另外一个分组 - 3.删除某个分组 若分组上有任务则该属性不能被操作。''' request = TOPRequest('taob...
taobao.crm.memberinfo.update 编辑会员资料 检查一个分组上是否有异步任务,异步任务包括 - 1.将一个分组下的所有用户添加到另外一个分组 - 2.将一个分组下的所有用户移动到另外一个分组 - 3.删除某个分组 若分组上有任务则该属性不能被操作。
def comment(self): """ Comments/Uncomments the selected lines or the current lines if there is no selection. """ cursor = self.editor.textCursor() # get the indent at which comment should be inserted and whether to # comment or uncomment the selected text ...
Comments/Uncomments the selected lines or the current lines if there is no selection.
def from_set(self, fileset, check_if_dicoms=True): """Overwrites self.items with the given set of files. Will filter the fileset and keep only Dicom files. Parameters ---------- fileset: iterable of str Paths to files check_if_dicoms: bool Whether to che...
Overwrites self.items with the given set of files. Will filter the fileset and keep only Dicom files. Parameters ---------- fileset: iterable of str Paths to files check_if_dicoms: bool Whether to check if the items in fileset are dicom file paths
def simxSetObjectFloatParameter(clientID, objectHandle, parameterID, parameterValue, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' return c_SetObjectFloatParameter(clientID, objectHandle, parameterID, parameterValue, operationMode)
Please have a look at the function description/documentation in the V-REP user manual
def FeatureReader( fh, format='gff', alt_introns_subtract="exons", gtf_parse=None): """ yield chrom, strand, cds_exons, introns, exons, name gtf_parse Example: # parse gene_id from transcript_id "AC073130.2-001"; gene_id "TES"; gene_name = lambda s: s.split(';')[1].split()[1].strip('"') for c...
yield chrom, strand, cds_exons, introns, exons, name gtf_parse Example: # parse gene_id from transcript_id "AC073130.2-001"; gene_id "TES"; gene_name = lambda s: s.split(';')[1].split()[1].strip('"') for chrom, strand, cds_exons, introns, exons, name in FeatureReader( sys.stdin, format='gtf', gtf_pars...
def find_and_replace_channel_refs(self, text): '''Find occurrences of Slack channel referenfces and attempts to replace them with just channel names. Args: text (string): The message text Returns: string: The message text with channel references replaced. ...
Find occurrences of Slack channel referenfces and attempts to replace them with just channel names. Args: text (string): The message text Returns: string: The message text with channel references replaced.
def save(self, submission, result, grade, problems, tests, custom, archive): # pylint: disable=unused-argument """ saves a new submission in the repo (done async) """ # Save submission to repo self._logger.info("Save submission " + str(submission["_id"]) + " to git repo") # Verify that ...
saves a new submission in the repo (done async)
def _get_stats(self, task, start_date): """ Fetches statistic information for given task and start range. """ stats = [] stats_dir = self._sdir(task.base_dir) date = start_date end_date = datetime.date.today() delta = datetime.timedelta(days=1) while...
Fetches statistic information for given task and start range.
def _getattr(obj, name, default): """Like getattr but return `default` if None or False. By default, getattr(obj, name, default) returns default only if attr does not exist, here, we return `default` even if attr evaluates to None or False. """ value = getattr(obj, name, default) if value: ...
Like getattr but return `default` if None or False. By default, getattr(obj, name, default) returns default only if attr does not exist, here, we return `default` even if attr evaluates to None or False.
def refresh(self, wait_for_active=False, retry_seconds=5): """ Refresh all of the fields of the Table object by calling the underlying DescribeTable request. :type wait_for_active: bool :param wait_for_active: If True, this command will not return until the table sta...
Refresh all of the fields of the Table object by calling the underlying DescribeTable request. :type wait_for_active: bool :param wait_for_active: If True, this command will not return until the table status, as returned from Amazon DynamoDB, is 'ACTIVE'. :type ...
def user_call(self, frame, argument_list): """This method is called when there is the remote possibility that we ever need to stop in this function.""" if self.stop_here(frame): pdb.Pdb.user_call(self, frame, argument_list)
This method is called when there is the remote possibility that we ever need to stop in this function.
def get_prefix(self, form, name): """ Return the prefix that is used for the formset. """ return '{form_prefix}{prefix_name}-{field_name}'.format( form_prefix=form.prefix + '-' if form.prefix else '', prefix_name=self.prefix_name, field_name=name)
Return the prefix that is used for the formset.
def concatenate(self, other): """Return a new name which is the concatenation of self and other. @rtype: dns.name.Name object @raises AbsoluteConcatenation: self is absolute and other is not the empty name """ if self.is_absolute() and len(other) > 0: raise A...
Return a new name which is the concatenation of self and other. @rtype: dns.name.Name object @raises AbsoluteConcatenation: self is absolute and other is not the empty name
def check_license(self): """Checks if license_file' is configured and adds it to 'self.filelist' if the value contains a valid path. """ opts = self.distribution.get_option_dict('metadata') # ignore the source of the value _, license_file = opts.get('license_file', (Non...
Checks if license_file' is configured and adds it to 'self.filelist' if the value contains a valid path.
def actions(self, state): "In the leftmost empty column, try all non-conflicting rows." if state[-1] is not None: return [] # All columns filled; no successors else: col = state.index(None) return [row for row in range(self.N) if not self....
In the leftmost empty column, try all non-conflicting rows.
def wiki(i): """ Input: { (repo_uoa) (module_uoa) (data_uoa) } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 ...
Input: { (repo_uoa) (module_uoa) (data_uoa) } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 }
def get_final_attrs(self, classes=True): """Returns a dict containing the final attributes to be rendered.""" final_attrs = copy.copy(self.get_default_attrs()) final_attrs.update(self.attrs) if classes: final_attrs['class'] = self.get_final_css() else: fin...
Returns a dict containing the final attributes to be rendered.
def gettext(self, msgid, stream=sys.stdout, splitter="--text follows this line--\n"): """Get the first text part we can find and print it as a message. This is a simple cowpath, most of the time you want the first plain part. 'msgid' is the message to be used 'stream' is printed to wit...
Get the first text part we can find and print it as a message. This is a simple cowpath, most of the time you want the first plain part. 'msgid' is the message to be used 'stream' is printed to with the header, splitter, first-textpart 'splitter' is text used to split the header from t...
def set_application(self, app, callback=None): """ Set ``CommandLineInterface`` instance for this connection. (This can be replaced any time.) :param cli: CommandLineInterface instance. :param callback: Callable that takes the result of the CLI. """ assert isinst...
Set ``CommandLineInterface`` instance for this connection. (This can be replaced any time.) :param cli: CommandLineInterface instance. :param callback: Callable that takes the result of the CLI.
def _function_signature(func): """Return the signature of a callable as a string. Parameters ---------- func : callable Function whose signature to extract. Returns ------- sig : string Signature of the function. """ if sys.version_info.major > 2: # Python 3...
Return the signature of a callable as a string. Parameters ---------- func : callable Function whose signature to extract. Returns ------- sig : string Signature of the function.
def as_colr( self, label_args=None, type_args=None, value_args=None): """ Like __str__, except it returns a colorized Colr instance. """ label_args = label_args or {'fore': 'red'} type_args = type_args or {'fore': 'yellow'} value_args = value_args or {'fore': 'blue', 'style':...
Like __str__, except it returns a colorized Colr instance.
def create(cls, name, granted_element=None): """ Create a new ACL :param str name: Name of ACL :param list granted_elements: Elements to grant access to. Can be engines, policies or other acl's. :type granted_elements: list(str,Element) :raises Create...
Create a new ACL :param str name: Name of ACL :param list granted_elements: Elements to grant access to. Can be engines, policies or other acl's. :type granted_elements: list(str,Element) :raises CreateElementFailed: failed creating ACL :return: instance with...
def is_throttled(e): """ Determines whether the exception is due to API throttling. :param e: Exception raised :return: True if it's a throttling exception else False """ return True if (hasattr(e, 'response') and e.respon...
Determines whether the exception is due to API throttling. :param e: Exception raised :return: True if it's a throttling exception else False
def _get_decision_trees_bulk(self, payload, valid_indices, invalid_indices, invalid_dts): """Tool for the function get_decision_trees_bulk. :param list payload: contains the informations necessary for getting the trees. Its form is the same than for the function. get_decision_trees_bulk. :param lis...
Tool for the function get_decision_trees_bulk. :param list payload: contains the informations necessary for getting the trees. Its form is the same than for the function. get_decision_trees_bulk. :param list valid_indices: list of the indices of the valid agent id. :param list invalid_indices: list...
def get_instructions_bytes(bytecode, opc, varnames=None, names=None, constants=None, cells=None, linestarts=None, line_offset=0): """Iterate over the instructions in a bytecode string. Generates a sequence of Instruction namedtuples giving the details of each opcode. Additional ...
Iterate over the instructions in a bytecode string. Generates a sequence of Instruction namedtuples giving the details of each opcode. Additional information about the code's runtime environment (e.g. variable names, constants) can be specified using optional arguments.
def _saveModel(model, experimentDir, checkpointLabel, newSerialization=False): """Save model""" checkpointDir = _getModelCheckpointDir(experimentDir, checkpointLabel) if newSerialization: model.writeToCheckpoint(checkpointDir) else: model.save(saveModelDir=checkpointDir)
Save model
async def read(self, container = None, size = None): """ Coroutine method to read from the stream and return the data. Raises EOFError when the stream end has been reached; raises IOError if there are other errors. :param container: A routine container :param si...
Coroutine method to read from the stream and return the data. Raises EOFError when the stream end has been reached; raises IOError if there are other errors. :param container: A routine container :param size: maximum read size, or unlimited if is None
def _dispatch_event(self): """ Dispatch the event to the handler. """ data = self._prepare_data() if data is not None: self._handler(self._event, data) self._reset_event_data()
Dispatch the event to the handler.
def remove_organization_from_ckan(portal_url, apikey, organization_id): """Toma un id de organización y la purga del portal de destino. Args: portal_url (str): La URL del portal CKAN de destino. apikey (str): La apikey de un usuario con los permisos que le permitan bo...
Toma un id de organización y la purga del portal de destino. Args: portal_url (str): La URL del portal CKAN de destino. apikey (str): La apikey de un usuario con los permisos que le permitan borrar la organización. organization_id(str): Id o name de la organiz...
def _set_authentication_key(self, v, load=False): """ Setter method for authentication_key, mapped from YANG variable /ntp/authentication_key (list) If this variable is read-only (config: false) in the source YANG file, then _set_authentication_key is considered as a private method. Backends looking...
Setter method for authentication_key, mapped from YANG variable /ntp/authentication_key (list) If this variable is read-only (config: false) in the source YANG file, then _set_authentication_key is considered as a private method. Backends looking to populate this variable should do so via calling thisOb...
def push_pushed_id(self, content, pushed_id, content_url=None): '''Push a notification to a specific pushed user by Pushed ID. Param: content -> content of Pushed notification message pushed_id -> user's pushed ID content_url (optional) -> enrich message with URL R...
Push a notification to a specific pushed user by Pushed ID. Param: content -> content of Pushed notification message pushed_id -> user's pushed ID content_url (optional) -> enrich message with URL Returns Shipment ID as string
def fit(self, X, y): """ Fit MLKR model Parameters ---------- X : (n x d) array of samples y : (n) data labels """ X, y = self._prepare_inputs(X, y, y_numeric=True, ensure_min_samples=2) n, d = X.shape if y.shape[0] != n: ...
Fit MLKR model Parameters ---------- X : (n x d) array of samples y : (n) data labels