code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def isheavy(self): """ Check if the current selection is too large. """ selection_size_bytes = self._calc_selection_size() if selection_size_bytes > self.MAX_DATA_ARRAY_SIZE: return True else: return False
Check if the current selection is too large.
Below is the the instruction that describes the task: ### Input: Check if the current selection is too large. ### Response: def isheavy(self): """ Check if the current selection is too large. """ selection_size_bytes = self._calc_selection_size() if selection_size_bytes > self.MAX...
def is_fasta(filename): """Check if filename is FASTA based on extension Return: Boolean """ if re.search("\.fa*s[ta]*$", filename, flags=re.I): return True elif re.search("\.fa$", filename, flags=re.I): return True else: return False
Check if filename is FASTA based on extension Return: Boolean
Below is the the instruction that describes the task: ### Input: Check if filename is FASTA based on extension Return: Boolean ### Response: def is_fasta(filename): """Check if filename is FASTA based on extension Return: Boolean """ if re.search("\.fa*s[ta]*$", filename, flags=...
def set_representative_structure(self, seq_outdir=None, struct_outdir=None, pdb_file_type=None, engine='needle', always_use_homology=False, rez_cutoff=0.0, seq_ident_cutoff=0.5, allow_missing_on_termini=0.2, a...
Set a representative structure from a structure in the structures attribute. Each gene can have a combination of the following, which will be analyzed to set a representative structure. * Homology model(s) * Ranked PDBs * BLASTed PDBs If the ``always_use_homology`` ...
Below is the the instruction that describes the task: ### Input: Set a representative structure from a structure in the structures attribute. Each gene can have a combination of the following, which will be analyzed to set a representative structure. * Homology model(s) * Ranked PDB...
def features(entrystream, type=None, traverse=False): """ Pull features out of the specified entry stream. :param entrystream: a stream of entries :param type: retrieve only features of the specified type; set to :code:`None` to retrieve all features :param traverse: by default, on...
Pull features out of the specified entry stream. :param entrystream: a stream of entries :param type: retrieve only features of the specified type; set to :code:`None` to retrieve all features :param traverse: by default, only top-level features are selected; set to :c...
Below is the the instruction that describes the task: ### Input: Pull features out of the specified entry stream. :param entrystream: a stream of entries :param type: retrieve only features of the specified type; set to :code:`None` to retrieve all features :param traverse: by default,...
def native_(s, encoding='latin-1', errors='strict'): ''' Python 3: If ``s`` is an instance of ``text_type``, return ``s``, otherwise return ``str(s, encoding, errors)`` Python 2: If ``s`` is an instance of ``text_type``, return ``s.encode(encoding, errors)``, otherwise return ``str(s)`` ''' ...
Python 3: If ``s`` is an instance of ``text_type``, return ``s``, otherwise return ``str(s, encoding, errors)`` Python 2: If ``s`` is an instance of ``text_type``, return ``s.encode(encoding, errors)``, otherwise return ``str(s)``
Below is the the instruction that describes the task: ### Input: Python 3: If ``s`` is an instance of ``text_type``, return ``s``, otherwise return ``str(s, encoding, errors)`` Python 2: If ``s`` is an instance of ``text_type``, return ``s.encode(encoding, errors)``, otherwise return ``str(s)`` ### Res...
def set_ram(self, ram): """ Set the RAM amount for the GNS3 VM. :param ram: amount of memory """ yield from self._execute("modifyvm", [self._vmname, "--memory", str(ram)], timeout=3) log.info("GNS3 VM RAM amount set to {}".format(ram))
Set the RAM amount for the GNS3 VM. :param ram: amount of memory
Below is the the instruction that describes the task: ### Input: Set the RAM amount for the GNS3 VM. :param ram: amount of memory ### Response: def set_ram(self, ram): """ Set the RAM amount for the GNS3 VM. :param ram: amount of memory """ yield from self._execut...
def write(self, out): """Write ICC Profile to the file.""" if not self.rawtagtable: self.rawtagtable = self.rawtagdict.items() tags = tagblock(self.rawtagtable) self.writeHeader(out, 128 + len(tags)) out.write(tags) out.flush() return self
Write ICC Profile to the file.
Below is the the instruction that describes the task: ### Input: Write ICC Profile to the file. ### Response: def write(self, out): """Write ICC Profile to the file.""" if not self.rawtagtable: self.rawtagtable = self.rawtagdict.items() tags = tagblock(self.rawtagtable) ...
def lookup(ctx, path): """ Determine which tests intersect a source interval. """ regions = parse_intervals(path, as_context=ctx.obj['semantic']) _report_from_regions(regions, ctx.obj)
Determine which tests intersect a source interval.
Below is the the instruction that describes the task: ### Input: Determine which tests intersect a source interval. ### Response: def lookup(ctx, path): """ Determine which tests intersect a source interval. """ regions = parse_intervals(path, as_context=ctx.obj['semantic']) _report_from_region...
def temporary_file_path(root_dir=None, cleanup=True, suffix='', permissions=None): """ A with-context that creates a temporary file and returns its path. :API: public You may specify the following keyword args: :param str root_dir: The parent directory to create the temporary file. :param bool c...
A with-context that creates a temporary file and returns its path. :API: public You may specify the following keyword args: :param str root_dir: The parent directory to create the temporary file. :param bool cleanup: Whether or not to clean up the temporary file.
Below is the the instruction that describes the task: ### Input: A with-context that creates a temporary file and returns its path. :API: public You may specify the following keyword args: :param str root_dir: The parent directory to create the temporary file. :param bool cleanup: Whether or not t...
def _parse_cod_segment(cls, fptr): """Parse the COD segment. Parameters ---------- fptr : file Open file object. Returns ------- CODSegment The current COD segment. """ offset = fptr.tell() - 2 read_buffer = fptr....
Parse the COD segment. Parameters ---------- fptr : file Open file object. Returns ------- CODSegment The current COD segment.
Below is the the instruction that describes the task: ### Input: Parse the COD segment. Parameters ---------- fptr : file Open file object. Returns ------- CODSegment The current COD segment. ### Response: def _parse_cod_segment(cls, fptr): ...
def _auto_help_text(self, help_text): """Given a method with a docstring, convert the docstring to more CLI appropriate wording, and also disambiguate the word "object" on the base class docstrings. """ # Delete API docs if there are any. api_doc_delimiter = '=====API DOC...
Given a method with a docstring, convert the docstring to more CLI appropriate wording, and also disambiguate the word "object" on the base class docstrings.
Below is the the instruction that describes the task: ### Input: Given a method with a docstring, convert the docstring to more CLI appropriate wording, and also disambiguate the word "object" on the base class docstrings. ### Response: def _auto_help_text(self, help_text): """Given a metho...
def groups_data(self): """All data about all groups (get-only). :getter: Returns all data about all groups :type: list of GroupData """ return _ListProxy(GroupData(num, name, symbol, variant) for (num, name, symbol, variant) in...
All data about all groups (get-only). :getter: Returns all data about all groups :type: list of GroupData
Below is the the instruction that describes the task: ### Input: All data about all groups (get-only). :getter: Returns all data about all groups :type: list of GroupData ### Response: def groups_data(self): """All data about all groups (get-only). :getter: Returns all data about ...
def _set_BC(self, pores, bctype, bcvalues=None, mode='merge'): r""" Apply boundary conditions to specified pores Parameters ---------- pores : array_like The pores where the boundary conditions should be applied bctype : string Specifies the type...
r""" Apply boundary conditions to specified pores Parameters ---------- pores : array_like The pores where the boundary conditions should be applied bctype : string Specifies the type or the name of boundary condition to apply. The types can ...
Below is the the instruction that describes the task: ### Input: r""" Apply boundary conditions to specified pores Parameters ---------- pores : array_like The pores where the boundary conditions should be applied bctype : string Specifies the type o...
def add(self, item): """add a Text MessageElement to the existing Text Strings can be passed and are automatically converted in to item.Text() :param item: Text text, an element to add to the text """ if self._is_stringable(item) or self._is_qstring(item): ...
add a Text MessageElement to the existing Text Strings can be passed and are automatically converted in to item.Text() :param item: Text text, an element to add to the text
Below is the the instruction that describes the task: ### Input: add a Text MessageElement to the existing Text Strings can be passed and are automatically converted in to item.Text() :param item: Text text, an element to add to the text ### Response: def add(self, item): """add a...
def get_mac_address_table_input_request_type_get_next_request_last_mac_address_details_last_mac_address(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_mac_address_table = ET.Element("get_mac_address_table") config = get_mac_address_table inp...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def get_mac_address_table_input_request_type_get_next_request_last_mac_address_details_last_mac_address(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_ma...
def merge_base(self, left='master', right='HEAD'): """Returns the merge-base of master and HEAD in bash: `git merge-base left right`""" return self._check_output(['merge-base', left, right], raise_type=Scm.LocalException)
Returns the merge-base of master and HEAD in bash: `git merge-base left right`
Below is the the instruction that describes the task: ### Input: Returns the merge-base of master and HEAD in bash: `git merge-base left right` ### Response: def merge_base(self, left='master', right='HEAD'): """Returns the merge-base of master and HEAD in bash: `git merge-base left right`""" return self._...
def _process_json(data): """ return a list of GradCommittee objects. """ requests = [] for item in data: committee = GradCommittee() committee.status = item.get('status') committee.committee_type = item.get('committeeType') committee.dept = item.get('dept') co...
return a list of GradCommittee objects.
Below is the the instruction that describes the task: ### Input: return a list of GradCommittee objects. ### Response: def _process_json(data): """ return a list of GradCommittee objects. """ requests = [] for item in data: committee = GradCommittee() committee.status = item.get...
def _conn_string_odbc(self, db_key, instance=None, conn_key=None, db_name=None): ''' Return a connection string to use with odbc ''' if instance: dsn, host, username, password, database, driver = self._get_access_info(instance, db_key, db_name) elif conn_key: dsn,...
Return a connection string to use with odbc
Below is the the instruction that describes the task: ### Input: Return a connection string to use with odbc ### Response: def _conn_string_odbc(self, db_key, instance=None, conn_key=None, db_name=None): ''' Return a connection string to use with odbc ''' if instance: dsn, host,...
def _parse_args(args): """Setup argparser to process arguments and generate help""" # parser uses custom usage string, with 'usage: ' removed, as it is # added automatically via argparser. parser = argparse.ArgumentParser(description="Remove and/or rearrange " + "se...
Setup argparser to process arguments and generate help
Below is the the instruction that describes the task: ### Input: Setup argparser to process arguments and generate help ### Response: def _parse_args(args): """Setup argparser to process arguments and generate help""" # parser uses custom usage string, with 'usage: ' removed, as it is # added automati...
def get_requests_for_local_unit(relation_name=None): """Extract any certificates data targeted at this unit down relation_name. :param relation_name: str Name of relation to check for data. :returns: List of bundles of certificates. :rtype: List of dicts """ local_name = local_unit().replace('/...
Extract any certificates data targeted at this unit down relation_name. :param relation_name: str Name of relation to check for data. :returns: List of bundles of certificates. :rtype: List of dicts
Below is the the instruction that describes the task: ### Input: Extract any certificates data targeted at this unit down relation_name. :param relation_name: str Name of relation to check for data. :returns: List of bundles of certificates. :rtype: List of dicts ### Response: def get_requests_for_loc...
def get_connection(backend=None, fail_silently=False, **kwargs): """Load an email backend and return an instance of it. If backend is None (default), use settings.EMAIL_BACKEND. Both fail_silently and other keyword arguments are used in the constructor of the backend. """ klass = perform_import(...
Load an email backend and return an instance of it. If backend is None (default), use settings.EMAIL_BACKEND. Both fail_silently and other keyword arguments are used in the constructor of the backend.
Below is the the instruction that describes the task: ### Input: Load an email backend and return an instance of it. If backend is None (default), use settings.EMAIL_BACKEND. Both fail_silently and other keyword arguments are used in the constructor of the backend. ### Response: def get_connection(back...
def __check_spaces(sentence): """ Here we check to see that we have the correct number of spaces in the correct locations. :param _sentence: :return: """ # We have to run the process multiple times: # Once to search for all spaces, and check if there are adjoining spaces; # The seco...
Here we check to see that we have the correct number of spaces in the correct locations. :param _sentence: :return:
Below is the the instruction that describes the task: ### Input: Here we check to see that we have the correct number of spaces in the correct locations. :param _sentence: :return: ### Response: def __check_spaces(sentence): """ Here we check to see that we have the correct number of spaces in the...
def mmGetPlotStability(self, title="Stability", showReset=False, resetShading=0.25): """ Returns plot of the overlap metric between union SDRs within a sequence. @param title an optional title for the figure @return (Plot) plot """ plot = Plot(self, title) self._mmCo...
Returns plot of the overlap metric between union SDRs within a sequence. @param title an optional title for the figure @return (Plot) plot
Below is the the instruction that describes the task: ### Input: Returns plot of the overlap metric between union SDRs within a sequence. @param title an optional title for the figure @return (Plot) plot ### Response: def mmGetPlotStability(self, title="Stability", showReset=False, ...
def binify_and_jsd(df1, df2, bins, pair=None): """Binify and calculate jensen-shannon divergence between two dataframes Parameters ---------- df1, df2 : pandas.DataFrames Dataframes to calculate JSD between columns of. Must have overlapping column names bins : array-like Bin...
Binify and calculate jensen-shannon divergence between two dataframes Parameters ---------- df1, df2 : pandas.DataFrames Dataframes to calculate JSD between columns of. Must have overlapping column names bins : array-like Bins to use for transforming df{1,2} into probability dis...
Below is the the instruction that describes the task: ### Input: Binify and calculate jensen-shannon divergence between two dataframes Parameters ---------- df1, df2 : pandas.DataFrames Dataframes to calculate JSD between columns of. Must have overlapping column names bins : array-l...
def rule_action(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") rule = ET.SubElement(config, "rule", xmlns="urn:brocade.com:mgmt:brocade-aaa") index_key = ET.SubElement(rule, "index") index_key.text = kwargs.pop('index') action = ET.SubEl...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def rule_action(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") rule = ET.SubElement(config, "rule", xmlns="urn:brocade.com:mgmt:brocade-aaa") index_k...
def formula_balance(model): """Calculate formula compositions for each reaction. Call :func:`reaction_formula` for each reaction. Yield (reaction, result) pairs, where result has two formula compositions or `None`. Args: model: :class:`psamm.datasource.native.NativeModel`. """ # M...
Calculate formula compositions for each reaction. Call :func:`reaction_formula` for each reaction. Yield (reaction, result) pairs, where result has two formula compositions or `None`. Args: model: :class:`psamm.datasource.native.NativeModel`.
Below is the the instruction that describes the task: ### Input: Calculate formula compositions for each reaction. Call :func:`reaction_formula` for each reaction. Yield (reaction, result) pairs, where result has two formula compositions or `None`. Args: model: :class:`psamm.datasource.nat...
def run(self): """Run the test batch """ self.info_log("The test batch is ready.") self.executed_tests = [] for test in self.tests: localhost_instance = LocalhostInstance( runner=self, browser_config=self.browser_config, ...
Run the test batch
Below is the the instruction that describes the task: ### Input: Run the test batch ### Response: def run(self): """Run the test batch """ self.info_log("The test batch is ready.") self.executed_tests = [] for test in self.tests: localhost_instance = Localhost...
def ks_synth(freq): """ Synthesize the given frequency into a Stream by using a model based on Karplus-Strong. """ ks_mem = (sum(lz.sinusoid(x * freq) for x in [1, 3, 9]) + lz.white_noise() + lz.Stream(-1, 1)) / 5 return lz.karplus_strong(freq, memory=ks_mem)
Synthesize the given frequency into a Stream by using a model based on Karplus-Strong.
Below is the the instruction that describes the task: ### Input: Synthesize the given frequency into a Stream by using a model based on Karplus-Strong. ### Response: def ks_synth(freq): """ Synthesize the given frequency into a Stream by using a model based on Karplus-Strong. """ ks_mem = (sum(lz.sinus...
def _get_hanging_wall_term(self, C, dists, rup): """ Compute and return hanging wall model term, see page 1038. """ if rup.dip == 90.0: return np.zeros_like(dists.rx) else: Fhw = np.zeros_like(dists.rx) Fhw[dists.rx > 0] = 1. # Comp...
Compute and return hanging wall model term, see page 1038.
Below is the the instruction that describes the task: ### Input: Compute and return hanging wall model term, see page 1038. ### Response: def _get_hanging_wall_term(self, C, dists, rup): """ Compute and return hanging wall model term, see page 1038. """ if rup.dip == 90.0: ...
def __add_sentence_root_node(self, sent_number): """ adds the root node of a sentence to the graph and the list of sentences (``self.sentences``). the node has a ``tokens` attribute, which contains a list of the tokens (token node IDs) of this sentence. Parameters ------...
adds the root node of a sentence to the graph and the list of sentences (``self.sentences``). the node has a ``tokens` attribute, which contains a list of the tokens (token node IDs) of this sentence. Parameters ---------- sent_number : int the index of the sentence ...
Below is the the instruction that describes the task: ### Input: adds the root node of a sentence to the graph and the list of sentences (``self.sentences``). the node has a ``tokens` attribute, which contains a list of the tokens (token node IDs) of this sentence. Parameters ------...
def get_occurrence(self, occ): """ Return a persisted occurrences matching the occ and remove it from lookup since it has already been matched """ return self.lookup.pop( (occ.event, occ.original_start, occ.original_end), occ)
Return a persisted occurrences matching the occ and remove it from lookup since it has already been matched
Below is the the instruction that describes the task: ### Input: Return a persisted occurrences matching the occ and remove it from lookup since it has already been matched ### Response: def get_occurrence(self, occ): """ Return a persisted occurrences matching the occ and remove it from ...
def _compute_labels(self, element, data, mapping): """ Computes labels for the nodes and adds it to the data. """ if element.vdims: edges = Dataset(element)[element[element.vdims[0].name]>0] nodes = list(np.unique([edges.dimension_values(i) for i in range(2)])) ...
Computes labels for the nodes and adds it to the data.
Below is the the instruction that describes the task: ### Input: Computes labels for the nodes and adds it to the data. ### Response: def _compute_labels(self, element, data, mapping): """ Computes labels for the nodes and adds it to the data. """ if element.vdims: edges...
def create(context, name, component_types, active, product_id, data): """create(context, name, component_types, active, product_id, data) Create a topic. >>> dcictl topic-create [OPTIONS] :param string name: Name of the topic [required] :param string component_types: list of component types separ...
create(context, name, component_types, active, product_id, data) Create a topic. >>> dcictl topic-create [OPTIONS] :param string name: Name of the topic [required] :param string component_types: list of component types separated by commas :param boolean active: Set the topic in the (in)active sta...
Below is the the instruction that describes the task: ### Input: create(context, name, component_types, active, product_id, data) Create a topic. >>> dcictl topic-create [OPTIONS] :param string name: Name of the topic [required] :param string component_types: list of component types separated by ...
def convert_layer(node, **kwargs): """Convert MXNet layer to ONNX""" op = str(node["op"]) if op not in MXNetGraph.registry_: raise AttributeError("No conversion function registered for op type %s yet." % op) convert_func = MXNetGraph.registry_[op] return convert_func(...
Convert MXNet layer to ONNX
Below is the the instruction that describes the task: ### Input: Convert MXNet layer to ONNX ### Response: def convert_layer(node, **kwargs): """Convert MXNet layer to ONNX""" op = str(node["op"]) if op not in MXNetGraph.registry_: raise AttributeError("No conversion function re...
def get_backend_init_list(backend_vals): """Turn backend config dict into command line items.""" cmd_list = [] for (key, val) in backend_vals.items(): cmd_list.append('-backend-config') cmd_list.append(key + '=' + val) return cmd_list
Turn backend config dict into command line items.
Below is the the instruction that describes the task: ### Input: Turn backend config dict into command line items. ### Response: def get_backend_init_list(backend_vals): """Turn backend config dict into command line items.""" cmd_list = [] for (key, val) in backend_vals.items(): cmd_list.append...
def add_role(ctx, role): """Grant a role to an existing user""" if role is None: log('Specify the role with --role') return if ctx.obj['username'] is None: log('Specify the username with --username') return change_user = ctx.obj['db'].objectmodels['user'].find_one({ ...
Grant a role to an existing user
Below is the the instruction that describes the task: ### Input: Grant a role to an existing user ### Response: def add_role(ctx, role): """Grant a role to an existing user""" if role is None: log('Specify the role with --role') return if ctx.obj['username'] is None: log('Speci...
def remove_row(self, row_num=None): """ Remove a row from the grid """ #DeleteRows(self, pos, numRows, updateLabel if not row_num and row_num != 0: row_num = self.GetNumberRows() - 1 label = self.GetCellValue(row_num, 0) self.DeleteRows(pos=row_num, nu...
Remove a row from the grid
Below is the the instruction that describes the task: ### Input: Remove a row from the grid ### Response: def remove_row(self, row_num=None): """ Remove a row from the grid """ #DeleteRows(self, pos, numRows, updateLabel if not row_num and row_num != 0: row_num =...
def guess_version_by_running_live_package( pkg_key, default="?" ): # type: (str,str) -> Any """Guess the version of a pkg when pip doesn't provide it. :param str pkg_key: key of the package :param str default: default version to return if unable to find :returns: version :rtype: string ""...
Guess the version of a pkg when pip doesn't provide it. :param str pkg_key: key of the package :param str default: default version to return if unable to find :returns: version :rtype: string
Below is the the instruction that describes the task: ### Input: Guess the version of a pkg when pip doesn't provide it. :param str pkg_key: key of the package :param str default: default version to return if unable to find :returns: version :rtype: string ### Response: def guess_version_by_runnin...
def keys(self): """Get the keys associated with this lease. :return: """ result = self.client.post(self.client.get_url("/kv/lease/timetolive"), json={"ID": self.id, "keys": True}) keys = result['keys'] if ...
Get the keys associated with this lease. :return:
Below is the the instruction that describes the task: ### Input: Get the keys associated with this lease. :return: ### Response: def keys(self): """Get the keys associated with this lease. :return: """ result = self.client.post(self.client.get_url("/kv/lease/timetolive"), ...
def updated_on(self): """The updated timestamp of the object as a datetime.datetime.""" s = self._info.get('updated', None) return dateutil.parser.parse(s) if s else None
The updated timestamp of the object as a datetime.datetime.
Below is the the instruction that describes the task: ### Input: The updated timestamp of the object as a datetime.datetime. ### Response: def updated_on(self): """The updated timestamp of the object as a datetime.datetime.""" s = self._info.get('updated', None) return dateutil.parser.parse(s) if s els...
def overlay_gateway_map_vlan_vni_auto(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels") name_key = ET.SubElement(overlay_gateway, "name") name_...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def overlay_gateway_map_vlan_vni_auto(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:br...
def use(parser, token): ''' Counterpart to `macro`, lets you render any block/macro in place. ''' args, kwargs = parser.parse_args(token) assert isinstance(args[0], ast.Str), \ 'First argument to "include" tag must be a string' name = args[0].s action = ast.YieldFrom( value...
Counterpart to `macro`, lets you render any block/macro in place.
Below is the the instruction that describes the task: ### Input: Counterpart to `macro`, lets you render any block/macro in place. ### Response: def use(parser, token): ''' Counterpart to `macro`, lets you render any block/macro in place. ''' args, kwargs = parser.parse_args(token) assert isin...
def _base_body(self): """Return the base XML body, which has the following form: .. code :: xml <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Header> <credentials xmlns="http://www.sonos.com/Services/1.1"> <sessionId>self._session_i...
Return the base XML body, which has the following form: .. code :: xml <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Header> <credentials xmlns="http://www.sonos.com/Services/1.1"> <sessionId>self._session_id</sessionId> <dev...
Below is the the instruction that describes the task: ### Input: Return the base XML body, which has the following form: .. code :: xml <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Header> <credentials xmlns="http://www.sonos.com/Services/1.1"> ...
def get_sources(self, resources): """ Filter resources based on which have this reference """ rtype = self.rtype # E.g. category label = self.props.label # E.g. category1 result = [ resource for resource in resources.values() if is_reference_target(...
Filter resources based on which have this reference
Below is the the instruction that describes the task: ### Input: Filter resources based on which have this reference ### Response: def get_sources(self, resources): """ Filter resources based on which have this reference """ rtype = self.rtype # E.g. category label = self.props.label # E...
def roche_requiv_contact_L1(q, sma, compno=1): """ TODO: add documentation """ return ConstraintParameter(q._bundle, "requiv_contact_L1(%s, %d)" % (", ".join(["{%s}" % (param.uniquetwig if hasattr(param, 'uniquetwig') else param.expr) for param in (q, sma)]), compno))
TODO: add documentation
Below is the the instruction that describes the task: ### Input: TODO: add documentation ### Response: def roche_requiv_contact_L1(q, sma, compno=1): """ TODO: add documentation """ return ConstraintParameter(q._bundle, "requiv_contact_L1(%s, %d)" % (", ".join(["{%s}" % (param.uniquetwig if hasattr...
def to_pinyin(s, accented=True): """Convert *s* to Pinyin. If *accented* is ``True``, diacritics are added to the Pinyin syllables. If it's ``False``, numbers are used to indicate tone. """ identity = identify(s) if identity == PINYIN: if _has_accented_vowels(s): return s i...
Convert *s* to Pinyin. If *accented* is ``True``, diacritics are added to the Pinyin syllables. If it's ``False``, numbers are used to indicate tone.
Below is the the instruction that describes the task: ### Input: Convert *s* to Pinyin. If *accented* is ``True``, diacritics are added to the Pinyin syllables. If it's ``False``, numbers are used to indicate tone. ### Response: def to_pinyin(s, accented=True): """Convert *s* to Pinyin. If *accen...
def report_list(self, service_id=None, service_port=None, hostfilter=None): """ Returns a list of ports with IPs, banners and vulnerabilities (warning, slow!) :param service_id: t_services.id :param service_port: Port (tcp/#, udp/#, info/#) :param hostfilter: Valid hostfilter or...
Returns a list of ports with IPs, banners and vulnerabilities (warning, slow!) :param service_id: t_services.id :param service_port: Port (tcp/#, udp/#, info/#) :param hostfilter: Valid hostfilter or None :return: { 'port': [t_hosts.f_ipaddr, t_services.f_banner, (t_vulndata...
Below is the the instruction that describes the task: ### Input: Returns a list of ports with IPs, banners and vulnerabilities (warning, slow!) :param service_id: t_services.id :param service_port: Port (tcp/#, udp/#, info/#) :param hostfilter: Valid hostfilter or None :return: { 'p...
def magnetic_deformation(structure_A, structure_B): """ Calculates 'magnetic deformation proxy', a measure of deformation (norm of finite strain) between 'non-magnetic' (non-spin-polarized) and ferromagnetic structures. Adapted from Bocarsly et al. 2017, doi: 10.1021/acs.chemmater.6b04729 ...
Calculates 'magnetic deformation proxy', a measure of deformation (norm of finite strain) between 'non-magnetic' (non-spin-polarized) and ferromagnetic structures. Adapted from Bocarsly et al. 2017, doi: 10.1021/acs.chemmater.6b04729 :param structure_A: Structure :param structure_B: Struct...
Below is the the instruction that describes the task: ### Input: Calculates 'magnetic deformation proxy', a measure of deformation (norm of finite strain) between 'non-magnetic' (non-spin-polarized) and ferromagnetic structures. Adapted from Bocarsly et al. 2017, doi: 10.1021/acs.chemmater.6b04...
def get_parameter_tbl(self, parameter): """ This method returns parameters as list of dict in case of table type parameter """ par = [] for entry in parameter.findall('Entry'): instance = defaultdict(list) instance['Instance'] = entry.find('Instanc...
This method returns parameters as list of dict in case of table type parameter
Below is the the instruction that describes the task: ### Input: This method returns parameters as list of dict in case of table type parameter ### Response: def get_parameter_tbl(self, parameter): """ This method returns parameters as list of dict in case of table type parameter ...
def dump(): """ dump function """ try: sensors = subprocess.check_output('sensors').decode('utf-8') except (FileNotFoundError, subprocess.CalledProcessError): print("Couldn't read CPU temp") else: cores = [] for line in sensors.splitlines(): if lin...
dump function
Below is the the instruction that describes the task: ### Input: dump function ### Response: def dump(): """ dump function """ try: sensors = subprocess.check_output('sensors').decode('utf-8') except (FileNotFoundError, subprocess.CalledProcessError): print("Couldn't read CPU ...
def version(*names, **kwargs): ''' Common interface for obtaining the version of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.version vim salt '*' pkg_resource.version foo bar baz salt '*' pkg_resource.version 'python*' ''' ret = {} v...
Common interface for obtaining the version of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.version vim salt '*' pkg_resource.version foo bar baz salt '*' pkg_resource.version 'python*'
Below is the the instruction that describes the task: ### Input: Common interface for obtaining the version of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.version vim salt '*' pkg_resource.version foo bar baz salt '*' pkg_resource.version 'python*' ...
def _format_obj_count(objects): """Formats object count.""" result = [] regex = re.compile(r'<(?P<type>\w+) \'(?P<name>\S+)\'>') for obj_type, obj_count in objects.items(): if obj_count != 0: match = re.findall(regex, repr(obj_type)) if match: obj_type, ob...
Formats object count.
Below is the the instruction that describes the task: ### Input: Formats object count. ### Response: def _format_obj_count(objects): """Formats object count.""" result = [] regex = re.compile(r'<(?P<type>\w+) \'(?P<name>\S+)\'>') for obj_type, obj_count in objects.items(): if obj_count != 0...
def release_pool(self): """Release pool and all its connection""" if self._current_acquired > 0: raise PoolException("Can't release pool: %d connection(s) still acquired" % self._current_acquired) while not self._pool.empty(): conn = self.acquire() conn.close(...
Release pool and all its connection
Below is the the instruction that describes the task: ### Input: Release pool and all its connection ### Response: def release_pool(self): """Release pool and all its connection""" if self._current_acquired > 0: raise PoolException("Can't release pool: %d connection(s) still acquired" %...
def _config_getter(get_opt, key, value_regex=None, cwd=None, user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' Common code fo...
Common code for config.get_* functions, builds and runs the git CLI command and returns the result dict for the calling function to parse.
Below is the the instruction that describes the task: ### Input: Common code for config.get_* functions, builds and runs the git CLI command and returns the result dict for the calling function to parse. ### Response: def _config_getter(get_opt, key, value_regex=None, ...
def cleaned_request(request_type, *args, **kwargs): """ Perform a cleaned requests request """ s = requests.Session() # this removes netrc checking s.trust_env = False return s.request(request_type, *args, **kwargs)
Perform a cleaned requests request
Below is the the instruction that describes the task: ### Input: Perform a cleaned requests request ### Response: def cleaned_request(request_type, *args, **kwargs): """ Perform a cleaned requests request """ s = requests.Session() # this removes netrc checking s.trust_env = False return s.requ...
def get_queryset(self): ''' Only serve site-specific languages ''' request = self.request return (Languages.for_site(request.site) .languages.filter().order_by('pk'))
Only serve site-specific languages
Below is the the instruction that describes the task: ### Input: Only serve site-specific languages ### Response: def get_queryset(self): ''' Only serve site-specific languages ''' request = self.request return (Languages.for_site(request.site) .lang...
def add_duration( dt, # type: Union[datetime, date] years=0, # type: int months=0, # type: int weeks=0, # type: int days=0, # type: int hours=0, # type: int minutes=0, # type: int seconds=0, # type: int microseconds=0, ): # type: (...) -> Union[datetime, date] """ A...
Adds a duration to a date/datetime instance.
Below is the the instruction that describes the task: ### Input: Adds a duration to a date/datetime instance. ### Response: def add_duration( dt, # type: Union[datetime, date] years=0, # type: int months=0, # type: int weeks=0, # type: int days=0, # type: int hours=0, # type: int ...
def _normalize_data_types(self, strategy): ''' some contexts only retrieves strings, giving back right type ''' for k, v in strategy.iteritems(): if not isinstance(v, str): # There is probably nothing to do continue if v == 'true': ...
some contexts only retrieves strings, giving back right type
Below is the the instruction that describes the task: ### Input: some contexts only retrieves strings, giving back right type ### Response: def _normalize_data_types(self, strategy): ''' some contexts only retrieves strings, giving back right type ''' for k, v in strategy.iteritems(): i...
def from_(self, win_pts): """Reverse of :meth:`to_`.""" # make relative to center pixel to convert from window # graphics space to standard X/Y coordinate space win_pts = np.asarray(win_pts, dtype=np.float) has_z = (win_pts.shape[-1] > 2) ctr_pt = list(self.viewer.get_ce...
Reverse of :meth:`to_`.
Below is the the instruction that describes the task: ### Input: Reverse of :meth:`to_`. ### Response: def from_(self, win_pts): """Reverse of :meth:`to_`.""" # make relative to center pixel to convert from window # graphics space to standard X/Y coordinate space win_pts = np.asarra...
def compile(schema, pointer, context, scope=None): """ Compiles schema with `JSON Schema`_ draft-04. :param schema: obj to compile :type schema: Mapping :param pointer: uri of the schema :type pointer: Pointer, str :param context: context of this schema :type context: Context .. _`...
Compiles schema with `JSON Schema`_ draft-04. :param schema: obj to compile :type schema: Mapping :param pointer: uri of the schema :type pointer: Pointer, str :param context: context of this schema :type context: Context .. _`JSON Schema`: http://json-schema.org
Below is the the instruction that describes the task: ### Input: Compiles schema with `JSON Schema`_ draft-04. :param schema: obj to compile :type schema: Mapping :param pointer: uri of the schema :type pointer: Pointer, str :param context: context of this schema :type context: Context ...
def parse_rst_params(doc): """ Parse a reStructuredText docstring and return a dictionary with parameter names and descriptions. >>> doc = ''' ... :param foo: foo parameter ... foo parameter ... ... :param bar: bar parameter ... :param baz: baz parameter ... ...
Parse a reStructuredText docstring and return a dictionary with parameter names and descriptions. >>> doc = ''' ... :param foo: foo parameter ... foo parameter ... ... :param bar: bar parameter ... :param baz: baz parameter ... baz parameter ... baz parameter...
Below is the the instruction that describes the task: ### Input: Parse a reStructuredText docstring and return a dictionary with parameter names and descriptions. >>> doc = ''' ... :param foo: foo parameter ... foo parameter ... ... :param bar: bar parameter ... :param baz: ...
def _handle_hidden_tables(self, tbl_list, attr_name): """ Return list of tables, potentially removing hidden elements Parameters ---------- tbl_list : list of node-like Type of list elements will vary depending upon parser used attr_name : str Nam...
Return list of tables, potentially removing hidden elements Parameters ---------- tbl_list : list of node-like Type of list elements will vary depending upon parser used attr_name : str Name of the accessor for retrieving HTML attributes Returns ...
Below is the the instruction that describes the task: ### Input: Return list of tables, potentially removing hidden elements Parameters ---------- tbl_list : list of node-like Type of list elements will vary depending upon parser used attr_name : str Name of ...
def detach(self): """ Detach the source from its customer. """ # First, wipe default source on all customers that use this. Customer.objects.filter(default_source=self.id).update(default_source=None) try: # TODO - we could use the return value of sync_from_stripe_data # or call its internals - self...
Detach the source from its customer.
Below is the the instruction that describes the task: ### Input: Detach the source from its customer. ### Response: def detach(self): """ Detach the source from its customer. """ # First, wipe default source on all customers that use this. Customer.objects.filter(default_source=self.id).update(default_s...
def codespan(self, text): """Rendering inline `code` text. :param text: text content for inline code. """ text = escape(text.rstrip(), smart_amp=False) return '<code>%s</code>' % text
Rendering inline `code` text. :param text: text content for inline code.
Below is the the instruction that describes the task: ### Input: Rendering inline `code` text. :param text: text content for inline code. ### Response: def codespan(self, text): """Rendering inline `code` text. :param text: text content for inline code. """ text = escape(t...
def profileTM(tmClass, tmDim, nRuns): """ profiling performance of TemporalMemory (TM) using the python cProfile module and ordered by cumulative time, see how to run on command-line above. @param tmClass implementation of TM (cpp, py, ..) @param tmDim number of columns in TM @param nRuns number of calls...
profiling performance of TemporalMemory (TM) using the python cProfile module and ordered by cumulative time, see how to run on command-line above. @param tmClass implementation of TM (cpp, py, ..) @param tmDim number of columns in TM @param nRuns number of calls of the profiled code (epochs)
Below is the the instruction that describes the task: ### Input: profiling performance of TemporalMemory (TM) using the python cProfile module and ordered by cumulative time, see how to run on command-line above. @param tmClass implementation of TM (cpp, py, ..) @param tmDim number of columns in TM @para...
def set_subnet_name(name): ''' Set the local subnet name :param str name: The new local subnet name .. note:: Spaces are changed to dashes. Other special characters are removed. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash ...
Set the local subnet name :param str name: The new local subnet name .. note:: Spaces are changed to dashes. Other special characters are removed. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash The following will be set as 'Mikes-Mac...
Below is the the instruction that describes the task: ### Input: Set the local subnet name :param str name: The new local subnet name .. note:: Spaces are changed to dashes. Other special characters are removed. :return: True if successful, False if not :rtype: bool CLI Example: ...
def first(seq, key=lambda x: bool(x), default=None, apply=lambda x: x): """Give the first value that satisfies the key test. Args: seq (iterable): key (callable): test for each element of iterable default: returned when all elements fail test apply (callable): applied to element...
Give the first value that satisfies the key test. Args: seq (iterable): key (callable): test for each element of iterable default: returned when all elements fail test apply (callable): applied to element before return, but not to default value Returns: first element in seq tha...
Below is the the instruction that describes the task: ### Input: Give the first value that satisfies the key test. Args: seq (iterable): key (callable): test for each element of iterable default: returned when all elements fail test apply (callable): applied to element before re...
def init_run(shell, no_daemon, daemon_options, daemon_outfile): """ Configure your shell. Add the following line in your shell RC file and then you are ready to go:: eval $(%(prog)s) To check if your shell is supported, simply run:: %(prog)s --no-daemon If you want to specify sh...
Configure your shell. Add the following line in your shell RC file and then you are ready to go:: eval $(%(prog)s) To check if your shell is supported, simply run:: %(prog)s --no-daemon If you want to specify shell other than $SHELL, you can give --shell option:: eval $(%(pro...
Below is the the instruction that describes the task: ### Input: Configure your shell. Add the following line in your shell RC file and then you are ready to go:: eval $(%(prog)s) To check if your shell is supported, simply run:: %(prog)s --no-daemon If you want to specify shell oth...
def _treat_devices_removed(self): """Process the removed devices.""" for device in self._removed_ports.copy(): eventlet.spawn_n(self._process_removed_port, device)
Process the removed devices.
Below is the the instruction that describes the task: ### Input: Process the removed devices. ### Response: def _treat_devices_removed(self): """Process the removed devices.""" for device in self._removed_ports.copy(): eventlet.spawn_n(self._process_removed_port, device)
def _ParseFileEntry(self, knowledge_base, file_entry): """Parses artifact file system data for a preprocessing attribute. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. file_entry (dfvfs.FileEntry): file entry that contains the artifact value data. Rais...
Parses artifact file system data for a preprocessing attribute. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. file_entry (dfvfs.FileEntry): file entry that contains the artifact value data. Raises: errors.PreProcessFail: if the preprocessing fails.
Below is the the instruction that describes the task: ### Input: Parses artifact file system data for a preprocessing attribute. Args: knowledge_base (KnowledgeBase): to fill with preprocessing information. file_entry (dfvfs.FileEntry): file entry that contains the artifact value data. ...
def _get_all_groups(): ''' A helper function that gets a list of group objects for all groups on the machine Returns: iter: A list of objects for all groups on the machine ''' with salt.utils.winapi.Com(): nt = win32com.client.Dispatch('AdsNameSpaces') results = nt.GetObject...
A helper function that gets a list of group objects for all groups on the machine Returns: iter: A list of objects for all groups on the machine
Below is the the instruction that describes the task: ### Input: A helper function that gets a list of group objects for all groups on the machine Returns: iter: A list of objects for all groups on the machine ### Response: def _get_all_groups(): ''' A helper function that gets a list of g...
def go_aspect(self, go_term): """ For GO terms, returns F, C, or P corresponding to its aspect """ if not go_term.startswith("GO:"): return None else: # Check ancestors for root terms if self.is_molecular_function(go_term): retu...
For GO terms, returns F, C, or P corresponding to its aspect
Below is the the instruction that describes the task: ### Input: For GO terms, returns F, C, or P corresponding to its aspect ### Response: def go_aspect(self, go_term): """ For GO terms, returns F, C, or P corresponding to its aspect """ if not go_term.startswith("GO:"): ...
def update_migration_issue_users(self, id, user_id, workflow_state, content_migration_id): """ Update a migration issue. Update the workflow_state of a migration issue """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """...
Update a migration issue. Update the workflow_state of a migration issue
Below is the the instruction that describes the task: ### Input: Update a migration issue. Update the workflow_state of a migration issue ### Response: def update_migration_issue_users(self, id, user_id, workflow_state, content_migration_id): """ Update a migration issue. Up...
def run(data, samples, noreverse, maxindels, force, ipyclient): """ run the major functions for clustering within samples """ ## list of samples to submit to queue subsamples = [] ## if sample is already done skip for sample in samples: ## If sample not in state 2 don't try to cluster it. ...
run the major functions for clustering within samples
Below is the the instruction that describes the task: ### Input: run the major functions for clustering within samples ### Response: def run(data, samples, noreverse, maxindels, force, ipyclient): """ run the major functions for clustering within samples """ ## list of samples to submit to queue subsa...
def name(self, id): """ resolves a name, both short and long names. """ data = self.bytes(id, 'N') if not data: print("%x has no name" % id) return if data[:1] == b'\x00': nameid, = struct.unpack_from(">" + self.fmt, data, 1) ...
resolves a name, both short and long names.
Below is the the instruction that describes the task: ### Input: resolves a name, both short and long names. ### Response: def name(self, id): """ resolves a name, both short and long names. """ data = self.bytes(id, 'N') if not data: print("%x has no name"...
def _to_timezone(self, dt): """Takes a naive timezone with an utc value and return it formatted as a local timezone.""" tz = self._get_tz() utc_dt = pytz.utc.localize(dt) return utc_dt.astimezone(tz)
Takes a naive timezone with an utc value and return it formatted as a local timezone.
Below is the the instruction that describes the task: ### Input: Takes a naive timezone with an utc value and return it formatted as a local timezone. ### Response: def _to_timezone(self, dt): """Takes a naive timezone with an utc value and return it formatted as a local timezone.""" ...
def _abs32(ins): """ Absolute value of top of the stack (32 bits in DEHL) """ output = _32bit_oper(ins.quad[2]) output.append('call __ABS32') output.append('push de') output.append('push hl') REQUIRES.add('abs32.asm') return output
Absolute value of top of the stack (32 bits in DEHL)
Below is the the instruction that describes the task: ### Input: Absolute value of top of the stack (32 bits in DEHL) ### Response: def _abs32(ins): """ Absolute value of top of the stack (32 bits in DEHL) """ output = _32bit_oper(ins.quad[2]) output.append('call __ABS32') output.append('push d...
def dimension_sort(odict, kdims, vdims, key_index): """ Sorts data by key using usual Python tuple sorting semantics or sorts in categorical order for any categorical Dimensions. """ sortkws = {} ndims = len(kdims) dimensions = kdims+vdims indexes = [(dimensions[i], int(i not in range(nd...
Sorts data by key using usual Python tuple sorting semantics or sorts in categorical order for any categorical Dimensions.
Below is the the instruction that describes the task: ### Input: Sorts data by key using usual Python tuple sorting semantics or sorts in categorical order for any categorical Dimensions. ### Response: def dimension_sort(odict, kdims, vdims, key_index): """ Sorts data by key using usual Python tuple so...
def partitions(self): """ Iterable containing disk's partition objects. Objects in the iterable are :py:class:`~hwd.storage.Partition` instances. """ if not self._partitions: self._partitions = [Partition(d, self) for d in self.device.c...
Iterable containing disk's partition objects. Objects in the iterable are :py:class:`~hwd.storage.Partition` instances.
Below is the the instruction that describes the task: ### Input: Iterable containing disk's partition objects. Objects in the iterable are :py:class:`~hwd.storage.Partition` instances. ### Response: def partitions(self): """ Iterable containing disk's partition objects. Objects in the itera...
def add_child( self, parent_slug=None, title="", level="", start_date=None, end_date=None, date_expression=None, notes=[], ): """ Adds a new resource component parented within `parent`. :param str parent_slug: The parent's slug...
Adds a new resource component parented within `parent`. :param str parent_slug: The parent's slug. :param str title: A title for the record. :param str level: The level of description. :return: The ID of the newly-created record.
Below is the the instruction that describes the task: ### Input: Adds a new resource component parented within `parent`. :param str parent_slug: The parent's slug. :param str title: A title for the record. :param str level: The level of description. :return: The ID of the newly-cre...
def load_config(strCsvCnfg, lgcTest=False, lgcPrint=True): """ Load py_pRF_mapping config file. Parameters ---------- strCsvCnfg : string Absolute file path of config file. lgcTest : Boolean Whether this is a test (pytest). If yes, absolute path of this function will be ...
Load py_pRF_mapping config file. Parameters ---------- strCsvCnfg : string Absolute file path of config file. lgcTest : Boolean Whether this is a test (pytest). If yes, absolute path of this function will be prepended to config file paths. lgcPrint : Boolean Print co...
Below is the the instruction that describes the task: ### Input: Load py_pRF_mapping config file. Parameters ---------- strCsvCnfg : string Absolute file path of config file. lgcTest : Boolean Whether this is a test (pytest). If yes, absolute path of this function will be pr...
def _set_bpdu_drop(self, v, load=False): """ Setter method for bpdu_drop, mapped from YANG variable /interface/hundredgigabitethernet/bpdu_drop (container) If this variable is read-only (config: false) in the source YANG file, then _set_bpdu_drop is considered as a private method. Backends looking t...
Setter method for bpdu_drop, mapped from YANG variable /interface/hundredgigabitethernet/bpdu_drop (container) If this variable is read-only (config: false) in the source YANG file, then _set_bpdu_drop is considered as a private method. Backends looking to populate this variable should do so via calling...
Below is the the instruction that describes the task: ### Input: Setter method for bpdu_drop, mapped from YANG variable /interface/hundredgigabitethernet/bpdu_drop (container) If this variable is read-only (config: false) in the source YANG file, then _set_bpdu_drop is considered as a private method. Ba...
def disable_ap_port(self, apid, port): """临时关闭接入点端口 临时关闭接入点端口,仅对公网域名,公网ip有效。 Args: - apid: 接入点ID - port: 要设置的端口号 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} ...
临时关闭接入点端口 临时关闭接入点端口,仅对公网域名,公网ip有效。 Args: - apid: 接入点ID - port: 要设置的端口号 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
Below is the the instruction that describes the task: ### Input: 临时关闭接入点端口 临时关闭接入点端口,仅对公网域名,公网ip有效。 Args: - apid: 接入点ID - port: 要设置的端口号 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg ...
def to_si(self, values, from_unit): """Return values in SI and the units to which the values have been converted.""" if from_unit in self.si_units: return values, from_unit elif from_unit == 'ton': return self.to_unit(values, 'tonne', from_unit), 'tonne' else: ...
Return values in SI and the units to which the values have been converted.
Below is the the instruction that describes the task: ### Input: Return values in SI and the units to which the values have been converted. ### Response: def to_si(self, values, from_unit): """Return values in SI and the units to which the values have been converted.""" if from_unit in self.si_unit...
def hybrid_forward(self, F, x, sampled_values, label, w_all, b_all): """Forward computation.""" sampled_candidates, expected_count_sampled, expected_count_true = sampled_values # (num_sampled, in_unit) w_sampled = w_all.slice(begin=(0, 0), end=(self._num_sampled, None)) w_true = ...
Forward computation.
Below is the the instruction that describes the task: ### Input: Forward computation. ### Response: def hybrid_forward(self, F, x, sampled_values, label, w_all, b_all): """Forward computation.""" sampled_candidates, expected_count_sampled, expected_count_true = sampled_values # (num_sampled...
def getPositionNearType(self, tagSet, idx): """Return the closest field position where given ASN.1 type is allowed. Some ASN.1 serialisation allow for skipping optional and defaulted fields. Some constructed ASN.1 types allow reordering of the fields. When recovering such objects it may...
Return the closest field position where given ASN.1 type is allowed. Some ASN.1 serialisation allow for skipping optional and defaulted fields. Some constructed ASN.1 types allow reordering of the fields. When recovering such objects it may be important to know at which field position, in field...
Below is the the instruction that describes the task: ### Input: Return the closest field position where given ASN.1 type is allowed. Some ASN.1 serialisation allow for skipping optional and defaulted fields. Some constructed ASN.1 types allow reordering of the fields. When recovering such ...
def csv_to_json(csv_filepath, json_filepath, fieldnames, ignore_first_line=True): """ Convert a CSV file in `csv_filepath` into a JSON file in `json_filepath`. Parameters ---------- csv_filepath: str Path to the input CSV file. json_filepath: str Path to the output JSON file. Will ...
Convert a CSV file in `csv_filepath` into a JSON file in `json_filepath`. Parameters ---------- csv_filepath: str Path to the input CSV file. json_filepath: str Path to the output JSON file. Will be overwritten if exists. fieldnames: List[str] Names of the fields in the CS...
Below is the the instruction that describes the task: ### Input: Convert a CSV file in `csv_filepath` into a JSON file in `json_filepath`. Parameters ---------- csv_filepath: str Path to the input CSV file. json_filepath: str Path to the output JSON file. Will be overwritten if exi...
def add_node(node, **kwds): """add_node from Sphinx """ nodes._add_node_class_names([node.__name__]) for key, val in kwds.iteritems(): try: visit, depart = val except ValueError: raise ValueError('Value for key %r must be a ' '(vis...
add_node from Sphinx
Below is the the instruction that describes the task: ### Input: add_node from Sphinx ### Response: def add_node(node, **kwds): """add_node from Sphinx """ nodes._add_node_class_names([node.__name__]) for key, val in kwds.iteritems(): try: visit, depart = val except Valu...
def execute(self, fn, *args, **kwargs): """Execute an operation and return the result.""" if self.in_executor_context(): corofn = asyncio.coroutine(lambda: fn(*args, **kwargs)) return corofn() future = self.submit(fn, *args, **kwargs) return future.result()
Execute an operation and return the result.
Below is the the instruction that describes the task: ### Input: Execute an operation and return the result. ### Response: def execute(self, fn, *args, **kwargs): """Execute an operation and return the result.""" if self.in_executor_context(): corofn = asyncio.coroutine(lambda: fn(*args...
def rl(self, r): """ Like the above, bus uses carry """ if self.C is None or not is_number(self.regs[r]): self.set(r, None) self.set_flag(None) return self.rlc(r) tmp = self.C v_ = self.getv(self.regs[r]) self.C = v_ & 1 ...
Like the above, bus uses carry
Below is the the instruction that describes the task: ### Input: Like the above, bus uses carry ### Response: def rl(self, r): """ Like the above, bus uses carry """ if self.C is None or not is_number(self.regs[r]): self.set(r, None) self.set_flag(None) r...
def _get_value(data_structure, key): """Return the value of a data_structure given a path. :param data_structure: Dictionary, list or subscriptable object. :param key: Array with the defined path ordered. """ if len(key) == 0: raise KeyError() value = data_structure[key[0]] if len(k...
Return the value of a data_structure given a path. :param data_structure: Dictionary, list or subscriptable object. :param key: Array with the defined path ordered.
Below is the the instruction that describes the task: ### Input: Return the value of a data_structure given a path. :param data_structure: Dictionary, list or subscriptable object. :param key: Array with the defined path ordered. ### Response: def _get_value(data_structure, key): """Return the value o...
def _parse_allele_data(self): """Parse alleles for ClinVar VCF, overrides parent method.""" # Get allele frequencies if they exist. pref_freq, frequencies = self._parse_frequencies() info_clnvar_single_tags = ['ALLELEID', 'CLNSIG', 'CLNHGVS'] cln_data = {x.lower(): self.info[x]...
Parse alleles for ClinVar VCF, overrides parent method.
Below is the the instruction that describes the task: ### Input: Parse alleles for ClinVar VCF, overrides parent method. ### Response: def _parse_allele_data(self): """Parse alleles for ClinVar VCF, overrides parent method.""" # Get allele frequencies if they exist. pref_freq, frequencies ...
def random_subsets(self, relative_sizes, by_duration=False, balance_labels=False, label_list_ids=None): """ Create a bunch of subsets with the given sizes relative to the size or duration of the full corpus. Basically the same as calling ``random_subset`` or ``random_subset_by_duration`` multipl...
Create a bunch of subsets with the given sizes relative to the size or duration of the full corpus. Basically the same as calling ``random_subset`` or ``random_subset_by_duration`` multiple times with different values. But this method makes sure that every subset contains only utterances, that a...
Below is the the instruction that describes the task: ### Input: Create a bunch of subsets with the given sizes relative to the size or duration of the full corpus. Basically the same as calling ``random_subset`` or ``random_subset_by_duration`` multiple times with different values. But this method ...
def get_course_track_selection_url(course_run, query_parameters): """ Return track selection url for the given course. Arguments: course_run (dict): A dictionary containing course run metadata. query_parameters (dict): A dictionary containing query parameters to be added to course selection...
Return track selection url for the given course. Arguments: course_run (dict): A dictionary containing course run metadata. query_parameters (dict): A dictionary containing query parameters to be added to course selection url. Raises: (KeyError): Raised when course run dict does not ha...
Below is the the instruction that describes the task: ### Input: Return track selection url for the given course. Arguments: course_run (dict): A dictionary containing course run metadata. query_parameters (dict): A dictionary containing query parameters to be added to course selection url. ...
def remove_tags(self, tags): """ Add tags to a server. Accepts tags as strings or Tag objects. """ if self.cloud_manager.remove_tags(self, tags): new_tags = [tag for tag in self.tags if tag not in tags] object.__setattr__(self, 'tags', new_tags)
Add tags to a server. Accepts tags as strings or Tag objects.
Below is the the instruction that describes the task: ### Input: Add tags to a server. Accepts tags as strings or Tag objects. ### Response: def remove_tags(self, tags): """ Add tags to a server. Accepts tags as strings or Tag objects. """ if self.cloud_manager.remove_tags(self, tag...
def as_region_filter(shape_list, origin=1): """ Often, the regions files implicitly assume the lower-left corner of the image as a coordinate (1,1). However, the python convetion is that the array index starts from 0. By default (origin = 1), coordinates of the returned mpl artists have coordinate s...
Often, the regions files implicitly assume the lower-left corner of the image as a coordinate (1,1). However, the python convetion is that the array index starts from 0. By default (origin = 1), coordinates of the returned mpl artists have coordinate shifted by (1, 1). If you do not want this shift, use...
Below is the the instruction that describes the task: ### Input: Often, the regions files implicitly assume the lower-left corner of the image as a coordinate (1,1). However, the python convetion is that the array index starts from 0. By default (origin = 1), coordinates of the returned mpl artists have...
def load_files(files, tag=None, sat_id=None, altitude_bin=None): '''Loads a list of COSMIC data files, supplied by user. Returns a list of dicts, a dict for each file. ''' output = [None]*len(files) drop_idx = [] for (i,file) in enumerate(files): try: #data = net...
Loads a list of COSMIC data files, supplied by user. Returns a list of dicts, a dict for each file.
Below is the the instruction that describes the task: ### Input: Loads a list of COSMIC data files, supplied by user. Returns a list of dicts, a dict for each file. ### Response: def load_files(files, tag=None, sat_id=None, altitude_bin=None): '''Loads a list of COSMIC data files, supplied by user. ...
def get_nmr_prize_pool(self, round_num=0, tournament=1): """Get NMR prize pool for the given round and tournament. Args: round_num (int, optional): The round you are interested in, defaults to current round. tournament (int, optional): ID of the tournament, defau...
Get NMR prize pool for the given round and tournament. Args: round_num (int, optional): The round you are interested in, defaults to current round. tournament (int, optional): ID of the tournament, defaults to 1 Returns: decimal.Decimal: prize pool i...
Below is the the instruction that describes the task: ### Input: Get NMR prize pool for the given round and tournament. Args: round_num (int, optional): The round you are interested in, defaults to current round. tournament (int, optional): ID of the tournament, defa...
def _append_bytes(self, value, _file): # pylint: disable=no-self-use """Call this function to write bytes contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file """ # binascii.b2a_base64(value) -> plistlib.Data #...
Call this function to write bytes contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file
Below is the the instruction that describes the task: ### Input: Call this function to write bytes contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file ### Response: def _append_bytes(self, value, _file): # pylint: disable=no-self-use ...
def shape(self): """Compute the shape of the dataset as (rows, cols).""" if not self.data: return (0, 0) return (len(self.data), len(self.dimensions))
Compute the shape of the dataset as (rows, cols).
Below is the the instruction that describes the task: ### Input: Compute the shape of the dataset as (rows, cols). ### Response: def shape(self): """Compute the shape of the dataset as (rows, cols).""" if not self.data: return (0, 0) return (len(self.data), len(self.dimensions))