code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def register_yaml(): """Register a encoder/decoder for YAML serialization. It is slower than JSON, but allows for more data types to be serialized. Useful if you need to send data such as dates""" try: import yaml registry.register('yaml', yaml.safe_dump, yaml.safe_load, ...
Register a encoder/decoder for YAML serialization. It is slower than JSON, but allows for more data types to be serialized. Useful if you need to send data such as dates
def select_tqdm(): """If running in a jupyter notebook, then returns tqdm_notebook. Otherwise returns a regular tqdm progress bar. Returns ------- progress: function """ try: progress = tqdm.tqdm_notebook assert get_ipython().has_trait('kernel') except (NameError, Assert...
If running in a jupyter notebook, then returns tqdm_notebook. Otherwise returns a regular tqdm progress bar. Returns ------- progress: function
def make_combined_periodogram(pflist, outfile, addmethods=False): '''This just puts all of the period-finders on a single periodogram. This will renormalize all of the periodograms so their values lie between 0 and 1, with values lying closer to 1 being more significant. Periodograms that give the same...
This just puts all of the period-finders on a single periodogram. This will renormalize all of the periodograms so their values lie between 0 and 1, with values lying closer to 1 being more significant. Periodograms that give the same best periods will have their peaks line up together. Parameters ...
def remove_from_group(self, devices): """Remove device(s) from the group.""" ids = {d.id for d in self.devices_in_group()} ids.difference_update(self._device_ids(devices)) self._set_group(ids)
Remove device(s) from the group.
def lint_api(api_name, old, new, locations): """Lint an acceptable api metadata.""" is_new_api = not old api_location = locations['api'] changelog = new.get('changelog', {}) changelog_location = api_location if locations['changelog']: changelog_location = list(locations['changelog'].val...
Lint an acceptable api metadata.
def u2(self, phi, lam, q): """Apply u2 to q.""" return self.append(U2Gate(phi, lam), [q], [])
Apply u2 to q.
def add_unique_element(self, location, element): """ Create an entry located at ``location``. Args: location: String or :class:`LocationDescriptor` to describe a "separator location" (i.e. dir1/dir2/dir3 for instance). element: Element to store. ...
Create an entry located at ``location``. Args: location: String or :class:`LocationDescriptor` to describe a "separator location" (i.e. dir1/dir2/dir3 for instance). element: Element to store. Returns: The created node with the elemen...
def generate_metadata_entry(self, entry_point, toolchain, spec): """ After the toolchain and spec have been executed, this may be called to generate the artifact export entry for persistence into the metadata file. """ export_target = spec['export_target'] toolch...
After the toolchain and spec have been executed, this may be called to generate the artifact export entry for persistence into the metadata file.
async def create_invite(self, *, reason=None, **fields): """|coro| Creates an instant invite. You must have :attr:`~.Permissions.create_instant_invite` permission to do this. Parameters ------------ max_age: :class:`int` How long the invite should l...
|coro| Creates an instant invite. You must have :attr:`~.Permissions.create_instant_invite` permission to do this. Parameters ------------ max_age: :class:`int` How long the invite should last. If it's 0 then the invite doesn't expire. Defaults ...
def get_process_pid(process_name): """ check for process' pid file and returns pid from there """ try: pid_filename = get_pid_filename(process_name) with open(pid_filename, mode='r') as pid_file: pid = int(pid_file.read().strip()) except IOError: pid = None return pid
check for process' pid file and returns pid from there
def drawBackground(self, painter, rect): """When an area of the window is exposed, we just copy out of the server-side, off-screen pixmap to that area. """ if not self.pixmap: return x1, y1, x2, y2 = rect.getCoords() width = x2 - x1 + 1 height = y2 - y...
When an area of the window is exposed, we just copy out of the server-side, off-screen pixmap to that area.
def intersect(self, other_seg, tol=1e-12): """NOT FULLY IMPLEMENTED. Finds the intersections of two segments. returns a list of tuples (t1, t2) such that self.point(t1) == other_seg.point(t2). Note: This will fail if the two segments coincide for more than a finite collection of...
NOT FULLY IMPLEMENTED. Finds the intersections of two segments. returns a list of tuples (t1, t2) such that self.point(t1) == other_seg.point(t2). Note: This will fail if the two segments coincide for more than a finite collection of points. Note: Arc related intersections are ...
def make_param(self, name, raw_uri, disk_size): """Return a MountParam given a GCS bucket, disk image or local path.""" if raw_uri.startswith('https://www.googleapis.com/compute'): # Full Image URI should look something like: # https://www.googleapis.com/compute/v1/projects/<project>/global/images/ ...
Return a MountParam given a GCS bucket, disk image or local path.
def mention(self): """ Get mention if a Chat has a username, or get full name if this is a Private Chat, otherwise None is returned """ if self.username: return '@' + self.username if self.type == ChatType.PRIVATE: return self.full_name return None
Get mention if a Chat has a username, or get full name if this is a Private Chat, otherwise None is returned
def acoustic_similarity_directories(directories, analysis_function, distance_function, stop_check=None, call_back=None, multiprocessing=True): """ Analyze many directories. Parameters ---------- directories : list of str List of fully specified paths to the directories to be analyzed "...
Analyze many directories. Parameters ---------- directories : list of str List of fully specified paths to the directories to be analyzed
def _initialize(self, runtime): """Common initializer for OsidManager and OsidProxyManager""" if runtime is None: raise NullArgument() if self._my_runtime is not None: raise IllegalState('this manager has already been initialized.') self._my_runtime = runtime ...
Common initializer for OsidManager and OsidProxyManager
def _internal2external_grad(xi, bounds): """ Calculate the internal (unconstrained) to external (constained) parameter gradiants. """ grad = empty_like(xi) for i, (v, bound) in enumerate(zip(xi, bounds)): lower, upper = bound if lower is None and upper is None: # No constraints ...
Calculate the internal (unconstrained) to external (constained) parameter gradiants.
def _unpack_batch_response(response): """Convert requests.Response -> [(headers, payload)]. Creates a generator of tuples of emulating the responses to :meth:`requests.Session.request`. :type response: :class:`requests.Response` :param response: HTTP response / headers from a request. """ ...
Convert requests.Response -> [(headers, payload)]. Creates a generator of tuples of emulating the responses to :meth:`requests.Session.request`. :type response: :class:`requests.Response` :param response: HTTP response / headers from a request.
def is_instance_throughput_too_low(self, inst_id): """ Return whether the throughput of the master instance is greater than the acceptable threshold """ r = self.instance_throughput_ratio(inst_id) if r is None: logger.debug("{} instance {} throughput is not " ...
Return whether the throughput of the master instance is greater than the acceptable threshold
def send_document(self, chat_id=None, document=None, reply_to_message_id=None, reply_markup=None): """ Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the futur...
Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
def time_restarts(data_path): """ When called will create a file and measure its mtime on restarts """ path = os.path.join(data_path, 'last_restarted') if not os.path.isfile(path): with open(path, 'a'): os.utime(path, None) last_modified = os.stat(path).st_mtime with open(path,...
When called will create a file and measure its mtime on restarts
async def request_proof(self, connection: Connection): """ Example: connection = await Connection.create(source_id) await connection.connect(phone_number) name = "proof name" requested_attrs = [{"name": "age", "restrictions": [{"schema_id": "6XFh8yBzrpJQmNyZzgoTqB:2:schem...
Example: connection = await Connection.create(source_id) await connection.connect(phone_number) name = "proof name" requested_attrs = [{"name": "age", "restrictions": [{"schema_id": "6XFh8yBzrpJQmNyZzgoTqB:2:schema_name:0.0.11", "schema_name":"Faber Student Info", "schema_version":"1.0",...
def load_stdlib(): '''Scans sys.path for standard library modules. ''' if _stdlib: return _stdlib prefixes = tuple({os.path.abspath(p) for p in ( sys.prefix, getattr(sys, 'real_prefix', sys.prefix), getattr(sys, 'base_prefix', sys.prefix), )}) for sp in sys.path...
Scans sys.path for standard library modules.
def extract(self, url=None, raw_html=None): """\ Main method to extract an article object from a URL, pass in a url and get back a Article """ cc = CrawlCandidate(self.config, url, raw_html) return self.crawl(cc)
\ Main method to extract an article object from a URL, pass in a url and get back a Article
def add(self, sim, module, package=None): """ Add simulation to layer. """ super(Simulations, self).add(sim, module, package) # only update layer info if it is missing! if sim not in self.layer: # copy simulation source parameters to :attr:`Layer.layer` ...
Add simulation to layer.
def MakeExponentialPmf(lam, high, n=200): """Makes a PMF discrete approx to an exponential distribution. lam: parameter lambda in events per unit time high: upper bound n: number of values in the Pmf returns: normalized Pmf """ pmf = Pmf() for x in numpy.linspace(0, high, n): p...
Makes a PMF discrete approx to an exponential distribution. lam: parameter lambda in events per unit time high: upper bound n: number of values in the Pmf returns: normalized Pmf
def end(self, *args): """ End a nested log. """ if self._is_verbose: # verbose log has no end method return self if not args: self._indent -= 1 return self self.writeln('end', *args) self._indent -= 1 retur...
End a nested log.
def cov(m, y=None, rowvar=1, bias=0, ddof=None, weights=None, repeat_weights=0): """ Estimate a covariance matrix, given data. Covariance indicates the level to which two variables vary together. If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`, then the covariance matrix elem...
Estimate a covariance matrix, given data. Covariance indicates the level to which two variables vary together. If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`, then the covariance matrix element :math:`C_{ij}` is the covariance of :math:`x_i` and :math:`x_j`. The element :math:`C...
def compare_notebooks(notebook_expected, notebook_actual, fmt=None, allow_expected_differences=True, raise_on_first_difference=True, compare_outputs=False): """Compare the two notebooks, and raise with a me...
Compare the two notebooks, and raise with a meaningful message that explains the differences, if any
def start(dispatcher, future, *, loop=None, skip_updates=None, on_startup=None, on_shutdown=None): """ Execute Future. :param dispatcher: instance of Dispatcher :param future: future :param loop: instance of AbstractEventLoop :param skip_updates: :param on_startup: :param on_s...
Execute Future. :param dispatcher: instance of Dispatcher :param future: future :param loop: instance of AbstractEventLoop :param skip_updates: :param on_startup: :param on_shutdown: :return:
def _publish_daemon(self, log_queue=None): ''' Bind to the interface specified in the configuration file ''' salt.utils.process.appendproctitle(self.__class__.__name__) if log_queue: salt.log.setup.set_multiprocessing_logging_queue(log_queue) salt.log.setu...
Bind to the interface specified in the configuration file
def describe_file_set(modules): """Build a file set from a specified Python modules. Args: modules: Iterable of Python module to describe. Returns: Initialized FileSet instance describing the modules. """ descriptor = FileSet() file_descriptors = [] for module in modules: ...
Build a file set from a specified Python modules. Args: modules: Iterable of Python module to describe. Returns: Initialized FileSet instance describing the modules.
def query_work_items_for_artifact_uris(self, artifact_uri_query, project=None): """QueryWorkItemsForArtifactUris. [Preview API] Queries work items linked to a given list of artifact URI. :param :class:`<ArtifactUriQuery> <azure.devops.v5_0.work_item_tracking.models.ArtifactUriQuery>` artifact_ur...
QueryWorkItemsForArtifactUris. [Preview API] Queries work items linked to a given list of artifact URI. :param :class:`<ArtifactUriQuery> <azure.devops.v5_0.work_item_tracking.models.ArtifactUriQuery>` artifact_uri_query: Defines a list of artifact URI for querying work items. :param str project...
def get_instance(self, payload): """ Build an instance of MachineToMachineInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.available_phone_number.machine_to_machine.MachineToMachineInstance :rtype: twilio.rest.api.v2010.account...
Build an instance of MachineToMachineInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.available_phone_number.machine_to_machine.MachineToMachineInstance :rtype: twilio.rest.api.v2010.account.available_phone_number.machine_to_machine.MachineToM...
def context_lookup(self, vars): """ Lookup the variables in the provided dictionary, resolve with entries in the context """ while isinstance(vars, IscmExpr): vars = vars.resolve(self.context) # for (k,v) in vars.items(): if isinstance(v, I...
Lookup the variables in the provided dictionary, resolve with entries in the context
def _get_struct_fillstyle(self, shape_number): """Get the values for the FILLSTYLE record.""" obj = _make_object("FillStyle") obj.FillStyleType = style_type = unpack_ui8(self._src) if style_type == 0x00: if shape_number <= 2: obj.Color = self._get_struct_rgb(...
Get the values for the FILLSTYLE record.
def _dataframe_fields(self): """ Creates a dictionary of all fields to include with DataFrame. With the result of the calls to class properties changing based on the class index value, the dictionary should be regenerated every time the index is changed when the dataframe proper...
Creates a dictionary of all fields to include with DataFrame. With the result of the calls to class properties changing based on the class index value, the dictionary should be regenerated every time the index is changed when the dataframe property is requested. Returns -------...
def Split(cls, extended_path_mask): ''' Splits the given path into their components: recursive, dirname, in_filters and out_filters :param str: extended_path_mask: The "extended path mask" to split :rtype: tuple(bool,bool,str,list(str),list(str)) :returns: ...
Splits the given path into their components: recursive, dirname, in_filters and out_filters :param str: extended_path_mask: The "extended path mask" to split :rtype: tuple(bool,bool,str,list(str),list(str)) :returns: Returns the extended path 5 components: -...
def assembly_plus_protons(input_file, path=True, pdb_name=None, save_output=False, force_save=False): """Returns an Assembly with protons added by Reduce. Notes ----- Looks for a pre-existing Reduce output in the standard location before running Reduce. If the protein cont...
Returns an Assembly with protons added by Reduce. Notes ----- Looks for a pre-existing Reduce output in the standard location before running Reduce. If the protein contains oligosaccharides or glycans, use reduce_correct_carbohydrates. Parameters ---------- input_file : str or pathlib....
def get_array(self, variable_name, period): """ Return the value of ``variable_name`` for ``period``, if this value is alreay in the cache (if it has been set as an input or previously calculated). Unlike :any:`calculate`, this method *does not* trigger calculations and *does not* use a...
Return the value of ``variable_name`` for ``period``, if this value is alreay in the cache (if it has been set as an input or previously calculated). Unlike :any:`calculate`, this method *does not* trigger calculations and *does not* use any formula.
def close(self): """Close the underlying stream and audio interface.""" if self._audio_stream: self.stop() self._audio_stream.close() self._audio_stream = None
Close the underlying stream and audio interface.
def execute_request_handler(self): """ Invoke the request handler defined by the :func:`sanic.app.Sanic.handle_request` method :return: None """ self._response_timeout_handler = self.loop.call_later( self.response_timeout, self.response_timeout_callback ...
Invoke the request handler defined by the :func:`sanic.app.Sanic.handle_request` method :return: None
def load_params(self, path, exclude_free_params=False): """ Load parameters from file. """ if not os.path.exists(path): return; logging.info("loading parameters from %s" % path) # Decide which parameters to load if exclude_free_params: params_to_load =...
Load parameters from file.
def reissue_activation(self, activation_key): """ Creates a new ``activation_key`` resetting activation timeframe when users let the previous key expire. :param activation_key: String containing the secret SHA1 activation key. """ try: userena = ...
Creates a new ``activation_key`` resetting activation timeframe when users let the previous key expire. :param activation_key: String containing the secret SHA1 activation key.
def geis2mef(sciname, convert_dq=True): """ Converts a GEIS science file and its corresponding data quality file (if present) to MEF format Writes out both files to disk. Returns the new name of the science image. """ clobber = True mode = 'update' memmap = True # Input was speci...
Converts a GEIS science file and its corresponding data quality file (if present) to MEF format Writes out both files to disk. Returns the new name of the science image.
def find_orphans(model): """ Return metabolites that are only consumed in reactions. Metabolites that are involved in an exchange reaction are never considered to be orphaned. Parameters ---------- model : cobra.Model The metabolic model under investigation. """ exchange =...
Return metabolites that are only consumed in reactions. Metabolites that are involved in an exchange reaction are never considered to be orphaned. Parameters ---------- model : cobra.Model The metabolic model under investigation.
def reflect_table(conn, table_name, schema='public'): """Reflect basic table attributes.""" column_meta = list(get_column_metadata(conn, table_name, schema=schema)) primary_key_columns = list(get_primary_keys(conn, table_name, schema=schema)) columns = [Column(**column_data) for column_data in column_...
Reflect basic table attributes.
def _compute_term_frequency(self, matrix, smooth=0.4): """ Computes TF metrics for each sentence (column) in the given matrix. You can read more about smoothing parameter at URL below: http://nlp.stanford.edu/IR-book/html/htmledition/maximum-tf-normalization-1.html """ as...
Computes TF metrics for each sentence (column) in the given matrix. You can read more about smoothing parameter at URL below: http://nlp.stanford.edu/IR-book/html/htmledition/maximum-tf-normalization-1.html
def expand(self): """ Creates a combination of all sub-sentences. Returns: List<List<str>>: A list with all subsentence expansions combined in every possible way """ old_expanded = [[]] for sub in self._tree: ...
Creates a combination of all sub-sentences. Returns: List<List<str>>: A list with all subsentence expansions combined in every possible way
def getDocNumber(xml): """ Parse <doc_number> tag from `xml`. Args: xml (str): XML string returned from :func:`aleph.aleph.downloadRecords` Returns: str: Doc ID as string or "-1" if not found. """ dom = dhtmlparser.parseString(xml) doc_number_tag = dom.find("doc_number") ...
Parse <doc_number> tag from `xml`. Args: xml (str): XML string returned from :func:`aleph.aleph.downloadRecords` Returns: str: Doc ID as string or "-1" if not found.
def run_vcfanno(vcf_file, data, decomposed=False): """Run vcfanno, providing annotations from external databases if needed. Puts together lua and conf files from multiple inputs by file names. """ conf_files = dd.get_vcfanno(data) if conf_files: with_basepaths = collections.defaultdict(list...
Run vcfanno, providing annotations from external databases if needed. Puts together lua and conf files from multiple inputs by file names.
def process(self, tup): """Process steps: 1. Index third positional value from input to elasticsearch. """ self.es.bulk( self.generate_bulk_body(tup.values[2]), index=self.index, doc_type=self.doc_type)
Process steps: 1. Index third positional value from input to elasticsearch.
def day_display(year, month, all_month_events, day): """ Returns the events that occur on the given day. Works by getting all occurrences for the month, then drilling down to only those occurring on the given day. """ # Get a dict with all of the events for the month count = CountHandler(yea...
Returns the events that occur on the given day. Works by getting all occurrences for the month, then drilling down to only those occurring on the given day.
def render_prev_next_links(self, scheme=None): """Render the rel=prev and rel=next links to a Markup object for injection into a template""" output = '' if self.has_prev: output += '<link rel="prev" href="{}" />\n'.format(self.get_full_page_url(self.prev, scheme=scheme)) ...
Render the rel=prev and rel=next links to a Markup object for injection into a template
def compute_distance(self, other, default=None): """ Compute the minimal distance between the line string and `other`. Parameters ---------- other : tuple of number \ or imgaug.augmentables.kps.Keypoint \ or imgaug.augmentables.LineString ...
Compute the minimal distance between the line string and `other`. Parameters ---------- other : tuple of number \ or imgaug.augmentables.kps.Keypoint \ or imgaug.augmentables.LineString Other object to which to compute the distance. default ...
def flatten(image, bgcolor=None): """ Flatten an image, with an optional background color """ if bgcolor: background = PIL.Image.new('RGB', image.size, bgcolor) background.paste(image, mask=image.split()[3]) return background return image.convert('RGB')
Flatten an image, with an optional background color
def content_type(self): """Returns the content-type value determined by file extension.""" if hasattr(self, '_content_type'): return self._content_type filename, extension = os.path.splitext(self._file_path) if extension == '.csv': self._content_type = 'text/csv...
Returns the content-type value determined by file extension.
def add_class_button_status(self): """Function to enable or disable add class button.""" if self.class_form.text() and self.radius_form.value() >= 0: self.add_class_button.setEnabled(True) else: self.add_class_button.setEnabled(False)
Function to enable or disable add class button.
def iteritems(obj, **kwargs): """replacement for six's iteritems for Python2/3 compat uses 'iteritems' if available and otherwise uses 'items'. Passes kwargs to method.""" func = getattr(obj, "iteritems", None) if not func: func = obj.items return func(**kwargs)
replacement for six's iteritems for Python2/3 compat uses 'iteritems' if available and otherwise uses 'items'. Passes kwargs to method.
def match_path(pathname, included_patterns=None, excluded_patterns=None, case_sensitive=True): """ Matches a pathname against a set of acceptable and ignored patterns. :param pathname: A pathname which will be matched against a pattern. :param includ...
Matches a pathname against a set of acceptable and ignored patterns. :param pathname: A pathname which will be matched against a pattern. :param included_patterns: Allow filenames matching wildcard patterns specified in this list. If no pattern is specified, the function treats the path...
def liquid_precipitation_quantity(self, value=99.0): """Corresponds to IDD Field `liquid_precipitation_quantity` Args: value (float): value for IDD Field `liquid_precipitation_quantity` Unit: hr Missing value: 99.0 if `value` is None it will n...
Corresponds to IDD Field `liquid_precipitation_quantity` Args: value (float): value for IDD Field `liquid_precipitation_quantity` Unit: hr Missing value: 99.0 if `value` is None it will not be checked against the specification and is a...
def add_avatar_image(self, mime_type, *, id_=None, image_bytes=None, width=None, height=None, url=None, nbytes=None): """ Add a source of the avatar image. All sources of an avatar image added to an avatar set must be *the same image*, i...
Add a source of the avatar image. All sources of an avatar image added to an avatar set must be *the same image*, in different formats and sizes. :param mime_type: The MIME type of the avatar image. :param id_: The SHA1 of the image data. :param nbytes: The size of the image da...
def replace_config(config, name): '''Replace the top-level pipeline configurable object. This investigates a number of sources, including `external_stages_path` and `external_stages_modules` configuration and `streamcorpus_pipeline.stages` entry points, and uses these to find the actual :data:`sub_...
Replace the top-level pipeline configurable object. This investigates a number of sources, including `external_stages_path` and `external_stages_modules` configuration and `streamcorpus_pipeline.stages` entry points, and uses these to find the actual :data:`sub_modules` for :mod:`streamcorpus_pipel...
def insertImage(page, rect, filename=None, pixmap=None, stream=None, rotate=0, keep_proportion = True, overlay=True): """Insert an image in a rectangle on the current page. Notes: Exactly one of filename, pixmap or stream must be provided. Args: rect: (rect-l...
Insert an image in a rectangle on the current page. Notes: Exactly one of filename, pixmap or stream must be provided. Args: rect: (rect-like) where to place the source image filename: (str) name of an image file pixmap: (obj) a Pixmap object stream: (bytes) an image in ...
def read_iter(): '''Return the path to the final rho*.mag file from the tomodir. ''' filename = 'exe/inv.lastmod' linestring = open(filename, 'r').readline().strip() linestring = linestring.replace('\n', '') linestring = linestring.replace('../', '') return linestring
Return the path to the final rho*.mag file from the tomodir.
def stop(name, kill=False, runas=None): ''' Stop a VM :param str name: Name/ID of VM to stop :param bool kill: Perform a hard shutdown :param str runas: The user that the prlctl command will be run as Example: .. code-block:: bash salt '*' parallels.stop...
Stop a VM :param str name: Name/ID of VM to stop :param bool kill: Perform a hard shutdown :param str runas: The user that the prlctl command will be run as Example: .. code-block:: bash salt '*' parallels.stop macvm runas=macdev salt '*' parallels.stop ...
def join_group_with_token(self, group_hashtag, group_jid, join_token): """ Tries to join into a specific group, using a cryptographic token that was received earlier from a search :param group_hashtag: The public hashtag of the group into which to join (like '#Music') :param group_jid: ...
Tries to join into a specific group, using a cryptographic token that was received earlier from a search :param group_hashtag: The public hashtag of the group into which to join (like '#Music') :param group_jid: The JID of the same group :param join_token: a token that can be extracted in the c...
def get_git_version(cls): """ Return version of git current shell points to. If version cannot be parsed None is returned. @rtype: tuple or None """ try: output = cls.run_git_shell('git version') except CalledProcessError: cls.LOG.warning...
Return version of git current shell points to. If version cannot be parsed None is returned. @rtype: tuple or None
def create_vmfs_datastore(datastore_name, disk_id, vmfs_major_version, safety_checks=True, service_instance=None): ''' Creates a ESXi host disk group with the specified cache and capacity disks. datastore_name The name of the datastore to be created. disk_id T...
Creates a ESXi host disk group with the specified cache and capacity disks. datastore_name The name of the datastore to be created. disk_id The disk id (canonical name) on which the datastore is created. vmfs_major_version The VMFS major version. safety_checks Specify...
def to_cartopy(self): """Convert to a CartoPy projection.""" globe = self.cartopy_globe proj_name = self._attrs['grid_mapping_name'] try: proj_handler = self.projection_registry[proj_name] except KeyError: raise ValueError('Unhandled projection: {}'.format...
Convert to a CartoPy projection.
def _get_metadata_model(name=None): """Find registered Metadata object.""" if name is not None: try: return registry[name] except KeyError: if len(registry) == 1: valid_names = 'Try using the name "%s" or simply leaving it '\ ...
Find registered Metadata object.
def get_uids(self): """Returns a uids list of the objects this action must be performed against to. If no values for uids param found in the request, returns the uid of the current context """ uids = self.get_uids_from_request() if not uids and api.is_object(self.context)...
Returns a uids list of the objects this action must be performed against to. If no values for uids param found in the request, returns the uid of the current context
def glob(self): """Returns a sorted glob of files belonging to a given problem""" file_glob = glob.glob(BASE_NAME.format('*', self.num, '*', '.*')) # Sort globbed files by tuple (filename, extension) return sorted(file_glob, key=lambda f: os.path.splitext(f))
Returns a sorted glob of files belonging to a given problem
def factory(self, url): ''' Return (expiration, obj) corresponding to provided url, exercising the cache_policy as necessary. ''' try: return self.fetch(url) except BaseException as exc: logger.exception('Reppy cache fetch error on %s' % url) ...
Return (expiration, obj) corresponding to provided url, exercising the cache_policy as necessary.
def _get_command(self): """Return command with options and targets, ready for execution.""" targets = ' '.join(self.targets) cmd_str = self._linter.command_with_options + ' ' + targets cmd_shlex = shlex.split(cmd_str) return list(cmd_shlex)
Return command with options and targets, ready for execution.
def send_query(self, ID, methodname, returnable, *args, **kwargs): """将调用请求的ID,方法名,参数包装为请求数据后编码为字节串发送出去. Parameters: ID (str): - 任务ID methodname (str): - 要调用的方法名 returnable (bool): - 是否要求返回结果 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键...
将调用请求的ID,方法名,参数包装为请求数据后编码为字节串发送出去. Parameters: ID (str): - 任务ID methodname (str): - 要调用的方法名 returnable (bool): - 是否要求返回结果 args (Any): - 要调用的方法的位置参数 kwargs (Any): - 要调用的方法的关键字参数 Return: (bool): - 准确地说没有错误就会返回True
def tag_namespace(cls, tag): """return the namespace for a given tag, or '' if no namespace given""" md = re.match("^(?:\{([^\}]*)\})", tag) if md is not None: return md.group(1)
return the namespace for a given tag, or '' if no namespace given
def next(self): """Next point in iteration """ x, y = next(self.scan) xs = int(round(x)) ys = int(round(y)) return xs, ys
Next point in iteration
def _infer_mutants_handler(self, request): """Returns JSON for the `vz-line-chart`s for a feature. Args: request: A request that should contain 'feature_name', 'example_index', 'inference_address', 'model_name', 'model_type', 'model_version', and 'model_signature'. Returns: A...
Returns JSON for the `vz-line-chart`s for a feature. Args: request: A request that should contain 'feature_name', 'example_index', 'inference_address', 'model_name', 'model_type', 'model_version', and 'model_signature'. Returns: A list of JSON objects, one for each chart.
def __x_google_quota_descriptor(self, metric_costs): """Describes the metric costs for a call. Args: metric_costs: Dict of metric definitions to the integer cost value against that metric. Returns: A dict descriptor describing the Quota limits for the endpoint. """ return { ...
Describes the metric costs for a call. Args: metric_costs: Dict of metric definitions to the integer cost value against that metric. Returns: A dict descriptor describing the Quota limits for the endpoint.
def depart(self): """ Remove the current remote unit, for the active hook context, from this conversation. This should be called from a `-departed` hook. """ unit = hookenv.remote_unit() self.units.remove(unit) if self.units: unitdata.kv().set(self.ke...
Remove the current remote unit, for the active hook context, from this conversation. This should be called from a `-departed` hook.
def uniq(container): """ Check if all of a container's elements are unique. Successively tries first to rely that the elements are hashable, then falls back on them being sortable, and finally falls back on brute force. """ try: return len(set(unbool(i) for i in container)) == len...
Check if all of a container's elements are unique. Successively tries first to rely that the elements are hashable, then falls back on them being sortable, and finally falls back on brute force.
def pkg_not_found(self, bol, pkg, message, eol): """Print message when package not found """ print("{0}No such package {1}: {2}{3}".format(bol, pkg, message, eol))
Print message when package not found
def _colorize(self, msg, color=None, encode=False): """ Colorize a string. """ # Valid colors colors = { 'red': '31', 'green': '32', 'yellow': '33' } # No color specified or unsupported color if not...
Colorize a string.
def run(): """This client pushes a file into Workbench.""" # Grab server args args = client_helper.grab_server_args() # Start up workbench connection workbench = zerorpc.Client(timeout=300, heartbeat=60) workbench.connect('tcp://'+args['server']+':'+args['port']) # Upload the file int...
This client pushes a file into Workbench.
def get_slice(self, start_index=None, stop_index=None, as_list=False): """ For sorted Series will return either a Series or list of all of the rows where the index is greater than or equal to the start_index if provided and less than or equal to the stop_index if provided. If either the ...
For sorted Series will return either a Series or list of all of the rows where the index is greater than or equal to the start_index if provided and less than or equal to the stop_index if provided. If either the start or stop index is None then will include from the first or last element, similar to st...
def ValidateChildren(self, problems): """Validate StopTimes and headways of this trip.""" assert self._schedule, "Trip must be in a schedule to ValidateChildren" # TODO: validate distance values in stop times (if applicable) self.ValidateNoDuplicateStopSequences(problems) stoptimes = self.GetStopTi...
Validate StopTimes and headways of this trip.
def value_for_element(cls, elem): """Deserialize the given XML `Element` into its representative value. Depending on the content of the element, the returned value may be: * a string, integer, or boolean value * a `datetime.datetime` instance * a list of `Resource` insta...
Deserialize the given XML `Element` into its representative value. Depending on the content of the element, the returned value may be: * a string, integer, or boolean value * a `datetime.datetime` instance * a list of `Resource` instances * a single `Resource` instance ...
def get_vm_ids_by_ud(access_token, subscription_id, resource_group, vmssname, updatedomain): '''look at VMSS VM instance view to get VM IDs by UD''' instance_viewlist = azurerm.list_vmss_vm_instance_view(access_token, subscription_id, resource_group, vm...
look at VMSS VM instance view to get VM IDs by UD
def centroid_distance(item_a, time_a, item_b, time_b, max_value): """ Euclidean distance between the centroids of item_a and item_b. Args: item_a: STObject from the first set in ObjectMatcher time_a: Time integer being evaluated item_b: STObject from the second set in ObjectMatcher ...
Euclidean distance between the centroids of item_a and item_b. Args: item_a: STObject from the first set in ObjectMatcher time_a: Time integer being evaluated item_b: STObject from the second set in ObjectMatcher time_b: Time integer being evaluated max_value: Maximum distan...
def WriteVcard(filename, vcard, fopen=codecs.open): """Writes a vCard into the given filename.""" if os.access(filename, os.F_OK): logger.warning('File exists at "{}", skipping.'.format(filename)) return False try: with fopen(filename, 'w', encoding='utf-8') as f: logger....
Writes a vCard into the given filename.
def newton_refine1(s, new_s, curve1, t, new_t, curve2): """Image for :func:`.newton_refine` docstring.""" if NO_IMAGES: return points = np.hstack([curve1.evaluate(s), curve2.evaluate(t)]) points_new = np.hstack([curve1.evaluate(new_s), curve2.evaluate(new_t)]) ax = curve1.plot(256) curv...
Image for :func:`.newton_refine` docstring.
def _get_requested_spec(self, obj, spec_name): """Helper to translate user specifications to needed objects.""" requested = self._specs_in[spec_name] if isinstance(requested, str): return _get_attr_by_tag(obj, requested, spec_name) else: return requested
Helper to translate user specifications to needed objects.
def WriteMoDiff(diffObj): """ Writes the difference managedObject(output of CompareManagedObject) on the terminal. """ tabsize = 8 print str(diffObj.Dn).ljust(tabsize * 10), str(diffObj.InputObject.propMoMeta.name).ljust(tabsize * 4), str( diffObj.SideIndicator).ljust(tabsize * 3), str(diffObj.DiffProperty)
Writes the difference managedObject(output of CompareManagedObject) on the terminal.
def mean(self, expression, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None, edges=False): """Calculate the mean for expression, possibly on a grid defined by binby. Example: >>> df.mean("x") -0.067131491264005971 >>> df.mean("(x**2+y**2)*...
Calculate the mean for expression, possibly on a grid defined by binby. Example: >>> df.mean("x") -0.067131491264005971 >>> df.mean("(x**2+y**2)**0.5", binby="E", shape=4) array([ 2.43483742, 4.41840721, 8.26742458, 15.53846476]) :param expression: {expression} ...
def filtmask(sp, fmin=0.02, fmax=0.15, debugplot=0): """Filter spectrum in Fourier space and apply cosine bell. Parameters ---------- sp : numpy array Spectrum to be filtered and masked. fmin : float Minimum frequency to be employed. fmax : float Maximum frequency to be ...
Filter spectrum in Fourier space and apply cosine bell. Parameters ---------- sp : numpy array Spectrum to be filtered and masked. fmin : float Minimum frequency to be employed. fmax : float Maximum frequency to be employed. debugplot : int Debugging level for me...
def create(self, **kwargs): """ Create an instance of the Blob Store Service with the typical starting settings. """ self.service.create(**kwargs) predix.config.set_env_value(self.use_class, 'url', self.service.settings.data['url']) predix.config....
Create an instance of the Blob Store Service with the typical starting settings.
def hl_table2canvas(self, w, res_dict): """Highlight mask on canvas when user click on table.""" objlist = [] # Remove existing highlight if self.maskhltag: try: self.canvas.delete_object_by_tag(self.maskhltag, redraw=False) except Exception: ...
Highlight mask on canvas when user click on table.
def curry_pair_dictionary(key_pair_dict, default_value=0.0): """ Transform dictionary from pairs of keys to dict -> dict -> float """ result = defaultdict(dict) for (a, b), value in key_pair_dict.items(): result[a][b] = value return result
Transform dictionary from pairs of keys to dict -> dict -> float
def _updateBoostFactorsLocal(self): """ Update boost factors when local inhibition is used """ # Determine the target activation level for each column # The targetDensity is the average activeDutyCycles of the neighboring # columns of each column. targetDensity = numpy.zeros(self._numColumns...
Update boost factors when local inhibition is used