code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def label_to_node(self, selection='leaves'): '''Return a dictionary mapping labels (strings) to ``Node`` objects * If ``selection`` is ``"all"``, the dictionary will contain all nodes * If ``selection`` is ``"leaves"``, the dictionary will only contain leaves * If ``selection`` is ``"...
Return a dictionary mapping labels (strings) to ``Node`` objects * If ``selection`` is ``"all"``, the dictionary will contain all nodes * If ``selection`` is ``"leaves"``, the dictionary will only contain leaves * If ``selection`` is ``"internal"``, the dictionary will only contain internal n...
Below is the the instruction that describes the task: ### Input: Return a dictionary mapping labels (strings) to ``Node`` objects * If ``selection`` is ``"all"``, the dictionary will contain all nodes * If ``selection`` is ``"leaves"``, the dictionary will only contain leaves * If ``selec...
def remove_from_ptr_size(self, ptr_size): # type: (int) -> bool ''' Remove the space for a path table record from the volume descriptor. Parameters: ptr_size - The length of the Path Table Record being removed from this Volume Descriptor. Returns: True if exten...
Remove the space for a path table record from the volume descriptor. Parameters: ptr_size - The length of the Path Table Record being removed from this Volume Descriptor. Returns: True if extents need to be removed from the Volume Descriptor, False otherwise.
Below is the the instruction that describes the task: ### Input: Remove the space for a path table record from the volume descriptor. Parameters: ptr_size - The length of the Path Table Record being removed from this Volume Descriptor. Returns: True if extents need to be removed f...
def validateBusName(n): """ Verifies that the supplied name is a valid DBus Bus name. Throws an L{error.MarshallingError} if the format is invalid @type n: C{string} @param n: A DBus bus name """ try: if '.' not in n: raise Exception('At least two components required') ...
Verifies that the supplied name is a valid DBus Bus name. Throws an L{error.MarshallingError} if the format is invalid @type n: C{string} @param n: A DBus bus name
Below is the the instruction that describes the task: ### Input: Verifies that the supplied name is a valid DBus Bus name. Throws an L{error.MarshallingError} if the format is invalid @type n: C{string} @param n: A DBus bus name ### Response: def validateBusName(n): """ Verifies that the suppl...
def get_release_data(self, package_name: str, version: str) -> Tuple[str, str, str]: """ Returns ``(package_name, version, manifest_uri)`` associated with the given package name and version, *if* they are published to the currently set registry. * Parameters: * ``name``: Mus...
Returns ``(package_name, version, manifest_uri)`` associated with the given package name and version, *if* they are published to the currently set registry. * Parameters: * ``name``: Must be a valid package name. * ``version``: Must be a valid package version.
Below is the the instruction that describes the task: ### Input: Returns ``(package_name, version, manifest_uri)`` associated with the given package name and version, *if* they are published to the currently set registry. * Parameters: * ``name``: Must be a valid package name. ...
def home_dir(): ''' Returns: str : Path to home directory (or ``Documents`` directory on Windows). ''' if os.name == 'nt': from win32com.shell import shell, shellcon return shell.SHGetFolderPath(0, shellcon.CSIDL_PERSONAL, 0, 0) else: return os.path.expanduser('~')
Returns: str : Path to home directory (or ``Documents`` directory on Windows).
Below is the the instruction that describes the task: ### Input: Returns: str : Path to home directory (or ``Documents`` directory on Windows). ### Response: def home_dir(): ''' Returns: str : Path to home directory (or ``Documents`` directory on Windows). ''' if os.name == 'nt': ...
def count_tokens(tokens, to_lower=False, counter=None): r"""Counts tokens in the specified string. For token_delim='(td)' and seq_delim='(sd)', a specified string of two sequences of tokens may look like:: (td)token1(td)token2(td)token3(td)(sd)(td)token4(td)token5(td)(sd) Parameters ----...
r"""Counts tokens in the specified string. For token_delim='(td)' and seq_delim='(sd)', a specified string of two sequences of tokens may look like:: (td)token1(td)token2(td)token3(td)(sd)(td)token4(td)token5(td)(sd) Parameters ---------- tokens : list of str A source list of tok...
Below is the the instruction that describes the task: ### Input: r"""Counts tokens in the specified string. For token_delim='(td)' and seq_delim='(sd)', a specified string of two sequences of tokens may look like:: (td)token1(td)token2(td)token3(td)(sd)(td)token4(td)token5(td)(sd) Parameters...
def get_assessments_offered_by_query(self, assessment_offered_query): """Gets a list of ``AssessmentOffered`` elements matching the given assessment offered query. arg: assessment_offered_query (osid.assessment.AssessmentOfferedQuery): the assessment offered query ...
Gets a list of ``AssessmentOffered`` elements matching the given assessment offered query. arg: assessment_offered_query (osid.assessment.AssessmentOfferedQuery): the assessment offered query return: (osid.assessment.AssessmentOfferedList) - the returned ...
Below is the the instruction that describes the task: ### Input: Gets a list of ``AssessmentOffered`` elements matching the given assessment offered query. arg: assessment_offered_query (osid.assessment.AssessmentOfferedQuery): the assessment offered query return:...
def handle_endtag(self, tag): """ Called by HTMLParser.feed when an end tag is found. """ if tag in PARENT_ELEMENTS: self.current_parent_element['tag'] = '' self.current_parent_element['attrs'] = '' if tag == 'li': self.parsing_li = True ...
Called by HTMLParser.feed when an end tag is found.
Below is the the instruction that describes the task: ### Input: Called by HTMLParser.feed when an end tag is found. ### Response: def handle_endtag(self, tag): """ Called by HTMLParser.feed when an end tag is found. """ if tag in PARENT_ELEMENTS: self.current_parent_ele...
def catvl(z, ver, vnew, lamb, lambnew, br): """ trapz integrates over altitude axis, axis = -2 concatenate over reaction dimension, axis = -1 br: column integrated brightness lamb: wavelength [nm] ver: volume emission rate [photons / cm^-3 s^-3 ...] """ if ver is not None: br =...
trapz integrates over altitude axis, axis = -2 concatenate over reaction dimension, axis = -1 br: column integrated brightness lamb: wavelength [nm] ver: volume emission rate [photons / cm^-3 s^-3 ...]
Below is the the instruction that describes the task: ### Input: trapz integrates over altitude axis, axis = -2 concatenate over reaction dimension, axis = -1 br: column integrated brightness lamb: wavelength [nm] ver: volume emission rate [photons / cm^-3 s^-3 ...] ### Response: def catvl(z, ver...
def stop_process(self, pids, status='success'): ''' stop_process(self, pids, status='success') Stops a running process :Parameters: * *pid* (`string`) -- Identifier of an existing process * *result* (`string`) -- the value the process will be terminated with. Any of the...
stop_process(self, pids, status='success') Stops a running process :Parameters: * *pid* (`string`) -- Identifier of an existing process * *result* (`string`) -- the value the process will be terminated with. Any of the following possible values: success , failure , error , warning , t...
Below is the the instruction that describes the task: ### Input: stop_process(self, pids, status='success') Stops a running process :Parameters: * *pid* (`string`) -- Identifier of an existing process * *result* (`string`) -- the value the process will be terminated with. Any of th...
def detach(gandi, resource, background, force): """ Detach disks from currectly attached vm. Resource can be a disk name, or ID """ resource = sorted(tuple(set(resource))) if not force: proceed = click.confirm('Are you sure you want to detach %s?' % ', '.join...
Detach disks from currectly attached vm. Resource can be a disk name, or ID
Below is the the instruction that describes the task: ### Input: Detach disks from currectly attached vm. Resource can be a disk name, or ID ### Response: def detach(gandi, resource, background, force): """ Detach disks from currectly attached vm. Resource can be a disk name, or ID """ resour...
def repeat_func_eof(func: Callable[[], Union[T, Awaitable[T]]], eof: Any, *, interval: float=0, use_is: bool=False) -> AsyncIterator[T]: """ Repeats the result of a 0-ary function until an `eof` item is reached. The `eof` item itself is not part of the resulting stream; by setting `use_is` to true, eof ...
Repeats the result of a 0-ary function until an `eof` item is reached. The `eof` item itself is not part of the resulting stream; by setting `use_is` to true, eof is checked by identity rather than equality. `times` and `interval` behave exactly like with `aiostream.create.repeat`.
Below is the the instruction that describes the task: ### Input: Repeats the result of a 0-ary function until an `eof` item is reached. The `eof` item itself is not part of the resulting stream; by setting `use_is` to true, eof is checked by identity rather than equality. `times` and `interval` behave e...
def aes_decrypt(key, stdin, chunk_size=65536): """ Generator that decrypts a content stream using AES 256 in CBC mode. :param key: Any string to use as the decryption key. :param stdin: Where to read the encrypted data from. :param chunk_size: Largest amount to read at once. """ if not ...
Generator that decrypts a content stream using AES 256 in CBC mode. :param key: Any string to use as the decryption key. :param stdin: Where to read the encrypted data from. :param chunk_size: Largest amount to read at once.
Below is the the instruction that describes the task: ### Input: Generator that decrypts a content stream using AES 256 in CBC mode. :param key: Any string to use as the decryption key. :param stdin: Where to read the encrypted data from. :param chunk_size: Largest amount to read at once. ### Respo...
def fetch_local_package(self, config): """Make a local path available to current stacker config. Args: config (dict): 'local' path config dictionary """ # Update sys.path & merge in remote configs (if necessary) self.update_paths_and_config(config=config, ...
Make a local path available to current stacker config. Args: config (dict): 'local' path config dictionary
Below is the the instruction that describes the task: ### Input: Make a local path available to current stacker config. Args: config (dict): 'local' path config dictionary ### Response: def fetch_local_package(self, config): """Make a local path available to current stacker config. ...
def _peg_pose_in_hole_frame(self): """ A helper function that takes in a named data field and returns the pose of that object in the base frame. """ # World frame peg_pos_in_world = self.sim.data.get_body_xpos("cylinder") peg_rot_in_world = self.sim.data.get_body_...
A helper function that takes in a named data field and returns the pose of that object in the base frame.
Below is the the instruction that describes the task: ### Input: A helper function that takes in a named data field and returns the pose of that object in the base frame. ### Response: def _peg_pose_in_hole_frame(self): """ A helper function that takes in a named data field and returns the ...
def create_question_pdfs(nb, pages_per_q, folder, zoom) -> list: """ Converts each cells in tbe notebook to a PDF named something like 'q04c.pdf'. Places PDFs in the specified folder and returns the list of created PDF locations. """ html_cells = nb_to_html_cells(nb) q_nums = nb_to_q_nums(nb...
Converts each cells in tbe notebook to a PDF named something like 'q04c.pdf'. Places PDFs in the specified folder and returns the list of created PDF locations.
Below is the the instruction that describes the task: ### Input: Converts each cells in tbe notebook to a PDF named something like 'q04c.pdf'. Places PDFs in the specified folder and returns the list of created PDF locations. ### Response: def create_question_pdfs(nb, pages_per_q, folder, zoom) -> list: ...
def reads_supporting_variants(variants, samfile, **kwargs): """ Given a SAM/BAM file and a collection of variants, generates a sequence of variants paired with reads which support each variant. """ for variant, allele_reads in reads_overlapping_variants( variants=variants, sa...
Given a SAM/BAM file and a collection of variants, generates a sequence of variants paired with reads which support each variant.
Below is the the instruction that describes the task: ### Input: Given a SAM/BAM file and a collection of variants, generates a sequence of variants paired with reads which support each variant. ### Response: def reads_supporting_variants(variants, samfile, **kwargs): """ Given a SAM/BAM file and a col...
def plot_predict(self, h=5, past_values=20, intervals=True, oos_data=None, **kwargs): """ Makes forecast with the estimated model Parameters ---------- h : int (default : 5) How many steps ahead would you like to forecast? past_values : int (default : 20) ...
Makes forecast with the estimated model Parameters ---------- h : int (default : 5) How many steps ahead would you like to forecast? past_values : int (default : 20) How many past observations to show on the forecast graph? intervals : Boolean ...
Below is the the instruction that describes the task: ### Input: Makes forecast with the estimated model Parameters ---------- h : int (default : 5) How many steps ahead would you like to forecast? past_values : int (default : 20) How many past observations ...
def _parse_rd(self, config): """ _parse_rd scans the provided configuration block and extracts the vrf rd. The return dict is intended to be merged into the response dict. Args: config (str): The vrf configuration block from the nodes running configuration ...
_parse_rd scans the provided configuration block and extracts the vrf rd. The return dict is intended to be merged into the response dict. Args: config (str): The vrf configuration block from the nodes running configuration Returns: dict: resourc...
Below is the the instruction that describes the task: ### Input: _parse_rd scans the provided configuration block and extracts the vrf rd. The return dict is intended to be merged into the response dict. Args: config (str): The vrf configuration block from the nodes running ...
def make_query(catalog): """A function to prepare a query """ query = {} request = api.get_request() index = get_search_index_for(catalog) limit = request.form.get("limit") q = request.form.get("q") if len(q) > 0: query[index] = q + "*" else: return None portal_...
A function to prepare a query
Below is the the instruction that describes the task: ### Input: A function to prepare a query ### Response: def make_query(catalog): """A function to prepare a query """ query = {} request = api.get_request() index = get_search_index_for(catalog) limit = request.form.get("limit") q = ...
def gen_localdir(self, localdir): """ Generate local directory where track will be saved. Create it if not exists. """ directory = "{0}/{1}/".format(localdir, self.get("username")) if not os.path.exists(directory): os.makedirs(directory) return directo...
Generate local directory where track will be saved. Create it if not exists.
Below is the the instruction that describes the task: ### Input: Generate local directory where track will be saved. Create it if not exists. ### Response: def gen_localdir(self, localdir): """ Generate local directory where track will be saved. Create it if not exists. """ ...
def _check_require_version(namespace, stacklevel): """A context manager which tries to give helpful warnings about missing gi.require_version() which could potentially break code if only an older version than expected is installed or a new version gets introduced. :: with _check_require_ve...
A context manager which tries to give helpful warnings about missing gi.require_version() which could potentially break code if only an older version than expected is installed or a new version gets introduced. :: with _check_require_version("Gtk", stacklevel): load_namespace_and_o...
Below is the the instruction that describes the task: ### Input: A context manager which tries to give helpful warnings about missing gi.require_version() which could potentially break code if only an older version than expected is installed or a new version gets introduced. :: with _check...
def bfs_multi_edges(G, source, reverse=False, keys=True, data=False): """Produce edges in a breadth-first-search starting at source. ----- Based on http://www.ics.uci.edu/~eppstein/PADS/BFS.py by D. Eppstein, July 2004. """ from collections import deque from functools import partial if r...
Produce edges in a breadth-first-search starting at source. ----- Based on http://www.ics.uci.edu/~eppstein/PADS/BFS.py by D. Eppstein, July 2004.
Below is the the instruction that describes the task: ### Input: Produce edges in a breadth-first-search starting at source. ----- Based on http://www.ics.uci.edu/~eppstein/PADS/BFS.py by D. Eppstein, July 2004. ### Response: def bfs_multi_edges(G, source, reverse=False, keys=True, data=False): """...
def get_templates(): """ Returns each of the templates with env vars injected. """ injected = {} for name, data in templates.items(): injected[name] = dict([(k, v % env) for k, v in data.items()]) return injected
Returns each of the templates with env vars injected.
Below is the the instruction that describes the task: ### Input: Returns each of the templates with env vars injected. ### Response: def get_templates(): """ Returns each of the templates with env vars injected. """ injected = {} for name, data in templates.items(): injected[name] = dic...
def get_statements(self): """Convert network edges into Statements. Returns ------- list of Statements Converted INDRA Statements. """ edges = _get_dict_from_list('edges', self.cx) for edge in edges: edge_type = edge.get('i') i...
Convert network edges into Statements. Returns ------- list of Statements Converted INDRA Statements.
Below is the the instruction that describes the task: ### Input: Convert network edges into Statements. Returns ------- list of Statements Converted INDRA Statements. ### Response: def get_statements(self): """Convert network edges into Statements. Returns ...
def destroy(ads): """Cleans up AndroidDevice objects. Args: ads: A list of AndroidDevice objects. """ for ad in ads: try: ad.services.stop_all() except: ad.log.exception('Failed to clean up properly.')
Cleans up AndroidDevice objects. Args: ads: A list of AndroidDevice objects.
Below is the the instruction that describes the task: ### Input: Cleans up AndroidDevice objects. Args: ads: A list of AndroidDevice objects. ### Response: def destroy(ads): """Cleans up AndroidDevice objects. Args: ads: A list of AndroidDevice objects. """ for ad in ads: ...
def apply_to_model(self, model): ''' Apply this theme to a model. .. warning:: Typically, don't call this method directly. Instead, set the theme on the :class:`~bokeh.document.Document` the model is a part of. ''' model.apply_theme(self._for_class(model.__class...
Apply this theme to a model. .. warning:: Typically, don't call this method directly. Instead, set the theme on the :class:`~bokeh.document.Document` the model is a part of.
Below is the the instruction that describes the task: ### Input: Apply this theme to a model. .. warning:: Typically, don't call this method directly. Instead, set the theme on the :class:`~bokeh.document.Document` the model is a part of. ### Response: def apply_to_model(self, mode...
def check_dashboard_cookie(self): """ Check if the dashboard cookie should exist through bikasetup configuration. If it should exist but doesn't exist yet, the function creates it with all values as default. If it should exist and already exists, it returns the value. ...
Check if the dashboard cookie should exist through bikasetup configuration. If it should exist but doesn't exist yet, the function creates it with all values as default. If it should exist and already exists, it returns the value. Otherwise, the function returns None. :...
Below is the the instruction that describes the task: ### Input: Check if the dashboard cookie should exist through bikasetup configuration. If it should exist but doesn't exist yet, the function creates it with all values as default. If it should exist and already exists, it return...
def _parse_stop_words_file(self, path): """Load stop words from the given path. Parse the stop words file, saving each word found in it in a set for the language of the file. This language is obtained from the file name. If the file doesn't exist, the method will have no effect....
Load stop words from the given path. Parse the stop words file, saving each word found in it in a set for the language of the file. This language is obtained from the file name. If the file doesn't exist, the method will have no effect. Args: path: Path to the stop ...
Below is the the instruction that describes the task: ### Input: Load stop words from the given path. Parse the stop words file, saving each word found in it in a set for the language of the file. This language is obtained from the file name. If the file doesn't exist, the method will have ...
def split_input(img): """ img: an RGB image of shape (s, 2s, 3). :return: [input, output] """ # split the image into left + right pairs s = img.shape[0] assert img.shape[1] == 2 * s input, output = img[:, :s, :], img[:, s:, :] if args.mode == 'BtoA': input, output = output, i...
img: an RGB image of shape (s, 2s, 3). :return: [input, output]
Below is the the instruction that describes the task: ### Input: img: an RGB image of shape (s, 2s, 3). :return: [input, output] ### Response: def split_input(img): """ img: an RGB image of shape (s, 2s, 3). :return: [input, output] """ # split the image into left + right pairs s = img....
def _CompositeMapByteStream( self, byte_stream, byte_offset=0, context=None, **unused_kwargs): """Maps a sequence of composite data types on a byte stream. Args: byte_stream (bytes): byte stream. byte_offset (Optional[int]): offset into the byte stream where to start. context (Optional[...
Maps a sequence of composite data types on a byte stream. Args: byte_stream (bytes): byte stream. byte_offset (Optional[int]): offset into the byte stream where to start. context (Optional[DataTypeMapContext]): data type map context. Returns: object: mapped value. Raises: Ma...
Below is the the instruction that describes the task: ### Input: Maps a sequence of composite data types on a byte stream. Args: byte_stream (bytes): byte stream. byte_offset (Optional[int]): offset into the byte stream where to start. context (Optional[DataTypeMapContext]): data type map con...
def get_default_config(self): """ Returns default configuration options. """ config = super(SmartCollector, self).get_default_config() config.update({ 'path': 'smart', 'bin': 'smartctl', 'use_sudo': False, 'sudo_cmd': ...
Returns default configuration options.
Below is the the instruction that describes the task: ### Input: Returns default configuration options. ### Response: def get_default_config(self): """ Returns default configuration options. """ config = super(SmartCollector, self).get_default_config() config.update({ ...
def all(self, customer_id, data={}, **kwargs): """" Get all tokens for given customer Id Args: customer_id : Customer Id for which tokens have to be fetched Returns: Token dicts for given cutomer Id """ url = "{}/{}/tokens".format(self.base_url, ...
Get all tokens for given customer Id Args: customer_id : Customer Id for which tokens have to be fetched Returns: Token dicts for given cutomer Id
Below is the the instruction that describes the task: ### Input: Get all tokens for given customer Id Args: customer_id : Customer Id for which tokens have to be fetched Returns: Token dicts for given cutomer Id ### Response: def all(self, customer_id, data={}, **kwargs): ...
def delete(fun): ''' Remove specific function contents of minion. Returns True on success. CLI Example: .. code-block:: bash salt '*' mine.delete 'network.interfaces' ''' if __opts__['file_client'] == 'local': data = __salt__['data.get']('mine_cache') if isinstance(dat...
Remove specific function contents of minion. Returns True on success. CLI Example: .. code-block:: bash salt '*' mine.delete 'network.interfaces'
Below is the the instruction that describes the task: ### Input: Remove specific function contents of minion. Returns True on success. CLI Example: .. code-block:: bash salt '*' mine.delete 'network.interfaces' ### Response: def delete(fun): ''' Remove specific function contents of minio...
def optional(e, default=Ignore): """ Create a PEG function to optionally match an expression. """ def match_optional(s, grm=None, pos=0): try: return e(s, grm, pos) except PegreError: return PegreResult(s, default, (pos, pos)) return match_optional
Create a PEG function to optionally match an expression.
Below is the the instruction that describes the task: ### Input: Create a PEG function to optionally match an expression. ### Response: def optional(e, default=Ignore): """ Create a PEG function to optionally match an expression. """ def match_optional(s, grm=None, pos=0): try: ...
def removeAll(self): """Remove all objects Returns: len(int): affected rows """ before_len = len(self.model.db) self.model.db = [] if not self._batch.enable.is_set(): self.model.save_db() return before_len - len(self.model.db)
Remove all objects Returns: len(int): affected rows
Below is the the instruction that describes the task: ### Input: Remove all objects Returns: len(int): affected rows ### Response: def removeAll(self): """Remove all objects Returns: len(int): affected rows """ before_len = len(self.mo...
def PorodGuinier(q, a, alpha, Rg): """Empirical Porod-Guinier scattering Inputs: ------- ``q``: independent variable ``a``: factor of the power-law branch ``alpha``: power-law exponent ``Rg``: radius of gyration Formula: -------- ``G * exp(-q^2*Rg^2/3)`` if ...
Empirical Porod-Guinier scattering Inputs: ------- ``q``: independent variable ``a``: factor of the power-law branch ``alpha``: power-law exponent ``Rg``: radius of gyration Formula: -------- ``G * exp(-q^2*Rg^2/3)`` if ``q>q_sep`` and ``a*q^alpha`` otherwise. ...
Below is the the instruction that describes the task: ### Input: Empirical Porod-Guinier scattering Inputs: ------- ``q``: independent variable ``a``: factor of the power-law branch ``alpha``: power-law exponent ``Rg``: radius of gyration Formula: -------- `...
def remove_tags(self, tags, **kwargs): """ :param tags: Tags to remove from the job :type tags: list of strings Removes each of the specified tags from the job. Takes no action for tags that the job does not currently have. """ dxpy.api.job_remove_tags(self._dx...
:param tags: Tags to remove from the job :type tags: list of strings Removes each of the specified tags from the job. Takes no action for tags that the job does not currently have.
Below is the the instruction that describes the task: ### Input: :param tags: Tags to remove from the job :type tags: list of strings Removes each of the specified tags from the job. Takes no action for tags that the job does not currently have. ### Response: def remove_tags(self, tags, **...
def _prevNonCommentBlock(self, block): """Return the closest non-empty line, ignoring comments (result <= line). Return -1 if the document """ block = self._prevNonEmptyBlock(block) while block.isValid() and self._isCommentBlock(block): block = self._prevNonEmptyBlock...
Return the closest non-empty line, ignoring comments (result <= line). Return -1 if the document
Below is the the instruction that describes the task: ### Input: Return the closest non-empty line, ignoring comments (result <= line). Return -1 if the document ### Response: def _prevNonCommentBlock(self, block): """Return the closest non-empty line, ignoring comments (result <= line). Re...
def retrieve_loadbalancer_status(self, loadbalancer, **_params): """Retrieves status for a certain load balancer.""" return self.get(self.lbaas_loadbalancer_path_status % (loadbalancer), params=_params)
Retrieves status for a certain load balancer.
Below is the the instruction that describes the task: ### Input: Retrieves status for a certain load balancer. ### Response: def retrieve_loadbalancer_status(self, loadbalancer, **_params): """Retrieves status for a certain load balancer.""" return self.get(self.lbaas_loadbalancer_path_status % (lo...
def _execute(self, line): """ Evaluate the line and print the result. """ output = self.app.output # WORKAROUND: Due to a bug in Jedi, the current directory is removed # from sys.path. See: https://github.com/davidhalter/jedi/issues/1148 if '' not in sys.path: ...
Evaluate the line and print the result.
Below is the the instruction that describes the task: ### Input: Evaluate the line and print the result. ### Response: def _execute(self, line): """ Evaluate the line and print the result. """ output = self.app.output # WORKAROUND: Due to a bug in Jedi, the current director...
def coarsegrain(P, n): """ Coarse-grains transition matrix P to n sets using PCCA Coarse-grains transition matrix P such that the dominant eigenvalues are preserved, using: ..math: \tilde{P} = M^T P M (M^T M)^{-1} See [2]_ for the derivation of this form from the coarse-graining method fi...
Coarse-grains transition matrix P to n sets using PCCA Coarse-grains transition matrix P such that the dominant eigenvalues are preserved, using: ..math: \tilde{P} = M^T P M (M^T M)^{-1} See [2]_ for the derivation of this form from the coarse-graining method first derived in [1]_. Reference...
Below is the the instruction that describes the task: ### Input: Coarse-grains transition matrix P to n sets using PCCA Coarse-grains transition matrix P such that the dominant eigenvalues are preserved, using: ..math: \tilde{P} = M^T P M (M^T M)^{-1} See [2]_ for the derivation of this form ...
def delete_resourcegroupitems(scenario_id, item_ids, **kwargs): """ Delete specified items in a group, in a scenario. """ user_id = int(kwargs.get('user_id')) #check the scenario exists _get_scenario(scenario_id, user_id) for item_id in item_ids: rgi = db.DBSession.query(Resource...
Delete specified items in a group, in a scenario.
Below is the the instruction that describes the task: ### Input: Delete specified items in a group, in a scenario. ### Response: def delete_resourcegroupitems(scenario_id, item_ids, **kwargs): """ Delete specified items in a group, in a scenario. """ user_id = int(kwargs.get('user_id')) #ch...
def get_input_files(oqparam, hazard=False): """ :param oqparam: an OqParam instance :param hazard: if True, consider only the hazard files :returns: input path names in a specific order """ fnames = [] # files entering in the checksum for key in oqparam.inputs: fname = oqparam.input...
:param oqparam: an OqParam instance :param hazard: if True, consider only the hazard files :returns: input path names in a specific order
Below is the the instruction that describes the task: ### Input: :param oqparam: an OqParam instance :param hazard: if True, consider only the hazard files :returns: input path names in a specific order ### Response: def get_input_files(oqparam, hazard=False): """ :param oqparam: an OqParam instanc...
def on_message(self, msg=None): """ Poll the websocket for a new packet. `Client.listen()` calls this. :param msg (string(byte array)): Optional. Parse the specified message instead of receiving a packet from the socket. """ if msg is None: try: ...
Poll the websocket for a new packet. `Client.listen()` calls this. :param msg (string(byte array)): Optional. Parse the specified message instead of receiving a packet from the socket.
Below is the the instruction that describes the task: ### Input: Poll the websocket for a new packet. `Client.listen()` calls this. :param msg (string(byte array)): Optional. Parse the specified message instead of receiving a packet from the socket. ### Response: def on_message(self, ...
def encode_username_password( username: Union[str, bytes], password: Union[str, bytes] ) -> bytes: """Encodes a username/password pair in the format used by HTTP auth. The return value is a byte string in the form ``username:password``. .. versionadded:: 5.1 """ if isinstance(username, unicode...
Encodes a username/password pair in the format used by HTTP auth. The return value is a byte string in the form ``username:password``. .. versionadded:: 5.1
Below is the the instruction that describes the task: ### Input: Encodes a username/password pair in the format used by HTTP auth. The return value is a byte string in the form ``username:password``. .. versionadded:: 5.1 ### Response: def encode_username_password( username: Union[str, bytes], passwo...
def disconnect(self): ''' Disconnect from the current host, but do not update the closed state. After the transport is disconnected, the closed state will be True if this is called after a protocol shutdown, or False if the disconnect was in error. TODO: do we really nee...
Disconnect from the current host, but do not update the closed state. After the transport is disconnected, the closed state will be True if this is called after a protocol shutdown, or False if the disconnect was in error. TODO: do we really need closed vs. connected states? this only a...
Below is the the instruction that describes the task: ### Input: Disconnect from the current host, but do not update the closed state. After the transport is disconnected, the closed state will be True if this is called after a protocol shutdown, or False if the disconnect was in error. ...
def get_default_bios_settings(self, only_allowed_settings=True): """Get default BIOS settings. :param: only_allowed_settings: True when only allowed BIOS settings are to be returned. If False, All the BIOS settings supported by iLO are returned. :return: a dictio...
Get default BIOS settings. :param: only_allowed_settings: True when only allowed BIOS settings are to be returned. If False, All the BIOS settings supported by iLO are returned. :return: a dictionary of default BIOS settings(factory settings). Depending ...
Below is the the instruction that describes the task: ### Input: Get default BIOS settings. :param: only_allowed_settings: True when only allowed BIOS settings are to be returned. If False, All the BIOS settings supported by iLO are returned. :return: a dictionary of...
def hexists(self, key, field): """Determine if hash field exists.""" fut = self.execute(b'HEXISTS', key, field) return wait_convert(fut, bool)
Determine if hash field exists.
Below is the the instruction that describes the task: ### Input: Determine if hash field exists. ### Response: def hexists(self, key, field): """Determine if hash field exists.""" fut = self.execute(b'HEXISTS', key, field) return wait_convert(fut, bool)
def qualify(self): """ Convert attribute values, that are references to other objects, into I{qref}. Qualfied using default document namespace. Since many wsdls are written improperly: when the document does not define a default namespace, the schema target namespace is used ...
Convert attribute values, that are references to other objects, into I{qref}. Qualfied using default document namespace. Since many wsdls are written improperly: when the document does not define a default namespace, the schema target namespace is used to qualify references.
Below is the the instruction that describes the task: ### Input: Convert attribute values, that are references to other objects, into I{qref}. Qualfied using default document namespace. Since many wsdls are written improperly: when the document does not define a default namespace, the schem...
def log_rho_bg(trigs, bins, counts): ''' Calculate the log of background fall-off Parameters ---------- trigs: array SNR values of all the triggers bins: string bins for histogrammed triggers path: string counts for histogrammed t...
Calculate the log of background fall-off Parameters ---------- trigs: array SNR values of all the triggers bins: string bins for histogrammed triggers path: string counts for histogrammed triggers Returns ------- ...
Below is the the instruction that describes the task: ### Input: Calculate the log of background fall-off Parameters ---------- trigs: array SNR values of all the triggers bins: string bins for histogrammed triggers path: string c...
def _set_with_metadata(self, name, value, layer=None, source=None): """Set a value in the named layer with the given source. Parameters ---------- name : str The name of the value value The value to store layer : str, optional The name...
Set a value in the named layer with the given source. Parameters ---------- name : str The name of the value value The value to store layer : str, optional The name of the layer to store the value in. If none is supplied then the v...
Below is the the instruction that describes the task: ### Input: Set a value in the named layer with the given source. Parameters ---------- name : str The name of the value value The value to store layer : str, optional The name of the la...
def get_mzid_specfile_ids(mzidfn, namespace): """Returns mzid spectra data filenames and their IDs used in the mzIdentML file as a dict. Keys == IDs, values == fns""" sid_fn = {} for specdata in mzid_specdata_generator(mzidfn, namespace): sid_fn[specdata.attrib['id']] = specdata.attrib['name'] ...
Returns mzid spectra data filenames and their IDs used in the mzIdentML file as a dict. Keys == IDs, values == fns
Below is the the instruction that describes the task: ### Input: Returns mzid spectra data filenames and their IDs used in the mzIdentML file as a dict. Keys == IDs, values == fns ### Response: def get_mzid_specfile_ids(mzidfn, namespace): """Returns mzid spectra data filenames and their IDs used in the ...
def keys(self, remote=False): """ Returns the database names for this client. Default is to return only the locally cached database names, specify ``remote=True`` to make a remote request to include all databases. :param bool remote: Dictates whether the list of locally cached ...
Returns the database names for this client. Default is to return only the locally cached database names, specify ``remote=True`` to make a remote request to include all databases. :param bool remote: Dictates whether the list of locally cached database names are returned or a remote...
Below is the the instruction that describes the task: ### Input: Returns the database names for this client. Default is to return only the locally cached database names, specify ``remote=True`` to make a remote request to include all databases. :param bool remote: Dictates whether the list ...
def _parse_tags(tag_file): """Parses a tag file, according to RFC 2822. This includes line folding, permitting extra-long field values. See http://www.faqs.org/rfcs/rfc2822.html for more information. """ tag_name = None tag_value = None # Line folding is handled by yi...
Parses a tag file, according to RFC 2822. This includes line folding, permitting extra-long field values. See http://www.faqs.org/rfcs/rfc2822.html for more information.
Below is the the instruction that describes the task: ### Input: Parses a tag file, according to RFC 2822. This includes line folding, permitting extra-long field values. See http://www.faqs.org/rfcs/rfc2822.html for more information. ### Response: def _parse_tags(tag_file): """Pa...
def are_equivalent_pyxb(a_pyxb, b_pyxb, ignore_timestamps=False): """Determine if SystemMetadata PyXB objects are semantically equivalent. Normalize then compare SystemMetadata PyXB objects for equivalency. Args: a_pyxb, b_pyxb : SystemMetadata PyXB objects to compare reset_timestamps: bool ...
Determine if SystemMetadata PyXB objects are semantically equivalent. Normalize then compare SystemMetadata PyXB objects for equivalency. Args: a_pyxb, b_pyxb : SystemMetadata PyXB objects to compare reset_timestamps: bool ``True``: Timestamps in the SystemMetadata are set to a standard v...
Below is the the instruction that describes the task: ### Input: Determine if SystemMetadata PyXB objects are semantically equivalent. Normalize then compare SystemMetadata PyXB objects for equivalency. Args: a_pyxb, b_pyxb : SystemMetadata PyXB objects to compare reset_timestamps: bool ...
def md5_object(obj): """ If an object is hashable, return the string of the MD5. Parameters ----------- obj: object Returns ---------- md5: str, MD5 hash """ hasher = hashlib.md5() if isinstance(obj, basestring) and PY3: # in python3 convert strings to bytes before ...
If an object is hashable, return the string of the MD5. Parameters ----------- obj: object Returns ---------- md5: str, MD5 hash
Below is the the instruction that describes the task: ### Input: If an object is hashable, return the string of the MD5. Parameters ----------- obj: object Returns ---------- md5: str, MD5 hash ### Response: def md5_object(obj): """ If an object is hashable, return the string of t...
def _get_synonym(self, line): """Given line, return optional attribute synonym value in a namedtuple. Example synonym and its storage in a namedtuple: synonym: "The other white meat" EXACT MARKETING_SLOGAN [MEAT:00324, BACONBASE:03021] text: "The other white meat" scope:...
Given line, return optional attribute synonym value in a namedtuple. Example synonym and its storage in a namedtuple: synonym: "The other white meat" EXACT MARKETING_SLOGAN [MEAT:00324, BACONBASE:03021] text: "The other white meat" scope: EXACT typename: MARKETING_S...
Below is the the instruction that describes the task: ### Input: Given line, return optional attribute synonym value in a namedtuple. Example synonym and its storage in a namedtuple: synonym: "The other white meat" EXACT MARKETING_SLOGAN [MEAT:00324, BACONBASE:03021] text: "The other ...
def send_produce_request(self, payloads=(), acks=1, timeout=1000, fail_on_error=True, callback=None): """ Encode and send some ProduceRequests ProduceRequests will be grouped by (topic, partition) and then sent to a specific broker. Output is a list of respo...
Encode and send some ProduceRequests ProduceRequests will be grouped by (topic, partition) and then sent to a specific broker. Output is a list of responses in the same order as the list of payloads specified Arguments: payloads (list of ProduceRequest): produce requests to...
Below is the the instruction that describes the task: ### Input: Encode and send some ProduceRequests ProduceRequests will be grouped by (topic, partition) and then sent to a specific broker. Output is a list of responses in the same order as the list of payloads specified Argument...
def set_quantity(self, twig=None, value=None, **kwargs): """ TODO: add documentation """ # TODO: handle twig having parameter key (value@, default_unit@, adjust@, etc) # TODO: does this return anything (update the docstring)? return self.get_parameter(twig=twig, **kwargs)...
TODO: add documentation
Below is the the instruction that describes the task: ### Input: TODO: add documentation ### Response: def set_quantity(self, twig=None, value=None, **kwargs): """ TODO: add documentation """ # TODO: handle twig having parameter key (value@, default_unit@, adjust@, etc) # TO...
def group(self, meta=None, meta_aggregates=None, regs=None, regs_aggregates=None, meta_group_name="_group"): """ *Wrapper of* ``GROUP`` The GROUP operator is used for grouping both regions and/or metadata of input dataset samples according to distinct values of certain att...
*Wrapper of* ``GROUP`` The GROUP operator is used for grouping both regions and/or metadata of input dataset samples according to distinct values of certain attributes (known as grouping attributes); new grouping attributes are added to samples in the output dataset, storing the results...
Below is the the instruction that describes the task: ### Input: *Wrapper of* ``GROUP`` The GROUP operator is used for grouping both regions and/or metadata of input dataset samples according to distinct values of certain attributes (known as grouping attributes); new grouping attributes ar...
def detokenize(self, inputs, delim=' '): """ Detokenizes single sentence and removes token separator characters. :param inputs: sequence of tokens :param delim: tokenization delimiter returns: string representing detokenized sentence """ detok = delim.join([self...
Detokenizes single sentence and removes token separator characters. :param inputs: sequence of tokens :param delim: tokenization delimiter returns: string representing detokenized sentence
Below is the the instruction that describes the task: ### Input: Detokenizes single sentence and removes token separator characters. :param inputs: sequence of tokens :param delim: tokenization delimiter returns: string representing detokenized sentence ### Response: def detokenize(self, ...
def main(args): '''main entry point of app Arguments: args {namespace} -- arguments provided in cli ''' print("\nNote it's very possible that this doesn't work correctly so take what it gives with a bucketload of salt\n") ######################### # # ...
main entry point of app Arguments: args {namespace} -- arguments provided in cli
Below is the the instruction that describes the task: ### Input: main entry point of app Arguments: args {namespace} -- arguments provided in cli ### Response: def main(args): '''main entry point of app Arguments: args {namespace} -- arguments provided in cli ''' ...
def script(self, sql_script, split_algo='sql_split', prep_statements=True, dump_fails=True): """Wrapper method providing access to the SQLScript class's methods and properties.""" return Execute(sql_script, split_algo, prep_statements, dump_fails, self)
Wrapper method providing access to the SQLScript class's methods and properties.
Below is the the instruction that describes the task: ### Input: Wrapper method providing access to the SQLScript class's methods and properties. ### Response: def script(self, sql_script, split_algo='sql_split', prep_statements=True, dump_fails=True): """Wrapper method providing access to the SQLScript cl...
def add(self, service, workers=1, args=None, kwargs=None): """Add a new service to the ServiceManager :param service: callable that return an instance of :py:class:`Service` :type service: callable :param workers: number of processes/workers for this service :type workers: int ...
Add a new service to the ServiceManager :param service: callable that return an instance of :py:class:`Service` :type service: callable :param workers: number of processes/workers for this service :type workers: int :param args: additional positional arguments for this service ...
Below is the the instruction that describes the task: ### Input: Add a new service to the ServiceManager :param service: callable that return an instance of :py:class:`Service` :type service: callable :param workers: number of processes/workers for this service :type workers: int ...
def setup_top(self): """Create top-level elements of the hybrid schema.""" self.top_grammar = SchemaNode("grammar") self.top_grammar.attr = { "xmlns": "http://relaxng.org/ns/structure/1.0", "datatypeLibrary": "http://www.w3.org/2001/XMLSchema-datatypes"} self.tree...
Create top-level elements of the hybrid schema.
Below is the the instruction that describes the task: ### Input: Create top-level elements of the hybrid schema. ### Response: def setup_top(self): """Create top-level elements of the hybrid schema.""" self.top_grammar = SchemaNode("grammar") self.top_grammar.attr = { "xmlns": "...
def _ask_password(): """Securely and interactively ask for a password""" password = "Foo" password_trial = "" while password != password_trial: password = getpass.getpass() password_trial = getpass.getpass(prompt="Repeat:") if password != password_trial: print("\nPa...
Securely and interactively ask for a password
Below is the the instruction that describes the task: ### Input: Securely and interactively ask for a password ### Response: def _ask_password(): """Securely and interactively ask for a password""" password = "Foo" password_trial = "" while password != password_trial: password = getpass.g...
def dynacRepresentation(self): """ Return the Pynac representation of this Set4DAperture instance. """ details = [ self.energyDefnFlag.val, self.energy.val, self.phase.val, self.x.val, self.y.val, self.radius.val, ...
Return the Pynac representation of this Set4DAperture instance.
Below is the the instruction that describes the task: ### Input: Return the Pynac representation of this Set4DAperture instance. ### Response: def dynacRepresentation(self): """ Return the Pynac representation of this Set4DAperture instance. """ details = [ self.energyDe...
def version_list(package): """ List the versions of a package. """ team, owner, pkg = parse_package(package) session = _get_session(team) response = session.get( "{url}/api/version/{owner}/{pkg}/".format( url=get_registry_url(team), owner=owner, pkg=p...
List the versions of a package.
Below is the the instruction that describes the task: ### Input: List the versions of a package. ### Response: def version_list(package): """ List the versions of a package. """ team, owner, pkg = parse_package(package) session = _get_session(team) response = session.get( "{url}/ap...
def get_root_path(self, name): """ Attempt to compute a root path for a (hopefully importable) name. Based in part on Flask's `root_path` calculation. See: https://github.com/mitsuhiko/flask/blob/master/flask/helpers.py#L777 """ module = modules.get(name) i...
Attempt to compute a root path for a (hopefully importable) name. Based in part on Flask's `root_path` calculation. See: https://github.com/mitsuhiko/flask/blob/master/flask/helpers.py#L777
Below is the the instruction that describes the task: ### Input: Attempt to compute a root path for a (hopefully importable) name. Based in part on Flask's `root_path` calculation. See: https://github.com/mitsuhiko/flask/blob/master/flask/helpers.py#L777 ### Response: def get_root_path(self, ...
def scatter(self, *args, **kwargs): """Adds a :py:class:`.ScatterSeries` to the chart. :param \*data: The data for the series as either (x,y) values or two big\ tuples/lists of x and y values respectively. :param str name: The name to be associated with the series. :param str co...
Adds a :py:class:`.ScatterSeries` to the chart. :param \*data: The data for the series as either (x,y) values or two big\ tuples/lists of x and y values respectively. :param str name: The name to be associated with the series. :param str color: The hex colour of the line. :param...
Below is the the instruction that describes the task: ### Input: Adds a :py:class:`.ScatterSeries` to the chart. :param \*data: The data for the series as either (x,y) values or two big\ tuples/lists of x and y values respectively. :param str name: The name to be associated with the series....
def _read_footer(file_obj): """Read the footer from the given file object and returns a FileMetaData object. This method assumes that the fo references a valid parquet file. """ footer_size = _get_footer_size(file_obj) if logger.isEnabledFor(logging.DEBUG): logger.debug("Footer size in byte...
Read the footer from the given file object and returns a FileMetaData object. This method assumes that the fo references a valid parquet file.
Below is the the instruction that describes the task: ### Input: Read the footer from the given file object and returns a FileMetaData object. This method assumes that the fo references a valid parquet file. ### Response: def _read_footer(file_obj): """Read the footer from the given file object and return...
def p_kwl_kwl(self, p): ''' kwl : kwl SEPARATOR kwl ''' _LOGGER.debug("kwl -> kwl ; kwl") if p[3] is not None: p[0] = p[3] elif p[1] is not None: p[0] = p[1] else: p[0] = TypedClass(None, TypedClass.UNKNOWN)
kwl : kwl SEPARATOR kwl
Below is the the instruction that describes the task: ### Input: kwl : kwl SEPARATOR kwl ### Response: def p_kwl_kwl(self, p): ''' kwl : kwl SEPARATOR kwl ''' _LOGGER.debug("kwl -> kwl ; kwl") if p[3] is not None: p[0] = p[3] elif p[1] is not None: p...
def auth(self): """ Access the auth :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesList :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesList """ if self._auth is None: self._auth = AuthTypesList( se...
Access the auth :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesList :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesList
Below is the the instruction that describes the task: ### Input: Access the auth :returns: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesList :rtype: twilio.rest.api.v2010.account.sip.domain.auth_types.AuthTypesList ### Response: def auth(self): """ Access the auth ...
def get_groups_from_category(self, category) -> typing.Iterator['Group']: """ Args: category: group category Returns: generator over all groups from a specific category in this coalition """ Mission.validator_group_category.validate(category, 'get_groups_from_categor...
Args: category: group category Returns: generator over all groups from a specific category in this coalition
Below is the the instruction that describes the task: ### Input: Args: category: group category Returns: generator over all groups from a specific category in this coalition ### Response: def get_groups_from_category(self, category) -> typing.Iterator['Group']: """ Args: ...
def run_cmd_unit(self, sentry_unit, cmd): """Run a command on a unit, return the output and exit code.""" output, code = sentry_unit.run(cmd) if code == 0: self.log.debug('{} `{}` command returned {} ' '(OK)'.format(sentry_unit.info['unit_name'], ...
Run a command on a unit, return the output and exit code.
Below is the the instruction that describes the task: ### Input: Run a command on a unit, return the output and exit code. ### Response: def run_cmd_unit(self, sentry_unit, cmd): """Run a command on a unit, return the output and exit code.""" output, code = sentry_unit.run(cmd) if code == 0...
def CargarFormatoPDF(self, archivo="liquidacion_form_c1116b_wslpg.csv"): "Cargo el formato de campos a generar desde una planilla CSV" # si no encuentro archivo, lo busco en el directorio predeterminado: if not os.path.exists(archivo): archivo = os.path.join(self.InstallDir, "planti...
Cargo el formato de campos a generar desde una planilla CSV
Below is the the instruction that describes the task: ### Input: Cargo el formato de campos a generar desde una planilla CSV ### Response: def CargarFormatoPDF(self, archivo="liquidacion_form_c1116b_wslpg.csv"): "Cargo el formato de campos a generar desde una planilla CSV" # si no encuentro archiv...
def download_handler(feed, placeholders): import shlex """ Parse and execute the download handler """ value = feed.retrieve_config('downloadhandler', 'greg') if value == 'greg': while os.path.isfile(placeholders.fullpath): placeholders.fullpath = placeholders.fullpath + '_' ...
Parse and execute the download handler
Below is the the instruction that describes the task: ### Input: Parse and execute the download handler ### Response: def download_handler(feed, placeholders): import shlex """ Parse and execute the download handler """ value = feed.retrieve_config('downloadhandler', 'greg') if value == 'gr...
def print_response(self, input='', keep=False, *args, **kwargs): """ print response, if cookie is set then print that each line :param args: :param keep: if True more output is to come :param cookie: set a custom cookie, if set to 'None' then self.cookie wi...
print response, if cookie is set then print that each line :param args: :param keep: if True more output is to come :param cookie: set a custom cookie, if set to 'None' then self.cookie will be used. if set to 'False' disables cookie output entirely ...
Below is the the instruction that describes the task: ### Input: print response, if cookie is set then print that each line :param args: :param keep: if True more output is to come :param cookie: set a custom cookie, if set to 'None' then self.cookie will be used. ...
def tempdir(cls, suffix='', prefix=None, dir=None): """Returns a new temporary directory. Arguments are as for :meth:`~rpaths.Path.tempfile`, except that the `text` argument is not accepted. The directory is readable, writable, and searchable only by the creating user. ...
Returns a new temporary directory. Arguments are as for :meth:`~rpaths.Path.tempfile`, except that the `text` argument is not accepted. The directory is readable, writable, and searchable only by the creating user. The caller is responsible for deleting the directory when done...
Below is the the instruction that describes the task: ### Input: Returns a new temporary directory. Arguments are as for :meth:`~rpaths.Path.tempfile`, except that the `text` argument is not accepted. The directory is readable, writable, and searchable only by the creating user. ...
def fit(self, order=3): """ Overriden since this eos works with volume**(2/3) instead of volume. """ x = self.volumes**(-2./3.) self.eos_params = np.polyfit(x, self.energies, order) self._set_params()
Overriden since this eos works with volume**(2/3) instead of volume.
Below is the the instruction that describes the task: ### Input: Overriden since this eos works with volume**(2/3) instead of volume. ### Response: def fit(self, order=3): """ Overriden since this eos works with volume**(2/3) instead of volume. """ x = self.volumes**(-2./3.) ...
def get(config, messages, freq, pidDir=None, reactor=None): """Return a service which monitors processes based on directory contents Construct and return a service that, when started, will run processes based on the contents of the 'config' directory, restarting them if file contents change and stoppin...
Return a service which monitors processes based on directory contents Construct and return a service that, when started, will run processes based on the contents of the 'config' directory, restarting them if file contents change and stopping them if the file is removed. It also listens for restart and...
Below is the the instruction that describes the task: ### Input: Return a service which monitors processes based on directory contents Construct and return a service that, when started, will run processes based on the contents of the 'config' directory, restarting them if file contents change and stopp...
def get_finder(import_path): """ Get a finder class from an import path. Raises ``demosys.core.exceptions.ImproperlyConfigured`` if the finder is not found. This function uses an lru cache. :param import_path: string representing an import path :return: An instance of the finder """ Fin...
Get a finder class from an import path. Raises ``demosys.core.exceptions.ImproperlyConfigured`` if the finder is not found. This function uses an lru cache. :param import_path: string representing an import path :return: An instance of the finder
Below is the the instruction that describes the task: ### Input: Get a finder class from an import path. Raises ``demosys.core.exceptions.ImproperlyConfigured`` if the finder is not found. This function uses an lru cache. :param import_path: string representing an import path :return: An instance o...
def flatten(sequence, levels = 1): """ Example: >>> nested = [[1,2], [[3]]] >>> list(flatten(nested)) [1, 2, [3]] """ if levels == 0: for x in sequence: yield x else: for x in sequence: for y in flatten(x, levels - 1): yield y
Example: >>> nested = [[1,2], [[3]]] >>> list(flatten(nested)) [1, 2, [3]]
Below is the the instruction that describes the task: ### Input: Example: >>> nested = [[1,2], [[3]]] >>> list(flatten(nested)) [1, 2, [3]] ### Response: def flatten(sequence, levels = 1): """ Example: >>> nested = [[1,2], [[3]]] >>> list(flatten(nested)) [1, 2, [3]] """ if levels == 0: for x in sequen...
def _writeStructureLink(self, link, fileObject, replaceParamFile): """ Write Structure Link to File Method """ fileObject.write('%s\n' % link.type) fileObject.write('NUMSTRUCTS %s\n' % link.numElements) # Retrieve lists of structures weirs = link.weirs ...
Write Structure Link to File Method
Below is the the instruction that describes the task: ### Input: Write Structure Link to File Method ### Response: def _writeStructureLink(self, link, fileObject, replaceParamFile): """ Write Structure Link to File Method """ fileObject.write('%s\n' % link.type) fileObject.w...
def extern_store_dict(self, context_handle, vals_ptr, vals_len): """Given storage and an array of Handles, return a new Handle to represent the dict. Array of handles alternates keys and values (i.e. key0, value0, key1, value1, ...). It is assumed that an even number of values were passed. """ c =...
Given storage and an array of Handles, return a new Handle to represent the dict. Array of handles alternates keys and values (i.e. key0, value0, key1, value1, ...). It is assumed that an even number of values were passed.
Below is the the instruction that describes the task: ### Input: Given storage and an array of Handles, return a new Handle to represent the dict. Array of handles alternates keys and values (i.e. key0, value0, key1, value1, ...). It is assumed that an even number of values were passed. ### Response: def...
def check_recommended_global_attributes(self, dataset): ''' Check the global recommended attributes for 1.1 templates. These go an extra step besides just checking that they exist. :param netCDF4.Dataset dataset: An open netCDF dataset Basic "does it exist" checks are done in B...
Check the global recommended attributes for 1.1 templates. These go an extra step besides just checking that they exist. :param netCDF4.Dataset dataset: An open netCDF dataset Basic "does it exist" checks are done in BaseNCEICheck:check_recommended :title = "" ; //........................
Below is the the instruction that describes the task: ### Input: Check the global recommended attributes for 1.1 templates. These go an extra step besides just checking that they exist. :param netCDF4.Dataset dataset: An open netCDF dataset Basic "does it exist" checks are done in BaseNCEI...
def get_min_max_mag(self): "Return the minimum and maximum magnitudes" mag, num_bins = self._get_min_mag_and_num_bins() return mag, mag + self. bin_width * (num_bins - 1)
Return the minimum and maximum magnitudes
Below is the the instruction that describes the task: ### Input: Return the minimum and maximum magnitudes ### Response: def get_min_max_mag(self): "Return the minimum and maximum magnitudes" mag, num_bins = self._get_min_mag_and_num_bins() return mag, mag + self. bin_width * (num_bins - 1)
def normal_curve_single(obj, u, normalize): """ Evaluates the curve normal vector at the input parameter, u. Curve normal is calculated from the 2nd derivative of the curve at the input parameter, u. The output returns a list containing the starting point (i.e. origin) of the vector and the vector itself. ...
Evaluates the curve normal vector at the input parameter, u. Curve normal is calculated from the 2nd derivative of the curve at the input parameter, u. The output returns a list containing the starting point (i.e. origin) of the vector and the vector itself. :param obj: input curve :type obj: abstract...
Below is the the instruction that describes the task: ### Input: Evaluates the curve normal vector at the input parameter, u. Curve normal is calculated from the 2nd derivative of the curve at the input parameter, u. The output returns a list containing the starting point (i.e. origin) of the vector and th...
def get_app_guid(self, app_name): """ Returns the GUID for the app instance with the given name. """ summary = self.space.get_space_summary() for app in summary['apps']: if app['name'] == app_name: return app['guid']
Returns the GUID for the app instance with the given name.
Below is the the instruction that describes the task: ### Input: Returns the GUID for the app instance with the given name. ### Response: def get_app_guid(self, app_name): """ Returns the GUID for the app instance with the given name. """ summary = self.space.get_spa...
def unmount(self, client): """Unmounts a backend within Vault""" getattr(client, self.unmount_fun)(mount_point=self.path)
Unmounts a backend within Vault
Below is the the instruction that describes the task: ### Input: Unmounts a backend within Vault ### Response: def unmount(self, client): """Unmounts a backend within Vault""" getattr(client, self.unmount_fun)(mount_point=self.path)
def map(self, fn, *seq): "Perform a map operation distributed among the workers. Will " "block until done." results = Queue() args = zip(*seq) for seq in args: j = SimpleJob(results, fn, seq) self.put(j) # Aggregate results r = [] ...
Perform a map operation distributed among the workers. Will
Below is the the instruction that describes the task: ### Input: Perform a map operation distributed among the workers. Will ### Response: def map(self, fn, *seq): "Perform a map operation distributed among the workers. Will " "block until done." results = Queue() args = zip(*seq) ...
def broadcast_transaction(self, hex_tx): """ Dispatch a raw transaction to the network. """ resp = self.obj.sendrawtransaction(hex_tx) if len(resp) > 0: return {'transaction_hash': resp, 'success': True} else: return error_reply('Invalid response from bit...
Dispatch a raw transaction to the network.
Below is the the instruction that describes the task: ### Input: Dispatch a raw transaction to the network. ### Response: def broadcast_transaction(self, hex_tx): """ Dispatch a raw transaction to the network. """ resp = self.obj.sendrawtransaction(hex_tx) if len(resp) > 0: ...
def async_task(self, func): """ Execute handler as task and return None. Use this decorator for slow handlers (with timeouts) .. code-block:: python3 @dp.message_handler(commands=['command']) @dp.async_task async def cmd_with_timeout(message: types.M...
Execute handler as task and return None. Use this decorator for slow handlers (with timeouts) .. code-block:: python3 @dp.message_handler(commands=['command']) @dp.async_task async def cmd_with_timeout(message: types.Message): await asyncio.sleep(120...
Below is the the instruction that describes the task: ### Input: Execute handler as task and return None. Use this decorator for slow handlers (with timeouts) .. code-block:: python3 @dp.message_handler(commands=['command']) @dp.async_task async def cmd_with_tim...
def create_parser(): """Setup argument Parsing.""" description = """RPC Release Diff Generator -------------------------- Finds changes in OpenStack-Ansible, OpenStack-Ansible roles, and OpenStack projects between two RPC-OpenStack revisions. """ parser = argparse.ArgumentParser( usage='%(prog)s'...
Setup argument Parsing.
Below is the the instruction that describes the task: ### Input: Setup argument Parsing. ### Response: def create_parser(): """Setup argument Parsing.""" description = """RPC Release Diff Generator -------------------------- Finds changes in OpenStack-Ansible, OpenStack-Ansible roles, and OpenStack projec...
def intersect(self, **kwargs): """ Intersect a Line or Point Collection and the Shoreline Returns the point of intersection along the coastline Should also return a linestring buffer around the interseciton point so we can calculate the direction to bounce a part...
Intersect a Line or Point Collection and the Shoreline Returns the point of intersection along the coastline Should also return a linestring buffer around the interseciton point so we can calculate the direction to bounce a particle.
Below is the the instruction that describes the task: ### Input: Intersect a Line or Point Collection and the Shoreline Returns the point of intersection along the coastline Should also return a linestring buffer around the interseciton point so we can calculate the direction to...
def save_file(self, filename, text): """Save the given text under the given control filename and the current path.""" if not filename.endswith('.py'): filename += '.py' path = os.path.join(self.currentpath, filename) with open(path, 'w', encoding="utf-8") as file_: ...
Save the given text under the given control filename and the current path.
Below is the the instruction that describes the task: ### Input: Save the given text under the given control filename and the current path. ### Response: def save_file(self, filename, text): """Save the given text under the given control filename and the current path.""" if not file...
def _set_configspec(self, section, copy): """ Called by validate. Handles setting the configspec on subsections including sections to be validated by __many__ """ configspec = section.configspec many = configspec.get('__many__') if isinstance(many, dict): ...
Called by validate. Handles setting the configspec on subsections including sections to be validated by __many__
Below is the the instruction that describes the task: ### Input: Called by validate. Handles setting the configspec on subsections including sections to be validated by __many__ ### Response: def _set_configspec(self, section, copy): """ Called by validate. Handles setting the configspec on...
def create(self, datapath, tracker_urls, comment=None, root_name=None, created_by=None, private=False, no_date=False, progress=None, callback=None): """ Create a metafile with the path given on object creation. Returns the last metafile dict that was written...
Create a metafile with the path given on object creation. Returns the last metafile dict that was written (as an object, not bencoded).
Below is the the instruction that describes the task: ### Input: Create a metafile with the path given on object creation. Returns the last metafile dict that was written (as an object, not bencoded). ### Response: def create(self, datapath, tracker_urls, comment=None, root_name=None, ...
def make_codon_list(protein_seq, template_dna=None, include_stop=True): """ Return a list of codons that would be translated to the given protein sequence. Codons are picked first to minimize the mutations relative to a template DNA sequence and second to prefer "optimal" codons. """ codon_l...
Return a list of codons that would be translated to the given protein sequence. Codons are picked first to minimize the mutations relative to a template DNA sequence and second to prefer "optimal" codons.
Below is the the instruction that describes the task: ### Input: Return a list of codons that would be translated to the given protein sequence. Codons are picked first to minimize the mutations relative to a template DNA sequence and second to prefer "optimal" codons. ### Response: def make_codon_list(...