code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def deleteJID(self, bare_jid): """ Delete all data associated with a JID. This includes the list of active/inactive devices, all sessions with that JID and all information about trusted keys. """ yield self.runInactiveDeviceCleanup() self.__sessions_cache.pop(bare_jid, ...
Delete all data associated with a JID. This includes the list of active/inactive devices, all sessions with that JID and all information about trusted keys.
def tree_type_checker(*ref): '''Tree type checker functor Returns: Functor that takes a tree, and returns true if that tree matches any of NeuriteTypes in ref Ex: >>> from neurom.core.types import NeuriteType, tree_type_checker >>> tree_filter = tree_type_checker(NeuriteTyp...
Tree type checker functor Returns: Functor that takes a tree, and returns true if that tree matches any of NeuriteTypes in ref Ex: >>> from neurom.core.types import NeuriteType, tree_type_checker >>> tree_filter = tree_type_checker(NeuriteType.axon, NeuriteType.basal_dendrite) ...
def _expression(expression): # type: (QuilParser.ExpressionContext) -> Any """ NB: Order of operations is already dealt with by the grammar. Here we can simply match on the type. """ if isinstance(expression, QuilParser.ParenthesisExpContext): return _expression(expression.expression()) ...
NB: Order of operations is already dealt with by the grammar. Here we can simply match on the type.
def _get_resource(self, label: str, source: dict, resource_type: str): """ Generic resoure fetcher handling errors. Args: label (str): The label to fetch source (dict): The dictionary to look up the label resource_type str: The display name of the reso...
Generic resoure fetcher handling errors. Args: label (str): The label to fetch source (dict): The dictionary to look up the label resource_type str: The display name of the resource type (used in errors)
def parse_single_results(data, sample, res1): """ parse results from cutadapt into sample data""" ## set default values #sample.stats_dfs.s2["reads_raw"] = 0 sample.stats_dfs.s2["trim_adapter_bp_read1"] = 0 sample.stats_dfs.s2["trim_quality_bp_read1"] = 0 sample.stats_dfs.s2["reads_filtered_by...
parse results from cutadapt into sample data
def _is_expired_response(self, response): """ Check if the response failed because of an expired access token. """ if response.status_code != 401: return False challenge = response.headers.get('www-authenticate', '') return 'error="invalid_token"' in challenge
Check if the response failed because of an expired access token.
def open(self): """Open the files """ segments = [] files = config.get('env', 'jpl', fallback=[]) if not files: raise JplConfigError("No JPL file defined") # Extraction of segments from each .bsp file for filepath in files: filepath = P...
Open the files
def json_unicode_to_utf8(data): """Change all strings in a JSON structure to UTF-8.""" if isinstance(data, unicode): return data.encode('utf-8') elif isinstance(data, dict): newdict = {} for key in data: newdict[json_unicode_to_utf8( key)] = json_unicode_t...
Change all strings in a JSON structure to UTF-8.
def parse(self, rrstr): # type: (bytes) -> None ''' Parse a Rock Ridge System Terminator record out of a string. Parameters: rrstr - The string to parse the record out of. Returns: Nothing. ''' if self._initialized: raise pycdlibexce...
Parse a Rock Ridge System Terminator record out of a string. Parameters: rrstr - The string to parse the record out of. Returns: Nothing.
def slice_after(predicate, iterable): """Returns groups of elements from iterable, slicing just after predicate(elem) is True """ record = [] for i, item in enumerate(iterable): record.append(item) if predicate(item): yield tuple(record) record = [] if r...
Returns groups of elements from iterable, slicing just after predicate(elem) is True
def _build_ftp_processor(cls, session: AppSession): '''Build FTPProcessor.''' ftp_client = session.factory['FTPClient'] fetch_params = session.factory.new( 'FTPProcessorFetchParams', remove_listing=session.args.remove_listing, retr_symlinks=session.args.retr_...
Build FTPProcessor.
def options(self, context, module_options): ''' SCRIPT Script version to execute (choices: bash, python) (default: bash) ''' scripts = {'PYTHON': get_script('mimipenguin/mimipenguin.py'), 'BASH' : get_script('mimipenguin/mimipenguin.sh')} self.script_choice =...
SCRIPT Script version to execute (choices: bash, python) (default: bash)
def compute_Kij(self, Xi, Xj, ni, nj, noise=False, hyper_deriv=None, k=None): r"""Compute covariance matrix between datasets `Xi` and `Xj`. Specify the orders of derivatives at each location with the `ni`, `nj` arrays. The `include_noise` flag is passed to the covariance kernel to ...
r"""Compute covariance matrix between datasets `Xi` and `Xj`. Specify the orders of derivatives at each location with the `ni`, `nj` arrays. The `include_noise` flag is passed to the covariance kernel to indicate whether noise is to be included (i.e., for evaluation of :math:`K+...
def createAction(self, parent=None, name=''): """ Overloads teh create action method to handle the proper base instance information, similar to the PyQt4 loading system. :param parent | <QWidget> || None name | <str> """ action ...
Overloads teh create action method to handle the proper base instance information, similar to the PyQt4 loading system. :param parent | <QWidget> || None name | <str>
def parse_params(self, y=None, y_target=None, beta=1e-2, decision_rule='EN', batch_size=1, confidence=0, learning_rate=1e-2, binary_search_steps=9, m...
:param y: (optional) A tensor with the true labels for an untargeted attack. If None (and y_target is None) then use the original labels the classifier assigns. :param y_target: (optional) A tensor with the target labels for a targeted attack. :param beta: Trades off L2...
def get_storage_account_keys(self, service_name): ''' Returns the primary and secondary access keys for the specified storage account. service_name: Name of the storage service account. ''' _validate_not_none('service_name', service_name) return self....
Returns the primary and secondary access keys for the specified storage account. service_name: Name of the storage service account.
def last_modified(self): """Retrieves the last modified time stamp of the incident/incidents from the output response Returns: last_modified(namedtuple): List of named tuples of last modified time stamp of the incident/incidents """ resource_list = self.t...
Retrieves the last modified time stamp of the incident/incidents from the output response Returns: last_modified(namedtuple): List of named tuples of last modified time stamp of the incident/incidents
def _multiplexed_buffer_helper(self, response): """A generator of multiplexed data blocks read from a buffered response.""" buf = self._result(response, binary=True) buf_length = len(buf) walker = 0 while True: if buf_length - walker < STREAM_HEADER_SIZE_BYTES...
A generator of multiplexed data blocks read from a buffered response.
def BatchConvert(self, metadata_value_pairs, token=None): """Converts a batch of GrrMessages into a set of RDFValues at once. Args: metadata_value_pairs: a list or a generator of tuples (metadata, value), where metadata is ExportedMetadata to be used for conversion and value is a GrrMessa...
Converts a batch of GrrMessages into a set of RDFValues at once. Args: metadata_value_pairs: a list or a generator of tuples (metadata, value), where metadata is ExportedMetadata to be used for conversion and value is a GrrMessage to be converted. token: Security token. Returns: ...
def load(self): """ Deferred loading of the scene :param scene: The scene object :param file: Resolved path if changed by finder """ self.path = self.find_scene(self.meta.path) if not self.path: raise ValueError("Scene '{}' not found".format(self.meta...
Deferred loading of the scene :param scene: The scene object :param file: Resolved path if changed by finder
def convert_lines_to_block(lines, block_map, link_stack, source_path, block_name=ALL_BLOCK_NAME): """Converts the specified block content lines (list of strings) into a Block object. Nested blocks are recursively converted into strings and cached in the block_map. Include tags are processed as well. The re...
Converts the specified block content lines (list of strings) into a Block object. Nested blocks are recursively converted into strings and cached in the block_map. Include tags are processed as well. The resulting block string is also added to the block_map, along with any nested blocks. PARAMETERS: ...
def create_archive(directory, filename, config={}, ignore_predicate=None, ignored_files=['.git', '.svn']): """ Creates an archive from a directory and returns the file that was created. """ with zipfile.ZipFile(filename, 'w', compression=zipfile.ZIP_DEFLATED) as zip_file: root_len = len(os.p...
Creates an archive from a directory and returns the file that was created.
def json( self, dirPath=None): """*Render the results in json format* **Key Arguments:** - ``dirPath`` -- the path to the directory to save the rendered results to. Default *None* **Return:** - `jsonSources` -- the top-level transient data ...
*Render the results in json format* **Key Arguments:** - ``dirPath`` -- the path to the directory to save the rendered results to. Default *None* **Return:** - `jsonSources` -- the top-level transient data - `jsonPhot` -- all photometry associated with the transient...
def address_to_ip(address): """Convert a hostname to a numerical IP addresses in an address. This should be a no-op if address already contains an actual numerical IP address. Args: address: This can be either a string containing a hostname (or an IP address) and a port or it can b...
Convert a hostname to a numerical IP addresses in an address. This should be a no-op if address already contains an actual numerical IP address. Args: address: This can be either a string containing a hostname (or an IP address) and a port or it can be just an IP address. Returns:...
def url_map(self, for_user=None, **kwargs): """ Returns a dictionary of urls mapped to Displayable subclass instances, including a fake homepage instance if none exists. Used in ``yacms.core.sitemaps``. """ class Home: title = _("Home") home = Home() ...
Returns a dictionary of urls mapped to Displayable subclass instances, including a fake homepage instance if none exists. Used in ``yacms.core.sitemaps``.
def _simulate_mixture(self, op: ops.Operation, data: _StateAndBuffer, indices: List[int]) -> None: """Simulate an op that is a mixtures of unitaries.""" probs, unitaries = zip(*protocols.mixture(op)) # We work around numpy barfing on choosing from a list of # numpy arrays (wh...
Simulate an op that is a mixtures of unitaries.
def get(self, tag=None, **kwargs): ''' Recursively searches children for tags of a certain type with matching attributes. ''' # Stupid workaround since we can not use dom_tag in the method declaration if tag is None: tag = dom_tag attrs = [(dom_tag.clean_attribute(attr), value) for ...
Recursively searches children for tags of a certain type with matching attributes.
def do_interact(self, arg): """ interact Start an interative interpreter whose global namespace contains all the names found in the current scope. """ ns = self.curframe.f_globals.copy() ns.update(self.curframe_locals) code.interact("*interactive*", local...
interact Start an interative interpreter whose global namespace contains all the names found in the current scope.
def write(self, filename, content, overwrite=False): ''' Write content to a file. :param str filename: The storage root-relative filename :param content: The content to write in the file :param bool overwrite: Whether to wllow overwrite or not :raises FileExists: If the ...
Write content to a file. :param str filename: The storage root-relative filename :param content: The content to write in the file :param bool overwrite: Whether to wllow overwrite or not :raises FileExists: If the file exists and `overwrite` is `False`
def bottleneck_layer(inputs, hparams, name="discrete_bottleneck"): """Computes latents given inputs (typically, compressed targets).""" [ latents_dense, latents_discrete, extra_loss, embed_fn, _, ] = hparams.bottleneck(inputs=inputs, ...
Computes latents given inputs (typically, compressed targets).
def invert(a, b): """ The multiplicitive inverse of a in the integers modulo b. :return int: x, where a * x == 1 mod b """ if HAVE_GMP: s = int(gmpy2.invert(a, b)) # according to documentation, gmpy2.invert might return 0 on # non-invertible element, although it seems to act...
The multiplicitive inverse of a in the integers modulo b. :return int: x, where a * x == 1 mod b
def quit(self): """ Exit the program due to user's choices. """ self.script.LOG.warn("Abort due to user choice!") sys.exit(self.QUIT_RC)
Exit the program due to user's choices.
def json_register(self): ''' The first char of 'code' stands for the different field. '1' for user_name '2' for user_email '3' for user_pass '4' for user_role The seconde char of 'code' stands for different status. '1' for invalide '2' for already ...
The first char of 'code' stands for the different field. '1' for user_name '2' for user_email '3' for user_pass '4' for user_role The seconde char of 'code' stands for different status. '1' for invalide '2' for already exists.
async def insert(self, values_lst: Iterable[SQLValuesToWrite], returning=False) -> Union[int, List[DataRecord]]: """ :param values_lst: :param returning: :return: return count if returning is False, otherwise records """ raise NotImplementedError()
:param values_lst: :param returning: :return: return count if returning is False, otherwise records
def post(self, request, **kwargs): """ Create a new current subscription for the user. Returns with status code 201. """ serializer = CreateSubscriptionSerializer(data=request.data) if serializer.is_valid(): try: customer, _created = Customer.get_or_create( subscriber=subscriber_request_callba...
Create a new current subscription for the user. Returns with status code 201.
def run_containers(command, parser, cl_args, unknown_args): """ run containers subcommand """ cluster, role, env = cl_args['cluster'], cl_args['role'], cl_args['environ'] topology = cl_args['topology-name'] container_id = cl_args['id'] try: result = tracker_access.get_topology_info(cluster, env, topology,...
run containers subcommand
def summary(self): '''Compute the execution summary''' out = {} for bench in self.runner.runned: key = self.key(bench) runs = {} for method, results in bench.results.items(): mean = results.total / bench.times name = bench.label...
Compute the execution summary
def _link_variables_on_expr(self, variable_manager, block, stmt_idx, stmt, expr): """ Link atoms (AIL expressions) in the given expression to corresponding variables identified previously. :param variable_manager: Variable manager of the function. :param ailment.Block block: AIL bloc...
Link atoms (AIL expressions) in the given expression to corresponding variables identified previously. :param variable_manager: Variable manager of the function. :param ailment.Block block: AIL block. :param int stmt_idx: ID of the statement. :param stmt: The AI...
def create_task(self, subject, desc): """Create a task :param subject: the task's subject :param desc: the task's content in plain-text :returns: the task's id """ task = zobjects.Task() task_creator = task.to_creator(subject, desc) resp = self.request('C...
Create a task :param subject: the task's subject :param desc: the task's content in plain-text :returns: the task's id
def h2i(self, pkt, x): """The field accepts string values like v12.1, v1.1 or integer values. String values have to start with a "v" folled by a floating point number. Valid numbers are between 0 and 255. """ if isinstance(x, str) and x.startswith("v") and len(x) <= 8: ...
The field accepts string values like v12.1, v1.1 or integer values. String values have to start with a "v" folled by a floating point number. Valid numbers are between 0 and 255.
def get_uuid_string(low=None, high=None, **x): """This method parses a UUID protobuf message type from its component 'high' and 'low' longs into a standard formatted UUID string Args: x (dict): containing keys, 'low' and 'high' corresponding to the UUID protobuf message type Return...
This method parses a UUID protobuf message type from its component 'high' and 'low' longs into a standard formatted UUID string Args: x (dict): containing keys, 'low' and 'high' corresponding to the UUID protobuf message type Returns: str: UUID formatted string
def classify_nearest(self, partial_labels): '''Simple semi-supervised classification, by assigning unlabeled vertices the label of nearest labeled vertex. partial_labels: (n,) array of integer labels, -1 for unlabeled. ''' labels = np.array(partial_labels, copy=True) unlabeled = labels == -1 ...
Simple semi-supervised classification, by assigning unlabeled vertices the label of nearest labeled vertex. partial_labels: (n,) array of integer labels, -1 for unlabeled.
def export_to_html( table, filename_or_fobj=None, encoding="utf-8", caption=False, *args, **kwargs ): """Export and return rows.Table data to HTML file.""" serialized_table = serialize(table, *args, **kwargs) fields = next(serialized_table) result = ["<table>\n\n"] if caption and table.name: ...
Export and return rows.Table data to HTML file.
def change(self, ident, rank=None): '''Change ident''' self.ident = ident if rank: self.rank = rank self.level = self._getLevel(rank, self.taxonomy) # count changes made to instance self.counter += 1
Change ident
def source(self, source): """When the source gets updated, update the select widget""" if isinstance(source, list): # if source is a list, get first item or None source = source[0] if len(source) > 0 else None self._source = source
When the source gets updated, update the select widget
def gte(min_value): """ Validates that a field value is greater than or equal to the value given to this validator. """ def validate(value): if value < min_value: return e("{} is not greater than or equal to {}", value, min_value) return validate
Validates that a field value is greater than or equal to the value given to this validator.
def post_install_postgresql(): """ example default hook for installing postgresql """ from django.conf import settings as s with settings(warn_only=True): sudo('/etc/init.d/postgresql-8.4 restart') sudo("""psql template1 -c "ALTER USER postgres with encrypted password '%s';" """% env...
example default hook for installing postgresql
def associate_address(self, instance_id, public_ip=None, allocation_id=None): """ Associate an Elastic IP address with a currently running instance. This requires one of ``public_ip`` or ``allocation_id`` depending on if you're associating a VPC address or a plain EC2 address. :...
Associate an Elastic IP address with a currently running instance. This requires one of ``public_ip`` or ``allocation_id`` depending on if you're associating a VPC address or a plain EC2 address. :type instance_id: string :param instance_id: The ID of the instance :type public_...
def _get_config_file(user, config): ''' Get absolute path to a user's ssh_config. ''' uinfo = __salt__['user.info'](user) if not uinfo: raise CommandExecutionError('User \'{0}\' does not exist'.format(user)) home = uinfo['home'] config = _expand_authorized_keys_path(config, user, hom...
Get absolute path to a user's ssh_config.
def log_wrapper(self): """ Wrapper to set logging parameters for output """ log = logging.getLogger('client.py') # Set the log format and log level try: debug = self.params["debug"] log.setLevel(logging.DEBUG) except KeyError: ...
Wrapper to set logging parameters for output
def telemetry_client(self, value: BotTelemetryClient) -> None: """ Sets the telemetry client for logging events. """ if value is None: self._telemetry_client = NullTelemetryClient() else: self._telemetry_client = value
Sets the telemetry client for logging events.
def tree(obj): """ Convert object to a tree of lists, dicts and simple values. The result can be serialized to JSON. """ from .objects import Object if isinstance(obj, (bool, int, float, str, bytes)): return obj elif isinstance(obj, (datetime.date, datetime.time)): return obj...
Convert object to a tree of lists, dicts and simple values. The result can be serialized to JSON.
def boolean(input): """Convert the given input to a boolean value. Intelligently handles boolean and non-string values, returning as-is and passing to the bool builtin respectively. This process is case-insensitive. Acceptable values: True * yes * y * ...
Convert the given input to a boolean value. Intelligently handles boolean and non-string values, returning as-is and passing to the bool builtin respectively. This process is case-insensitive. Acceptable values: True * yes * y * on * true *...
def post(fqdn, package, result, entry, bound, ekey, *argl, **argd): """Adds logging for the post-call result of calling the method externally. Args: fqdn (str): fully-qualified domain name of the function being logged. package (str): name of the package we are logging for. Usually the first ...
Adds logging for the post-call result of calling the method externally. Args: fqdn (str): fully-qualified domain name of the function being logged. package (str): name of the package we are logging for. Usually the first element of `fqdn.split('.')`. result: returned from calling ...
def get_prop(self, key, default_val=None): """ Returns a property set on the context. :Parameters: key String key to lookup in the context props dict default_val Value to return if key is not set on the context props """ if self.props....
Returns a property set on the context. :Parameters: key String key to lookup in the context props dict default_val Value to return if key is not set on the context props
def to_dict(self): """Convert Term into raw dictionary data.""" return { 'definition': self.definition, 'id': self.term_id, 'image': self.image.to_dict(), 'rank': self.rank, 'term': self.term }
Convert Term into raw dictionary data.
def hex_to_rgb(h): """ Returns 0 to 1 rgb from a hex list or tuple """ h = h.lstrip('#') return tuple(int(h[i:i+2], 16)/255. for i in (0, 2 ,4))
Returns 0 to 1 rgb from a hex list or tuple
def _validated_locations(self, locations): """Ensure that the given locations argument is valid. :raises: ValueError if a given locations includes an invalid location. """ # The set difference between the given locations and the available locations # will be the set of invalid l...
Ensure that the given locations argument is valid. :raises: ValueError if a given locations includes an invalid location.
def get_most_salient_words(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n=None): """ Order the words from `vocab` by "saliency score" (Chuang et al. 2012) from most to least salient. Optionally only return the `n` most salient words. J. Chuang, C. Manning, J. Heer 2012: "Termite: Visualiz...
Order the words from `vocab` by "saliency score" (Chuang et al. 2012) from most to least salient. Optionally only return the `n` most salient words. J. Chuang, C. Manning, J. Heer 2012: "Termite: Visualization Techniques for Assessing Textual Topic Models"
def from_instance(class_, instance, namespace=None, host=None, strict=False): """ Return a new :class:`~pywbem.CIMInstanceName` object from the key property values in a CIM instance and the key property definitions in a CIM class. If the `strict` parameter ...
Return a new :class:`~pywbem.CIMInstanceName` object from the key property values in a CIM instance and the key property definitions in a CIM class. If the `strict` parameter is `False`, and a property value does not exist in the `instance` that entry is not included in the constructed ...
def _check(self): """Check that entry attributes are legal.""" # Run the super method super(Photometry, self)._check() err_str = None has_flux = self._KEYS.FLUX in self has_flux_dens = self._KEYS.FLUX_DENSITY in self has_u_flux = self._KEYS.U_FLUX in self ...
Check that entry attributes are legal.
def getIncEdgesMap(self): """ Returns a dictionary that associates numbers of incoming edges in the weighted majority graph with the candidates that have that number of incoming edges. """ # We calculate the number of incoming edges for each candidate and store it into a diction...
Returns a dictionary that associates numbers of incoming edges in the weighted majority graph with the candidates that have that number of incoming edges.
def build(self) -> type: """ Build a subclass of `MappingJSONEncoder`. :return: the built subclass """ def _get_property_mappings(encoder: MappingJSONEncoder) -> List[JsonPropertyMapping]: return _get_all_property_mappings(encoder, self.mappings, self.superclasses) ...
Build a subclass of `MappingJSONEncoder`. :return: the built subclass
def main(args, options, parser): '''This function serves as a wrapper around the DockerRecipe and SingularityRecipe converters. We can either save to file if args.outfile is defined, or print to the console if not. ''' from spython.main.parse import ( DockerRecipe, SingularityRecipe ) # ...
This function serves as a wrapper around the DockerRecipe and SingularityRecipe converters. We can either save to file if args.outfile is defined, or print to the console if not.
def _match_one_or_many(self, models, results, relation, type_): """ Match the eargerly loaded resuls to their single parents. :param models: The parents :type models: list :param results: The results collection :type results: Collection :param relation: The rel...
Match the eargerly loaded resuls to their single parents. :param models: The parents :type models: list :param results: The results collection :type results: Collection :param relation: The relation :type relation: str :param type_: The match type :typ...
def write(self, string): """Write a string to the file.""" bytes_ = string.encode(self._encoding) self._file.write(bytes_)
Write a string to the file.
def _repr_html_(self): """ Jupyter Notebook magic repr function. """ # Make header. r = '</th><th>'.join(['Index', 'UWI', 'Data', 'Curves']) rows = '<tr><th>{}</th></tr>'.format(r) # Make rows. for i, w in enumerate(self.__list): rows += '<tr>...
Jupyter Notebook magic repr function.
def ReadFlowRequestsReadyForProcessing(self, client_id, flow_id, next_needed_request=None): """Reads all requests for a flow that can be processed by the worker.""" request_dict = self.flow...
Reads all requests for a flow that can be processed by the worker.
def parse_date(value: Union[date, StrIntFloat]) -> date: """ Parse a date/int/float/string and return a datetime.date. Raise ValueError if the input is well formatted but not a valid date. Raise ValueError if the input isn't well formatted. """ if isinstance(value, date): if isinstance(...
Parse a date/int/float/string and return a datetime.date. Raise ValueError if the input is well formatted but not a valid date. Raise ValueError if the input isn't well formatted.
def _item_to_database(self, iterator, database_pb): """Convert a database protobuf to the native object. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type database_pb: :class:`~google.spanner.admin.database.v1...
Convert a database protobuf to the native object. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type database_pb: :class:`~google.spanner.admin.database.v1.Database` :param database_pb: A database returned from...
def ParseVideoRow(self, parser_mediator, query, row, **unused_kwargs): """Parses a Video row. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. query (str): query that created the row. row (sqlite3.Row): ro...
Parses a Video row. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. query (str): query that created the row. row (sqlite3.Row): row.
def _summary_csv_by_researcher(summary_yaml, researcher, descrs, data): """Generate a CSV file with summary information for a researcher on this project. """ out_file = os.path.join(utils.safe_makedir(os.path.join(data["dirs"]["work"], "researcher")), "%s-summary.tsv" % run_info....
Generate a CSV file with summary information for a researcher on this project.
def generate_version_py(packagename=None, version=None, release=None, debug=None, uses_git=None, srcdir='.'): """ Generate a version.py file in the package with version information, and update developer version strings. This function should normally be called without any argumen...
Generate a version.py file in the package with version information, and update developer version strings. This function should normally be called without any arguments. In this case the package name and version is read in from the ``setup.cfg`` file (from the ``name`` or ``package_name`` entry and the ...
def repay_loan(self, order_id, amount): """ 归还借贷 :param order_id: :param amount: :return: """ params = {'order-id': order_id, 'amount': amount} path = f'/v1/margin/orders/{order_id}/repay' def _wrapper(_func): @wraps(_func) ...
归还借贷 :param order_id: :param amount: :return:
def id(self, value): """The id property. Args: value (string). the property value. """ if value == self._defaults['ai.device.id'] and 'ai.device.id' in self._values: del self._values['ai.device.id'] else: self._values['ai.device.id'] =...
The id property. Args: value (string). the property value.
def clean(self, *args, **kwargs): """Clean all loaded values to reload when switching envs""" for key in list(self.store.keys()): self.unset(key)
Clean all loaded values to reload when switching envs
def fun_residuals(params, xnor, ynor, w, bbox, k, ext): """Compute fit residuals""" spl = LSQUnivariateSpline( x=xnor, y=ynor, t=[item.value for item in params.values()], w=w, bbox=bbox, k=k, ext=ext, check_finite=False ) return spl.get_re...
Compute fit residuals
def do_default(value, default_value=u'', boolean=False): """If the value is undefined it will return the passed default value, otherwise the value of the variable: .. sourcecode:: jinja {{ my_variable|default('my_variable is not defined') }} This will output the value of ``my_variable`` if th...
If the value is undefined it will return the passed default value, otherwise the value of the variable: .. sourcecode:: jinja {{ my_variable|default('my_variable is not defined') }} This will output the value of ``my_variable`` if the variable was defined, otherwise ``'my_variable is not defi...
def get_resampled_top_edge(self, angle_var=0.1): """ This methods computes a simplified representation of a fault top edge by removing the points that are not describing a change of direction, provided a certain tolerance angle. :param float angle_var: Number represe...
This methods computes a simplified representation of a fault top edge by removing the points that are not describing a change of direction, provided a certain tolerance angle. :param float angle_var: Number representing the maximum deviation (in degrees) admitted without...
def create_service(resource_root, name, service_type, cluster_name="default"): """ Create a service @param resource_root: The root Resource object. @param name: Service name @param service_type: Service type @param cluster_name: Cluster name @return: An ApiService object """ apiserv...
Create a service @param resource_root: The root Resource object. @param name: Service name @param service_type: Service type @param cluster_name: Cluster name @return: An ApiService object
def ancestor(self, value): """Set the ancestor for the query :type value: :class:`~google.cloud.datastore.key.Key` :param value: the new ancestor key """ if not isinstance(value, Key): raise TypeError("Ancestor must be a Key") self._ancestor = value
Set the ancestor for the query :type value: :class:`~google.cloud.datastore.key.Key` :param value: the new ancestor key
def configureAndBuild(self, nocompressjs=False): """ Run :meth:`createCleanJsbConfig` and :meth:`build`. """ jsb = self.createCleanJsbConfig() self.buildFromJsbString(jsb, nocompressjs)
Run :meth:`createCleanJsbConfig` and :meth:`build`.
def mel_frequencies(n_mels=128, fmin=0.0, fmax=11025.0, htk=False): """Compute an array of acoustic frequencies tuned to the mel scale. The mel scale is a quasi-logarithmic function of acoustic frequency designed such that perceptually similar pitch intervals (e.g. octaves) appear equal in width over t...
Compute an array of acoustic frequencies tuned to the mel scale. The mel scale is a quasi-logarithmic function of acoustic frequency designed such that perceptually similar pitch intervals (e.g. octaves) appear equal in width over the full hearing range. Because the definition of the mel scale is cond...
def _set_interface_flooding_up_threshold(self, v, load=False): """ Setter method for interface_flooding_up_threshold, mapped from YANG variable /mpls_state/rsvp/interfaces/interface_flooding_up_threshold (feature-config-source) If this variable is read-only (config: false) in the source YANG file, then ...
Setter method for interface_flooding_up_threshold, mapped from YANG variable /mpls_state/rsvp/interfaces/interface_flooding_up_threshold (feature-config-source) If this variable is read-only (config: false) in the source YANG file, then _set_interface_flooding_up_threshold is considered as a private method....
def get_outlier_info(pronac): """ Return if a project with the given pronac is an outlier based on raised funds. """ df = data.planilha_captacao raised_funds_averages = data.segment_raised_funds_average.to_dict('index') segment_id = df[df['Pronac'] == pronac]['Segmento'].iloc[0] mean =...
Return if a project with the given pronac is an outlier based on raised funds.
def parse_from_file(filename, nodata=False): """Parse df message from file. @filename - path to file @nodata - do not load data @return - [binary header, metadata, binary data] """ header = None with open(filename, "rb") as file: header = read_machine_header(file) meta_raw ...
Parse df message from file. @filename - path to file @nodata - do not load data @return - [binary header, metadata, binary data]
def drop(self, labels, dim=None): """Drop variables or index labels from this dataset. Parameters ---------- labels : scalar or list of scalars Name(s) of variables or index labels to drop. dim : None or str, optional Dimension along which to drop index l...
Drop variables or index labels from this dataset. Parameters ---------- labels : scalar or list of scalars Name(s) of variables or index labels to drop. dim : None or str, optional Dimension along which to drop index labels. By default (if ``dim is No...
def value(self): """ The value of the LED bar graph. When no LEDs are lit, the value is 0. When all LEDs are lit, the value is 1. Values between 0 and 1 light LEDs linearly from first to last. Values between 0 and -1 light LEDs linearly from last to first. To light a par...
The value of the LED bar graph. When no LEDs are lit, the value is 0. When all LEDs are lit, the value is 1. Values between 0 and 1 light LEDs linearly from first to last. Values between 0 and -1 light LEDs linearly from last to first. To light a particular number of LEDs, simply divide...
def data_mod(self, *args, **kwargs): """ Register a function to modify data of member Instruments. The function is not partially applied to modify member data. When the Constellation receives a function call to register a function for data modification, it passes the call to ea...
Register a function to modify data of member Instruments. The function is not partially applied to modify member data. When the Constellation receives a function call to register a function for data modification, it passes the call to each instrument and registers it in the instrument's pysat....
def retrieve(self, id) : """ Retrieve a single deal Returns a single deal available to the user, according to the unique deal ID provided If the specified deal does not exist, the request will return an error :calls: ``get /deals/{id}`` :param int id: Unique identifier ...
Retrieve a single deal Returns a single deal available to the user, according to the unique deal ID provided If the specified deal does not exist, the request will return an error :calls: ``get /deals/{id}`` :param int id: Unique identifier of a Deal. :return: Dictionary that s...
def __normalized_name(self, message_type): """Normalized schema name. Generate a normalized schema name, taking the class name and stripping out everything but alphanumerics, and camel casing the remaining words. A normalized schema name is a name that matches [a-zA-Z][a-zA-Z0-9]* Args: mess...
Normalized schema name. Generate a normalized schema name, taking the class name and stripping out everything but alphanumerics, and camel casing the remaining words. A normalized schema name is a name that matches [a-zA-Z][a-zA-Z0-9]* Args: message_type: protorpc.message.Message class being par...
def _check_targets(self): """ Returns a function to terminate the ArciDispatch algorithm when all targets have been visited. :return: A function to terminate the ArciDispatch algorithm. :rtype: (str) -> bool """ if self.outputs: targets ...
Returns a function to terminate the ArciDispatch algorithm when all targets have been visited. :return: A function to terminate the ArciDispatch algorithm. :rtype: (str) -> bool
def dropped(self, component, event): """Adds the dropped *component* into the model. :meth:`Re-implemented<sparkle.gui.abstract_drag_view.AbstractDragView.dropped>` """ if isinstance(component, AbstractStimulusComponent): row, col = self.splitAt(event.pos()) inde...
Adds the dropped *component* into the model. :meth:`Re-implemented<sparkle.gui.abstract_drag_view.AbstractDragView.dropped>`
def authenticate_direct_bind(self, username, password): """ Performs a direct bind. We can do this since the RDN is the same as the login attribute. Hence we just string together a dn to find this user with. Args: username (str): Username of the user to bind (the fie...
Performs a direct bind. We can do this since the RDN is the same as the login attribute. Hence we just string together a dn to find this user with. Args: username (str): Username of the user to bind (the field specified as LDAP_BIND_RDN_ATTR) password (st...
def month(self): """ Get the overall Unsplash stats for the past 30 days. :return [Stat]: The Unsplash Stat. """ url = "/stats/month" result = self._get(url) return StatModel.parse(result)
Get the overall Unsplash stats for the past 30 days. :return [Stat]: The Unsplash Stat.
def param_names(self): """Combined names for the hyperparameters for the kernel, noise kernel and (if present) mean function. """ pn = CombinedBounds(self.k.param_names, self.noise_k.param_names) if self.mu is not None: pn = CombinedBounds(pn, self.mu.param_names) ret...
Combined names for the hyperparameters for the kernel, noise kernel and (if present) mean function.
def run_restore(self, snapshot: Dict[Union[str, Key], Any]) -> 'BaseItemCollection': """ Restores the state of a collection from a snapshot """ try: for name, snap in snapshot.items(): if isinstance(name, Key): self._nested_items[name.grou...
Restores the state of a collection from a snapshot
def _init_c2ps(self, go_sources, traverse_child): """Traverse up children.""" if not traverse_child: return {} c2ps = defaultdict(set) goids_seen = set() go2obj = self.go2obj for goid_src in go_sources: goobj_src = go2obj[goid_src] if g...
Traverse up children.
def pressure(self): """The current pressure being applied on the tool in use, normalized to the range [0, 1] and whether it has changed in this event. If this axis does not exist on the current tool, this property is (0, :obj:`False`). Returns: (float, bool): The current value of the the axis and whether...
The current pressure being applied on the tool in use, normalized to the range [0, 1] and whether it has changed in this event. If this axis does not exist on the current tool, this property is (0, :obj:`False`). Returns: (float, bool): The current value of the the axis and whether it has changed.
async def pin_chat_message(self, chat_id: typing.Union[base.Integer, base.String], message_id: base.Integer, disable_notification: typing.Union[base.Boolean, None] = None) -> base.Boolean: """ Use this method to pin a message in a supergroup. The bot must be an adm...
Use this method to pin a message in a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Source: https://core.telegram.org/bots/api#pinchatmessage :param chat_id: Unique identifier for the target chat or username of the target ...