code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def get_signature(self, req): """calculate the signature of the oss request Returns the signatue """ oss_url = url.URL(req.url) oss_headers = [ "{0}:{1}\n".format(key, val) for key, val in req.headers.lower_items() if key.startswith(self.X_OSS...
calculate the signature of the oss request Returns the signatue
def pydeps2reqs(deps): """Convert a deps instance into requirements. """ reqs = defaultdict(set) for k, v in list(deps.items()): # not a built-in p = v['path'] if p and not p.startswith(sys.real_prefix): if p.startswith(sys.prefix) and 'site-packages' in p: ...
Convert a deps instance into requirements.
def parse_url(url): """Return a clean URL. Remove the prefix for the Auth URL if Found. :param url: :return aurl: """ if url.startswith(('http', 'https', '//')): if url.startswith('//'): return urlparse.urlparse(url, scheme='http') else: return urlparse.urlpa...
Return a clean URL. Remove the prefix for the Auth URL if Found. :param url: :return aurl:
def is_valid_regex(string): """ Checks whether the re module can compile the given regular expression. Parameters ---------- string: str Returns ------- boolean """ try: re.compile(string) is_valid = True except re.error: is_valid = False return ...
Checks whether the re module can compile the given regular expression. Parameters ---------- string: str Returns ------- boolean
def yaml_to_str(data: Mapping) -> str: """ Return the given given config as YAML str. :param data: configuration dict :return: given configuration as yaml str """ return yaml.dump(data, Dumper=ruamel.yaml.RoundTripDumper)
Return the given given config as YAML str. :param data: configuration dict :return: given configuration as yaml str
def sv_variant(store, institute_id, case_name, variant_id=None, variant_obj=None, add_case=True, get_overlapping=True): """Pre-process an SV variant entry for detail page. Adds information to display variant Args: store(scout.adapter.MongoAdapter) institute_id(str) c...
Pre-process an SV variant entry for detail page. Adds information to display variant Args: store(scout.adapter.MongoAdapter) institute_id(str) case_name(str) variant_id(str) variant_obj(dcit) add_case(bool): If information about case files should be added R...
def z__update(self): """Triple quoted baseline representation. Return string with multiple triple quoted baseline strings when baseline had been compared multiple times against varying strings. :returns: source file baseline replacement text :rtype: str """ upd...
Triple quoted baseline representation. Return string with multiple triple quoted baseline strings when baseline had been compared multiple times against varying strings. :returns: source file baseline replacement text :rtype: str
def _set_comment(self, section, comment, key=None): """ Set a comment for section or key :param str section: Section to add comment to :param str comment: Comment to add :param str key: Key to add comment to """ if '\n' in comment: comment = '\n# '.j...
Set a comment for section or key :param str section: Section to add comment to :param str comment: Comment to add :param str key: Key to add comment to
def largest_compartment_id_met(model): """ Return the ID of the compartment with the most metabolites. Parameters ---------- model : cobra.Model The metabolic model under investigation. Returns ------- string Compartment ID of the compartment with the most metabolites. ...
Return the ID of the compartment with the most metabolites. Parameters ---------- model : cobra.Model The metabolic model under investigation. Returns ------- string Compartment ID of the compartment with the most metabolites.
def fit(self, target_type, target, adjust_thickness=False, adjust_site_atten=False, adjust_source_vel=False): """ Fit to a target crustal amplification or site term. The fitting process adjusts the velocity, site attenuation, and layer...
Fit to a target crustal amplification or site term. The fitting process adjusts the velocity, site attenuation, and layer thickness (if enabled) to fit a target values. The frequency range is specified by the input motion. Parameters ---------- target_type: str ...
def name(value): """Get the string title for a particular type. Given a value, get an appropriate string title for the type that can be used to re-cast the value later. """ if value is None: return 'any' for (test, name) in TESTS: if isinstance(value, test): return n...
Get the string title for a particular type. Given a value, get an appropriate string title for the type that can be used to re-cast the value later.
def is_valid_intensity_measure_types(self): """ If the IMTs and levels are extracted from the risk models, they must not be set directly. Moreover, if `intensity_measure_types_and_levels` is set directly, `intensity_measure_types` must not be set. """ if self.grou...
If the IMTs and levels are extracted from the risk models, they must not be set directly. Moreover, if `intensity_measure_types_and_levels` is set directly, `intensity_measure_types` must not be set.
def get_iam_policy(self): """Gets the access control policy for an instance resource. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_get_iam_policy] :end-before: [END bigtable_get_iam_policy] :rtype: :class:`google.cloud.bigtable.pol...
Gets the access control policy for an instance resource. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_get_iam_policy] :end-before: [END bigtable_get_iam_policy] :rtype: :class:`google.cloud.bigtable.policy.Policy` :returns: The cur...
def reorder(self, indices: mx.nd.NDArray) -> None: """ Reorders the avoid list according to the selected row indices. This can produce duplicates, but this is fixed if state changes occur in consume(). :param indices: An mx.nd.NDArray containing indices of hypotheses to select. ...
Reorders the avoid list according to the selected row indices. This can produce duplicates, but this is fixed if state changes occur in consume(). :param indices: An mx.nd.NDArray containing indices of hypotheses to select.
def create(container, portal_type, *args, **kwargs): """Creates an object in Bika LIMS This code uses most of the parts from the TypesTool see: `Products.CMFCore.TypesTool._constructInstance` :param container: container :type container: ATContentType/DexterityContentType/CatalogBrain :param po...
Creates an object in Bika LIMS This code uses most of the parts from the TypesTool see: `Products.CMFCore.TypesTool._constructInstance` :param container: container :type container: ATContentType/DexterityContentType/CatalogBrain :param portal_type: The portal type to create, e.g. "Client" :typ...
def comments(self): """获取答案下的所有评论. :return: 答案下的所有评论,返回生成器 :rtype: Comments.Iterable """ import math from .author import Author, ANONYMOUS from .comment import Comment api_url = Get_Answer_Comment_URL.format(self.aid) page = pages = 1 whi...
获取答案下的所有评论. :return: 答案下的所有评论,返回生成器 :rtype: Comments.Iterable
def compute_dosage(expec, alt=None): r""" Compute dosage from allele expectation. Parameters ---------- expec : array_like Allele expectations encoded as a samples-by-alleles matrix. alt : array_like, optional Alternative allele index. If ``None``, the allele having the minor ...
r""" Compute dosage from allele expectation. Parameters ---------- expec : array_like Allele expectations encoded as a samples-by-alleles matrix. alt : array_like, optional Alternative allele index. If ``None``, the allele having the minor allele frequency for the provided ``exp...
def normalize(self, mode="max", value=1): """ Normalize the spectrum with respect to the sum of intensity Args: mode (str): Normalization mode. Supported modes are "max" (set the max y value to value, e.g., in XRD patterns), "sum" (set the sum of y to...
Normalize the spectrum with respect to the sum of intensity Args: mode (str): Normalization mode. Supported modes are "max" (set the max y value to value, e.g., in XRD patterns), "sum" (set the sum of y to a value, i.e., like a probability density). value...
def get_jobs(self, project, **params): """ Gets jobs from project, filtered by parameters :param project: project (repository name) to query data for :param params: keyword arguments to filter results """ return self._get_json_list(self.JOBS_ENDPOINT, project, **params)
Gets jobs from project, filtered by parameters :param project: project (repository name) to query data for :param params: keyword arguments to filter results
def score_cosine(self, term1, term2, **kwargs): """ Compute a weighting score based on the cosine distance between the kernel density estimates of two terms. Args: term1 (str) term2 (str) Returns: float """ t1_kde = self.kde(term1, **kw...
Compute a weighting score based on the cosine distance between the kernel density estimates of two terms. Args: term1 (str) term2 (str) Returns: float
def get_config_path(): """ Determine the path to the config file. This will return, in this order of precedence: - the value of $BUGWARRIORRC if set - $XDG_CONFIG_HOME/bugwarrior/bugwarriorc if exists - ~/.bugwarriorrc if exists - <dir>/bugwarrior/bugwarriorc if exists, for dir in $XDG_CONFI...
Determine the path to the config file. This will return, in this order of precedence: - the value of $BUGWARRIORRC if set - $XDG_CONFIG_HOME/bugwarrior/bugwarriorc if exists - ~/.bugwarriorrc if exists - <dir>/bugwarrior/bugwarriorc if exists, for dir in $XDG_CONFIG_DIRS - $XDG_CONFIG_HOME/bugwa...
def get_limits(self): """ Return all known limits for this service, as a dict of their names to :py:class:`~.AwsLimit` objects. Limits from: docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html :returns: dict of limit names to :py:class:`~.AwsLimit` obj...
Return all known limits for this service, as a dict of their names to :py:class:`~.AwsLimit` objects. Limits from: docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html :returns: dict of limit names to :py:class:`~.AwsLimit` objects :rtype: dict
def _pos(self, k): """ Description: Position k breaking Parameters: k: position k is used for the breaking """ if k < 2: raise ValueError("k smaller than 2") G = np.zeros((self.m, self.m)) for i in range(self.m): ...
Description: Position k breaking Parameters: k: position k is used for the breaking
def __xd_iterator_pass_on(arr, view, fun): """ Like xd_iterator, but the fun return values are always passed on to the next and only the last returned. """ # create list of iterations iterations = [[None] if dim in view else list(range(arr.shape[dim])) for dim in range(arr.ndim)] # iterate...
Like xd_iterator, but the fun return values are always passed on to the next and only the last returned.
def register_producer(cls, producer): """ Register a default producer for events to use. :param producer: the default producer to to dispatch events on. """ log.info('@Registry.register_producer `{}`' .format(producer.__class__.__name__)) cls._producer = ...
Register a default producer for events to use. :param producer: the default producer to to dispatch events on.
def get_trending_daily_not_starred(self): """Gets trending repositories NOT starred by user :return: List of daily-trending repositories which are not starred """ trending_daily = self.get_trending_daily() # repos trending daily starred_repos = self.get_starred_repos() # repos ...
Gets trending repositories NOT starred by user :return: List of daily-trending repositories which are not starred
def check_token(token): ''' Verify http header token authentification ''' user = models.User.objects(api_key=token).first() return user or None
Verify http header token authentification
def loginfo(logger, msg, *args, **kwargs): ''' Logs messages as INFO, unless esgfpid.defaults.LOG_INFO_TO_DEBUG, (then it logs messages as DEBUG). ''' if esgfpid.defaults.LOG_INFO_TO_DEBUG: logger.debug(msg, *args, **kwargs) else: logger.info(msg, *args, **kwargs)
Logs messages as INFO, unless esgfpid.defaults.LOG_INFO_TO_DEBUG, (then it logs messages as DEBUG).
def yield_figs(self, **kwargs): # pragma: no cover """ This function *generates* a predefined list of matplotlib figures with minimal input from the user. """ yield self.plot_densities(title="PAW densities", show=False) yield self.plot_waves(title="PAW waves", show=False) ...
This function *generates* a predefined list of matplotlib figures with minimal input from the user.
def _get_tree_properties(root): """Inspect the binary tree and return its properties (e.g. height). :param root: Root node of the binary tree. :rtype: binarytree.Node :return: Binary tree properties. :rtype: dict """ is_descending = True is_ascending = True min_node_value = root.val...
Inspect the binary tree and return its properties (e.g. height). :param root: Root node of the binary tree. :rtype: binarytree.Node :return: Binary tree properties. :rtype: dict
def embed(self, rel, other, wrap=False): """Embeds a document inside this document. Arguments: - ``rel``: a string specifying the link relationship type of the embedded resource. ``rel`` should be a well-known link relation name from the IANA registry (http://www....
Embeds a document inside this document. Arguments: - ``rel``: a string specifying the link relationship type of the embedded resource. ``rel`` should be a well-known link relation name from the IANA registry (http://www.iana.org/assignments/link-relations/link-relations.x...
def config(self, kw=None, **kwargs): """configure redirect to support additional options""" themebg = kwargs.pop("themebg", self._themebg) toplevel = kwargs.pop("toplevel", self._toplevel) theme = kwargs.pop("theme", self.current_theme) color = self._get_bg_color() if the...
configure redirect to support additional options
def CopyRecord(record, **field_overrides): """Copies a record and its fields, recurses for any field that is a Record. For records that have nested mutable fields, use copy.deepcopy. Args: record: A Record instance to be copied. **field_overrides: Fields and their values to override in...
Copies a record and its fields, recurses for any field that is a Record. For records that have nested mutable fields, use copy.deepcopy. Args: record: A Record instance to be copied. **field_overrides: Fields and their values to override in the new copy. Returns: A copy of the given r...
def get_child_bin_ids(self, bin_id): """Gets the child ``Ids`` of the given bin. arg: bin_id (osid.id.Id): the ``Id`` to query return: (osid.id.IdList) - the children of the bin raise: NotFound - ``bin_id`` not found raise: NullArgument - ``bin_id`` is ``null`` rais...
Gets the child ``Ids`` of the given bin. arg: bin_id (osid.id.Id): the ``Id`` to query return: (osid.id.IdList) - the children of the bin raise: NotFound - ``bin_id`` not found raise: NullArgument - ``bin_id`` is ``null`` raise: OperationFailed - unable to complete request...
def table( self, dirPath=None): """*Render the results as an ascii table* **Key Arguments:** - ``dirPath`` -- the path to the directory to save the rendered results to. Default *None* **Return:** - `tableSources` -- the top-level transient data ...
*Render the results as an ascii table* **Key Arguments:** - ``dirPath`` -- the path to the directory to save the rendered results to. Default *None* **Return:** - `tableSources` -- the top-level transient data - `tablePhot` -- all photometry associated with the tran...
def fmt_repr(obj): """Print a orphaned string representation of an object without the clutter of its parent object. """ items = ["%s = %r" % (k, v) for k, v in list(exclude_fields(obj).items())] return "<%s: {%s}>" % (obj.__class__.__name__, ', '.join(items))
Print a orphaned string representation of an object without the clutter of its parent object.
def _shape_text(self, text, colsep=u"\t", rowsep=u"\n", transpose=False, skiprows=0, comments='#'): """Decode the shape of the given text""" assert colsep != rowsep out = [] text_rows = text.split(rowsep)[skiprows:] for row in text_rows: str...
Decode the shape of the given text
def open_resource(self, filename, mode='r'): """Open a file and also save it as a resource. Opens a file, reports it to the observers as a resource, and returns the opened file. In Sacred terminology a resource is a file that the experiment needed to access during a run. In cas...
Open a file and also save it as a resource. Opens a file, reports it to the observers as a resource, and returns the opened file. In Sacred terminology a resource is a file that the experiment needed to access during a run. In case of a MongoObserver that means making sure the ...
def argmin(self, values): """return the index into values corresponding to the minimum value of the group Parameters ---------- values : array_like, [keys] values to pick the argmin of per group Returns ------- unique: ndarray, [groups] u...
return the index into values corresponding to the minimum value of the group Parameters ---------- values : array_like, [keys] values to pick the argmin of per group Returns ------- unique: ndarray, [groups] unique keys argmin : ndarray, ...
def _validate(self): """Assure this is a valid VLAN header instance.""" if self.tpid.value not in (EtherType.VLAN, EtherType.VLAN_QINQ): raise UnpackException return
Assure this is a valid VLAN header instance.
def answering_questions(self, attempt, validation_token, quiz_submission_id, access_code=None, quiz_questions=None): """ Answering questions. Provide or update an answer to one or more QuizQuestions. """ path = {} data = {} params = {} # REQUIR...
Answering questions. Provide or update an answer to one or more QuizQuestions.
def session_from_client_config(client_config, scopes, **kwargs): """Creates a :class:`requests_oauthlib.OAuth2Session` from client configuration loaded from a Google-format client secrets file. Args: client_config (Mapping[str, Any]): The client configuration in the Google `client secre...
Creates a :class:`requests_oauthlib.OAuth2Session` from client configuration loaded from a Google-format client secrets file. Args: client_config (Mapping[str, Any]): The client configuration in the Google `client secrets`_ format. scopes (Sequence[str]): The list of scopes to reque...
def is_checked(self) -> bool: """One task ran (checked).""" if not self.redis_key_checked: return False value = self._red.get(self.redis_key_checked) if not value: return False return True
One task ran (checked).
def get_sla_template_path(service_type=ServiceTypes.ASSET_ACCESS): """ Get the template for a ServiceType. :param service_type: ServiceTypes :return: Path of the template, str """ if service_type == ServiceTypes.ASSET_ACCESS: name = 'access_sla_template.json' elif service_type == Se...
Get the template for a ServiceType. :param service_type: ServiceTypes :return: Path of the template, str
def get_aside(self, aside_usage_id): """ Create an XBlockAside in this runtime. The `aside_usage_id` is used to find the Aside class and data. """ aside_type = self.id_reader.get_aside_type_from_usage(aside_usage_id) xblock_usage = self.id_reader.get_usage_id_from_aside(...
Create an XBlockAside in this runtime. The `aside_usage_id` is used to find the Aside class and data.
def unstash_index(self, sync=False, branch=None): """Returns an unstash index if one is available.""" stash_list = self.git_exec(['stash', 'list'], no_verbose=True) if branch is None: branch = self.get_current_branch_name() for stash in stash_list.splitlines(): ...
Returns an unstash index if one is available.
def flush_headers(self, sync: bool = False) -> None: """ 通过异步写入 header """ if self._headers_sent: return self._headers_sent = True self.handel_default() self.write( b"HTTP/%s %d %s\r\n" % ( encode_str(self._version), ...
通过异步写入 header
def runSearchRnaQuantificationSets(self, request): """ Returns a SearchRnaQuantificationSetsResponse for the specified SearchRnaQuantificationSetsRequest object. """ return self.runSearchRequest( request, protocol.SearchRnaQuantificationSetsRequest, protoc...
Returns a SearchRnaQuantificationSetsResponse for the specified SearchRnaQuantificationSetsRequest object.
def scaffold_hits(searches, fasta, max_hits): """ get hits from each search against each RP scaffolds[scaffold] = # ORfs s2rp[scaffold] = {rp:[hits]} """ # initialize ## scaffolds[scaffold] = # ORFs scaffolds = {} for seq in parse_fasta(fasta): scaffold = seq[0].split()[0].sp...
get hits from each search against each RP scaffolds[scaffold] = # ORfs s2rp[scaffold] = {rp:[hits]}
def querysets_from_title_prefix(title_prefix=None, model=DEFAULT_MODEL, app=DEFAULT_APP): """Return a list of Querysets from a list of model numbers""" if title_prefix is None: title_prefix = [None] filter_dicts = [] model_list = [] if isinstance(title_prefix, basestring): title_pr...
Return a list of Querysets from a list of model numbers
def iodp_kly4s_lore(kly4s_file, meas_out='measurements.txt', spec_infile='specimens.txt', spec_out='specimens.txt', instrument='IODP-KLY4S', actual_volume="",dir_path='.', input_dir_path=''): """ Converts ascii files generated by SUFAR ver.4.0 and downloaded from the LIMS online repos...
Converts ascii files generated by SUFAR ver.4.0 and downloaded from the LIMS online repository to MagIC (datamodel 3) files Parameters ---------- kly4s_file : str input LORE downloaded csv file, required meas_output : str measurement output filename, default "measurements.txt" s...
def list(self): """ List all device management extension packages """ url = "api/v0002/mgmt/custom/bundle" r = self._apiClient.get(url) if r.status_code == 200: return r.json() else: raise ApiException(r)
List all device management extension packages
def sort_response(response: Dict[str, Any]) -> OrderedDict: """ Sort the keys in a JSON-RPC response object. This has no effect other than making it nicer to read. Useful in Python 3.5 only, dictionaries are already sorted in newer Python versions. Example:: >>> json.dumps(sort_response({...
Sort the keys in a JSON-RPC response object. This has no effect other than making it nicer to read. Useful in Python 3.5 only, dictionaries are already sorted in newer Python versions. Example:: >>> json.dumps(sort_response({'id': 2, 'result': 5, 'jsonrpc': '2.0'})) {"jsonrpc": "2.0", "re...
def register_handler(self, name, handler, esc_strings): """Register a handler instance by name with esc_strings.""" self._handlers[name] = handler for esc_str in esc_strings: self._esc_handlers[esc_str] = handler
Register a handler instance by name with esc_strings.
def finalize(self, process_row = None): """ Restore the LigolwSegmentList objects to the XML tables in preparation for output. All segments from all segment lists are inserted into the tables in time order, but this is NOT behaviour external applications should rely on. This is done simply in the belief th...
Restore the LigolwSegmentList objects to the XML tables in preparation for output. All segments from all segment lists are inserted into the tables in time order, but this is NOT behaviour external applications should rely on. This is done simply in the belief that it might assist in constructing well balanc...
def delete(queue, items): ''' Delete an item or items from a queue ''' con = _conn(queue) with con: cur = con.cursor() if isinstance(items, six.string_types): items = _quote_escape(items) cmd = """DELETE FROM {0} WHERE name = '{1}'""".format(queue, items) ...
Delete an item or items from a queue
def rasterize(path, pitch, origin, resolution=None, fill=True, width=None): """ Rasterize a Path2D object into a boolean image ("mode 1"). Parameters ------------ path: Path2D object pitch: float, length in model s...
Rasterize a Path2D object into a boolean image ("mode 1"). Parameters ------------ path: Path2D object pitch: float, length in model space of a pixel edge origin: (2,) float, origin position in model space resolution: (2,) int, resolution in pixel space fill: bool, if T...
def remove_import_statements(code): """Removes lines with import statements from the code. Args: code: The code to be stripped. Returns: The code without import statements. """ new_code = [] for line in code.splitlines(): if not line.lstrip().startswith('import ') and \...
Removes lines with import statements from the code. Args: code: The code to be stripped. Returns: The code without import statements.
def config_stop(args): '''Abort a task (method configuration) by submission ID in given space''' r = fapi.abort_submission(args.project, args.workspace, args.submission_id) fapi._check_response_code(r, 204) return ("Aborted {0} in {1}/{2}".format(args.submission_id, ...
Abort a task (method configuration) by submission ID in given space
def getprop(self, prop_name): """Get a property of the device. This is a convenience wrapper for "adb shell getprop xxx". Args: prop_name: A string that is the name of the property to get. Returns: A string that is the value of the property, or None if the prop...
Get a property of the device. This is a convenience wrapper for "adb shell getprop xxx". Args: prop_name: A string that is the name of the property to get. Returns: A string that is the value of the property, or None if the property doesn't exist.
def parse_if(self): """Parse an if construct.""" node = result = nodes.If(lineno=self.stream.expect('name:if').lineno) while 1: node.test = self.parse_tuple(with_condexpr=False) node.body = self.parse_statements(('name:elif', 'name:else', ...
Parse an if construct.
def camel_to_underscore(string): """Convert camelcase to lowercase and underscore. Recipe from http://stackoverflow.com/a/1176023 Args: string (str): The string to convert. Returns: str: The converted string. """ string = FIRST_CAP_RE.sub(r'\1_\2', string) return ALL_CAP_R...
Convert camelcase to lowercase and underscore. Recipe from http://stackoverflow.com/a/1176023 Args: string (str): The string to convert. Returns: str: The converted string.
def json_as_html(self): """ Print out self.json in a nice way. """ # To avoid circular import from cspreports import utils formatted_json = utils.format_report(self.json) return mark_safe("<pre>\n%s</pre>" % escape(formatted_json))
Print out self.json in a nice way.
def as_dict(self, verbosity=1, fmt=None, **kwargs): """ Dict representation of Structure. Args: verbosity (int): Verbosity level. Default of 1 includes both direct and cartesian coordinates for all sites, lattice parameters, etc. Useful for reading an...
Dict representation of Structure. Args: verbosity (int): Verbosity level. Default of 1 includes both direct and cartesian coordinates for all sites, lattice parameters, etc. Useful for reading and for insertion into a database. Set to 0 for an extreme...
def set_plugins(self, input_plugins): """Set the plugin list according to the Glances server.""" header = "glances_" for item in input_plugins: # Import the plugin try: plugin = __import__(header + item) except ImportError: # Se...
Set the plugin list according to the Glances server.
def greenhall_sx(t, F, alpha): """ Eqn (8) from Greenhall2004 """ if F == float('inf'): return greenhall_sw(t, alpha+2) a = 2*greenhall_sw(t, alpha) b = greenhall_sw(t-1.0/float(F), alpha) c = greenhall_sw(t+1.0/float(F), alpha) return pow(F, 2)*(a-b-c)
Eqn (8) from Greenhall2004
def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images...
Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images.
def configure(conf, channel=False, group=False, fm_integration=False): """Guide user to set up the bot, saves configuration at `conf`. # Arguments conf (str): Path where to save the configuration file. May contain `~` for user's home. channel (Optional[bool]): Configure a channel. ...
Guide user to set up the bot, saves configuration at `conf`. # Arguments conf (str): Path where to save the configuration file. May contain `~` for user's home. channel (Optional[bool]): Configure a channel. group (Optional[bool]): Configure a group. fm_integration (Optional[bool])...
def gen_batch(data, batch_size, maxiter=np.inf, random_state=None): """ Create random batches for Stochastic gradients. Batch index generator for SGD that will yeild random batches for a a defined number of iterations, which can be infinite. This generator makes consecutive passes through the data,...
Create random batches for Stochastic gradients. Batch index generator for SGD that will yeild random batches for a a defined number of iterations, which can be infinite. This generator makes consecutive passes through the data, drawing without replacement on each pass. Parameters ---------- ...
def get_file(profile, branch, file_path): """Get a file from a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. bra...
Get a file from a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. branch The name of a branch. fi...
def bfs_conditional(G, source, reverse=False, keys=True, data=False, yield_nodes=True, yield_if=None, continue_if=None, visited_nodes=None, yield_source=False): """ Produce edges in a breadth-first-search starting at source, but only return nodes t...
Produce edges in a breadth-first-search starting at source, but only return nodes that satisfiy a condition, and only iterate past a node if it satisfies a different condition. conditions are callables that take (G, child, edge) and return true or false CommandLine: python -m utool.util_graph ...
def set_home_location(self): '''set home location from last map click''' try: latlon = self.module('map').click_position except Exception: print("No map available") return lat = float(latlon[0]) lon = float(latlon[1]) if self.wploader.c...
set home location from last map click
def post(ctx, uri, input_file): """POST file data to a specific URI Note that POST is not used for most web services URIs. Instead, PUT is used for creating resources. """ http_client = get_wva(ctx).get_http_client() cli_pprint(http_client.post(uri, input_file.read()))
POST file data to a specific URI Note that POST is not used for most web services URIs. Instead, PUT is used for creating resources.
def make_password(password, salt=None, hasher='default'): """ Turn a plain-text password into a hash for database storage Same as encode() but generate a new random salt. If password is None then return a concatenation of UNUSABLE_PASSWORD_PREFIX and a random string, which disallows logins. Addition...
Turn a plain-text password into a hash for database storage Same as encode() but generate a new random salt. If password is None then return a concatenation of UNUSABLE_PASSWORD_PREFIX and a random string, which disallows logins. Additional random string reduces chances of gaining access to staff or sup...
def deactivate(self): """Remove any builtins which might have been added by add_builtins, or restore overwritten ones to their previous values.""" remove_builtin = self.remove_builtin for key, val in self._orig_builtins.iteritems(): remove_builtin(key, val) self._orig...
Remove any builtins which might have been added by add_builtins, or restore overwritten ones to their previous values.
def switch_led_on(self, ids): """ Switches on the LED of the motors with the specified ids. """ self._set_LED(dict(zip(ids, itertools.repeat(True))))
Switches on the LED of the motors with the specified ids.
def azureContainerSAS(self, *args, **kwargs): """ Get Shared-Access-Signature for Azure Container Get a shared access signature (SAS) string for use with a specific Azure Blob Storage container. The `level` parameter can be `read-write` or `read-only` and determines whi...
Get Shared-Access-Signature for Azure Container Get a shared access signature (SAS) string for use with a specific Azure Blob Storage container. The `level` parameter can be `read-write` or `read-only` and determines which type of credentials are returned. If level is read-write, it w...
def container_fs_usage_bytes(self, metric, scraper_config): """ Number of bytes that are consumed by the container on this filesystem. """ metric_name = scraper_config['namespace'] + '.filesystem.usage' if metric.type not in METRIC_TYPES: self.log.error("Metric type %...
Number of bytes that are consumed by the container on this filesystem.
def start(self): '''Begin fetching the next request.''' self._current_session = session = self._http_client.session() request = self.next_request() assert request if request.url_info.password or \ request.url_info.hostname_with_port in self._hostnames_with_auth:...
Begin fetching the next request.
def _fill(self): """Advance the iterator without returning the old head.""" try: self._head = self._iterable.next() except StopIteration: self._head = None
Advance the iterator without returning the old head.
def evaluate(self, item): """ Pull the field off the item """ try: for match in PATH_PATTERN.finditer(self.field): path = match.group(0) if path[0] == "[": # If we're selecting an item at a specific index of an # array, ...
Pull the field off the item
def check_tag_data(data): "Raise a ValueError if DATA doesn't seem to be a well-formed ID3 tag." if len(data) < 10: raise ValueError("Tag too short") if data[0:3] != b"ID3": raise ValueError("Missing ID3 identifier") if data[3] >= 5 or data[4] != 0: raise ValueError("Unknown ID3 ...
Raise a ValueError if DATA doesn't seem to be a well-formed ID3 tag.
def experiment_group_post_delete(sender, **kwargs): """Delete all group outputs.""" instance = kwargs['instance'] auditor.record(event_type=EXPERIMENT_GROUP_DELETED, instance=instance) remove_bookmarks(object_id=instance.id, content_type='experimentgroup')
Delete all group outputs.
def _make_resource(self): """ Returns a resource instance. """ with self._lock: for i in self._unavailable_range(): if self._reference_queue[i] is None: rtracker = _ResourceTracker( self._factory(**self._factory_argu...
Returns a resource instance.
def get_internal_instances(self, phase=None): """Get a list of internal instances (in a specific phase) If phase is None, return all internal instances whtever the phase :param phase: phase to filter (never used) :type phase: :return: internal instances list :rtype: lis...
Get a list of internal instances (in a specific phase) If phase is None, return all internal instances whtever the phase :param phase: phase to filter (never used) :type phase: :return: internal instances list :rtype: list
def _get_template_dirs(): """existing directories where to search for jinja2 templates. The order is important. The first found template from the first found dir wins!""" return filter(lambda x: os.path.exists(x), [ # user dir os.path.join(os.path.expanduser('~'), '.py2pack', 'templates'), ...
existing directories where to search for jinja2 templates. The order is important. The first found template from the first found dir wins!
def listRemoteDatawraps(location = conf.pyGeno_REMOTE_LOCATION) : """Lists all the datawraps availabe from a remote a remote location.""" loc = location + "/datawraps.json" response = urllib2.urlopen(loc) js = json.loads(response.read()) return js
Lists all the datawraps availabe from a remote a remote location.
def _load_data(self, band): """From Morrissey+ 2005, with the actual data coming from http://www.astro.caltech.edu/~capak/filters/. According to the latter, these are in QE units and thus need to be multiplied by the wavelength when integrating per-energy. """ # `band` s...
From Morrissey+ 2005, with the actual data coming from http://www.astro.caltech.edu/~capak/filters/. According to the latter, these are in QE units and thus need to be multiplied by the wavelength when integrating per-energy.
def delete_all_objects(self, async_=False): """ Deletes all objects from this container. By default the call will block until all objects have been deleted. By passing True for the 'async_' parameter, this method will not block, and instead return an object that can be used to f...
Deletes all objects from this container. By default the call will block until all objects have been deleted. By passing True for the 'async_' parameter, this method will not block, and instead return an object that can be used to follow the progress of the deletion. When deletion is com...
def disclaim_key_flags(): """Declares that the current module will not define any more key flags. Normally, the module that calls the DEFINE_xxx functions claims the flag to be its key flag. This is undesirable for modules that define additional DEFINE_yyy functions with its own flag parsers and serializers...
Declares that the current module will not define any more key flags. Normally, the module that calls the DEFINE_xxx functions claims the flag to be its key flag. This is undesirable for modules that define additional DEFINE_yyy functions with its own flag parsers and serializers, since that module will accide...
def find_replace_string(obj, find, replace): """Performs a string.replace() on the input object. Args: obj (object): The object to find/replace. It will be cast to ``str``. find (str): The string to search for. replace (str): The string to replace with. Returns: str: The rep...
Performs a string.replace() on the input object. Args: obj (object): The object to find/replace. It will be cast to ``str``. find (str): The string to search for. replace (str): The string to replace with. Returns: str: The replaced string.
def _processJobsWithRunningServices(self): """Get jobs whose services have started""" while True: jobGraph = self.serviceManager.getJobGraphWhoseServicesAreRunning(0) if jobGraph is None: # Stop trying to get jobs when function returns None break logge...
Get jobs whose services have started
def get_random_url(ltd="com"): """Get a random url with the given ltd. Args: ltd (str): The ltd to use (e.g. com). Returns: str: The random url. """ url = [ "https://", RandomInputHelper.get_random_value(8, [string.ascii_lowerca...
Get a random url with the given ltd. Args: ltd (str): The ltd to use (e.g. com). Returns: str: The random url.
def get(self, project): """Query the project status. Returns a ``CLAMData`` instance or raises an exception according to the returned HTTP Status code""" try: data = self.request(project + '/') except: raise if not isinstance(data, clam.common.data.CLAMData): ...
Query the project status. Returns a ``CLAMData`` instance or raises an exception according to the returned HTTP Status code
def pixy_set_servos(self, s0, s1): """ Sends the setServos Pixy command. This method sets the pan/tilt servos that are plugged into Pixy's two servo ports. :param s0: value 0 to 1000 :param s1: value 0 to 1000 :returns: No return value. """ task = async...
Sends the setServos Pixy command. This method sets the pan/tilt servos that are plugged into Pixy's two servo ports. :param s0: value 0 to 1000 :param s1: value 0 to 1000 :returns: No return value.
def qteMacroNameMangling(self, macroCls): """ Convert the class name of a macro class to macro name. The name mangling inserts a '-' character after every capital letter and then lowers the entire string. Example: if the class name of ``macroCls`` is 'ThisIsAMacro' then...
Convert the class name of a macro class to macro name. The name mangling inserts a '-' character after every capital letter and then lowers the entire string. Example: if the class name of ``macroCls`` is 'ThisIsAMacro' then this method will return 'this-is-a-macro', ie. every ...
def run(cmd, stdout=None, stderr=None, **kwargs): """ A blocking wrapper around subprocess.Popen(), but with a simpler interface for the stdout/stderr arguments: stdout=False / stderr=False stdout/stderr will be redirected to /dev/null (or discarded in some other suitable manner) st...
A blocking wrapper around subprocess.Popen(), but with a simpler interface for the stdout/stderr arguments: stdout=False / stderr=False stdout/stderr will be redirected to /dev/null (or discarded in some other suitable manner) stdout=True / stderr=True stdout/stderr will be captured...
def bind(self, cube): """ When one column needs to match, use the key. """ if self.measure: table, column = self.measure.bind(cube) else: table, column = cube.fact_table, cube.fact_pk # apply the SQL aggregation function: column = getattr(func, self.functi...
When one column needs to match, use the key.
def get_data(self, url='',headers={}, date=str(datetime.date.today()), dict_to_store={}, type='', repo_name=''): """ Retrieves data from json and stores it in the supplied dict. Accepts 'clones' or 'views' as type. """ #JSON url = (url + '/traffic/' + type) ...
Retrieves data from json and stores it in the supplied dict. Accepts 'clones' or 'views' as type.
def concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False, keys=None, levels=None, names=None, verify_integrity=False, sort=None, copy=True): """ Concatenate pandas objects along a particular axis with optional set logic along the other axes. Can also add a layer o...
Concatenate pandas objects along a particular axis with optional set logic along the other axes. Can also add a layer of hierarchical indexing on the concatenation axis, which may be useful if the labels are the same (or overlapping) on the passed axis number. Parameters ---------- objs : ...