code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def find_overlaps(self, index=False): """ Find overlaps in a striplog. Args: index (bool): If True, returns indices of intervals with gaps after them. Returns: Striplog: A striplog of all the overlaps as intervals. """ return self.__f...
Find overlaps in a striplog. Args: index (bool): If True, returns indices of intervals with gaps after them. Returns: Striplog: A striplog of all the overlaps as intervals.
def rgb_color(self): """Return the color property as list of [R, G, B], each 0-255.""" self.update() return [self._red, self._green, self._blue]
Return the color property as list of [R, G, B], each 0-255.
def _append_count_to_matrix(qtl_matrixfile, lod_threshold): """ Append an extra column at the end of the matrix file containing for each row (marker) the number of QTL found if the marker is known ie: Locus != '' :arg qtl_matrix, the matrix in which to save the output. :arg threshold, threshold use...
Append an extra column at the end of the matrix file containing for each row (marker) the number of QTL found if the marker is known ie: Locus != '' :arg qtl_matrix, the matrix in which to save the output. :arg threshold, threshold used to determine if a given LOD value is reflective the presen...
def get_hours_description(self): """Generates a description for only the HOUR portion of the expression Returns: The HOUR description """ expression = self._expression_parts[2] return self.get_segment_description( expression, _("every hour"),...
Generates a description for only the HOUR portion of the expression Returns: The HOUR description
def compute_layer(cls, data, params, layout): """ Compute position for the layer in all panels Positions can override this function instead of `compute_panel` if the position computations are independent of the panel. i.e when not colliding """ def fn(pdata): ...
Compute position for the layer in all panels Positions can override this function instead of `compute_panel` if the position computations are independent of the panel. i.e when not colliding
def fast_hamiltonian_terms(Ep, epsilonp, detuning_knob, omega_level, rm, xi, theta, unfolding, matrix_form=False, file_name=None, return_code=False): r"""Return a fast function that returns the Hamiltonian terms. We test a basic t...
r"""Return a fast function that returns the Hamiltonian terms. We test a basic two-level system. >>> import numpy as np >>> from scipy.constants import physical_constants >>> from sympy import Matrix, symbols >>> from fast.electric_field import electric_field_amplitude_top >>> from fast.symbol...
def _fast_write(self, outfile, value): """Function for fast writing to motor files.""" outfile.truncate(0) outfile.write(str(int(value))) outfile.flush()
Function for fast writing to motor files.
def pfm_to_pwm(self, pfm, pseudo=0.001): """Convert PFM with counts to a PFM with fractions. Parameters ---------- pfm : list 2-dimensional list with counts. pseudo : float Pseudocount used in conversion. Returns ------- p...
Convert PFM with counts to a PFM with fractions. Parameters ---------- pfm : list 2-dimensional list with counts. pseudo : float Pseudocount used in conversion. Returns ------- pwm : list 2-dimensional list with fracti...
def enumerate_builtins(tokens): """ Returns a list of all the builtins being used in *tokens*. """ out = [] for index, tok in enumerate(tokens): token_type = tok[0] token_string = tok[1] if token_string in builtins: # Note: I need to test if print can be replaced ...
Returns a list of all the builtins being used in *tokens*.
def zendesk_ticket(self): """ | Description: The ID of the Zendesk Support ticket created from this chat. Available only if using version 2 of the Zendesk Chat-Support integration """ if self.api and self.zendesk_ticket_id: return self.api._get_zendesk_ticket(self.zendesk_ti...
| Description: The ID of the Zendesk Support ticket created from this chat. Available only if using version 2 of the Zendesk Chat-Support integration
def setup_request_sessions(self): """ Sets up a requests.Session object for sharing headers across API requests. """ self.req_session = requests.Session() self.req_session.headers.update(self.headers)
Sets up a requests.Session object for sharing headers across API requests.
def create_process_work_item_type(self, work_item_type, process_id): """CreateProcessWorkItemType. [Preview API] Creates a work item type in the process. :param :class:`<CreateProcessWorkItemTypeRequest> <azure.devops.v5_0.work_item_tracking_process.models.CreateProcessWorkItemTypeRequest>` work...
CreateProcessWorkItemType. [Preview API] Creates a work item type in the process. :param :class:`<CreateProcessWorkItemTypeRequest> <azure.devops.v5_0.work_item_tracking_process.models.CreateProcessWorkItemTypeRequest>` work_item_type: :param str process_id: The ID of the process on which to cre...
def RemoveClientLabels(self, client_id, owner, labels, cursor=None): """Removes a list of user labels from a given client.""" query = ("DELETE FROM client_labels " "WHERE client_id = %s AND owner_username_hash = %s " "AND label IN ({})").format(", ".join(["%s"] * len(labels))) arg...
Removes a list of user labels from a given client.
def raw_chroma_accuracy(ref_voicing, ref_cent, est_voicing, est_cent, cent_tolerance=50): """Compute the raw chroma accuracy given two pitch (frequency) sequences in cents and matching voicing indicator sequences. The first pitch and voicing arrays are treated as the reference (truth...
Compute the raw chroma accuracy given two pitch (frequency) sequences in cents and matching voicing indicator sequences. The first pitch and voicing arrays are treated as the reference (truth), and the second two as the estimate (prediction). All 4 sequences must be of the same length. Examples -...
def loop(self): ''' Tracks the time in a loop. The estimated time to completion can be calculated and if verbose is set to *True*, the object will print estimated time to completion, and percent complete. Actived in every loop to keep track''' self.count += 1 sel...
Tracks the time in a loop. The estimated time to completion can be calculated and if verbose is set to *True*, the object will print estimated time to completion, and percent complete. Actived in every loop to keep track
def init_config(self, **kw): """ Get a configuration object for this type of YubiKey. """ return YubiKeyConfigUSBHID(ykver=self.version_num(), \ capabilities = self.capabilities, \ **kw)
Get a configuration object for this type of YubiKey.
def write_if_allowed(filename: str, content: str, overwrite: bool = False, mock: bool = False) -> None: """ Writes the contents to a file, if permitted. Args: filename: filename to write content: contents to write overwr...
Writes the contents to a file, if permitted. Args: filename: filename to write content: contents to write overwrite: permit overwrites? mock: pretend to write, but don't Raises: RuntimeError: if file exists but overwriting not permitted
def local_moe_tpu(inputs, hidden_size, output_size, num_experts, loss_coef=1e-3, overhead=1.0): """Local mixture of experts that works well on TPU. See https://arxiv.org/abs/1701.06538 There are num_experts expert networks...
Local mixture of experts that works well on TPU. See https://arxiv.org/abs/1701.06538 There are num_experts expert networks, each containing a relu-activated hidden layer of size hidden_size, followed by an output projection. The number of parameters is thus: num_experts * (input_size * hidden_size + hid...
def calculate(self, T, P, zs, ws, method): r'''Method to calculate heat capacity of a liquid mixture at temperature `T`, pressure `P`, mole fractions `zs` and weight fractions `ws` with a given method. This method has no exception handling; see `mixture_property` for that. ...
r'''Method to calculate heat capacity of a liquid mixture at temperature `T`, pressure `P`, mole fractions `zs` and weight fractions `ws` with a given method. This method has no exception handling; see `mixture_property` for that. Parameters ---------- T : floa...
def wc(filename, contents, parsed=None, is_jekyll=False): """Count the words, characters, and paragraphs in a string. Args: contents: the original string to count filename (optional): the filename as provided to the CLI parsed (optional): a parsed string, expected to be plaintext only ...
Count the words, characters, and paragraphs in a string. Args: contents: the original string to count filename (optional): the filename as provided to the CLI parsed (optional): a parsed string, expected to be plaintext only is_jekyll: whether the original contents were from a Jekyl...
def remove_output_data_port(self, data_port_id, force=False, destroy=True): """Remove an output data port from the state :param int data_port_id: the id of the output data port to remove :raises exceptions.AttributeError: if the specified input data port does not exist """ if da...
Remove an output data port from the state :param int data_port_id: the id of the output data port to remove :raises exceptions.AttributeError: if the specified input data port does not exist
def do_json_set(self, params): """ \x1b[1mNAME\x1b[0m json_set - Sets the value for the given (possibly nested) key on a JSON object serialized in the given path \x1b[1mSYNOPSIS\x1b[0m json_set <path> <keys> <value> <value_type> [confirm] \x1b[1mDESCRIPTION\x1b[0m If the key exists and...
\x1b[1mNAME\x1b[0m json_set - Sets the value for the given (possibly nested) key on a JSON object serialized in the given path \x1b[1mSYNOPSIS\x1b[0m json_set <path> <keys> <value> <value_type> [confirm] \x1b[1mDESCRIPTION\x1b[0m If the key exists and the value is different, the znode will be ...
def get(location, **kwargs): """Get Geocode :param ``location``: Your search location you want geocoded. :param ``provider``: The geocoding engine you want to use. :param ``method``: Define the method (geocode, method). """ provider = kwargs.get('provider', 'bing').lower().strip() method =...
Get Geocode :param ``location``: Your search location you want geocoded. :param ``provider``: The geocoding engine you want to use. :param ``method``: Define the method (geocode, method).
def control_loop(): '''Main loop, retrieving the schedule. ''' set_service_status(Service.SCHEDULE, ServiceStatus.BUSY) notify.notify('READY=1') while not terminate(): notify.notify('WATCHDOG=1') # Try getting an updated schedule get_schedule() session = get_session()...
Main loop, retrieving the schedule.
def _whitespace_tokenize(self, text): """Runs basic whitespace cleaning and splitting on a piece of text.""" text = text.strip() tokens = text.split() return tokens
Runs basic whitespace cleaning and splitting on a piece of text.
def PopEvents(self): """Pops events from the heap. Yields: EventObject: event. """ event = self.PopEvent() while event: yield event event = self.PopEvent()
Pops events from the heap. Yields: EventObject: event.
def describe_load_balancers(names=None, load_balancer_arns=None, region=None, key=None, keyid=None, profile=None): ''' Describes the specified load balancer or all of your ...
Describes the specified load balancer or all of your load balancers. Returns: list CLI example: .. code-block:: bash salt myminion boto_elbv2.describe_load_balancers salt myminion boto_elbv2.describe_load_balancers alb_name salt myminion boto_elbv2.describe_load_balancers "[alb_n...
def set_scrollbars_cb(self, w, tf): """This callback is invoked when the user checks the 'Use Scrollbars' box in the preferences pane.""" scrollbars = 'on' if tf else 'off' self.t_.set(scrollbars=scrollbars)
This callback is invoked when the user checks the 'Use Scrollbars' box in the preferences pane.
def shell(self, *args, **kwargs): """ Run command `adb shell` """ args = ['shell'] + list(args) return self.run_cmd(*args, **kwargs)
Run command `adb shell`
def build_self_reference(filename, clean_wcs=False): """ This function creates a reference, undistorted WCS that can be used to apply a correction to the WCS of the input file. Parameters ---------- filename : str Filename of image which will be corrected, and which will form the basis ...
This function creates a reference, undistorted WCS that can be used to apply a correction to the WCS of the input file. Parameters ---------- filename : str Filename of image which will be corrected, and which will form the basis of the undistorted WCS. clean_wcs : bool Spe...
def fft(fEM, time, freq, ftarg): r"""Fourier Transform using the Fast Fourier Transform. The function is called from one of the modelling routines in :mod:`model`. Consult these modelling routines for a description of the input and output parameters. Returns ------- tEM : array Ret...
r"""Fourier Transform using the Fast Fourier Transform. The function is called from one of the modelling routines in :mod:`model`. Consult these modelling routines for a description of the input and output parameters. Returns ------- tEM : array Returns time-domain EM response of ``fEM...
def system(self): """returns an object to work with the site system""" if self._resources is None: self.__init() if "system" in self._resources: url = self._url + "/system" return _system.System(url=url, securityHandler=self._...
returns an object to work with the site system
def getParent(self, returned_properties=None): """Get the parent workitem of this workitem If no parent, None will be returned. :param returned_properties: the returned properties that you want. Refer to :class:`rtcclient.client.RTCClient` for more explanations :return: a :...
Get the parent workitem of this workitem If no parent, None will be returned. :param returned_properties: the returned properties that you want. Refer to :class:`rtcclient.client.RTCClient` for more explanations :return: a :class:`rtcclient.workitem.Workitem` object :rtype:...
def get_objects(self): """Return iterable of "object descriptions", which are tuple with these items: * `name` * `dispname` * `type` * `docname` * `anchor` * `priority` For details on each item, see :py:meth:`~sphinx.domains.Domain.get_objects`. ...
Return iterable of "object descriptions", which are tuple with these items: * `name` * `dispname` * `type` * `docname` * `anchor` * `priority` For details on each item, see :py:meth:`~sphinx.domains.Domain.get_objects`.
def ext_pillar(minion_id, # pylint: disable=W0613 pillar, # pylint: disable=W0613 conf, nesting_key=None): ''' Get pillar data from Vault for the configuration ``conf``. ''' comps = conf.split() paths = [comp for comp in comps if comp.startswith('path=...
Get pillar data from Vault for the configuration ``conf``.
def accessible(self,fromstate, tostate): """Is state tonode directly accessible (in one step) from state fromnode? (i.e. is there an edge between the nodes). If so, return the probability, else zero""" if (not (fromstate in self.nodes)) or (not (tostate in self.nodes)) or not (fromstate in self.edges_ou...
Is state tonode directly accessible (in one step) from state fromnode? (i.e. is there an edge between the nodes). If so, return the probability, else zero
def revoke_access_token(self): """ Revoke the access token currently in use. """ if not self._access_token: return self.execute_post('authentication/revoke', json=dict( token_type_hint='access_token', token=self._access_token )) ...
Revoke the access token currently in use.
def set_layer(self, layer=None): """Set layer and update UI accordingly. :param layer: A QgsVectorLayer. :type layer: QgsVectorLayer """ if layer: self.layer = layer else: self.layer = self.input_layer_combo_box.currentLayer() if not self....
Set layer and update UI accordingly. :param layer: A QgsVectorLayer. :type layer: QgsVectorLayer
def _varLib_finder(source, directory="", ext="ttf"): """Finder function to be used with varLib.build to find master TTFs given the filename of the source UFO master as specified in the designspace. It replaces the UFO directory with the one specified in 'directory' argument, and replaces the file extens...
Finder function to be used with varLib.build to find master TTFs given the filename of the source UFO master as specified in the designspace. It replaces the UFO directory with the one specified in 'directory' argument, and replaces the file extension with 'ext'.
def Stat(self, urns): """Returns metadata about all urns. Currently the metadata include type, and last update time. Args: urns: The urns of the objects to open. Yields: A dict of metadata. Raises: ValueError: A string was passed instead of an iterable. """ if isinstanc...
Returns metadata about all urns. Currently the metadata include type, and last update time. Args: urns: The urns of the objects to open. Yields: A dict of metadata. Raises: ValueError: A string was passed instead of an iterable.
def _get_team_stats_table(self, selector): """Helper function for stats tables on season pages. Returns a DataFrame.""" doc = self.get_main_doc() table = doc(selector) df = sportsref.utils.parse_table(table) df.set_index('team_id', inplace=True) return df
Helper function for stats tables on season pages. Returns a DataFrame.
def write(self, data, assert_ss=True, deassert_ss=True): """Half-duplex SPI write. If assert_ss is True, the SS line will be asserted low, the specified bytes will be clocked out the MOSI line, and if deassert_ss is True the SS line be put back high. """ # Fail MOSI is not speci...
Half-duplex SPI write. If assert_ss is True, the SS line will be asserted low, the specified bytes will be clocked out the MOSI line, and if deassert_ss is True the SS line be put back high.
def authentication_url(self): """Redirect your users to here to authenticate them.""" params = { 'client_id': self.client_id, 'response_type': self.type, 'redirect_uri': self.callback_url } return AUTHENTICATION_URL + "?" + urlencode(params)
Redirect your users to here to authenticate them.
def get_text_rule_groups(declarations): """ Given a list of declarations, return a list of output.Rule objects. """ property_map = {'text-anchor-dx': 'anchor_dx', # does nothing 'text-anchor-dy': 'anchor_dy', # does nothing 'text-align': 'horizontal_alignment', ...
Given a list of declarations, return a list of output.Rule objects.
def rotate_z(self, angle): """ Rotates mesh about the z-axis. Parameters ---------- angle : float Angle in degrees to rotate about the z-axis. """ axis_rotation(self.points, angle, inplace=True, axis='z')
Rotates mesh about the z-axis. Parameters ---------- angle : float Angle in degrees to rotate about the z-axis.
def _get_organisations(self): """ :returns: list of organisations, sorted alphabetically :rtype: list(list(str)) """ organisations = [] for child in self.vcard.getChildren(): if child.name == "ORG": organisations.append(child.value) ret...
:returns: list of organisations, sorted alphabetically :rtype: list(list(str))
def getPlainText(self, identify=None): """ Convenience function for templates which want access to the raw text, without XML tags. """ frags = getattr(self, 'frags', None) if frags: plains = [] for frag in frags: if hasattr(frag, '...
Convenience function for templates which want access to the raw text, without XML tags.
def add_common_files_to_file_list(self): ''' The (several thousands) common-disease files from the repo tarball are added to the files object. try adding the 'common-disease-mondo' files as well? ''' repo_dir = '/'.join((self.rawdir, 'git')) common_di...
The (several thousands) common-disease files from the repo tarball are added to the files object. try adding the 'common-disease-mondo' files as well?
def import_locations(self, data, index='WMO'): """Parse NOAA weather station data files. ``import_locations()`` returns a dictionary with keys containing either the WMO or ICAO identifier, and values that are ``Station`` objects that describes the large variety of data exported by NOAA_...
Parse NOAA weather station data files. ``import_locations()`` returns a dictionary with keys containing either the WMO or ICAO identifier, and values that are ``Station`` objects that describes the large variety of data exported by NOAA_. It expects data files in one of the following f...
def BLX(self, params): """ BLX Rj Branch to the address in Rj, storing the next instruction in the Link Register """ Rj = self.get_one_parameter(self.ONE_PARAMETER, params) self.check_arguments(LR_or_general_purpose_registers=(Rj,)) def BLX_func(): ...
BLX Rj Branch to the address in Rj, storing the next instruction in the Link Register
def cleanup(self, sched, coro): """Remove this coro from the waiting for signal queue.""" try: sched.sigwait[self.name].remove((self, coro)) except ValueError: pass return True
Remove this coro from the waiting for signal queue.
def init(cls, repo_dir=None, temp=False, initial_commit=False): """Run `git init` in the repo_dir. Defaults to current working directory if repo_dir is not supplied. If 'temp' is True, a temporary directory will be created for you and the repository will be initialized. The tempdir is ...
Run `git init` in the repo_dir. Defaults to current working directory if repo_dir is not supplied. If 'temp' is True, a temporary directory will be created for you and the repository will be initialized. The tempdir is scheduled for deletion (when the process exits) through an exit fun...
def parse(self, fd): """very simple parser - but why would we want it to be complex?""" def resolve_args(args): # FIXME break this out, it's in common with the templating stuff elsewhere root = self.sections[0] val_dict = dict(('<' + t + '>', u) for (t, u) in root.ge...
very simple parser - but why would we want it to be complex?
def untag(self): """ Copies the object, removing any special tagging from it :return: An Asn1Value object """ new_obj = self.__class__() new_obj._copy(self, copy.deepcopy) return new_obj
Copies the object, removing any special tagging from it :return: An Asn1Value object
def main(arguments): """Parse arguments, request the urls, notify if different.""" formatter_class = argparse.ArgumentDefaultsHelpFormatter parser = argparse.ArgumentParser(description=__doc__, formatter_class=formatter_class) parser.add_argument('infile', help="Inpu...
Parse arguments, request the urls, notify if different.
def local_manager_is_default(self, adm_gid, gid): """Check whether gid is default group for local manager group. """ config = self.root['settings']['ugm_localmanager'].attrs rule = config[adm_gid] if gid not in rule['target']: raise Exception(u"group '%s' not managed ...
Check whether gid is default group for local manager group.
def _InstallInstallers(self): """Install the installer built by RepackTemplates.""" # 32 bit binary will refuse to install on a 64bit system so we only install # the 64 bit version installer_amd64 = glob.glob( os.path.join(args.output_dir, "dbg_*_amd64.exe")).pop() self._CleanupInstall() ...
Install the installer built by RepackTemplates.
def deserialize_date(string): """ Deserializes string to date. :param string: str. :type string: str :return: date. :rtype: date """ try: from dateutil.parser import parse return parse(string).date() except ImportError: return string
Deserializes string to date. :param string: str. :type string: str :return: date. :rtype: date
def clean_report(self, options, sosreport): # pragma: no cover '''this is the primary function, to put everything together and analyze an sosreport''' if options.report_dir: # override the default location for artifacts (/tmp) if os.path.isdir(options.report_dir): self.repor...
this is the primary function, to put everything together and analyze an sosreport
def ucas_download_single(url, output_dir = '.', merge = False, info_only = False, **kwargs): '''video page''' html = get_content(url) # resourceID is UUID resourceID = re.findall( r'resourceID":"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})', html)[0] assert resourceID != '', 'Canno...
video page
def add_url_rule(self, rule, endpoint=None, view_func=None, **options): """ A helper method to register a rule (and optionally a view function) to the application. The endpoint is automatically prefixed with the blueprint's name. """ if self.url_prefix: rule ...
A helper method to register a rule (and optionally a view function) to the application. The endpoint is automatically prefixed with the blueprint's name.
def bounds(filename, start_re, end_re, encoding='utf8'): """ Compute chunk bounds from text file according to start_re and end_re: yields (start_match, Bounds) tuples. """ start_re, end_re = re.compile(start_re), re.compile(end_re) mo, line_start, line_end, byte_start, byte_end = [None]*5 of...
Compute chunk bounds from text file according to start_re and end_re: yields (start_match, Bounds) tuples.
def _interpret_oserror(exc, cwd, cmd): """Interpret an OSError exc and raise the appropriate dbt exception. """ if len(cmd) == 0: raise dbt.exceptions.CommandError(cwd, cmd) # all of these functions raise unconditionally if os.name == 'nt': _handle_windows_error(exc, cwd, cmd) ...
Interpret an OSError exc and raise the appropriate dbt exception.
def get(quantity, min_type=EventType.firstevent, max_type=EventType.lastevent): """Return events at the front of the event queue, within the specified minimum and maximum type, and remove them from the queue. Args: quantity (int): The maximum number of events to return. min_type (int): The ...
Return events at the front of the event queue, within the specified minimum and maximum type, and remove them from the queue. Args: quantity (int): The maximum number of events to return. min_type (int): The minimum value for the event type of the returned events. max_type (int): The ma...
def _delete(self, **kwargs): """wrapped with delete, override that in a subclass to customize """ requests_params = self._handle_requests_params(kwargs) delete_uri = self._meta_data['uri'] session = self._meta_data['bigip']._meta_data['icr_session'] # Check the generation for m...
wrapped with delete, override that in a subclass to customize
def get_role_secret_id_accessor(self, role_name, secret_id_accessor, mount_point='approle'): """POST /auth/<mount_point>/role/<role name>/secret-id-accessor/lookup :param role_name: :type role_name: :param secret_id_accessor: :type secret_id_accessor: :param mount_point:...
POST /auth/<mount_point>/role/<role name>/secret-id-accessor/lookup :param role_name: :type role_name: :param secret_id_accessor: :type secret_id_accessor: :param mount_point: :type mount_point: :return: :rtype:
def Md5Hex(filename=None, contents=None): ''' :param unicode filename: The file from which the md5 should be calculated. If the filename is given, the contents should NOT be given. :param unicode contents: The contents for which the md5 should be calculated. If the contents are give...
:param unicode filename: The file from which the md5 should be calculated. If the filename is given, the contents should NOT be given. :param unicode contents: The contents for which the md5 should be calculated. If the contents are given, the filename should NOT be given. :rty...
def query_folder(self, dir_name): """查询目录属性(https://www.qcloud.com/document/product/436/6063) :param dir_name:查询的目录的名称 :return:查询出来的结果,为json格式 """ if dir_name[0] == '/': dir_name = dir_name[1:len(dir_name)] self.url = 'http://' + self.config.region + '.file.m...
查询目录属性(https://www.qcloud.com/document/product/436/6063) :param dir_name:查询的目录的名称 :return:查询出来的结果,为json格式
def repair(self, volume_id_or_uri, timeout=-1): """ Removes extra presentations from a specified volume on the storage system. Args: volume_id_or_uri: Can be either the volume id or the volume uri. timeout: Timeout in seconds. Wait for tas...
Removes extra presentations from a specified volume on the storage system. Args: volume_id_or_uri: Can be either the volume id or the volume uri. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in...
def get_fields_dict(self, row): """ Returns a dict of field name and cleaned value pairs to initialize the model. Beware, it aligns the lists of fields and row values with Nones to allow for adding fields not found in the CSV. Whitespace around the value of the cell is stripped. ...
Returns a dict of field name and cleaned value pairs to initialize the model. Beware, it aligns the lists of fields and row values with Nones to allow for adding fields not found in the CSV. Whitespace around the value of the cell is stripped.
def _commit(self, config_text=None, force=False, reload_original_config=True): """ This method is the same as the :py:method:`commit`: method, however, it has an extra command that will trigger the reload of the running config. The reason behind this is that in some circumstances you don´ want ...
This method is the same as the :py:method:`commit`: method, however, it has an extra command that will trigger the reload of the running config. The reason behind this is that in some circumstances you don´ want to reload the running config, for example, when doing a rollback. See :py:method:`c...
def search_files(self, search=None): """ Search for files, returning a FileRecord for each result. FileRecords have two additional methods patched into them, get_url() and download_to(file_name), which will retrieve the URL for the file content and download that content to a named file o...
Search for files, returning a FileRecord for each result. FileRecords have two additional methods patched into them, get_url() and download_to(file_name), which will retrieve the URL for the file content and download that content to a named file on disk, respectively. :param FileRecordSearch se...
def set_iter_mesh(self, mesh, shift=None, is_time_reversal=True, is_mesh_symmetry=True, is_eigenvectors=False, is_gamma_center=False): """Create an IterMesh instancer Attr...
Create an IterMesh instancer Attributes ---------- See set_mesh method.
def stacks_2_eqns(self,stacks): """returns equation strings from stacks""" if stacks: return list(map(lambda p: self.stack_2_eqn(p), stacks)) else: return []
returns equation strings from stacks
def get_all_reserved_instances_offerings(self, reserved_instances_id=None, instance_type=None, availability_zone=None, product_description=None, ...
Describes Reserved Instance offerings that are available for purchase. :type reserved_instances_id: str :param reserved_instances_id: Displays Reserved Instances with the specified offering IDs. :type instance_type: str :param instance_type: Displa...
def delete(self): """Delete the message.""" url = self._imgur._base_url + "/3/message/{0}".format(self.id) return self._imgur._send_request(url, method='DELETE')
Delete the message.
def fb_github_project_workdir(self, project_and_path, github_org='facebook'): 'This helper lets Facebook-internal CI special-cases FB projects' project, path = project_and_path.split('/', 1) return self.github_project_workdir(github_org + '/' + project, path)
This helper lets Facebook-internal CI special-cases FB projects
def timestamp(self, message="", checkpoint=None, finished=False, raise_error=True): """ Print message, time, and time elapsed, perhaps creating checkpoint. This prints your given message, along with the current time, and time elapsed since the previous timestamp() call...
Print message, time, and time elapsed, perhaps creating checkpoint. This prints your given message, along with the current time, and time elapsed since the previous timestamp() call. If you specify a HEADING by beginning the message with "###", it surrounds the message with newlines fo...
def _register_handler(event, fun, external=False): """Register a function to be an event handler""" registry = core.HANDLER_REGISTRY if external: registry = core.EXTERNAL_HANDLER_REGISTRY if not isinstance(event, basestring): # If not basestring, it is a BaseEvent subclass. # Th...
Register a function to be an event handler
def get_range(self): """Return the bounds currently visible.""" p, z = np.asarray(self.pan), np.asarray(self.zoom) x0, y0 = -1. / z - p x1, y1 = +1. / z - p return (x0, y0, x1, y1)
Return the bounds currently visible.
def cache_distribution(cls, zf, source, target_dir): """Possibly cache an egg from within a zipfile into target_cache. Given a zipfile handle and a filename corresponding to an egg distribution within that zip, maybe write to the target cache and return a Distribution.""" dependency_basename = os...
Possibly cache an egg from within a zipfile into target_cache. Given a zipfile handle and a filename corresponding to an egg distribution within that zip, maybe write to the target cache and return a Distribution.
def set_chat_description(self, chat_id, description): """ Use this method to change the description of a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. :param chat_id: Int...
Use this method to change the description of a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success. :param chat_id: Int or Str: Unique identifier for the target chat or username of the target c...
def update_external_link(self, id, **kwargs): # noqa: E501 """Update a specific external link # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_external_...
Update a specific external link # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.update_external_link(id, async_req=True) >>> result = thread.get() :pa...
def announcements_view(request): ''' The view of manager announcements. ''' page_name = "Manager Announcements" userProfile = UserProfile.objects.get(user=request.user) announcement_form = None manager_positions = Manager.objects.filter(incumbent=userProfile) if manager_positions: announ...
The view of manager announcements.
def transformation_get(node_id): """Get all the transformations of a node. The node id must be specified in the url. You can also pass transformation_type. """ exp = experiment(session) # get the parameters transformation_type = request_parameter(parameter="transformation_type", ...
Get all the transformations of a node. The node id must be specified in the url. You can also pass transformation_type.
def call_hook(self, hook, *args, **kwargs): """ Calls each registered hook """ for function in self.hooks[hook]: function.__call__(*args, **kwargs)
Calls each registered hook
def sweep(self, min_freq, max_freq, bins, repeats, runs=0, time_limit=0, overlap=0, fft_window='hann', fft_overlap=0.5, crop=False, log_scale=True, remove_dc=False, detrend=None, lnb_lo=0, tune_delay=0, reset_stream=False, base_buffer_size=0, max_buffer_size=0, max_threads=0, max_queue_size=...
Sweep spectrum using frequency hopping
def dump_grammar(self, out=sys.stdout): """ Print grammar rules """ for rule in sorted(self.rule2name.items()): out.write("%s\n" % rule2str(rule[0])) return
Print grammar rules
def get_requirement_from_url(url): """Get a requirement from the URL, if possible. This looks for #egg in the URL""" link = Link(url) egg_info = link.egg_fragment if not egg_info: egg_info = splitext(link.filename)[0] return package_to_requirement(egg_info)
Get a requirement from the URL, if possible. This looks for #egg in the URL
def symbol(self): ''' Gets the symbol `p`, `l`, `n`, etc. ''' if self.color == BLACK: return PIECE_SYMBOLS[self.piece_type].upper() else: return PIECE_SYMBOLS[self.piece_type]
Gets the symbol `p`, `l`, `n`, etc.
def from_tibiadata(cls, content): """Parses a TibiaData.com response into a :class:`World` Parameters ---------- content: :class:`str` The raw JSON content from TibiaData Returns ------- :class:`World` The World described in the page, or ...
Parses a TibiaData.com response into a :class:`World` Parameters ---------- content: :class:`str` The raw JSON content from TibiaData Returns ------- :class:`World` The World described in the page, or ``None``. Raises ------ ...
def get_dataset(catalog, identifier=None, title=None): """Devuelve un Dataset del catálogo.""" msg = "Se requiere un 'identifier' o 'title' para buscar el dataset." assert identifier or title, msg catalog = read_catalog_obj(catalog) # búsqueda optimizada por identificador if identifier: ...
Devuelve un Dataset del catálogo.
def GetRootFileEntry(self): """Retrieves the root file entry. Returns: EncodedStreamFileEntry: a file entry or None if not available. """ path_spec = encoded_stream_path_spec.EncodedStreamPathSpec( encoding_method=self._encoding_method, parent=self._path_spec.parent) return se...
Retrieves the root file entry. Returns: EncodedStreamFileEntry: a file entry or None if not available.
def get(self, **url_params): """ Makes the HTTP GET to the url. """ if url_params: self.http_method_args["params"].update(url_params) return self.http_method("GET")
Makes the HTTP GET to the url.
def get_ontology(self, id=None, uri=None, match=None): """ get the saved-ontology with given ID or via other methods... """ if not id and not uri and not match: return None if type(id) == type("string"): uri = id id = None if not ...
get the saved-ontology with given ID or via other methods...
def add_loss(self, loss, name=None): """Adds a loss and returns a wrapper for that loss.""" self.bookkeeper.add_loss(loss, name=name) return Loss(self.bookkeeper, tensor=loss, name=name)
Adds a loss and returns a wrapper for that loss.
def _increment(self, n=1): """Move forward n tokens in the stream.""" if self._cur_position >= self.num_tokens-1: self._cur_positon = self.num_tokens - 1 self._finished = True else: self._cur_position += n
Move forward n tokens in the stream.
def _get_url(url): """Retrieve requested URL""" try: data = HTTP_SESSION.get(url, stream=True) data.raise_for_status() except requests.exceptions.RequestException as exc: raise FetcherException(exc) return data
Retrieve requested URL
def getPreferenceCounts(self): """ Returns a list of the number of times each preference is given. """ preferenceCounts = [] for preference in self.preferences: preferenceCounts.append(preference.count) return preferenceCounts
Returns a list of the number of times each preference is given.
def default_fields(cls, include_virtual=True, **kwargs): """The default fields and their dtypes. By default, this returns whatever the class's ``_staticfields`` and ``_virtualfields`` is set to as a dictionary of fieldname, dtype (the dtype of virtualfields is given by VIRTUALFIELD_DTYPE...
The default fields and their dtypes. By default, this returns whatever the class's ``_staticfields`` and ``_virtualfields`` is set to as a dictionary of fieldname, dtype (the dtype of virtualfields is given by VIRTUALFIELD_DTYPE). This function should be overridden by subclasses to add d...