code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def remove_series(self, series): """Removes a :py:class:`.Series` from the chart. :param Series series: The :py:class:`.Series` to remove. :raises ValueError: if you try to remove the last\ :py:class:`.Series`.""" if len(self.all_series()) == 1: raise ValueError("Ca...
Removes a :py:class:`.Series` from the chart. :param Series series: The :py:class:`.Series` to remove. :raises ValueError: if you try to remove the last\ :py:class:`.Series`.
Below is the the instruction that describes the task: ### Input: Removes a :py:class:`.Series` from the chart. :param Series series: The :py:class:`.Series` to remove. :raises ValueError: if you try to remove the last\ :py:class:`.Series`. ### Response: def remove_series(self, series): ...
def print(self, rows): """ Write the data to our output stream (stdout). If the table is not rendered yet, we will make a renderer instance which will freeze state. """ if not self.default_renderer: self.default_renderer = self.make_renderer() self.default_renderer.p...
Write the data to our output stream (stdout). If the table is not rendered yet, we will make a renderer instance which will freeze state.
Below is the the instruction that describes the task: ### Input: Write the data to our output stream (stdout). If the table is not rendered yet, we will make a renderer instance which will freeze state. ### Response: def print(self, rows): """ Write the data to our output stream (stdout). ...
def create_file_from_bytes( self, share_name, directory_name, file_name, file, index=0, count=None, content_settings=None, metadata=None, progress_callback=None, max_connections=1, max_retries=5, retry_wait=1.0, timeout=None): ''' Creates a new file from an array of bytes...
Creates a new file from an array of bytes, or updates the content of an existing file, with automatic chunking and progress notifications. :param str share_name: Name of existing share. :param str directory_name: The path to the directory. :param str file...
Below is the the instruction that describes the task: ### Input: Creates a new file from an array of bytes, or updates the content of an existing file, with automatic chunking and progress notifications. :param str share_name: Name of existing share. :param str directory...
def process_lsof(self, users, types): """ Get the list of users and file types to collect for and collect the data from lsof """ d = {} for u in users: d[u] = {} tmp = os.popen("lsof -wbu %s | awk '{ print $5 }'" % ( u)).read().spli...
Get the list of users and file types to collect for and collect the data from lsof
Below is the the instruction that describes the task: ### Input: Get the list of users and file types to collect for and collect the data from lsof ### Response: def process_lsof(self, users, types): """ Get the list of users and file types to collect for and collect the data from l...
def hyphenify(self, ascii=False): """Turn non-word characters (incl. underscore) into single hyphens. If ascii=True, return ASCII-only. If also lossless=True, use the UTF-8 codes for the non-ASCII characters. """ s = str(self) s = re.sub("""['"\u2018\u2019\u201c\u20...
Turn non-word characters (incl. underscore) into single hyphens. If ascii=True, return ASCII-only. If also lossless=True, use the UTF-8 codes for the non-ASCII characters.
Below is the the instruction that describes the task: ### Input: Turn non-word characters (incl. underscore) into single hyphens. If ascii=True, return ASCII-only. If also lossless=True, use the UTF-8 codes for the non-ASCII characters. ### Response: def hyphenify(self, ascii=False): """...
def on_admin_login(self, context, connection): ''' Oook.. Think my heads going to explode So Mimikatz's DPAPI module requires the path to Chrome's database in double quotes otherwise it can't interpret paths with spaces. Problem is Invoke-Mimikatz interpretes double qoutes ...
Oook.. Think my heads going to explode So Mimikatz's DPAPI module requires the path to Chrome's database in double quotes otherwise it can't interpret paths with spaces. Problem is Invoke-Mimikatz interpretes double qoutes as seperators for the arguments to pass to the injected mimikatz binary....
Below is the the instruction that describes the task: ### Input: Oook.. Think my heads going to explode So Mimikatz's DPAPI module requires the path to Chrome's database in double quotes otherwise it can't interpret paths with spaces. Problem is Invoke-Mimikatz interpretes double qoutes as ...
def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bin_dir = __salt__['config.option']('postgres.bins_dir') util_bin = salt.utils.path.which(util) if not util_bin: if pg_bin_dir: return salt.utils.pa...
... versionadded:: 2016.3.2 Helper function to locate various psql related binaries
Below is the the instruction that describes the task: ### Input: ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ### Response: def _find_pg_binary(util): ''' ... versionadded:: 2016.3.2 Helper function to locate various psql related binaries ''' pg_bi...
def ensure_row_dep_constraint( self, M_c, T, X_L, X_D, row1, row2, dependent=True, wrt=None, max_iter=100, force=False): """Ensures dependencey or indepdendency between rows with respect to columns.""" X_L_list, X_D_list, was_multistate = su.ensure_multistate(X_L, X_D) ...
Ensures dependencey or indepdendency between rows with respect to columns.
Below is the the instruction that describes the task: ### Input: Ensures dependencey or indepdendency between rows with respect to columns. ### Response: def ensure_row_dep_constraint( self, M_c, T, X_L, X_D, row1, row2, dependent=True, wrt=None, max_iter=100, force=False): ...
def _addHdlProcToRun(self, trigger: SimSignal, proc) -> None: """ Add hdl process to execution queue :param trigger: instance of SimSignal :param proc: python generator function representing HDL process """ # first process in time has to plan executing of apply values on...
Add hdl process to execution queue :param trigger: instance of SimSignal :param proc: python generator function representing HDL process
Below is the the instruction that describes the task: ### Input: Add hdl process to execution queue :param trigger: instance of SimSignal :param proc: python generator function representing HDL process ### Response: def _addHdlProcToRun(self, trigger: SimSignal, proc) -> None: """ ...
def locked(self): """ Determines if the queue is locked. """ if len(self.failed) == 0: return False for fail in self.failed: for job in self.active_jobs: if fail.alias in job.depends_on: return True
Determines if the queue is locked.
Below is the the instruction that describes the task: ### Input: Determines if the queue is locked. ### Response: def locked(self): """ Determines if the queue is locked. """ if len(self.failed) == 0: return False for fail in self.failed: for job in self.active_jobs:...
def set_mask(self, mask_img): """Sets a mask img to this. So every operation to self, this mask will be taken into account. Parameters ---------- mask_img: nifti-like image, NeuroImage or str 3D mask array: True where a voxel should be used. Can either be: ...
Sets a mask img to this. So every operation to self, this mask will be taken into account. Parameters ---------- mask_img: nifti-like image, NeuroImage or str 3D mask array: True where a voxel should be used. Can either be: - a file path to a Nifti image ...
Below is the the instruction that describes the task: ### Input: Sets a mask img to this. So every operation to self, this mask will be taken into account. Parameters ---------- mask_img: nifti-like image, NeuroImage or str 3D mask array: True where a voxel should be used. ...
def _cert_file(name, cert_type): ''' Return expected path of a Let's Encrypt live cert ''' return os.path.join(LE_LIVE, name, '{0}.pem'.format(cert_type))
Return expected path of a Let's Encrypt live cert
Below is the the instruction that describes the task: ### Input: Return expected path of a Let's Encrypt live cert ### Response: def _cert_file(name, cert_type): ''' Return expected path of a Let's Encrypt live cert ''' return os.path.join(LE_LIVE, name, '{0}.pem'.format(cert_type))
def empty(): """ Create an empty set. """ if not hasattr(empty, '_instance'): empty._instance = Interval(AtomicInterval(OPEN, inf, -inf, OPEN)) return empty._instance
Create an empty set.
Below is the the instruction that describes the task: ### Input: Create an empty set. ### Response: def empty(): """ Create an empty set. """ if not hasattr(empty, '_instance'): empty._instance = Interval(AtomicInterval(OPEN, inf, -inf, OPEN)) return empty._instance
def payload_set(self, value): """ Set the message payload (and update header) :param value: New payload value :type value: str :rtype: None """ payload = saveJSON(value, pretty=False) super(APPDataMessage, self).payload_set(payload)
Set the message payload (and update header) :param value: New payload value :type value: str :rtype: None
Below is the the instruction that describes the task: ### Input: Set the message payload (and update header) :param value: New payload value :type value: str :rtype: None ### Response: def payload_set(self, value): """ Set the message payload (and update header) :p...
def get_modules(path, prepend_module_root=True): """Return a list containing tuples of e.g. ('test_project.utils', 'example/test_project/utils.py') """ module_root = os.path.split(path)[1] modules = list() for root, directories, filenames in os.walk(path): for filename in filenames: ...
Return a list containing tuples of e.g. ('test_project.utils', 'example/test_project/utils.py')
Below is the the instruction that describes the task: ### Input: Return a list containing tuples of e.g. ('test_project.utils', 'example/test_project/utils.py') ### Response: def get_modules(path, prepend_module_root=True): """Return a list containing tuples of e.g. ('test_project.utils', 'example/test...
def get_family_hierarchy_session(self, proxy=None): """Gets the ``OsidSession`` associated with the family hierarchy service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.relationship.FamilyHierarchySession) - a ``FamilyHierarchySession`` for families raise: ...
Gets the ``OsidSession`` associated with the family hierarchy service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.relationship.FamilyHierarchySession) - a ``FamilyHierarchySession`` for families raise: NullArgument - ``proxy`` is ``null`` raise: OperationF...
Below is the the instruction that describes the task: ### Input: Gets the ``OsidSession`` associated with the family hierarchy service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.relationship.FamilyHierarchySession) - a ``FamilyHierarchySession`` for families ra...
def _algebraic_rules_scalar(): """Set the default algebraic rules for scalars""" a = wc("a", head=SCALAR_VAL_TYPES) b = wc("b", head=SCALAR_VAL_TYPES) x = wc("x", head=SCALAR_TYPES) y = wc("y", head=SCALAR_TYPES) z = wc("z", head=SCALAR_TYPES) indranges__ = wc("indranges__", head=IndexRange...
Set the default algebraic rules for scalars
Below is the the instruction that describes the task: ### Input: Set the default algebraic rules for scalars ### Response: def _algebraic_rules_scalar(): """Set the default algebraic rules for scalars""" a = wc("a", head=SCALAR_VAL_TYPES) b = wc("b", head=SCALAR_VAL_TYPES) x = wc("x", head=SCALAR_T...
def EnsurePythonVersion(self, major, minor): """Exit abnormally if the Python version is not late enough.""" if sys.version_info < (major, minor): v = sys.version.split()[0] print("Python %d.%d or greater required, but you have Python %s" %(major,minor,v)) sys.exit(2)
Exit abnormally if the Python version is not late enough.
Below is the the instruction that describes the task: ### Input: Exit abnormally if the Python version is not late enough. ### Response: def EnsurePythonVersion(self, major, minor): """Exit abnormally if the Python version is not late enough.""" if sys.version_info < (major, minor): v =...
def get_table_column_statistics(self, db_name, tbl_name, col_name): """ Parameters: - db_name - tbl_name - col_name """ self.send_get_table_column_statistics(db_name, tbl_name, col_name) return self.recv_get_table_column_statistics()
Parameters: - db_name - tbl_name - col_name
Below is the the instruction that describes the task: ### Input: Parameters: - db_name - tbl_name - col_name ### Response: def get_table_column_statistics(self, db_name, tbl_name, col_name): """ Parameters: - db_name - tbl_name - col_name """ self.send_get_table_column...
def rbf(ra, coeff, mag): """ Calculate the median ground motion for a given magnitude and distance :param ra: Distance value [km] :param coeff: The set of coefficients :param mag: Magnitude value :returns: """ a1ca, a1cb, a1cc, a1cd, a1ce, a2ca, a2cb, a2cc, a2cd...
Calculate the median ground motion for a given magnitude and distance :param ra: Distance value [km] :param coeff: The set of coefficients :param mag: Magnitude value :returns:
Below is the the instruction that describes the task: ### Input: Calculate the median ground motion for a given magnitude and distance :param ra: Distance value [km] :param coeff: The set of coefficients :param mag: Magnitude value :returns: ### Response: def rbf(ra, coeff,...
def EscapeWildcards(string): """Escapes wildcard characters for strings intended to be used with `LIKE`. Databases don't automatically escape wildcard characters ('%', '_'), so any non-literal string that is passed to `LIKE` and is expected to match literally has to be manually escaped. Args: string: A ...
Escapes wildcard characters for strings intended to be used with `LIKE`. Databases don't automatically escape wildcard characters ('%', '_'), so any non-literal string that is passed to `LIKE` and is expected to match literally has to be manually escaped. Args: string: A string to escape. Returns: ...
Below is the the instruction that describes the task: ### Input: Escapes wildcard characters for strings intended to be used with `LIKE`. Databases don't automatically escape wildcard characters ('%', '_'), so any non-literal string that is passed to `LIKE` and is expected to match literally has to be manual...
def create_definition(self, definition, project, definition_to_clone_id=None, definition_to_clone_revision=None): """CreateDefinition. Creates a new definition. :param :class:`<BuildDefinition> <azure.devops.v5_0.build.models.BuildDefinition>` definition: The definition. :param str proje...
CreateDefinition. Creates a new definition. :param :class:`<BuildDefinition> <azure.devops.v5_0.build.models.BuildDefinition>` definition: The definition. :param str project: Project ID or project name :param int definition_to_clone_id: :param int definition_to_clone_revision: ...
Below is the the instruction that describes the task: ### Input: CreateDefinition. Creates a new definition. :param :class:`<BuildDefinition> <azure.devops.v5_0.build.models.BuildDefinition>` definition: The definition. :param str project: Project ID or project name :param int defini...
def parse_text(self,text): """Parse string (helper function)""" try: return self.rProgram.ignore(cStyleComment).parseString(text, parseAll=True) except SemanticException as err: print(err) exit(3) except ParseException as err: print...
Parse string (helper function)
Below is the the instruction that describes the task: ### Input: Parse string (helper function) ### Response: def parse_text(self,text): """Parse string (helper function)""" try: return self.rProgram.ignore(cStyleComment).parseString(text, parseAll=True) except SemanticExcep...
def set_warndays(name, warndays): ''' Set the number of days of warning before a password change is required. See man passwd. CLI Example: .. code-block:: bash salt '*' shadow.set_warndays username 7 ''' pre_info = info(name) if warndays == pre_info['warn']: return Tru...
Set the number of days of warning before a password change is required. See man passwd. CLI Example: .. code-block:: bash salt '*' shadow.set_warndays username 7
Below is the the instruction that describes the task: ### Input: Set the number of days of warning before a password change is required. See man passwd. CLI Example: .. code-block:: bash salt '*' shadow.set_warndays username 7 ### Response: def set_warndays(name, warndays): ''' Set t...
def list_functions(mod_name): """Lists all functions declared in a module. http://stackoverflow.com/a/1107150/3004221 Args: mod_name: the module name Returns: A list of functions declared in that module. """ mod = sys.modules[mod_name] return [func.__name__ for func in mod....
Lists all functions declared in a module. http://stackoverflow.com/a/1107150/3004221 Args: mod_name: the module name Returns: A list of functions declared in that module.
Below is the the instruction that describes the task: ### Input: Lists all functions declared in a module. http://stackoverflow.com/a/1107150/3004221 Args: mod_name: the module name Returns: A list of functions declared in that module. ### Response: def list_functions(mod_name): "...
def IndexReadPostingLists(self, index_urn, keywords, start_time, end_time, last_seen_map=None): """Finds all objects associated with any of the keywords. Args: index...
Finds all objects associated with any of the keywords. Args: index_urn: The base urn of the index. keywords: A collection of keywords that we are interested in. start_time: Only considers keywords added at or after this point in time. end_time: Only considers keywords at or before this poin...
Below is the the instruction that describes the task: ### Input: Finds all objects associated with any of the keywords. Args: index_urn: The base urn of the index. keywords: A collection of keywords that we are interested in. start_time: Only considers keywords added at or after this point in...
def cleanup(self): """ Do cleanup (stop and remove watchdogs that are no longer needed) :return: None """ for task in self.__done_registry: task.stop() self.__done_registry.clear() self.cleanup_event().clear()
Do cleanup (stop and remove watchdogs that are no longer needed) :return: None
Below is the the instruction that describes the task: ### Input: Do cleanup (stop and remove watchdogs that are no longer needed) :return: None ### Response: def cleanup(self): """ Do cleanup (stop and remove watchdogs that are no longer needed) :return: None """ for task in self.__done_registry: ta...
def picard_formatconverter(picard, align_sam): """Convert aligned SAM file to BAM format. """ out_bam = "%s.bam" % os.path.splitext(align_sam)[0] if not file_exists(out_bam): with tx_tmpdir(picard._config) as tmp_dir: with file_transaction(picard._config, out_bam) as tx_out_bam: ...
Convert aligned SAM file to BAM format.
Below is the the instruction that describes the task: ### Input: Convert aligned SAM file to BAM format. ### Response: def picard_formatconverter(picard, align_sam): """Convert aligned SAM file to BAM format. """ out_bam = "%s.bam" % os.path.splitext(align_sam)[0] if not file_exists(out_bam): ...
def context(): """ Returns a new JobBackend instance which connects to AETROS Trainer based on "model" in aetros.yml or (internal: env:AETROS_MODEL_NAME environment variable). internal: If env:AETROS_JOB_ID is not defined, it creates a new job. Job is ended either by calling JobBackend.done(), Job...
Returns a new JobBackend instance which connects to AETROS Trainer based on "model" in aetros.yml or (internal: env:AETROS_MODEL_NAME environment variable). internal: If env:AETROS_JOB_ID is not defined, it creates a new job. Job is ended either by calling JobBackend.done(), JobBackend.fail() or JobBacken...
Below is the the instruction that describes the task: ### Input: Returns a new JobBackend instance which connects to AETROS Trainer based on "model" in aetros.yml or (internal: env:AETROS_MODEL_NAME environment variable). internal: If env:AETROS_JOB_ID is not defined, it creates a new job. Job is ende...
def fix_partial_utf8_punct_in_1252(text): """ Fix particular characters that seem to be found in the wild encoded in UTF-8 and decoded in Latin-1 or Windows-1252, even when this fix can't be consistently applied. One form of inconsistency we need to deal with is that some character might be fro...
Fix particular characters that seem to be found in the wild encoded in UTF-8 and decoded in Latin-1 or Windows-1252, even when this fix can't be consistently applied. One form of inconsistency we need to deal with is that some character might be from the Latin-1 C1 control character set, while others a...
Below is the the instruction that describes the task: ### Input: Fix particular characters that seem to be found in the wild encoded in UTF-8 and decoded in Latin-1 or Windows-1252, even when this fix can't be consistently applied. One form of inconsistency we need to deal with is that some character m...
def datetime2et(dt): """ Converts a standard Python datetime to a double precision value representing the number of TDB seconds past the J2000 epoch corresponding to the input epoch. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/req/time.html#The%20J2000%20Epoch :param dt: A standard Pyt...
Converts a standard Python datetime to a double precision value representing the number of TDB seconds past the J2000 epoch corresponding to the input epoch. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/req/time.html#The%20J2000%20Epoch :param dt: A standard Python datetime :type time: date...
Below is the the instruction that describes the task: ### Input: Converts a standard Python datetime to a double precision value representing the number of TDB seconds past the J2000 epoch corresponding to the input epoch. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/req/time.html#The%20J2000%20...
def disconnect(self, cback): "See signal" return self.signal.disconnect(cback, subscribers=self.subscribers, instance=self.instance)
See signal
Below is the the instruction that describes the task: ### Input: See signal ### Response: def disconnect(self, cback): "See signal" return self.signal.disconnect(cback, subscribers=self.subscribers, instance=self.instance)
def list_staged_files(self) -> typing.List[str]: """ :return: staged files :rtype: list of str """ staged_files: typing.List[str] = [x.a_path for x in self.repo.index.diff('HEAD')] LOGGER.debug('staged files: %s', staged_files) return staged_files
:return: staged files :rtype: list of str
Below is the the instruction that describes the task: ### Input: :return: staged files :rtype: list of str ### Response: def list_staged_files(self) -> typing.List[str]: """ :return: staged files :rtype: list of str """ staged_files: typing.List[str] = [x.a_path for ...
def update_swarm(self, version, swarm_spec=None, rotate_worker_token=False, rotate_manager_token=False): """ Update the Swarm's configuration Args: version (int): The version number of the swarm object being updated. This is required to avoid con...
Update the Swarm's configuration Args: version (int): The version number of the swarm object being updated. This is required to avoid conflicting writes. swarm_spec (dict): Configuration settings to update. Use :py:meth:`~docker.api.swarm.SwarmApiMixin.cr...
Below is the the instruction that describes the task: ### Input: Update the Swarm's configuration Args: version (int): The version number of the swarm object being updated. This is required to avoid conflicting writes. swarm_spec (dict): Configuration settings to upd...
def get_application_by_name(self, team_name, application_name): """ Retrieves an application using the given team name and application name. :param team_name: The name of the team of the application to be retrieved. :param application_name: The name of the application to be retrieved. ...
Retrieves an application using the given team name and application name. :param team_name: The name of the team of the application to be retrieved. :param application_name: The name of the application to be retrieved.
Below is the the instruction that describes the task: ### Input: Retrieves an application using the given team name and application name. :param team_name: The name of the team of the application to be retrieved. :param application_name: The name of the application to be retrieved. ### Response: de...
def add_constraint(self, name, tpe, val): """ adds a constraint for the plan """ self.constraint.append([name, tpe, val])
adds a constraint for the plan
Below is the the instruction that describes the task: ### Input: adds a constraint for the plan ### Response: def add_constraint(self, name, tpe, val): """ adds a constraint for the plan """ self.constraint.append([name, tpe, val])
def build_error(self, err): """ When an exception is encountered, this generates a JSON error message for display to the user. :param err: The exception seen. The message is exposed to the user, so beware of sensitive data leaking. :type err: Exception :retu...
When an exception is encountered, this generates a JSON error message for display to the user. :param err: The exception seen. The message is exposed to the user, so beware of sensitive data leaking. :type err: Exception :returns: A response object
Below is the the instruction that describes the task: ### Input: When an exception is encountered, this generates a JSON error message for display to the user. :param err: The exception seen. The message is exposed to the user, so beware of sensitive data leaking. :type err: Exc...
def extend(self, item): """Extend the list with another list. Each member of the list must be a string.""" if not isinstance(item, list): raise TypeError( 'You can only extend lists with lists. ' 'You supplied \"%s\"' % type(item)) for entry in...
Extend the list with another list. Each member of the list must be a string.
Below is the the instruction that describes the task: ### Input: Extend the list with another list. Each member of the list must be a string. ### Response: def extend(self, item): """Extend the list with another list. Each member of the list must be a string.""" if not isinstance(it...
def _import_platform_generator(platform): ''' Given a specific platform (under the Capirca conventions), return the generator class. The generator class is identified looking under the <platform> module for a class inheriting the `ACLGenerator` class. ''' log.debug('Using platform: %s', plat...
Given a specific platform (under the Capirca conventions), return the generator class. The generator class is identified looking under the <platform> module for a class inheriting the `ACLGenerator` class.
Below is the the instruction that describes the task: ### Input: Given a specific platform (under the Capirca conventions), return the generator class. The generator class is identified looking under the <platform> module for a class inheriting the `ACLGenerator` class. ### Response: def _import_platfo...
def acknowledge_alarm(self, alarm, comment=None): """ Acknowledges a specific alarm associated with a parameter. :param alarm: Alarm instance :type alarm: :class:`.Alarm` :param str comment: Optional comment to associate with the state change. ...
Acknowledges a specific alarm associated with a parameter. :param alarm: Alarm instance :type alarm: :class:`.Alarm` :param str comment: Optional comment to associate with the state change.
Below is the the instruction that describes the task: ### Input: Acknowledges a specific alarm associated with a parameter. :param alarm: Alarm instance :type alarm: :class:`.Alarm` :param str comment: Optional comment to associate with the state change. ### Resp...
def fetch_assets(self): """ download bootstrap assets to control host. If present on the control host they will be uploaded to the target host during bootstrapping. """ # allow overwrites from the commandline packages = set( env.instance.config.get('bootstrap-packages...
download bootstrap assets to control host. If present on the control host they will be uploaded to the target host during bootstrapping.
Below is the the instruction that describes the task: ### Input: download bootstrap assets to control host. If present on the control host they will be uploaded to the target host during bootstrapping. ### Response: def fetch_assets(self): """ download bootstrap assets to control host. If p...
def _parse_game_date_and_location(self, boxscore): """ Retrieve the game's date and location. The date and location of the game follow a more complicated parsing scheme and should be handled differently from other tags. Both fields are separated by a newline character ('\n') wit...
Retrieve the game's date and location. The date and location of the game follow a more complicated parsing scheme and should be handled differently from other tags. Both fields are separated by a newline character ('\n') with the first line being the date and the second being the locati...
Below is the the instruction that describes the task: ### Input: Retrieve the game's date and location. The date and location of the game follow a more complicated parsing scheme and should be handled differently from other tags. Both fields are separated by a newline character ('\n') with ...
def debug(level=logging.DEBUG): """ Turn on the debugging """ from jcvi.apps.console import magenta, yellow format = yellow("%(asctime)s [%(module)s]") format += magenta(" %(message)s") logging.basicConfig(level=level, format=format, datefmt="%H:%M:%S")
Turn on the debugging
Below is the the instruction that describes the task: ### Input: Turn on the debugging ### Response: def debug(level=logging.DEBUG): """ Turn on the debugging """ from jcvi.apps.console import magenta, yellow format = yellow("%(asctime)s [%(module)s]") format += magenta(" %(message)s") ...
def shutdown(self): """Stops all active periodic tasks and closes the socket.""" self.stop_all_periodic_tasks() for channel in self._bcm_sockets: log.debug("Closing bcm socket for channel {}".format(channel)) bcm_socket = self._bcm_sockets[channel] bcm_socket....
Stops all active periodic tasks and closes the socket.
Below is the the instruction that describes the task: ### Input: Stops all active periodic tasks and closes the socket. ### Response: def shutdown(self): """Stops all active periodic tasks and closes the socket.""" self.stop_all_periodic_tasks() for channel in self._bcm_sockets: ...
def search(self, CorpNum, DType, SDate, EDate, State, ItemCode, Page, PerPage, Order, UserID=None, QString=None): """ 목록 조회 args CorpNum : 팝빌회원 사업자번호 DType : 일자유형, R-등록일시, W-작성일자, I-발행일시 중 택 1 SDate : 시작일자, 표시형식(yyyyMMdd) EDate : ...
목록 조회 args CorpNum : 팝빌회원 사업자번호 DType : 일자유형, R-등록일시, W-작성일자, I-발행일시 중 택 1 SDate : 시작일자, 표시형식(yyyyMMdd) EDate : 종료일자, 표시형식(yyyyMMdd) State : 상태코드, 2,3번째 자리에 와일드카드(*) 사용가능 ItemCode : 명세서 종류코드 배열, 121-명세서, 1...
Below is the the instruction that describes the task: ### Input: 목록 조회 args CorpNum : 팝빌회원 사업자번호 DType : 일자유형, R-등록일시, W-작성일자, I-발행일시 중 택 1 SDate : 시작일자, 표시형식(yyyyMMdd) EDate : 종료일자, 표시형식(yyyyMMdd) State : 상태코드, 2,3번째 ...
def simple_predictive_probability(self, M_c, X_L, X_D, Y, Q): """Calculate probability of a cell taking a value given a latent state. :param Y: A list of constraints to apply when querying. Each constraint is a triplet of (r, d, v): r is the row index, d is the column index and...
Calculate probability of a cell taking a value given a latent state. :param Y: A list of constraints to apply when querying. Each constraint is a triplet of (r, d, v): r is the row index, d is the column index and v is the value of the constraint :type Y: list of lists ...
Below is the the instruction that describes the task: ### Input: Calculate probability of a cell taking a value given a latent state. :param Y: A list of constraints to apply when querying. Each constraint is a triplet of (r, d, v): r is the row index, d is the column index and v i...
def gen_cartesian_product(*args): """ generate cartesian product for lists Args: args (list of list): lists to be generated with cartesian product Returns: list: cartesian product in list Examples: >>> arg1 = [{"a": 1}, {"a": 2}] >>> arg2 = [{"x": 111, "y": 112}, {"x"...
generate cartesian product for lists Args: args (list of list): lists to be generated with cartesian product Returns: list: cartesian product in list Examples: >>> arg1 = [{"a": 1}, {"a": 2}] >>> arg2 = [{"x": 111, "y": 112}, {"x": 121, "y": 122}] >>> args = [arg1...
Below is the the instruction that describes the task: ### Input: generate cartesian product for lists Args: args (list of list): lists to be generated with cartesian product Returns: list: cartesian product in list Examples: >>> arg1 = [{"a": 1}, {"a": 2}] >>> arg2 = ...
def fix_length(data, size, axis=-1, **kwargs): '''Fix the length an array `data` to exactly `size`. If `data.shape[axis] < n`, pad according to the provided kwargs. By default, `data` is padded with trailing zeros. Examples -------- >>> y = np.arange(7) >>> # Default: pad with zeros >>...
Fix the length an array `data` to exactly `size`. If `data.shape[axis] < n`, pad according to the provided kwargs. By default, `data` is padded with trailing zeros. Examples -------- >>> y = np.arange(7) >>> # Default: pad with zeros >>> librosa.util.fix_length(y, 10) array([0, 1, 2, 3...
Below is the the instruction that describes the task: ### Input: Fix the length an array `data` to exactly `size`. If `data.shape[axis] < n`, pad according to the provided kwargs. By default, `data` is padded with trailing zeros. Examples -------- >>> y = np.arange(7) >>> # Default: pad wi...
def keep_absolute_mask__r2(X, y, model_generator, method_name, num_fcounts=11): """ Keep Absolute (mask) xlabel = "Max fraction of features kept" ylabel = "R^2" transform = "identity" sort_order = 6 """ return __run_measure(measures.keep_mask, X, y, model_generator, method_name, 0, num_fcoun...
Keep Absolute (mask) xlabel = "Max fraction of features kept" ylabel = "R^2" transform = "identity" sort_order = 6
Below is the the instruction that describes the task: ### Input: Keep Absolute (mask) xlabel = "Max fraction of features kept" ylabel = "R^2" transform = "identity" sort_order = 6 ### Response: def keep_absolute_mask__r2(X, y, model_generator, method_name, num_fcounts=11): """ Keep Absolute (ma...
def get_url(client, name, version, wheel=False, hashed_format=False): """Retrieves list of package URLs using PyPI's XML-RPC. Chooses URL of prefered archive and md5_digest. """ try: release_urls = client.release_urls(name, version) release_data = client.release_data(name, version) e...
Retrieves list of package URLs using PyPI's XML-RPC. Chooses URL of prefered archive and md5_digest.
Below is the the instruction that describes the task: ### Input: Retrieves list of package URLs using PyPI's XML-RPC. Chooses URL of prefered archive and md5_digest. ### Response: def get_url(client, name, version, wheel=False, hashed_format=False): """Retrieves list of package URLs using PyPI's XML-RPC. C...
def parse(self, ps, **kw): ''' ps -- ParsedSoap instance ''' namespaceURI = self.wsAddressURI elements = ("MessageID","Action","To","From","RelatesTo") d = {namespaceURI:elements} typecodes = self._getWSAddressTypeCodes(**d) pyobjs = ps.ParseHeaderElements...
ps -- ParsedSoap instance
Below is the the instruction that describes the task: ### Input: ps -- ParsedSoap instance ### Response: def parse(self, ps, **kw): ''' ps -- ParsedSoap instance ''' namespaceURI = self.wsAddressURI elements = ("MessageID","Action","To","From","RelatesTo") d = {names...
def get_mac_addr(mac_addr): """converts bytes to mac addr format :mac_addr: ctypes.structure :return: str mac addr in format 11:22:33:aa:bb:cc """ mac_addr = bytearray(mac_addr) mac = b':'.join([('%02x' % o).encode('ascii') for o in mac_addr]) ...
converts bytes to mac addr format :mac_addr: ctypes.structure :return: str mac addr in format 11:22:33:aa:bb:cc
Below is the the instruction that describes the task: ### Input: converts bytes to mac addr format :mac_addr: ctypes.structure :return: str mac addr in format 11:22:33:aa:bb:cc ### Response: def get_mac_addr(mac_addr): """converts bytes to mac addr format :ma...
def stage_files(pathmapper, # type: PathMapper stage_func=None, # type: Callable[..., Any] ignore_writable=False, # type: bool symlink=True, # type: bool secret_store=None # type: SecretStore ): # type: (...
Link or copy files to their targets. Create them as needed.
Below is the the instruction that describes the task: ### Input: Link or copy files to their targets. Create them as needed. ### Response: def stage_files(pathmapper, # type: PathMapper stage_func=None, # type: Callable[..., Any] ignore_writable=False, # type: bo...
def merge_and_fit(self, track, pairings): """ Merges another track with this one, ordering the points based on a distance heuristic Args: track (:obj:`Track`): Track to merge with pairings Returns: :obj:`Segment`: self """ for (se...
Merges another track with this one, ordering the points based on a distance heuristic Args: track (:obj:`Track`): Track to merge with pairings Returns: :obj:`Segment`: self
Below is the the instruction that describes the task: ### Input: Merges another track with this one, ordering the points based on a distance heuristic Args: track (:obj:`Track`): Track to merge with pairings Returns: :obj:`Segment`: self ### Response:...
def get_aggregation(self): """ Return the aggregation object. """ agg = A(self.agg_type, **self._params) if self._metric: agg.metric('metric', self._metric) return agg
Return the aggregation object.
Below is the the instruction that describes the task: ### Input: Return the aggregation object. ### Response: def get_aggregation(self): """ Return the aggregation object. """ agg = A(self.agg_type, **self._params) if self._metric: agg.metric('metric', self._metr...
def watch(self, key, *keys): """Watch the given keys to determine execution of the MULTI/EXEC block. """ # FIXME: we can send watch through one connection and then issue # 'multi/exec' command through other. # Possible fix: # "Remember" a connection that was used for ...
Watch the given keys to determine execution of the MULTI/EXEC block.
Below is the the instruction that describes the task: ### Input: Watch the given keys to determine execution of the MULTI/EXEC block. ### Response: def watch(self, key, *keys): """Watch the given keys to determine execution of the MULTI/EXEC block. """ # FIXME: we can send watch through one...
def alias_log(self, log_id, alias_id): """Adds an ``Id`` to a ``Log`` for the purpose of creating compatibility. The primary ``Id`` of the ``Log`` is determined by the provider. The new ``Id`` performs as an alias to the primary ``Id``. If the alias is a pointer to another log, it is re...
Adds an ``Id`` to a ``Log`` for the purpose of creating compatibility. The primary ``Id`` of the ``Log`` is determined by the provider. The new ``Id`` performs as an alias to the primary ``Id``. If the alias is a pointer to another log, it is reassigned to the given log ``Id``. ...
Below is the the instruction that describes the task: ### Input: Adds an ``Id`` to a ``Log`` for the purpose of creating compatibility. The primary ``Id`` of the ``Log`` is determined by the provider. The new ``Id`` performs as an alias to the primary ``Id``. If the alias is a pointer to an...
def parse_rule(cls, txt): """Parse a rule from a string. See rezconfig.package_filter for an overview of valid strings. Args: txt (str): String to parse. Returns: `Rule` instance. """ types = {"glob": GlobRule, "regex": RegexRul...
Parse a rule from a string. See rezconfig.package_filter for an overview of valid strings. Args: txt (str): String to parse. Returns: `Rule` instance.
Below is the the instruction that describes the task: ### Input: Parse a rule from a string. See rezconfig.package_filter for an overview of valid strings. Args: txt (str): String to parse. Returns: `Rule` instance. ### Response: def parse_rule(cls, txt): ...
def evaluate(args, embedding, vocab, global_step, eval_analogy=False): """Evaluation helper""" if 'eval_tokens' not in globals(): global eval_tokens eval_tokens_set = evaluation.get_tokens_in_evaluation_datasets(args) if not args.no_eval_analogy: eval_tokens_set.update(vocab...
Evaluation helper
Below is the the instruction that describes the task: ### Input: Evaluation helper ### Response: def evaluate(args, embedding, vocab, global_step, eval_analogy=False): """Evaluation helper""" if 'eval_tokens' not in globals(): global eval_tokens eval_tokens_set = evaluation.get_tokens_in_e...
def parse_coverage(coverage_report, parser): """ :param coverage_report: A string with the contents of a coverage file :type coverage_report: String :param parser: A string with name of the parser to use :type parser: String :return: Total coverage """ if parser in PARSERS: if co...
:param coverage_report: A string with the contents of a coverage file :type coverage_report: String :param parser: A string with name of the parser to use :type parser: String :return: Total coverage
Below is the the instruction that describes the task: ### Input: :param coverage_report: A string with the contents of a coverage file :type coverage_report: String :param parser: A string with name of the parser to use :type parser: String :return: Total coverage ### Response: def parse_coverage(c...
def lsa_twitter(cased_tokens): """ Latent Sentiment Analyis on random sampling of twitter search results for words listed in cased_tokens """ # Only 5 of these tokens are saved for a no_below=2 filter: # PyCons NLPS #PyCon2016 #NaturalLanguageProcessing #naturallanguageprocessing if cased_tokens is N...
Latent Sentiment Analyis on random sampling of twitter search results for words listed in cased_tokens
Below is the the instruction that describes the task: ### Input: Latent Sentiment Analyis on random sampling of twitter search results for words listed in cased_tokens ### Response: def lsa_twitter(cased_tokens): """ Latent Sentiment Analyis on random sampling of twitter search results for words listed in case...
def _load_key(key_object): """ Common code to load public and private keys into PublicKey and PrivateKey objects :param key_object: An asn1crypto.keys.PublicKeyInfo or asn1crypto.keys.PrivateKeyInfo object :raises: ValueError - when any of the parameters contain an invalid ...
Common code to load public and private keys into PublicKey and PrivateKey objects :param key_object: An asn1crypto.keys.PublicKeyInfo or asn1crypto.keys.PrivateKeyInfo object :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of t...
Below is the the instruction that describes the task: ### Input: Common code to load public and private keys into PublicKey and PrivateKey objects :param key_object: An asn1crypto.keys.PublicKeyInfo or asn1crypto.keys.PrivateKeyInfo object :raises: ValueError - when any of the ...
def disable_switchport(self, inter_type, inter): """ Change an interface's operation to L3. Args: inter_type: The type of interface you want to configure. Ex. tengigabitethernet, gigabitethernet, fortygigabitethernet. inter: The ID for the interface you w...
Change an interface's operation to L3. Args: inter_type: The type of interface you want to configure. Ex. tengigabitethernet, gigabitethernet, fortygigabitethernet. inter: The ID for the interface you want to configure. Ex. 1/0/1 Returns: True if com...
Below is the the instruction that describes the task: ### Input: Change an interface's operation to L3. Args: inter_type: The type of interface you want to configure. Ex. tengigabitethernet, gigabitethernet, fortygigabitethernet. inter: The ID for the interface you w...
def list(self, order=values.unset, from_=values.unset, bounds=values.unset, limit=None, page_size=None): """ Lists SyncListItemInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. ...
Lists SyncListItemInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. :param SyncListItemInstance.QueryResultOrder order: The order :param unicode from_: The from :param SyncListItemInstanc...
Below is the the instruction that describes the task: ### Input: Lists SyncListItemInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. :param SyncListItemInstance.QueryResultOrder order: The order ...
def xopen(filename, mode='r', compresslevel=6, threads=None): """ A replacement for the "open" function that can also open files that have been compressed with gzip, bzip2 or xz. If the filename is '-', standard output (mode 'w') or input (mode 'r') is returned. The file type is determined based on...
A replacement for the "open" function that can also open files that have been compressed with gzip, bzip2 or xz. If the filename is '-', standard output (mode 'w') or input (mode 'r') is returned. The file type is determined based on the filename: .gz is gzip, .bz2 is bzip2 and .xz is xz/lzma. Whe...
Below is the the instruction that describes the task: ### Input: A replacement for the "open" function that can also open files that have been compressed with gzip, bzip2 or xz. If the filename is '-', standard output (mode 'w') or input (mode 'r') is returned. The file type is determined based on the ...
def start (self): """Starts this UdpTelemetryServer.""" values = self._defn.name, self.server_host, self.server_port log.info('Listening for %s telemetry on %s:%d (UDP)' % values) super(UdpTelemetryServer, self).start()
Starts this UdpTelemetryServer.
Below is the the instruction that describes the task: ### Input: Starts this UdpTelemetryServer. ### Response: def start (self): """Starts this UdpTelemetryServer.""" values = self._defn.name, self.server_host, self.server_port log.info('Listening for %s telemetry on %s:%d (UDP)' % values) ...
def _setup_reference_files(data, tx_out_dir): """Create a reference directory with fasta and bwa indices. GRIDSS requires all files in a single directory, so setup with symlinks. This needs bwa aligner indices available, which we ensure with `get_aligner_with_aliases` during YAML sample setup. """ ...
Create a reference directory with fasta and bwa indices. GRIDSS requires all files in a single directory, so setup with symlinks. This needs bwa aligner indices available, which we ensure with `get_aligner_with_aliases` during YAML sample setup.
Below is the the instruction that describes the task: ### Input: Create a reference directory with fasta and bwa indices. GRIDSS requires all files in a single directory, so setup with symlinks. This needs bwa aligner indices available, which we ensure with `get_aligner_with_aliases` during YAML sample...
async def send_cred_def(self, s_id: str, revo: bool = True, rr_size: int = None) -> str: """ Create a credential definition as Issuer, store it in its wallet, and send it to the ledger. Raise CorruptWallet for wallet not pertaining to current ledger, BadLedgerTxn on failure to send cred...
Create a credential definition as Issuer, store it in its wallet, and send it to the ledger. Raise CorruptWallet for wallet not pertaining to current ledger, BadLedgerTxn on failure to send credential definition to ledger if need be, WalletState for closed wallet, or IndyError for any other fai...
Below is the the instruction that describes the task: ### Input: Create a credential definition as Issuer, store it in its wallet, and send it to the ledger. Raise CorruptWallet for wallet not pertaining to current ledger, BadLedgerTxn on failure to send credential definition to ledger if need be, ...
def format_instance(instance): """Serialise `instance` For children to be visualised and modified, they must provide an appropriate implementation of __str__. Data that isn't JSON compatible cannot be visualised nor modified. Attributes: name (str): Name of instance niceNa...
Serialise `instance` For children to be visualised and modified, they must provide an appropriate implementation of __str__. Data that isn't JSON compatible cannot be visualised nor modified. Attributes: name (str): Name of instance niceName (str, optional): Nice name of insta...
Below is the the instruction that describes the task: ### Input: Serialise `instance` For children to be visualised and modified, they must provide an appropriate implementation of __str__. Data that isn't JSON compatible cannot be visualised nor modified. Attributes: name (str): ...
def add_markup( self ): """add a new markup section""" if self.markup and self.markup_lines: # get rid of last line of markup if it's empty marks = self.markup_lines if len( marks ) > 0 and not string.strip( marks[-1] ): self.markup_lines = marks[:-1...
add a new markup section
Below is the the instruction that describes the task: ### Input: add a new markup section ### Response: def add_markup( self ): """add a new markup section""" if self.markup and self.markup_lines: # get rid of last line of markup if it's empty marks = self.markup_lines ...
def can_create_repository_with_record_types(self, repository_record_types): """Tests if this user can create a single ``Repository`` using the desired record types. While ``RepositoryManager.getRepositoryRecordTypes()`` can be used to examine which records are supported, this method tests ...
Tests if this user can create a single ``Repository`` using the desired record types. While ``RepositoryManager.getRepositoryRecordTypes()`` can be used to examine which records are supported, this method tests which record(s) are required for creating a specific ``Repository``. Providi...
Below is the the instruction that describes the task: ### Input: Tests if this user can create a single ``Repository`` using the desired record types. While ``RepositoryManager.getRepositoryRecordTypes()`` can be used to examine which records are supported, this method tests which record(s)...
def route(self, resource, view, *urls, **kwargs): """Create an api view. :param Resource resource: a resource class inherited from flask_rest_jsonapi.resource.Resource :param str view: the view name :param list urls: the urls of the view :param dict kwargs: additional options of...
Create an api view. :param Resource resource: a resource class inherited from flask_rest_jsonapi.resource.Resource :param str view: the view name :param list urls: the urls of the view :param dict kwargs: additional options of the route
Below is the the instruction that describes the task: ### Input: Create an api view. :param Resource resource: a resource class inherited from flask_rest_jsonapi.resource.Resource :param str view: the view name :param list urls: the urls of the view :param dict kwargs: additional op...
def get_queryset(self): """ Returns the list of items for this view. """ forums = self.request.forum_permission_handler.get_readable_forums( Forum.objects.all(), self.request.user, ) topics = Topic.objects.filter(forum__in=forums) topics_pk = map(lambda t: t.pk, track...
Returns the list of items for this view.
Below is the the instruction that describes the task: ### Input: Returns the list of items for this view. ### Response: def get_queryset(self): """ Returns the list of items for this view. """ forums = self.request.forum_permission_handler.get_readable_forums( Forum.objects.all(), self....
def _clean_css(self): """ Returns the cleaned CSS :param stylesheet: The Stylesheet object to parse :type stylesheet: tinycss.css21.Stylesheet """ # Init the cleaned CSS rules and contents string css_rules = [] # For every rule in the CSS for rul...
Returns the cleaned CSS :param stylesheet: The Stylesheet object to parse :type stylesheet: tinycss.css21.Stylesheet
Below is the the instruction that describes the task: ### Input: Returns the cleaned CSS :param stylesheet: The Stylesheet object to parse :type stylesheet: tinycss.css21.Stylesheet ### Response: def _clean_css(self): """ Returns the cleaned CSS :param stylesheet: The Styl...
def get_by_timestamp(self, prefix, timestamp): """Get the cache file to a given timestamp.""" year, week = get_year_week(timestamp) return self.get(prefix, year, week)
Get the cache file to a given timestamp.
Below is the the instruction that describes the task: ### Input: Get the cache file to a given timestamp. ### Response: def get_by_timestamp(self, prefix, timestamp): """Get the cache file to a given timestamp.""" year, week = get_year_week(timestamp) return self.get(prefix, year, week)
def get_filter_cardborder(*cardborder_type): """Returns game cards URL filter for a given cardborder type (TAG_CARDBORDER_NORMAL / TAG_CARDBORDER_FOIL). To be used in URL_GAMECARDS. :param str|unicode cardborder_type: :rtype: str|unicode """ filter_ = [] for type_ in cardborder_type: ...
Returns game cards URL filter for a given cardborder type (TAG_CARDBORDER_NORMAL / TAG_CARDBORDER_FOIL). To be used in URL_GAMECARDS. :param str|unicode cardborder_type: :rtype: str|unicode
Below is the the instruction that describes the task: ### Input: Returns game cards URL filter for a given cardborder type (TAG_CARDBORDER_NORMAL / TAG_CARDBORDER_FOIL). To be used in URL_GAMECARDS. :param str|unicode cardborder_type: :rtype: str|unicode ### Response: def get_filter_cardborder(*c...
def import_object(modname, name): """ Import the object given by *modname* and *name* and return it. If not found, or the import fails, returns None. """ try: __import__(modname) mod = sys.modules[modname] obj = mod for part in name.split('.'): obj = getat...
Import the object given by *modname* and *name* and return it. If not found, or the import fails, returns None.
Below is the the instruction that describes the task: ### Input: Import the object given by *modname* and *name* and return it. If not found, or the import fails, returns None. ### Response: def import_object(modname, name): """ Import the object given by *modname* and *name* and return it. If not ...
def shell_run(cmd, cin=None, cwd=None, timeout=10, critical=True, verbose=True): ''' Runs a shell command within a controlled environment. .. note:: |use_photon_m| :param cmd: The command to run * A string one would type into a console like \ :command:`git push -u origin...
Runs a shell command within a controlled environment. .. note:: |use_photon_m| :param cmd: The command to run * A string one would type into a console like \ :command:`git push -u origin master`. * Will be split using :py:func:`shlex.split`. * It is possible to use a list he...
Below is the the instruction that describes the task: ### Input: Runs a shell command within a controlled environment. .. note:: |use_photon_m| :param cmd: The command to run * A string one would type into a console like \ :command:`git push -u origin master`. * Will be split usi...
def conf_from_dict(conf_dict): ''' Creates a configuration dictionary from a dictionary. :param conf_dict: The configuration dictionary. ''' conf = Config(filename=conf_dict.get('__file__', '')) for k, v in six.iteritems(conf_dict): if k.startswith('__'): continue e...
Creates a configuration dictionary from a dictionary. :param conf_dict: The configuration dictionary.
Below is the the instruction that describes the task: ### Input: Creates a configuration dictionary from a dictionary. :param conf_dict: The configuration dictionary. ### Response: def conf_from_dict(conf_dict): ''' Creates a configuration dictionary from a dictionary. :param conf_dict: The confi...
def bottleneck_layer(inputs, hparams, name="discrete_bottleneck"): """Computes latents given inputs (typically, compressed targets).""" [ latents_dense, latents_discrete, extra_loss, embed_fn, _, ] = hparams.bottleneck(inputs=inputs, ...
Computes latents given inputs (typically, compressed targets).
Below is the the instruction that describes the task: ### Input: Computes latents given inputs (typically, compressed targets). ### Response: def bottleneck_layer(inputs, hparams, name="discrete_bottleneck"): """Computes latents given inputs (typically, compressed target...
def get_title(brain_or_object): """Get the Title for this object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Title :rtype: string """ if is_brain(brain_or_object) and base_hasattr(brain_or_...
Get the Title for this object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Title :rtype: string
Below is the the instruction that describes the task: ### Input: Get the Title for this object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: Title :rtype: string ### Response: def get_title(brain_or...
def _link_to(self, linked_picker): """Customize the options when linked with other date-time input""" yformat = self.config['options']['format'].replace('-01-01', '-12-31') self.config['options']['format'] = yformat
Customize the options when linked with other date-time input
Below is the the instruction that describes the task: ### Input: Customize the options when linked with other date-time input ### Response: def _link_to(self, linked_picker): """Customize the options when linked with other date-time input""" yformat = self.config['options']['format'].replace('-01-0...
def get_args(): """Construct the argument parser.""" parser = argparse.ArgumentParser( description='Word embedding evaluation with Gluon.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # Embeddings arguments group = parser.add_argument_group('Embedding arguments') group.a...
Construct the argument parser.
Below is the the instruction that describes the task: ### Input: Construct the argument parser. ### Response: def get_args(): """Construct the argument parser.""" parser = argparse.ArgumentParser( description='Word embedding evaluation with Gluon.', formatter_class=argparse.ArgumentDefaults...
def find_cached_dm(self): """ Find filename where cached data model json is stored. Returns --------- model_file : str data model json file location """ pmag_dir = find_pmag_dir.get_pmag_dir() if pmag_dir is None: pmag_dir = '.' ...
Find filename where cached data model json is stored. Returns --------- model_file : str data model json file location
Below is the the instruction that describes the task: ### Input: Find filename where cached data model json is stored. Returns --------- model_file : str data model json file location ### Response: def find_cached_dm(self): """ Find filename where cached data mo...
def find_pore_hulls(self, pores=None): r""" Finds the indices of the Voronoi nodes that define the convex hull around the given Delaunay nodes. Parameters ---------- pores : array_like The pores whose convex hull are sought. The given pores should be ...
r""" Finds the indices of the Voronoi nodes that define the convex hull around the given Delaunay nodes. Parameters ---------- pores : array_like The pores whose convex hull are sought. The given pores should be from the 'delaunay' network. If no pores ...
Below is the the instruction that describes the task: ### Input: r""" Finds the indices of the Voronoi nodes that define the convex hull around the given Delaunay nodes. Parameters ---------- pores : array_like The pores whose convex hull are sought. The given p...
def get_uri(self): """ Get the connection uri for pinot broker. e.g: http://localhost:9000/pql """ conn = self.get_connection(getattr(self, self.conn_name_attr)) host = conn.host if conn.port is not None: host += ':{port}'.format(port=conn.port) ...
Get the connection uri for pinot broker. e.g: http://localhost:9000/pql
Below is the the instruction that describes the task: ### Input: Get the connection uri for pinot broker. e.g: http://localhost:9000/pql ### Response: def get_uri(self): """ Get the connection uri for pinot broker. e.g: http://localhost:9000/pql """ conn = self.get...
def get_strain_state_dict(strains, stresses, eq_stress=None, tol=1e-10, add_eq=True, sort=True): """ Creates a dictionary of voigt-notation stress-strain sets keyed by "strain state", i. e. a tuple corresponding to the non-zero entries in ratios to the lowest nonzero value, ...
Creates a dictionary of voigt-notation stress-strain sets keyed by "strain state", i. e. a tuple corresponding to the non-zero entries in ratios to the lowest nonzero value, e.g. [0, 0.1, 0, 0.2, 0, 0] -> (0,1,0,2,0,0) This allows strains to be collected in stencils as to evaluate parameterized fini...
Below is the the instruction that describes the task: ### Input: Creates a dictionary of voigt-notation stress-strain sets keyed by "strain state", i. e. a tuple corresponding to the non-zero entries in ratios to the lowest nonzero value, e.g. [0, 0.1, 0, 0.2, 0, 0] -> (0,1,0,2,0,0) This allows stra...
def create_ticket(self, ticket=None, **kwargs): """ Create a new ``Ticket``. Additional arguments are passed to the ``create()`` function. Return the newly created ``Ticket``. """ if not ticket: ticket = self.create_ticket_str() if 'service' in kwargs: ...
Create a new ``Ticket``. Additional arguments are passed to the ``create()`` function. Return the newly created ``Ticket``.
Below is the the instruction that describes the task: ### Input: Create a new ``Ticket``. Additional arguments are passed to the ``create()`` function. Return the newly created ``Ticket``. ### Response: def create_ticket(self, ticket=None, **kwargs): """ Create a new ``Ticket``. Additional ...
def points(self, points): """ set points without copying """ if not isinstance(points, np.ndarray): raise TypeError('Points must be a numpy array') vtk_points = vtki.vtk_points(points, False) self.SetPoints(vtk_points) self.GetPoints().Modified() self.Modified...
set points without copying
Below is the the instruction that describes the task: ### Input: set points without copying ### Response: def points(self, points): """ set points without copying """ if not isinstance(points, np.ndarray): raise TypeError('Points must be a numpy array') vtk_points = vtki.vtk_poi...
def add_json_widget(self, config): """ Add an Ext Json Widget to the customization. The configuration json provided must be interpretable by KE-chain. The json will be validated against the widget json schema. The widget will be saved to KE-chain. :param config: The js...
Add an Ext Json Widget to the customization. The configuration json provided must be interpretable by KE-chain. The json will be validated against the widget json schema. The widget will be saved to KE-chain. :param config: The json configuration of the widget :type config: di...
Below is the the instruction that describes the task: ### Input: Add an Ext Json Widget to the customization. The configuration json provided must be interpretable by KE-chain. The json will be validated against the widget json schema. The widget will be saved to KE-chain. :param ...
def check_version(self, name, majorv=2, minorv=7): """ Make sure the package runs on the supported Python version """ if sys.version_info.major == majorv and sys.version_info.minor != minorv: sys.stderr.write("ERROR: %s is only for >= Python %d.%d but you are running %d.%d\n" %\ ...
Make sure the package runs on the supported Python version
Below is the the instruction that describes the task: ### Input: Make sure the package runs on the supported Python version ### Response: def check_version(self, name, majorv=2, minorv=7): """ Make sure the package runs on the supported Python version """ if sys.version_info.major == majorv...
def generate_sigproc_header(f): """ Generate a serialzed sigproc header which can be written to disk. Args: f (Filterbank object): Filterbank object for which to generate header Returns: header_str (str): Serialized string corresponding to header """ header_string = b'' header...
Generate a serialzed sigproc header which can be written to disk. Args: f (Filterbank object): Filterbank object for which to generate header Returns: header_str (str): Serialized string corresponding to header
Below is the the instruction that describes the task: ### Input: Generate a serialzed sigproc header which can be written to disk. Args: f (Filterbank object): Filterbank object for which to generate header Returns: header_str (str): Serialized string corresponding to header ### Response: ...
def _kill_worker_threads(self): """ Kill any currently executing worker threads. See :meth:`ServiceContainer.spawn_worker` """ num_workers = len(self._worker_threads) if num_workers: _log.warning('killing %s active workers(s)', num_workers) for worker_ct...
Kill any currently executing worker threads. See :meth:`ServiceContainer.spawn_worker`
Below is the the instruction that describes the task: ### Input: Kill any currently executing worker threads. See :meth:`ServiceContainer.spawn_worker` ### Response: def _kill_worker_threads(self): """ Kill any currently executing worker threads. See :meth:`ServiceContainer.spawn_worker` ...
def replace_find_selection(self, focus_replace_text=False): """Replace and find in the current selection""" if self.editor is not None: replace_text = to_text_string(self.replace_text.currentText()) search_text = to_text_string(self.search_text.currentText()) cas...
Replace and find in the current selection
Below is the the instruction that describes the task: ### Input: Replace and find in the current selection ### Response: def replace_find_selection(self, focus_replace_text=False): """Replace and find in the current selection""" if self.editor is not None: replace_text = to_text_stri...
def _LookUpSeasonDirectory(self, showID, showDir, seasonNum): """ Look up season directory. First attempt to find match from database, otherwise search TV show directory. If no match is found in the database the user can choose to accept a match from the TV show directory, enter a new directory name...
Look up season directory. First attempt to find match from database, otherwise search TV show directory. If no match is found in the database the user can choose to accept a match from the TV show directory, enter a new directory name to use or accept an autogenerated name. Parameters ---------- ...
Below is the the instruction that describes the task: ### Input: Look up season directory. First attempt to find match from database, otherwise search TV show directory. If no match is found in the database the user can choose to accept a match from the TV show directory, enter a new directory name to u...
def _login(self): '''Login to the SMTP server specified at instantiation Returns an authenticated SMTP instance. ''' server, port, mode, debug = self.connection_details if mode == 'SSL': smtp_class = smtplib.SMTP_SSL else: smtp_class = smtplib.SM...
Login to the SMTP server specified at instantiation Returns an authenticated SMTP instance.
Below is the the instruction that describes the task: ### Input: Login to the SMTP server specified at instantiation Returns an authenticated SMTP instance. ### Response: def _login(self): '''Login to the SMTP server specified at instantiation Returns an authenticated SMTP instance. ...
def get_prep_value(self, value): """Convert our JSON object to a string before we save""" if value == "": return None if isinstance(value, dict): value = json.dumps(value, cls=DjangoJSONEncoder) return value
Convert our JSON object to a string before we save
Below is the the instruction that describes the task: ### Input: Convert our JSON object to a string before we save ### Response: def get_prep_value(self, value): """Convert our JSON object to a string before we save""" if value == "": return None if isinstance(value, dict): ...
def from_points(points, box_type='bb'): """ Interpret a given point cloud as a RotatedBox, using PCA to determine the potential orientation (the longest component becomes width) This is basically an approximate version of a min-area-rectangle algorithm. TODO: Test whether using a true mi...
Interpret a given point cloud as a RotatedBox, using PCA to determine the potential orientation (the longest component becomes width) This is basically an approximate version of a min-area-rectangle algorithm. TODO: Test whether using a true min-area-rectangle algorithm would be more precise or faster. ...
Below is the the instruction that describes the task: ### Input: Interpret a given point cloud as a RotatedBox, using PCA to determine the potential orientation (the longest component becomes width) This is basically an approximate version of a min-area-rectangle algorithm. TODO: Test whether using ...
def _GetConnectionArgs(host=None, port=None, user=None, password=None, database=None, client_key_path=None, client_cert_path=None, ca_cert_path=None): """Bui...
Builds connection arguments for MySQLdb.Connect function.
Below is the the instruction that describes the task: ### Input: Builds connection arguments for MySQLdb.Connect function. ### Response: def _GetConnectionArgs(host=None, port=None, user=None, password=None, database=None, ...
def curve_locate(curve, point1, point2, point3): """Image for :meth`.Curve.locate` docstring.""" if NO_IMAGES: return ax = curve.plot(256) points = np.hstack([point1, point2, point3]) ax.plot( points[0, :], points[1, :], color="black", linestyle="None", marker="o" ) ax.axis(...
Image for :meth`.Curve.locate` docstring.
Below is the the instruction that describes the task: ### Input: Image for :meth`.Curve.locate` docstring. ### Response: def curve_locate(curve, point1, point2, point3): """Image for :meth`.Curve.locate` docstring.""" if NO_IMAGES: return ax = curve.plot(256) points = np.hstack([point1, po...