code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def from_config(config): """ Generate a matrix from a configuration dictionary. """ matrix = {} variables = config.keys() for entries in product(*config.values()): combination = dict(zip(variables, entries)) include = True for value in combination.values(): fo...
Generate a matrix from a configuration dictionary.
Below is the the instruction that describes the task: ### Input: Generate a matrix from a configuration dictionary. ### Response: def from_config(config): """ Generate a matrix from a configuration dictionary. """ matrix = {} variables = config.keys() for entries in product(*config.values()...
def path_dispatch_rename(rename_like_method): """ decorator for rename-like function, that need dispatch on 2 arguments """ def _wrapper_method(self, old_path, new_path): old_path, _old_path, old_sentinel = _split_path(old_path); new_path, _new_path, new_sentine...
decorator for rename-like function, that need dispatch on 2 arguments
Below is the the instruction that describes the task: ### Input: decorator for rename-like function, that need dispatch on 2 arguments ### Response: def path_dispatch_rename(rename_like_method): """ decorator for rename-like function, that need dispatch on 2 arguments """ def _wrap...
def insert_rule(self, chain, src=None, dest=None, target=None): """Insert a new rule in the chain """ if not chain: raise ValueError("Invalid chain") if not target: raise ValueError("Invalid target") if not (src or dest): raise ValueError("Need...
Insert a new rule in the chain
Below is the the instruction that describes the task: ### Input: Insert a new rule in the chain ### Response: def insert_rule(self, chain, src=None, dest=None, target=None): """Insert a new rule in the chain """ if not chain: raise ValueError("Invalid chain") if not targ...
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'collections') and self.collections is not None: _dict['collections'] = [x._to_dict() for x in self.collections] return _dict
Return a json dictionary representing this model.
Below is the the instruction that describes the task: ### Input: Return a json dictionary representing this model. ### Response: def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'collections') and self.collections is not None: ...
def destroy(self, deal_id, contact_id) : """ Remove an associated contact Remove a deal's associated contact If a deal with the supplied unique identifier does not exist, it returns an error This operation cannot be undone :calls: ``delete /deals/{deal_id}/associated_co...
Remove an associated contact Remove a deal's associated contact If a deal with the supplied unique identifier does not exist, it returns an error This operation cannot be undone :calls: ``delete /deals/{deal_id}/associated_contacts/{contact_id}`` :param int deal_id: Unique iden...
Below is the the instruction that describes the task: ### Input: Remove an associated contact Remove a deal's associated contact If a deal with the supplied unique identifier does not exist, it returns an error This operation cannot be undone :calls: ``delete /deals/{deal_id}/assoc...
def main( output_file: str, entry_point: Optional[str], console_script: Optional[str], python: Optional[str], site_packages: Optional[str], compressed: bool, compile_pyc: bool, extend_pythonpath: bool, pip_args: List[str], ) -> None: """ Shiv is a command line utility for bui...
Shiv is a command line utility for building fully self-contained Python zipapps as outlined in PEP 441, but with all their dependencies included!
Below is the the instruction that describes the task: ### Input: Shiv is a command line utility for building fully self-contained Python zipapps as outlined in PEP 441, but with all their dependencies included! ### Response: def main( output_file: str, entry_point: Optional[str], console_script: Op...
def get_data(self): "Get the data for this blob" array = ctypes.POINTER(ctypes.c_char * len(self)) return ctypes.cast(self.data, array).contents.raw
Get the data for this blob
Below is the the instruction that describes the task: ### Input: Get the data for this blob ### Response: def get_data(self): "Get the data for this blob" array = ctypes.POINTER(ctypes.c_char * len(self)) return ctypes.cast(self.data, array).contents.raw
def get_default(self, *args, **kwargs): """Get the default parameters as defined in the Settings instance. This function proceeds to seamlessly retrieve the argument to pass through, depending on either it was overidden or not: If no argument was overridden in a function of the toolbox,...
Get the default parameters as defined in the Settings instance. This function proceeds to seamlessly retrieve the argument to pass through, depending on either it was overidden or not: If no argument was overridden in a function of the toolbox, the default argument will be set to ``None...
Below is the the instruction that describes the task: ### Input: Get the default parameters as defined in the Settings instance. This function proceeds to seamlessly retrieve the argument to pass through, depending on either it was overidden or not: If no argument was overridden in a functi...
def apply(self, func, keep_attrs=None, args=(), **kwargs): """Apply a function over the data variables in this dataset. Parameters ---------- func : function Function which can be called in the form `func(x, *args, **kwargs)` to transform each DataArray `x` in th...
Apply a function over the data variables in this dataset. Parameters ---------- func : function Function which can be called in the form `func(x, *args, **kwargs)` to transform each DataArray `x` in this dataset into another DataArray. keep_attrs : bo...
Below is the the instruction that describes the task: ### Input: Apply a function over the data variables in this dataset. Parameters ---------- func : function Function which can be called in the form `func(x, *args, **kwargs)` to transform each DataArray `x` in thi...
def get_manuelles(self, site, code_parametre, debut, fin, court=False): """ Recupération des mesures manuelles (labo) pour un site site: numéro du site (voir fonction liste_sites_prelevement) code_parametre: code ISO du paramètre à rechercher (C6H6=V4) debut: date de début du pr...
Recupération des mesures manuelles (labo) pour un site site: numéro du site (voir fonction liste_sites_prelevement) code_parametre: code ISO du paramètre à rechercher (C6H6=V4) debut: date de début du premier prélèvement fin: date de fin du dernier prélèvement court: Renvoie un ...
Below is the the instruction that describes the task: ### Input: Recupération des mesures manuelles (labo) pour un site site: numéro du site (voir fonction liste_sites_prelevement) code_parametre: code ISO du paramètre à rechercher (C6H6=V4) debut: date de début du premier prélèvement ...
def ExtractEvents(self, parser_mediator, registry_key, **kwargs): """Extracts events from a Windows Registry key. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows ...
Extracts events from a Windows Registry key. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
Below is the the instruction that describes the task: ### Input: Extracts events from a Windows Registry key. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Regi...
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ from pyramid.config import Configurator config = Configurator(settings=settings) # include twitcher components config.include('twitcher.config') config.include('twitcher.frontpage') confi...
This function returns a Pyramid WSGI application.
Below is the the instruction that describes the task: ### Input: This function returns a Pyramid WSGI application. ### Response: def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ from pyramid.config import Configurator config = Configurator(settings...
def post(self, text, attachments=None): """Post a message as the bot. :param str text: the text of the message :param attachments: a list of attachments :type attachments: :class:`list` :return: ``True`` if successful :rtype: bool """ return self.manager....
Post a message as the bot. :param str text: the text of the message :param attachments: a list of attachments :type attachments: :class:`list` :return: ``True`` if successful :rtype: bool
Below is the the instruction that describes the task: ### Input: Post a message as the bot. :param str text: the text of the message :param attachments: a list of attachments :type attachments: :class:`list` :return: ``True`` if successful :rtype: bool ### Response: def pos...
def main(): """Open B6/M8 file, filter entries by E-Value, and write said entries""" for entry in b6_evalue_filter(args.b6, args.e_value): args.output.write(entry.write())
Open B6/M8 file, filter entries by E-Value, and write said entries
Below is the the instruction that describes the task: ### Input: Open B6/M8 file, filter entries by E-Value, and write said entries ### Response: def main(): """Open B6/M8 file, filter entries by E-Value, and write said entries""" for entry in b6_evalue_filter(args.b6, args.e_value): args.output.w...
def is_installed(self, pkgname): """Given a package name, returns whether it is installed in the environment :param str pkgname: The name of a package :return: Whether the supplied package is installed in the environment :rtype: bool """ return any(d for d in self.get_d...
Given a package name, returns whether it is installed in the environment :param str pkgname: The name of a package :return: Whether the supplied package is installed in the environment :rtype: bool
Below is the the instruction that describes the task: ### Input: Given a package name, returns whether it is installed in the environment :param str pkgname: The name of a package :return: Whether the supplied package is installed in the environment :rtype: bool ### Response: def is_instal...
def normalize(self, mode="max", value=1): """ Normalize the spectrum with respect to the sum of intensity Args: mode (str): Normalization mode. Supported modes are "max" (set the max y value to value, e.g., in XRD patterns), "sum" (set the sum of y to...
Normalize the spectrum with respect to the sum of intensity Args: mode (str): Normalization mode. Supported modes are "max" (set the max y value to value, e.g., in XRD patterns), "sum" (set the sum of y to a value, i.e., like a probability density). value...
Below is the the instruction that describes the task: ### Input: Normalize the spectrum with respect to the sum of intensity Args: mode (str): Normalization mode. Supported modes are "max" (set the max y value to value, e.g., in XRD patterns), "sum" (set the sum ...
def simxCopyPasteObjects(clientID, objectHandles, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' c_objectHandles = (ct.c_int*len(objectHandles))(*objectHandles) c_objectHandles = ct.cast(c_objectHandles,ct.POINTER(ct.c_int)) # IronPytho...
Please have a look at the function description/documentation in the V-REP user manual
Below is the the instruction that describes the task: ### Input: Please have a look at the function description/documentation in the V-REP user manual ### Response: def simxCopyPasteObjects(clientID, objectHandles, operationMode): ''' Please have a look at the function description/documentation in the V-RE...
def list_subdomains(self, domain, limit=None, offset=None): """ Returns a list of all subdomains for the specified domain. """ return domain.list_subdomains(limit=limit, offset=offset)
Returns a list of all subdomains for the specified domain.
Below is the the instruction that describes the task: ### Input: Returns a list of all subdomains for the specified domain. ### Response: def list_subdomains(self, domain, limit=None, offset=None): """ Returns a list of all subdomains for the specified domain. """ return domain.list...
def dump_dataflow_images(df, index=0, batched=True, number=1000, output_dir=None, scale=1, resize=None, viz=None, flipRGB=False): """ Dump or visualize images of a :class:`DataFlow`. Args: df (DataFlow): the DataFlow. ...
Dump or visualize images of a :class:`DataFlow`. Args: df (DataFlow): the DataFlow. index (int): the index of the image component. batched (bool): whether the component contains batched images (NHW or NHWC) or not (HW or HWC). number (int): how many datapoint to take fro...
Below is the the instruction that describes the task: ### Input: Dump or visualize images of a :class:`DataFlow`. Args: df (DataFlow): the DataFlow. index (int): the index of the image component. batched (bool): whether the component contains batched images (NHW or NHWC) or ...
def to_rst(cls) -> str: """Output the registry as reStructuredText, for documentation.""" sep_line = '+' + 6 * '-' + '+' + '-' * 71 + '+\n' blank_line = '|' + 78 * ' ' + '|\n' table = '' for group in cls.groups: table += sep_line table += blank_line ...
Output the registry as reStructuredText, for documentation.
Below is the the instruction that describes the task: ### Input: Output the registry as reStructuredText, for documentation. ### Response: def to_rst(cls) -> str: """Output the registry as reStructuredText, for documentation.""" sep_line = '+' + 6 * '-' + '+' + '-' * 71 + '+\n' blank_line =...
def _run_check(self): """Execute a check command. Returns: True if the exit code of the command is 0 otherwise False. """ cmd = shlex.split(self.config['check_cmd']) self.log.info("running %s", ' '.join(cmd)) proc = subprocess.Popen(cmd, stdout=subprocess.PI...
Execute a check command. Returns: True if the exit code of the command is 0 otherwise False.
Below is the the instruction that describes the task: ### Input: Execute a check command. Returns: True if the exit code of the command is 0 otherwise False. ### Response: def _run_check(self): """Execute a check command. Returns: True if the exit code of the comma...
def is_unlocked(self): """``False`` if this is a private key that is protected with a passphrase and has not yet been unlocked, otherwise ``True``""" if self.is_public: return True if not self.is_protected: return True return self._key.unlocked
``False`` if this is a private key that is protected with a passphrase and has not yet been unlocked, otherwise ``True``
Below is the the instruction that describes the task: ### Input: ``False`` if this is a private key that is protected with a passphrase and has not yet been unlocked, otherwise ``True`` ### Response: def is_unlocked(self): """``False`` if this is a private key that is protected with a passphrase and has no...
def members(self): """Gets members of current team Returns: list of User Throws: RTMServiceError when request failed """ resp = self._rtm_client.get('v1/current_team.members?all=true') if resp.is_fail(): raise RTMServiceError( ...
Gets members of current team Returns: list of User Throws: RTMServiceError when request failed
Below is the the instruction that describes the task: ### Input: Gets members of current team Returns: list of User Throws: RTMServiceError when request failed ### Response: def members(self): """Gets members of current team Returns: list of Us...
def _encrypt(cipher, key, data, iv, padding): """ Encrypts plaintext :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-16 bytes long :param data: The plaintext - a byte...
Encrypts plaintext :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-16 bytes long :param data: The plaintext - a byte string :param iv: The initialization vector ...
Below is the the instruction that describes the task: ### Input: Encrypts plaintext :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-16 bytes long :param data: The plainte...
def SetConsoleTextAttribute(stream_id, attrs): """Set a console text attribute.""" handle = handles[stream_id] return windll.kernel32.SetConsoleTextAttribute(handle, attrs)
Set a console text attribute.
Below is the the instruction that describes the task: ### Input: Set a console text attribute. ### Response: def SetConsoleTextAttribute(stream_id, attrs): """Set a console text attribute.""" handle = handles[stream_id] return windll.kernel32.SetConsoleTextAttribute(handle, attrs)
def system(self, cmd): """Execute a command in a subshell. Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- int : child's exitstatus """ # Get likely encoding for the output. enc = DE...
Execute a command in a subshell. Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- int : child's exitstatus
Below is the the instruction that describes the task: ### Input: Execute a command in a subshell. Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- int : child's exitstatus ### Response: def system(self, cmd): ...
def _handle_login(self, event): """Manual password based login""" # TODO: Refactor to simplify self.log("Auth request for ", event.username, 'client:', event.clientuuid) # TODO: Define the requirements for secure passwords etc. # They're also required in the E...
Manual password based login
Below is the the instruction that describes the task: ### Input: Manual password based login ### Response: def _handle_login(self, event): """Manual password based login""" # TODO: Refactor to simplify self.log("Auth request for ", event.username, 'client:', event.clientu...
def add(self, host_value): """Add the given value to the collection. :param host: an ip address or a hostname :raises InvalidHostError: raised when the given value is not a valid ip address nor a hostname """ host_obj = self._host_factory(host_value) if self._get...
Add the given value to the collection. :param host: an ip address or a hostname :raises InvalidHostError: raised when the given value is not a valid ip address nor a hostname
Below is the the instruction that describes the task: ### Input: Add the given value to the collection. :param host: an ip address or a hostname :raises InvalidHostError: raised when the given value is not a valid ip address nor a hostname ### Response: def add(self, host_value): "...
def instance_class(self): """Instance class.""" return Class(self._env, lib.EnvGetInstanceClass(self._env, self._ist))
Instance class.
Below is the the instruction that describes the task: ### Input: Instance class. ### Response: def instance_class(self): """Instance class.""" return Class(self._env, lib.EnvGetInstanceClass(self._env, self._ist))
def as_completed(fs, timeout=None): """An iterator over the given futures that yields each as it completes. Args: fs: The sequence of Futures (possibly created by different Executors) to iterate over. timeout: The maximum number of seconds to wait. If None, then there is...
An iterator over the given futures that yields each as it completes. Args: fs: The sequence of Futures (possibly created by different Executors) to iterate over. timeout: The maximum number of seconds to wait. If None, then there is no limit on the wait time. Returns: ...
Below is the the instruction that describes the task: ### Input: An iterator over the given futures that yields each as it completes. Args: fs: The sequence of Futures (possibly created by different Executors) to iterate over. timeout: The maximum number of seconds to wait. If None,...
def warp_multi(src_ds_list, res='first', extent='intersection', t_srs='first', r='cubic', warptype=memwarp, outdir=None, dst_ndv=None, verbose=True, debug=False): """This parses and checks inputs, then calls desired warp function with appropriate arguments for each input ds Parameters ---------- sr...
This parses and checks inputs, then calls desired warp function with appropriate arguments for each input ds Parameters ---------- src_ds_list : list of gdal.Dataset objects List of original datasets to be warped res : arbitrary type Desired output resolution extent : arbitrary ...
Below is the the instruction that describes the task: ### Input: This parses and checks inputs, then calls desired warp function with appropriate arguments for each input ds Parameters ---------- src_ds_list : list of gdal.Dataset objects List of original datasets to be warped res : arb...
def create_unclaimed_draft(self, test_mode=False, files=None, file_urls=None, draft_type=None, subject=None, message=None, signers=None, cc_email_addresses=None, signing_redirect_url=None, form_fields_per_document=None, metadata=None, use_preexisting_fields=False, allow_decline=False): ''' Creates a new Draft t...
Creates a new Draft that can be claimed using the claim URL Creates a new Draft that can be claimed using the claim URL. The first authenticated user to access the URL will claim the Draft and will be shown either the "Sign and send" or the "Request signature" page with the Draft loaded...
Below is the the instruction that describes the task: ### Input: Creates a new Draft that can be claimed using the claim URL Creates a new Draft that can be claimed using the claim URL. The first authenticated user to access the URL will claim the Draft and will be shown either the "Sign an...
def update_ext(self, path, id, body=None): """Client extension hook for update.""" return self.put(path % id, body=body)
Client extension hook for update.
Below is the the instruction that describes the task: ### Input: Client extension hook for update. ### Response: def update_ext(self, path, id, body=None): """Client extension hook for update.""" return self.put(path % id, body=body)
async def _multipart(self, files_dict): ''' Forms multipart requests from a dict with name, path k/vs. Name does not have to be the actual file name. Args: files_dict (dict): A dict of `filename:filepath`s, to be sent as multipart files. Returns: ...
Forms multipart requests from a dict with name, path k/vs. Name does not have to be the actual file name. Args: files_dict (dict): A dict of `filename:filepath`s, to be sent as multipart files. Returns: multip_pkg (str): The strings representation of the con...
Below is the the instruction that describes the task: ### Input: Forms multipart requests from a dict with name, path k/vs. Name does not have to be the actual file name. Args: files_dict (dict): A dict of `filename:filepath`s, to be sent as multipart files. Returns...
def create_dcnm_out_part(self, tenant_id, fw_dict, is_fw_virt=False): """Create the DCNM OUT partition and update the result. """ res = fw_const.DCNM_OUT_PART_CREATE_SUCCESS tenant_name = fw_dict.get('tenant_name') ret = True try: self._create_out_partition(tenant_id,...
Create the DCNM OUT partition and update the result.
Below is the the instruction that describes the task: ### Input: Create the DCNM OUT partition and update the result. ### Response: def create_dcnm_out_part(self, tenant_id, fw_dict, is_fw_virt=False): """Create the DCNM OUT partition and update the result. """ res = fw_const.DCNM_OUT_PART_CREATE_S...
def symmetrically_add_atom(self, specie, point, coords_are_cartesian=False): """ Class method for adding a site at a specified point in a slab. Will add the corresponding site on the other side of the slab to maintain equivalent surfaces. Arg: specie (str): ...
Class method for adding a site at a specified point in a slab. Will add the corresponding site on the other side of the slab to maintain equivalent surfaces. Arg: specie (str): The specie to add point (coords): The coordinate of the site in the slab to add. ...
Below is the the instruction that describes the task: ### Input: Class method for adding a site at a specified point in a slab. Will add the corresponding site on the other side of the slab to maintain equivalent surfaces. Arg: specie (str): The specie to add ...
def _read_para_r1_counter(self, code, cbit, clen, *, desc, length, version): """Read HIP R1_COUNTER parameter. Structure of HIP R1_COUNTER parameter [RFC 5201][RFC 7401]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ...
Read HIP R1_COUNTER parameter. Structure of HIP R1_COUNTER parameter [RFC 5201][RFC 7401]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-...
Below is the the instruction that describes the task: ### Input: Read HIP R1_COUNTER parameter. Structure of HIP R1_COUNTER parameter [RFC 5201][RFC 7401]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1...
def _parse_vswitch_inspect_data(self, rd_list): """ Parse the Virtual_Network_Vswitch_Query_Byte_Stats data to get inspect data. """ def _parse_value(data_list, idx, keyword, offset): return idx + offset, data_list[idx].rpartition(keyword)[2].strip() vsw_dict = {} ...
Parse the Virtual_Network_Vswitch_Query_Byte_Stats data to get inspect data.
Below is the the instruction that describes the task: ### Input: Parse the Virtual_Network_Vswitch_Query_Byte_Stats data to get inspect data. ### Response: def _parse_vswitch_inspect_data(self, rd_list): """ Parse the Virtual_Network_Vswitch_Query_Byte_Stats data to get inspect data. ...
def _get_document_data(f, image_handler=None): ''' ``f`` is a ``ZipFile`` that is open Extract out the document data, numbering data and the relationship data. ''' if image_handler is None: def image_handler(image_id, relationship_dict): return relationship_dict.get(image_id) ...
``f`` is a ``ZipFile`` that is open Extract out the document data, numbering data and the relationship data.
Below is the the instruction that describes the task: ### Input: ``f`` is a ``ZipFile`` that is open Extract out the document data, numbering data and the relationship data. ### Response: def _get_document_data(f, image_handler=None): ''' ``f`` is a ``ZipFile`` that is open Extract out the document...
def refraction(alt_degrees, temperature_C, pressure_mbar): """Given an observed altitude, return how much the image is refracted. Zero refraction is returned both for objects very near the zenith, as well as for objects more than one degree below the horizon. """ r = 0.016667 / tan((alt_degrees + ...
Given an observed altitude, return how much the image is refracted. Zero refraction is returned both for objects very near the zenith, as well as for objects more than one degree below the horizon.
Below is the the instruction that describes the task: ### Input: Given an observed altitude, return how much the image is refracted. Zero refraction is returned both for objects very near the zenith, as well as for objects more than one degree below the horizon. ### Response: def refraction(alt_degrees, t...
def utc_datetime(dt=None, local_value=True): """ Convert local datetime and/or datetime without timezone information to UTC datetime with timezone information. :param dt: local datetime to convert. If is None, then system datetime value is used :param local_value: whether dt is a datetime in system timezone or UTC...
Convert local datetime and/or datetime without timezone information to UTC datetime with timezone information. :param dt: local datetime to convert. If is None, then system datetime value is used :param local_value: whether dt is a datetime in system timezone or UTC datetime without timezone information :return: d...
Below is the the instruction that describes the task: ### Input: Convert local datetime and/or datetime without timezone information to UTC datetime with timezone information. :param dt: local datetime to convert. If is None, then system datetime value is used :param local_value: whether dt is a datetime in sys...
def _guess_delimiter(self, data, delimiters): """ The delimiter /should/ occur the same number of times on each row. However, due to malformed data, it may not. We don't want an all or nothing approach, so we allow for small variations in this number. 1) build a table o...
The delimiter /should/ occur the same number of times on each row. However, due to malformed data, it may not. We don't want an all or nothing approach, so we allow for small variations in this number. 1) build a table of the frequency of each character on every line. 2) buil...
Below is the the instruction that describes the task: ### Input: The delimiter /should/ occur the same number of times on each row. However, due to malformed data, it may not. We don't want an all or nothing approach, so we allow for small variations in this number. 1) build a tabl...
def sort_batch_by_length(tensor: torch.Tensor, sequence_lengths: torch.Tensor): """ Sort a batch first tensor by some specified lengths. Parameters ---------- tensor : torch.FloatTensor, required. A batch first Pytorch tensor. sequence_lengths : torch.LongTensor, required. A ten...
Sort a batch first tensor by some specified lengths. Parameters ---------- tensor : torch.FloatTensor, required. A batch first Pytorch tensor. sequence_lengths : torch.LongTensor, required. A tensor representing the lengths of some dimension of the tensor which we want to sort b...
Below is the the instruction that describes the task: ### Input: Sort a batch first tensor by some specified lengths. Parameters ---------- tensor : torch.FloatTensor, required. A batch first Pytorch tensor. sequence_lengths : torch.LongTensor, required. A tensor representing the le...
def prep(self, wait, args, env=None): """ Given the return value of a preparefunc, prepare this CompatStarter. """ self.pattern = wait self.env = env self.args = args # wait is a function, supersedes the default behavior if callable(wait): ...
Given the return value of a preparefunc, prepare this CompatStarter.
Below is the the instruction that describes the task: ### Input: Given the return value of a preparefunc, prepare this CompatStarter. ### Response: def prep(self, wait, args, env=None): """ Given the return value of a preparefunc, prepare this CompatStarter. """ self...
def _load_custom_config(run_config): """Load custom configuration input HOCON file for cromwell. """ from pyhocon import ConfigFactory, HOCONConverter, ConfigTree conf = ConfigFactory.parse_file(run_config) out = {} if "database" in conf: out["database"] = HOCONConverter.to_hocon(ConfigT...
Load custom configuration input HOCON file for cromwell.
Below is the the instruction that describes the task: ### Input: Load custom configuration input HOCON file for cromwell. ### Response: def _load_custom_config(run_config): """Load custom configuration input HOCON file for cromwell. """ from pyhocon import ConfigFactory, HOCONConverter, ConfigTree ...
def html2data(html_string): """ Convert an html table to a data table and spans. Parameters ---------- html_string : str The string containing the html table Returns ------- table : list of lists of str spans : list of lists of lists of int A span is a list of [row,...
Convert an html table to a data table and spans. Parameters ---------- html_string : str The string containing the html table Returns ------- table : list of lists of str spans : list of lists of lists of int A span is a list of [row, column] pairs that define what cells ...
Below is the the instruction that describes the task: ### Input: Convert an html table to a data table and spans. Parameters ---------- html_string : str The string containing the html table Returns ------- table : list of lists of str spans : list of lists of lists of int ...
def _parse_keyvals(self, line_iter): """Generate dictionary from key/value pairs. """ out = None line = None for line in line_iter: if len(line) == 1 and line[0].upper() == line[0]: break else: # setup output dictionaries, t...
Generate dictionary from key/value pairs.
Below is the the instruction that describes the task: ### Input: Generate dictionary from key/value pairs. ### Response: def _parse_keyvals(self, line_iter): """Generate dictionary from key/value pairs. """ out = None line = None for line in line_iter: if len(lin...
def invoke( src, event_file='event.json', config_file='config.yaml', profile_name=None, verbose=False, ): """Simulates a call to your function. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :...
Simulates a call to your function. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str alt_event: An optional argument to override which event file to use. :param bool verbose: Wheth...
Below is the the instruction that describes the task: ### Input: Simulates a call to your function. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str alt_event: An optional argument to ove...
def add_example(self, example): "Add an example to the list of examples, checking it first." self.check_example(example) self.examples.append(example)
Add an example to the list of examples, checking it first.
Below is the the instruction that describes the task: ### Input: Add an example to the list of examples, checking it first. ### Response: def add_example(self, example): "Add an example to the list of examples, checking it first." self.check_example(example) self.examples.append(example)
def verification_start(self, phone_number, country_code, via='sms', locale=None, code_length=4): """ :param string phone_number: stored in your databse or you provided while creating new user. :param string country_code: stored in your databse or you provided while cre...
:param string phone_number: stored in your databse or you provided while creating new user. :param string country_code: stored in your databse or you provided while creating new user. :param string via: verification method either sms or call :param string locale: optional default none :p...
Below is the the instruction that describes the task: ### Input: :param string phone_number: stored in your databse or you provided while creating new user. :param string country_code: stored in your databse or you provided while creating new user. :param string via: verification method either sms o...
def gatk_filter_rnaseq(vrn_file, data): """ this incorporates filters listed here, dropping clusters of variants within a 35 nucleotide window, high fischer strand values and low quality by depth https://software.broadinstitute.org/gatk/guide/article?id=3891 java -jar GenomeAnalysisTK.jar -T Var...
this incorporates filters listed here, dropping clusters of variants within a 35 nucleotide window, high fischer strand values and low quality by depth https://software.broadinstitute.org/gatk/guide/article?id=3891 java -jar GenomeAnalysisTK.jar -T VariantFiltration -R hg_19.fasta -V input.vcf -wind...
Below is the the instruction that describes the task: ### Input: this incorporates filters listed here, dropping clusters of variants within a 35 nucleotide window, high fischer strand values and low quality by depth https://software.broadinstitute.org/gatk/guide/article?id=3891 java -jar GenomeAnal...
def find_single_file_project(self): # type: () -> List[str] """ Find well formed singler file project :return: """ files = [f for f in os.listdir(".") if os.path.isfile(f)] candidates = [] setup_source = self.setup_py_source() for file in files: ...
Find well formed singler file project :return:
Below is the the instruction that describes the task: ### Input: Find well formed singler file project :return: ### Response: def find_single_file_project(self): # type: () -> List[str] """ Find well formed singler file project :return: """ files = [f for f in os.li...
def apply(diff, recs, strict=True): """ Transform the records with the patch. May fail if the records do not match those expected in the patch. """ index_columns = diff['_index'] indexed = records.index(copy.deepcopy(list(recs)), index_columns) _add_records(indexed, diff['added'], index_colu...
Transform the records with the patch. May fail if the records do not match those expected in the patch.
Below is the the instruction that describes the task: ### Input: Transform the records with the patch. May fail if the records do not match those expected in the patch. ### Response: def apply(diff, recs, strict=True): """ Transform the records with the patch. May fail if the records do not match t...
def create_endpoint_folder(self, endpoint_id, folder): '''create an endpoint folder, catching the error if it exists. Parameters ========== endpoint_id: the endpoint id parameters folder: the relative path of the folder to create ''' try: res = self.transfer_client.oper...
create an endpoint folder, catching the error if it exists. Parameters ========== endpoint_id: the endpoint id parameters folder: the relative path of the folder to create
Below is the the instruction that describes the task: ### Input: create an endpoint folder, catching the error if it exists. Parameters ========== endpoint_id: the endpoint id parameters folder: the relative path of the folder to create ### Response: def create_endpoint_folder(self, en...
def set_join_rule(self, room_id, join_rule): """Set the rule for users wishing to join the room. Args: room_id(str): The room to set the rules for. join_rule(str): The chosen rule. One of: ["public", "knock", "invite", "private"] """ content = { ...
Set the rule for users wishing to join the room. Args: room_id(str): The room to set the rules for. join_rule(str): The chosen rule. One of: ["public", "knock", "invite", "private"]
Below is the the instruction that describes the task: ### Input: Set the rule for users wishing to join the room. Args: room_id(str): The room to set the rules for. join_rule(str): The chosen rule. One of: ["public", "knock", "invite", "private"] ### Response: def s...
def parse_fields_http(self, response, extra_org_map=None): """ The function for parsing ASN fields from a http response. Args: response (:obj:`str`): The response from the ASN http server. extra_org_map (:obj:`dict`): Dictionary mapping org handles to RIR...
The function for parsing ASN fields from a http response. Args: response (:obj:`str`): The response from the ASN http server. extra_org_map (:obj:`dict`): Dictionary mapping org handles to RIRs. This is for limited cases where ARIN REST (ASN fallback HTTP...
Below is the the instruction that describes the task: ### Input: The function for parsing ASN fields from a http response. Args: response (:obj:`str`): The response from the ASN http server. extra_org_map (:obj:`dict`): Dictionary mapping org handles to RIRs. This is...
def get_xy_steps(bbox, h_dim): r"""Return meshgrid spacing based on bounding box. bbox: dictionary Dictionary containing coordinates for corners of study area. h_dim: integer Horizontal resolution in meters. Returns ------- x_steps, (X, ) ndarray Number of grids in x di...
r"""Return meshgrid spacing based on bounding box. bbox: dictionary Dictionary containing coordinates for corners of study area. h_dim: integer Horizontal resolution in meters. Returns ------- x_steps, (X, ) ndarray Number of grids in x dimension. y_steps: (Y, ) ndarray...
Below is the the instruction that describes the task: ### Input: r"""Return meshgrid spacing based on bounding box. bbox: dictionary Dictionary containing coordinates for corners of study area. h_dim: integer Horizontal resolution in meters. Returns ------- x_steps, (X, ) ndarr...
def sndwrite(samples:np.ndarray, sr:int, outfile:str, encoding:str='auto') -> None: """ samples --> Array-like. the actual samples, shape=(nframes, channels) sr --> Sampling-rate outfile --> The name of the outfile. the extension will determine the file-format. ...
samples --> Array-like. the actual samples, shape=(nframes, channels) sr --> Sampling-rate outfile --> The name of the outfile. the extension will determine the file-format. The formats supported depend on the available backends Without additional backe...
Below is the the instruction that describes the task: ### Input: samples --> Array-like. the actual samples, shape=(nframes, channels) sr --> Sampling-rate outfile --> The name of the outfile. the extension will determine the file-format. The formats supported depen...
def cons(o, seq) -> ISeq: """Creates a new sequence where o is the first element and seq is the rest. If seq is None, return a list containing o. If seq is not a ISeq, attempt to coerce it to a ISeq and then cons o onto the resulting sequence.""" if seq is None: return llist.l(o) if isinstan...
Creates a new sequence where o is the first element and seq is the rest. If seq is None, return a list containing o. If seq is not a ISeq, attempt to coerce it to a ISeq and then cons o onto the resulting sequence.
Below is the the instruction that describes the task: ### Input: Creates a new sequence where o is the first element and seq is the rest. If seq is None, return a list containing o. If seq is not a ISeq, attempt to coerce it to a ISeq and then cons o onto the resulting sequence. ### Response: def cons(o, s...
def freeze_subjects(self): """Converts variable data into numpy arrays. This is required after all subjects have been added via the add_subject function, since we don't know ahead of time who is participating in the analysis due to various filtering possibilities. """ se...
Converts variable data into numpy arrays. This is required after all subjects have been added via the add_subject function, since we don't know ahead of time who is participating in the analysis due to various filtering possibilities.
Below is the the instruction that describes the task: ### Input: Converts variable data into numpy arrays. This is required after all subjects have been added via the add_subject function, since we don't know ahead of time who is participating in the analysis due to various filtering possib...
def AddDir(self, dirpath): """Adds a directory path as a source. Args: dirpath: a string representing a path to the directory. Returns: True if the directory is not an already existing source. """ if dirpath not in self._dirs: self._dirs.add(dirpath) return True return ...
Adds a directory path as a source. Args: dirpath: a string representing a path to the directory. Returns: True if the directory is not an already existing source.
Below is the the instruction that describes the task: ### Input: Adds a directory path as a source. Args: dirpath: a string representing a path to the directory. Returns: True if the directory is not an already existing source. ### Response: def AddDir(self, dirpath): """Adds a directory ...
def hash_codeblocks(text, hashes): """Hashes codeblocks (<pre> elements). Codeblocks are strictly defined to be (non-list) lines that are indented at least 4 spaces from the newline. Exactly 4 spaces will be stripped from the beginning of the line -- any leading whitespace after that is preserved. ...
Hashes codeblocks (<pre> elements). Codeblocks are strictly defined to be (non-list) lines that are indented at least 4 spaces from the newline. Exactly 4 spaces will be stripped from the beginning of the line -- any leading whitespace after that is preserved. Codeblock lines that are separated on...
Below is the the instruction that describes the task: ### Input: Hashes codeblocks (<pre> elements). Codeblocks are strictly defined to be (non-list) lines that are indented at least 4 spaces from the newline. Exactly 4 spaces will be stripped from the beginning of the line -- any leading whitespac...
def close(self): """Close this adapter stream. This method may only be called once in the lifetime of an AdapterStream and it will shutdown the underlying device adapter, disconnect all devices and stop all background activity. If this stream is configured to save a record of a...
Close this adapter stream. This method may only be called once in the lifetime of an AdapterStream and it will shutdown the underlying device adapter, disconnect all devices and stop all background activity. If this stream is configured to save a record of all RPCs, the RPCs wi...
Below is the the instruction that describes the task: ### Input: Close this adapter stream. This method may only be called once in the lifetime of an AdapterStream and it will shutdown the underlying device adapter, disconnect all devices and stop all background activity. If this s...
def get_inventory_by_name(nme, character): """ returns the inventory index by name """ for ndx, sk in enumerate(character["inventory"]): #print("sk = ", sk, " , nme = ", nme) if sk["name"] == nme: return ndx return 0
returns the inventory index by name
Below is the the instruction that describes the task: ### Input: returns the inventory index by name ### Response: def get_inventory_by_name(nme, character): """ returns the inventory index by name """ for ndx, sk in enumerate(character["inventory"]): #print("sk = ", sk, " , nme = ", nme) ...
def cmd_nc(host, port, family, ssl_enable, crlf, source_ip, source_port, protocol): """Some kind of netcat/ncat replacement. The execution emulates the feeling of this popular tools. Example: \b $ habu.nc --crlf www.portantier.com 80 Connected to 45.77.113.133 80 HEAD / HTTP/1.0 \b ...
Some kind of netcat/ncat replacement. The execution emulates the feeling of this popular tools. Example: \b $ habu.nc --crlf www.portantier.com 80 Connected to 45.77.113.133 80 HEAD / HTTP/1.0 \b HTTP/1.0 301 Moved Permanently Date: Thu, 26 Jul 2018 21:10:51 GMT Server: OpenB...
Below is the the instruction that describes the task: ### Input: Some kind of netcat/ncat replacement. The execution emulates the feeling of this popular tools. Example: \b $ habu.nc --crlf www.portantier.com 80 Connected to 45.77.113.133 80 HEAD / HTTP/1.0 \b HTTP/1.0 301 Moved ...
def _truncate(self, x, k): ''' given a vector x, leave its top-k absolute-value entries alone, and set the rest to 0 ''' not_F = np.argsort(np.abs(x))[:-k] x[not_F] = 0 return x
given a vector x, leave its top-k absolute-value entries alone, and set the rest to 0
Below is the the instruction that describes the task: ### Input: given a vector x, leave its top-k absolute-value entries alone, and set the rest to 0 ### Response: def _truncate(self, x, k): ''' given a vector x, leave its top-k absolute-value entries alone, and set the rest to 0 ''' not_F = np.ar...
def strip_spaces(x): """ Strips spaces :param x: :return: """ x = x.replace(b' ', b'') x = x.replace(b'\t', b'') return x
Strips spaces :param x: :return:
Below is the the instruction that describes the task: ### Input: Strips spaces :param x: :return: ### Response: def strip_spaces(x): """ Strips spaces :param x: :return: """ x = x.replace(b' ', b'') x = x.replace(b'\t', b'') return x
def stop(self, wait=False): """ Terminate the VM instance launched on the cloud for this specific node. """ if self.instance_id is not None: log.info("Shutting down node `%s` (VM instance `%s`) ...", self.name, self.instance_id) self._cloud_p...
Terminate the VM instance launched on the cloud for this specific node.
Below is the the instruction that describes the task: ### Input: Terminate the VM instance launched on the cloud for this specific node. ### Response: def stop(self, wait=False): """ Terminate the VM instance launched on the cloud for this specific node. """ if self.instance_id is n...
def chemical_formula(self): """the chemical formula of the molecule""" counts = {} for number in self.numbers: counts[number] = counts.get(number, 0)+1 items = [] for number, count in sorted(counts.items(), reverse=True): if count == 1: ite...
the chemical formula of the molecule
Below is the the instruction that describes the task: ### Input: the chemical formula of the molecule ### Response: def chemical_formula(self): """the chemical formula of the molecule""" counts = {} for number in self.numbers: counts[number] = counts.get(number, 0)+1 ite...
def setup(self): """Setup.""" self.blocks = self.config['block_comments'] self.lines = self.config['line_comments'] self.group_comments = self.config['group_comments'] # If the style isn't found, just go with CSS, then use the appropriate prefix. self.stylesheets = STYLE...
Setup.
Below is the the instruction that describes the task: ### Input: Setup. ### Response: def setup(self): """Setup.""" self.blocks = self.config['block_comments'] self.lines = self.config['line_comments'] self.group_comments = self.config['group_comments'] # If the style isn't...
async def update_firmware(port: str, firmware_file_path: str, loop: Optional[asyncio.AbstractEventLoop])\ -> Tuple[str, Tuple[bool, str]]: """ Run avrdude firmware upload command. Switch back to normal module port Note: For modul...
Run avrdude firmware upload command. Switch back to normal module port Note: For modules with old bootloader, the kernel could assign the module a new port after the update (since the board is automatically reset). Scan for such a port change and use the appropriate port. Returns a tuple of the new po...
Below is the the instruction that describes the task: ### Input: Run avrdude firmware upload command. Switch back to normal module port Note: For modules with old bootloader, the kernel could assign the module a new port after the update (since the board is automatically reset). Scan for such a port ch...
def deletion(args): """ %prog deletion [mac.mic.bam|mac.mic.bed] mic.gaps.bed Find IES based on mapping MAC reads to MIC genome. """ p = OptionParser(deletion.__doc__) p.add_option("--mindepth", default=3, type="int", help="Minimum depth to call a deletion") p.add_option("-...
%prog deletion [mac.mic.bam|mac.mic.bed] mic.gaps.bed Find IES based on mapping MAC reads to MIC genome.
Below is the the instruction that describes the task: ### Input: %prog deletion [mac.mic.bam|mac.mic.bed] mic.gaps.bed Find IES based on mapping MAC reads to MIC genome. ### Response: def deletion(args): """ %prog deletion [mac.mic.bam|mac.mic.bed] mic.gaps.bed Find IES based on mapping MAC reads...
def _get_ann_labels_data(self, order_ann, bins_ann): """Generate ColumnDataSource dictionary for annular labels. """ if self.yticks is None: return dict(x=[], y=[], text=[], angle=[]) mapping = self._compute_tick_mapping("radius", order_ann, bins_ann) values = [(la...
Generate ColumnDataSource dictionary for annular labels.
Below is the the instruction that describes the task: ### Input: Generate ColumnDataSource dictionary for annular labels. ### Response: def _get_ann_labels_data(self, order_ann, bins_ann): """Generate ColumnDataSource dictionary for annular labels. """ if self.yticks is None: ...
def tprint(text, font=DEFAULT_FONT, chr_ignore=True): r""" Print art text (support \n). :param text: input text :type text:str :param font: input font :type font:str :param chr_ignore: ignore not supported character :type chr_ignore:bool :return: None """ result = text2art(t...
r""" Print art text (support \n). :param text: input text :type text:str :param font: input font :type font:str :param chr_ignore: ignore not supported character :type chr_ignore:bool :return: None
Below is the the instruction that describes the task: ### Input: r""" Print art text (support \n). :param text: input text :type text:str :param font: input font :type font:str :param chr_ignore: ignore not supported character :type chr_ignore:bool :return: None ### Response: def t...
def request(self, method, params): """Send a JSONRPC request.""" identifier = random.randint(1, 1000) self._transport.write(jsonrpc_request(method, identifier, params)) self._buffer[identifier] = {'flag': asyncio.Event()} yield from self._buffer[identifier]['flag'].wait() ...
Send a JSONRPC request.
Below is the the instruction that describes the task: ### Input: Send a JSONRPC request. ### Response: def request(self, method, params): """Send a JSONRPC request.""" identifier = random.randint(1, 1000) self._transport.write(jsonrpc_request(method, identifier, params)) self._buffe...
def import_ecdsa_privatekey_from_file(filepath, password=None): """ <Purpose> Import the encrypted ECDSA key file in 'filepath', decrypt it, and return the key object in 'securesystemslib.formats.ECDSAKEY_SCHEMA' format. The 'cryptography' library is currently supported and performs the actual cryp...
<Purpose> Import the encrypted ECDSA key file in 'filepath', decrypt it, and return the key object in 'securesystemslib.formats.ECDSAKEY_SCHEMA' format. The 'cryptography' library is currently supported and performs the actual cryptographic routine. <Arguments> filepath: <filepath> file, a...
Below is the the instruction that describes the task: ### Input: <Purpose> Import the encrypted ECDSA key file in 'filepath', decrypt it, and return the key object in 'securesystemslib.formats.ECDSAKEY_SCHEMA' format. The 'cryptography' library is currently supported and performs the actual cryptog...
def calculate_P(self, T, P, method): r'''Method to calculate pressure-dependent liquid viscosity at temperature `T` and pressure `P` with a given method. This method has no exception handling; see `TP_dependent_property` for that. Parameters ---------- T : float...
r'''Method to calculate pressure-dependent liquid viscosity at temperature `T` and pressure `P` with a given method. This method has no exception handling; see `TP_dependent_property` for that. Parameters ---------- T : float Temperature at which to calculat...
Below is the the instruction that describes the task: ### Input: r'''Method to calculate pressure-dependent liquid viscosity at temperature `T` and pressure `P` with a given method. This method has no exception handling; see `TP_dependent_property` for that. Parameters ----...
def autolink(self, link, is_email=False): """Rendering a given link or email address. :param link: link content or email address. :param is_email: whether this is an email or not. """ text = link = escape(link) if is_email: link = 'mailto:%s' % link r...
Rendering a given link or email address. :param link: link content or email address. :param is_email: whether this is an email or not.
Below is the the instruction that describes the task: ### Input: Rendering a given link or email address. :param link: link content or email address. :param is_email: whether this is an email or not. ### Response: def autolink(self, link, is_email=False): """Rendering a given link or email...
def press_button(self, value): """ Click the button with the given label. """ button = find_button(world.browser, value) if not button: raise AssertionError( "Cannot find a button named '{}'.".format(value)) button.click()
Click the button with the given label.
Below is the the instruction that describes the task: ### Input: Click the button with the given label. ### Response: def press_button(self, value): """ Click the button with the given label. """ button = find_button(world.browser, value) if not button: raise AssertionError( ...
def _on_timeline_update(self, event): """Timeline update broadcast from Abode SocketIO server.""" if isinstance(event, (tuple, list)): event = event[0] event_type = event.get('event_type') event_code = event.get('event_code') if not event_type or not event_code: ...
Timeline update broadcast from Abode SocketIO server.
Below is the the instruction that describes the task: ### Input: Timeline update broadcast from Abode SocketIO server. ### Response: def _on_timeline_update(self, event): """Timeline update broadcast from Abode SocketIO server.""" if isinstance(event, (tuple, list)): event = event[0] ...
def _limit_and_df(self, query, limit, as_df=False): """adds a limit (limit==None := no limit) to any query and allow a return as pandas.DataFrame :param bool as_df: if is set to True results return as pandas.DataFrame :param `sqlalchemy.orm.query.Query` query: SQL Alchemy query :param ...
adds a limit (limit==None := no limit) to any query and allow a return as pandas.DataFrame :param bool as_df: if is set to True results return as pandas.DataFrame :param `sqlalchemy.orm.query.Query` query: SQL Alchemy query :param int limit: maximum number of results :return: query res...
Below is the the instruction that describes the task: ### Input: adds a limit (limit==None := no limit) to any query and allow a return as pandas.DataFrame :param bool as_df: if is set to True results return as pandas.DataFrame :param `sqlalchemy.orm.query.Query` query: SQL Alchemy query :...
def All(*validators): """ Combines all the given validator callables into one, running all the validators in sequence on the given value. """ @wraps(All) def built(value): for validator in validators: value = validator(value) return value return built
Combines all the given validator callables into one, running all the validators in sequence on the given value.
Below is the the instruction that describes the task: ### Input: Combines all the given validator callables into one, running all the validators in sequence on the given value. ### Response: def All(*validators): """ Combines all the given validator callables into one, running all the validators in...
def add(self, name, mech, usage='both', init_lifetime=None, accept_lifetime=None, impersonator=None, store=None): """Acquire more credentials to add to the current set This method works like :meth:`acquire`, except that it adds the acquired credentials for a single mecha...
Acquire more credentials to add to the current set This method works like :meth:`acquire`, except that it adds the acquired credentials for a single mechanism to a copy of the current set, instead of creating a new set for multiple mechanisms. Unlike :meth:`acquire`, you cannot pass Non...
Below is the the instruction that describes the task: ### Input: Acquire more credentials to add to the current set This method works like :meth:`acquire`, except that it adds the acquired credentials for a single mechanism to a copy of the current set, instead of creating a new set for mul...
def nurbs_to_bspline(obj, **kwargs): """ Extracts the non-rational components from rational parametric shapes, if possible. The possibility of converting a rational shape to a non-rational one depends on the weights vector. :param obj: NURBS shape :type obj: NURBS.Curve, NURBS.Surface or NURBS.Volume ...
Extracts the non-rational components from rational parametric shapes, if possible. The possibility of converting a rational shape to a non-rational one depends on the weights vector. :param obj: NURBS shape :type obj: NURBS.Curve, NURBS.Surface or NURBS.Volume :return: B-Spline shape :rtype: BSpli...
Below is the the instruction that describes the task: ### Input: Extracts the non-rational components from rational parametric shapes, if possible. The possibility of converting a rational shape to a non-rational one depends on the weights vector. :param obj: NURBS shape :type obj: NURBS.Curve, NURBS....
def debug_shell(user_ns, user_global_ns, traceback=None, execWrapper=None): """ Spawns some interactive shell. Tries to use IPython if available. Falls back to :func:`pdb.post_mortem` or :func:`simple_debug_shell`. :param dict[str] user_ns: :param dict[str] user_global_ns: :param traceback: ...
Spawns some interactive shell. Tries to use IPython if available. Falls back to :func:`pdb.post_mortem` or :func:`simple_debug_shell`. :param dict[str] user_ns: :param dict[str] user_global_ns: :param traceback: :param execWrapper: :return: nothing
Below is the the instruction that describes the task: ### Input: Spawns some interactive shell. Tries to use IPython if available. Falls back to :func:`pdb.post_mortem` or :func:`simple_debug_shell`. :param dict[str] user_ns: :param dict[str] user_global_ns: :param traceback: :param execWrapper...
def teardown(self): """ Clean up all resources when we're done with them. """ self.containers._teardown() self.networks._teardown() self.volumes._teardown() # We need to close the underlying APIClient explicitly to avoid # ResourceWarnings from unclosed H...
Clean up all resources when we're done with them.
Below is the the instruction that describes the task: ### Input: Clean up all resources when we're done with them. ### Response: def teardown(self): """ Clean up all resources when we're done with them. """ self.containers._teardown() self.networks._teardown() self.v...
def plotwrapper(f): """ This decorator allows for PyMC arguments of various types to be passed to the plotting functions. It identifies the type of object and locates its trace(s), then passes the data to the wrapped plotting function. """ def wrapper(pymc_obj, *args, **kwargs): start ...
This decorator allows for PyMC arguments of various types to be passed to the plotting functions. It identifies the type of object and locates its trace(s), then passes the data to the wrapped plotting function.
Below is the the instruction that describes the task: ### Input: This decorator allows for PyMC arguments of various types to be passed to the plotting functions. It identifies the type of object and locates its trace(s), then passes the data to the wrapped plotting function. ### Response: def plotwrapper(...
def execute(self): """ Execute the actions necessary to perform a `molecule init role` and returns None. :return: None """ role_name = self._command_args['role_name'] role_directory = os.getcwd() msg = 'Initializing new role {}...'.format(role_name) ...
Execute the actions necessary to perform a `molecule init role` and returns None. :return: None
Below is the the instruction that describes the task: ### Input: Execute the actions necessary to perform a `molecule init role` and returns None. :return: None ### Response: def execute(self): """ Execute the actions necessary to perform a `molecule init role` and returns ...
def get_vpnv4fs_table(self): """Returns global VPNv4 Flow Specification table. Creates the table if it does not exist. """ vpnv4fs_table = self._global_tables.get(RF_VPNv4_FLOWSPEC) # Lazy initialization of the table. if not vpnv4fs_table: vpnv4fs_table = VPN...
Returns global VPNv4 Flow Specification table. Creates the table if it does not exist.
Below is the the instruction that describes the task: ### Input: Returns global VPNv4 Flow Specification table. Creates the table if it does not exist. ### Response: def get_vpnv4fs_table(self): """Returns global VPNv4 Flow Specification table. Creates the table if it does not exist. ...
def to_json(self): """Returns an input shard state for the remaining inputs. Returns: A json-izable version of the remaining InputReader. """ return {self.BLOB_KEY_PARAM: self._blob_key, self.START_FILE_INDEX_PARAM: self._start_file_index, self.END_FILE_INDEX_PARAM: self....
Returns an input shard state for the remaining inputs. Returns: A json-izable version of the remaining InputReader.
Below is the the instruction that describes the task: ### Input: Returns an input shard state for the remaining inputs. Returns: A json-izable version of the remaining InputReader. ### Response: def to_json(self): """Returns an input shard state for the remaining inputs. Returns: A json-i...
def connect_post_namespaced_pod_proxy_with_path(self, name, namespace, path, **kwargs): # noqa: E501 """connect_post_namespaced_pod_proxy_with_path # noqa: E501 connect POST requests to proxy of Pod # noqa: E501 This method makes a synchronous HTTP request by default. To make an asyn...
connect_post_namespaced_pod_proxy_with_path # noqa: E501 connect POST requests to proxy of Pod # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_post_namespaced_pod_proxy_with...
Below is the the instruction that describes the task: ### Input: connect_post_namespaced_pod_proxy_with_path # noqa: E501 connect POST requests to proxy of Pod # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req...
def join(*vectors): r""" Takes an arbitrary number of aligned vectors of the same length and combines them into a single vector (vertically). E.g. taking two 100-sample feature vectors of once 5 and once 7 features, a 100x12 feature vector is created and returned. The feature vectors ...
r""" Takes an arbitrary number of aligned vectors of the same length and combines them into a single vector (vertically). E.g. taking two 100-sample feature vectors of once 5 and once 7 features, a 100x12 feature vector is created and returned. The feature vectors are expected to have the...
Below is the the instruction that describes the task: ### Input: r""" Takes an arbitrary number of aligned vectors of the same length and combines them into a single vector (vertically). E.g. taking two 100-sample feature vectors of once 5 and once 7 features, a 100x12 feature vector is created...
def parse_pdb_ligand_info(self, pdb_ligand_info): '''This only parses the ligand type as all the other information should be in the .cif file. The XML file has proper capitalization whereas the .cif file uses all caps for the ligand type.''' mtchs = re.findall('(<ligand.*?</ligand>)', pdb_lig...
This only parses the ligand type as all the other information should be in the .cif file. The XML file has proper capitalization whereas the .cif file uses all caps for the ligand type.
Below is the the instruction that describes the task: ### Input: This only parses the ligand type as all the other information should be in the .cif file. The XML file has proper capitalization whereas the .cif file uses all caps for the ligand type. ### Response: def parse_pdb_ligand_info(self, pdb_lig...
def unregister(self, label: str) -> None: """ Unregisters the entries in the encoder and decoder registries which have the label ``label``. """ self.unregister_encoder(label) self.unregister_decoder(label)
Unregisters the entries in the encoder and decoder registries which have the label ``label``.
Below is the the instruction that describes the task: ### Input: Unregisters the entries in the encoder and decoder registries which have the label ``label``. ### Response: def unregister(self, label: str) -> None: """ Unregisters the entries in the encoder and decoder registries which ...
def option(self, section, option): """ Returns the value of the option """ if self.config.has_section(section): if self.config.has_option(section, option): return (True, self.config.get(section, option)) return (False, 'Option: ' + option + ' does not exist') ...
Returns the value of the option
Below is the the instruction that describes the task: ### Input: Returns the value of the option ### Response: def option(self, section, option): """ Returns the value of the option """ if self.config.has_section(section): if self.config.has_option(section, option): retu...
def get(self, key, default=_sentinel): """ Gets the value from the key. If the key doesn't exist, the default value is returned, otherwise None. :param key: The key :param default: The default value :return: The value """ tup = self._data.get(key.lower())...
Gets the value from the key. If the key doesn't exist, the default value is returned, otherwise None. :param key: The key :param default: The default value :return: The value
Below is the the instruction that describes the task: ### Input: Gets the value from the key. If the key doesn't exist, the default value is returned, otherwise None. :param key: The key :param default: The default value :return: The value ### Response: def get(self, key, default=_...
def get_next_input(self): """ Returns the next line of input :return: string of input """ # TODO: could override input if we get input coming in at the same time all_input = Deployment.objects.get(pk=self.id).input or '' lines = all_input.splitlines() fir...
Returns the next line of input :return: string of input
Below is the the instruction that describes the task: ### Input: Returns the next line of input :return: string of input ### Response: def get_next_input(self): """ Returns the next line of input :return: string of input """ # TODO: could override input if we get in...
def child(self,index): "helper for __getitem__/__setitem__" if isinstance(index,tuple): attr,i = index return getattr(self,attr)[i] else: return getattr(self,index)
helper for __getitem__/__setitem__
Below is the the instruction that describes the task: ### Input: helper for __getitem__/__setitem__ ### Response: def child(self,index): "helper for __getitem__/__setitem__" if isinstance(index,tuple): attr,i = index return getattr(self,attr)[i] else: return getattr(self,index)
def _get_layer_converter_fn(layer, add_custom_layers = False): """Get the right converter function for Keras """ layer_type = type(layer) if layer_type in _KERAS_LAYER_REGISTRY: convert_func = _KERAS_LAYER_REGISTRY[layer_type] if convert_func is _layers2.convert_activation: a...
Get the right converter function for Keras
Below is the the instruction that describes the task: ### Input: Get the right converter function for Keras ### Response: def _get_layer_converter_fn(layer, add_custom_layers = False): """Get the right converter function for Keras """ layer_type = type(layer) if layer_type in _KERAS_LAYER_REGISTRY:...
async def update(self, fields=''): '''reload object info from emby |coro| Parameters ---------- fields : str additional fields to request when updating See Also -------- refresh : same thing send : post : ''' path = 'Users/{{UserId}}/Items/{}'.format(self.i...
reload object info from emby |coro| Parameters ---------- fields : str additional fields to request when updating See Also -------- refresh : same thing send : post :
Below is the the instruction that describes the task: ### Input: reload object info from emby |coro| Parameters ---------- fields : str additional fields to request when updating See Also -------- refresh : same thing send : post : ### Response: async def update(s...