code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def attention_lm_moe_memory_efficient(): """Memory-efficient version.""" hparams = attention_lm_moe_large() hparams.diet_experts = True hparams.layer_preprocess_sequence = "n" hparams.layer_postprocess_sequence = "da" hparams.layer_prepostprocess_dropout = 0.0 hparams.memory_efficient_ffn = True hparams...
Memory-efficient version.
Below is the the instruction that describes the task: ### Input: Memory-efficient version. ### Response: def attention_lm_moe_memory_efficient(): """Memory-efficient version.""" hparams = attention_lm_moe_large() hparams.diet_experts = True hparams.layer_preprocess_sequence = "n" hparams.layer_postproces...
def figure_rst(figure_list, sources_dir): """Generate RST for a list of PNG filenames. Depending on whether we have one or more figures, we use a single rst call to 'image' or a horizontal list. Parameters ---------- figure_list : list List of strings of the figures' absolute paths. ...
Generate RST for a list of PNG filenames. Depending on whether we have one or more figures, we use a single rst call to 'image' or a horizontal list. Parameters ---------- figure_list : list List of strings of the figures' absolute paths. sources_dir : str absolute path of Sphi...
Below is the the instruction that describes the task: ### Input: Generate RST for a list of PNG filenames. Depending on whether we have one or more figures, we use a single rst call to 'image' or a horizontal list. Parameters ---------- figure_list : list List of strings of the figures...
def _stack_bands(one, other): # type: (_Raster, _Raster) -> _Raster """Merges two rasters with non overlapping bands by stacking the bands. """ assert set(one.band_names).intersection(set(other.band_names)) == set() # We raise an error in the bands are the same. See above. if one.band_names ==...
Merges two rasters with non overlapping bands by stacking the bands.
Below is the the instruction that describes the task: ### Input: Merges two rasters with non overlapping bands by stacking the bands. ### Response: def _stack_bands(one, other): # type: (_Raster, _Raster) -> _Raster """Merges two rasters with non overlapping bands by stacking the bands. """ assert...
def handle_abs(self): """Gets the state as the raw abolute numbers.""" # pylint: disable=no-member x_raw = self.microbit.accelerometer.get_x() y_raw = self.microbit.accelerometer.get_y() x_abs = ('Absolute', 0x00, x_raw) y_abs = ('Absolute', 0x01, y_raw) return x_...
Gets the state as the raw abolute numbers.
Below is the the instruction that describes the task: ### Input: Gets the state as the raw abolute numbers. ### Response: def handle_abs(self): """Gets the state as the raw abolute numbers.""" # pylint: disable=no-member x_raw = self.microbit.accelerometer.get_x() y_raw = self.micro...
def walk_processes(top, topname='top', topdown=True, ignoreFlag=False): """Generator for recursive tree of climlab processes Starts walking from climlab process ``top`` and generates a complete list of all processes and sub-processes that are managed from ``top`` process. ``level`` indicades the rank o...
Generator for recursive tree of climlab processes Starts walking from climlab process ``top`` and generates a complete list of all processes and sub-processes that are managed from ``top`` process. ``level`` indicades the rank of specific process in the process hierarchy: .. note:: * level 0:...
Below is the the instruction that describes the task: ### Input: Generator for recursive tree of climlab processes Starts walking from climlab process ``top`` and generates a complete list of all processes and sub-processes that are managed from ``top`` process. ``level`` indicades the rank of specific...
def get_audit_log(self, begin_time=None, end_time=None): """ Return the console audit log entries, optionally filtered by their creation time. Authorization requirements: * Task permission to the "Audit and Log Management" task. Parameters: begin_time (:clas...
Return the console audit log entries, optionally filtered by their creation time. Authorization requirements: * Task permission to the "Audit and Log Management" task. Parameters: begin_time (:class:`~py:datetime.datetime`): Begin time for filtering. Log entries...
Below is the the instruction that describes the task: ### Input: Return the console audit log entries, optionally filtered by their creation time. Authorization requirements: * Task permission to the "Audit and Log Management" task. Parameters: begin_time (:class:`~py:d...
def locks(self): """ Display queries with active locks. Record( procpid=31776, relname=None, transactionid=None, granted=True, query_snippet='select * from hello;', age=datetime.timedelta(0, 0, 288174), ) :...
Display queries with active locks. Record( procpid=31776, relname=None, transactionid=None, granted=True, query_snippet='select * from hello;', age=datetime.timedelta(0, 0, 288174), ) :returns: list of Records
Below is the the instruction that describes the task: ### Input: Display queries with active locks. Record( procpid=31776, relname=None, transactionid=None, granted=True, query_snippet='select * from hello;', age=datetime.timedelta(0, ...
def read_csr(csr): ''' Returns a dict containing details of a certificate request. :depends: - OpenSSL command line tool csr: A path or PEM encoded string containing the CSR to read. CLI Example: .. code-block:: bash salt '*' x509.read_csr /etc/pki/mycert.csr ''' c...
Returns a dict containing details of a certificate request. :depends: - OpenSSL command line tool csr: A path or PEM encoded string containing the CSR to read. CLI Example: .. code-block:: bash salt '*' x509.read_csr /etc/pki/mycert.csr
Below is the the instruction that describes the task: ### Input: Returns a dict containing details of a certificate request. :depends: - OpenSSL command line tool csr: A path or PEM encoded string containing the CSR to read. CLI Example: .. code-block:: bash salt '*' x509.read...
def authenticate_credentials(self, request, access_token): """ Authenticate the request, given the access token. """ try: token = oauth2_provider.oauth2.models.AccessToken.objects.select_related('user') # provider_now switches to timezone aware datetime when ...
Authenticate the request, given the access token.
Below is the the instruction that describes the task: ### Input: Authenticate the request, given the access token. ### Response: def authenticate_credentials(self, request, access_token): """ Authenticate the request, given the access token. """ try: token = oauth2_prov...
def encoded_datastream(self): '''Generator for datastream content. Takes a list of sections of data within the current chunk (split on binaryContent start and end tags), runs a base64 decode, and yields the data. Computes datastream size and MD5 as data is decoded for sanity-checking ...
Generator for datastream content. Takes a list of sections of data within the current chunk (split on binaryContent start and end tags), runs a base64 decode, and yields the data. Computes datastream size and MD5 as data is decoded for sanity-checking purposes. If binary content is not...
Below is the the instruction that describes the task: ### Input: Generator for datastream content. Takes a list of sections of data within the current chunk (split on binaryContent start and end tags), runs a base64 decode, and yields the data. Computes datastream size and MD5 as data is de...
def set_transfer_spec(self): ''' run the function to set the transfer spec on error set associated exception ''' _ret = False try: self._args.transfer_spec_func(self._args) _ret = True except Exception as ex: self.notify_exception(AsperaTransferSpecErr...
run the function to set the transfer spec on error set associated exception
Below is the the instruction that describes the task: ### Input: run the function to set the transfer spec on error set associated exception ### Response: def set_transfer_spec(self): ''' run the function to set the transfer spec on error set associated exception ''' _ret = False try: ...
def _determine_timeout(default_timeout, specified_timeout, retry): """Determines how timeout should be applied to a wrapped method. Args: default_timeout (Optional[Timeout]): The default timeout specified at method creation time. specified_timeout (Optional[Timeout]): The timeout sp...
Determines how timeout should be applied to a wrapped method. Args: default_timeout (Optional[Timeout]): The default timeout specified at method creation time. specified_timeout (Optional[Timeout]): The timeout specified at invocation time. If :attr:`DEFAULT`, this will be s...
Below is the the instruction that describes the task: ### Input: Determines how timeout should be applied to a wrapped method. Args: default_timeout (Optional[Timeout]): The default timeout specified at method creation time. specified_timeout (Optional[Timeout]): The timeout specifi...
def cli(ctx, board, fpga, pack, type, size, project_dir, verbose, verbose_yosys, verbose_arachne): """Bitstream timing analysis.""" # Run scons exit_code = SCons(project_dir).time({ 'board': board, 'fpga': fpga, 'size': size, 'type': type, 'pack': pack, ...
Bitstream timing analysis.
Below is the the instruction that describes the task: ### Input: Bitstream timing analysis. ### Response: def cli(ctx, board, fpga, pack, type, size, project_dir, verbose, verbose_yosys, verbose_arachne): """Bitstream timing analysis.""" # Run scons exit_code = SCons(project_dir).time({ ...
def set_level(self, level): """ Set the logging level of this logger. :param level: must be an int or a str. """ for handler in self.__coloredlogs_handlers: handler.setLevel(level=level) self.logger.setLevel(level=level)
Set the logging level of this logger. :param level: must be an int or a str.
Below is the the instruction that describes the task: ### Input: Set the logging level of this logger. :param level: must be an int or a str. ### Response: def set_level(self, level): """ Set the logging level of this logger. :param level: must be an int or a str. """ ...
def _is_path(instance, attribute, s, exists=True): "Validator for path-yness" if not s: # allow False as a default return if exists: if os.path.exists(s): return else: raise OSError("path does not exist") else: # how do we tell if it's a pa...
Validator for path-yness
Below is the the instruction that describes the task: ### Input: Validator for path-yness ### Response: def _is_path(instance, attribute, s, exists=True): "Validator for path-yness" if not s: # allow False as a default return if exists: if os.path.exists(s): return ...
def nucmer_hits_to_ref_and_qry_coords(cls, nucmer_hits, contig=None): '''Same as nucmer_hits_to_ref_coords, except removes containing hits first, and returns ref and qry coords lists''' if contig is None: ctg_coords = {key: [] for key in nucmer_hits.keys()} else: ...
Same as nucmer_hits_to_ref_coords, except removes containing hits first, and returns ref and qry coords lists
Below is the the instruction that describes the task: ### Input: Same as nucmer_hits_to_ref_coords, except removes containing hits first, and returns ref and qry coords lists ### Response: def nucmer_hits_to_ref_and_qry_coords(cls, nucmer_hits, contig=None): '''Same as nucmer_hits_to_ref_coords,...
def _get_capabilities(self): """Get the servers NETCONF capabilities. :return: List of server capabilities. """ conn = self._get_connection() capabilities = [] for c in conn.server_capabilities: capabilities.append(c) LOG.debug("Server capabilities: %...
Get the servers NETCONF capabilities. :return: List of server capabilities.
Below is the the instruction that describes the task: ### Input: Get the servers NETCONF capabilities. :return: List of server capabilities. ### Response: def _get_capabilities(self): """Get the servers NETCONF capabilities. :return: List of server capabilities. """ conn =...
def set_loop_points(self, start_sample=-1, end_sample=0): '''Set the loop points within the sound. The sound must have been created with ``loop=True``. The default parameters cause the loop points to be set to the entire sound duration. :note: There is currently no API for converting ...
Set the loop points within the sound. The sound must have been created with ``loop=True``. The default parameters cause the loop points to be set to the entire sound duration. :note: There is currently no API for converting sample numbers to times. :param start_sample: sample number t...
Below is the the instruction that describes the task: ### Input: Set the loop points within the sound. The sound must have been created with ``loop=True``. The default parameters cause the loop points to be set to the entire sound duration. :note: There is currently no API for converting ...
def _compute_all_features(self): """Computes all the features (beatsync, framesync) from the audio.""" # Read actual audio waveform self._audio, _ = librosa.load(self.file_struct.audio_file, sr=self.sr) # Get duration of audio file self.dur ...
Computes all the features (beatsync, framesync) from the audio.
Below is the the instruction that describes the task: ### Input: Computes all the features (beatsync, framesync) from the audio. ### Response: def _compute_all_features(self): """Computes all the features (beatsync, framesync) from the audio.""" # Read actual audio waveform self._audio, _ =...
def aggregate_by_index(self, function, level=0): """ Aggregrate data in each record, grouping by index values. For each unique value of the index, applies a function to the group indexed by that value. Returns a Series indexed by those unique values. For the result to be a valid...
Aggregrate data in each record, grouping by index values. For each unique value of the index, applies a function to the group indexed by that value. Returns a Series indexed by those unique values. For the result to be a valid Series object, the aggregating function should return a simp...
Below is the the instruction that describes the task: ### Input: Aggregrate data in each record, grouping by index values. For each unique value of the index, applies a function to the group indexed by that value. Returns a Series indexed by those unique values. For the result to be a valid...
def association(self, group_xid): """Add association using xid value. Args: group_xid (str): The external id of the Group to associate. """ association = {'groupXid': group_xid} self._indicator_data.setdefault('associatedGroups', []).append(association)
Add association using xid value. Args: group_xid (str): The external id of the Group to associate.
Below is the the instruction that describes the task: ### Input: Add association using xid value. Args: group_xid (str): The external id of the Group to associate. ### Response: def association(self, group_xid): """Add association using xid value. Args: group_xid (...
def _get_timezone(self, root): """Find timezone informatation on bottom of the page.""" tz_str = root.xpath('//div[@class="smallfont" and @align="center"]')[0].text hours = int(self._tz_re.search(tz_str).group(1)) return tzoffset(tz_str, hours * 60)
Find timezone informatation on bottom of the page.
Below is the the instruction that describes the task: ### Input: Find timezone informatation on bottom of the page. ### Response: def _get_timezone(self, root): """Find timezone informatation on bottom of the page.""" tz_str = root.xpath('//div[@class="smallfont" and @align="center"]')[0].text ...
def _erase_card(self, number): """Destroy cards with this or higher number.""" with self._lock: if number < (len(self.cards) - 1): self._erase_card(number + 1) if number > (len(self.cards) - 1): return max_cards_horiz = int(curses.COLS ...
Destroy cards with this or higher number.
Below is the the instruction that describes the task: ### Input: Destroy cards with this or higher number. ### Response: def _erase_card(self, number): """Destroy cards with this or higher number.""" with self._lock: if number < (len(self.cards) - 1): self._erase_card(nu...
def inspect_task(self, task): """ Retrieve information about a task. Args: task (str): Task ID Returns: (dict): Information about the task. Raises: :py:class:`docker.errors.APIError` If the server returns an error. ""...
Retrieve information about a task. Args: task (str): Task ID Returns: (dict): Information about the task. Raises: :py:class:`docker.errors.APIError` If the server returns an error.
Below is the the instruction that describes the task: ### Input: Retrieve information about a task. Args: task (str): Task ID Returns: (dict): Information about the task. Raises: :py:class:`docker.errors.APIError` If the server returns a...
def config_name_from_full_name(full_name): """Extract the config name from a full resource name. >>> config_name_from_full_name('projects/my-proj/configs/my-config') "my-config" :type full_name: str :param full_name: The full resource name of a config. The full resource name looks like...
Extract the config name from a full resource name. >>> config_name_from_full_name('projects/my-proj/configs/my-config') "my-config" :type full_name: str :param full_name: The full resource name of a config. The full resource name looks like ``projects/project-name/configs/config-na...
Below is the the instruction that describes the task: ### Input: Extract the config name from a full resource name. >>> config_name_from_full_name('projects/my-proj/configs/my-config') "my-config" :type full_name: str :param full_name: The full resource name of a config. The full resou...
def golfclap(rest): "Clap for something" clapv = random.choice(phrases.clapvl) adv = random.choice(phrases.advl) adj = random.choice(phrases.adjl) if rest: clapee = rest.strip() karma.Karma.store.change(clapee, 1) return "/me claps %s for %s, %s %s." % (clapv, rest, adv, adj) return "/me claps %s, %s %s." %...
Clap for something
Below is the the instruction that describes the task: ### Input: Clap for something ### Response: def golfclap(rest): "Clap for something" clapv = random.choice(phrases.clapvl) adv = random.choice(phrases.advl) adj = random.choice(phrases.adjl) if rest: clapee = rest.strip() karma.Karma.store.change(clape...
def exc_thrown_by_descriptor(): """Return True if the last exception was thrown by a Descriptor instance. """ traceback = sys.exc_info()[2] tb_locals = traceback.tb_frame.f_locals # relying on naming convention to get the object that threw # the exception ...
Return True if the last exception was thrown by a Descriptor instance.
Below is the the instruction that describes the task: ### Input: Return True if the last exception was thrown by a Descriptor instance. ### Response: def exc_thrown_by_descriptor(): """Return True if the last exception was thrown by a Descriptor instance. """ traceback = sy...
def AnnotateBED(bed, GTF, genome_file, bedcols=None, promoter=[1000,200]): """ Annotates a bed file. :param bed: either a /path/to/file.bed or a Pandas dataframe in bed format. /path/to/file.bed implies bedcols. :param GTF: /path/to/file.gtf :param genome_file: /path/to/file.genome - a tab separate...
Annotates a bed file. :param bed: either a /path/to/file.bed or a Pandas dataframe in bed format. /path/to/file.bed implies bedcols. :param GTF: /path/to/file.gtf :param genome_file: /path/to/file.genome - a tab separated values of chr name and size information :param bedcols: a comma separated string ...
Below is the the instruction that describes the task: ### Input: Annotates a bed file. :param bed: either a /path/to/file.bed or a Pandas dataframe in bed format. /path/to/file.bed implies bedcols. :param GTF: /path/to/file.gtf :param genome_file: /path/to/file.genome - a tab separated values of chr na...
def process_file(self, path, dryrun): """ Print files path. """ # if dryrun just return files if dryrun: return path # scan file and match lines ret = [] with open(path, "r") as infile: for line in infile: if re.sea...
Print files path.
Below is the the instruction that describes the task: ### Input: Print files path. ### Response: def process_file(self, path, dryrun): """ Print files path. """ # if dryrun just return files if dryrun: return path # scan file and match lines ret ...
def tunnel_to_kernel(connection_info, sshserver, sshkey=None): """tunnel connections to a kernel via ssh This will open four SSH tunnels from localhost on this machine to the ports associated with the kernel. They can be either direct localhost-localhost tunnels, or if an intermediate server is ne...
tunnel connections to a kernel via ssh This will open four SSH tunnels from localhost on this machine to the ports associated with the kernel. They can be either direct localhost-localhost tunnels, or if an intermediate server is necessary, the kernel must be listening on a public IP. Par...
Below is the the instruction that describes the task: ### Input: tunnel connections to a kernel via ssh This will open four SSH tunnels from localhost on this machine to the ports associated with the kernel. They can be either direct localhost-localhost tunnels, or if an intermediate server is nec...
def get_domain_config(self, domain): """Makes a discovery of domain name and resolves configuration of DNS provider :param domain: str domain name :return: DomainConnectConfig domain connect config :raises: NoDomainConnectRecordException when no _doma...
Makes a discovery of domain name and resolves configuration of DNS provider :param domain: str domain name :return: DomainConnectConfig domain connect config :raises: NoDomainConnectRecordException when no _domainconnect record found :raises: NoDomain...
Below is the the instruction that describes the task: ### Input: Makes a discovery of domain name and resolves configuration of DNS provider :param domain: str domain name :return: DomainConnectConfig domain connect config :raises: NoDomainConnectRecordException ...
def my_protocol_parser(out, buf): """Parser is used with StreamParser for incremental protocol parsing. Parser is a generator function, but it is not a coroutine. Usually parsers are implemented as a state machine. more details in asyncio/parsers.py existing parsers: * HTTP protocol parsers a...
Parser is used with StreamParser for incremental protocol parsing. Parser is a generator function, but it is not a coroutine. Usually parsers are implemented as a state machine. more details in asyncio/parsers.py existing parsers: * HTTP protocol parsers asyncio/http/protocol.py * websocket...
Below is the the instruction that describes the task: ### Input: Parser is used with StreamParser for incremental protocol parsing. Parser is a generator function, but it is not a coroutine. Usually parsers are implemented as a state machine. more details in asyncio/parsers.py existing parsers: ...
def hash_data(data, hasher=NoParam, base=NoParam, types=False, hashlen=NoParam, convert=False): """ Get a unique hash depending on the state of the data. Args: data (object): Any sort of loosely organized data hasher (str or HASHER): Hash algorithm fro...
Get a unique hash depending on the state of the data. Args: data (object): Any sort of loosely organized data hasher (str or HASHER): Hash algorithm from hashlib, defaults to `sha512`. base (str or List[str]): Shorthand key or a list of symbols. Valid ...
Below is the the instruction that describes the task: ### Input: Get a unique hash depending on the state of the data. Args: data (object): Any sort of loosely organized data hasher (str or HASHER): Hash algorithm from hashlib, defaults to `sha512`. base (str o...
def haiz(obj, chart): """ Returns if an object is in Haiz. """ objGender = obj.gender() objFaction = obj.faction() if obj.id == const.MERCURY: # Gender and faction of mercury depends on orientality sun = chart.getObject(const.SUN) orientalityM = orientality(obj, sun) ...
Returns if an object is in Haiz.
Below is the the instruction that describes the task: ### Input: Returns if an object is in Haiz. ### Response: def haiz(obj, chart): """ Returns if an object is in Haiz. """ objGender = obj.gender() objFaction = obj.faction() if obj.id == const.MERCURY: # Gender and faction of mercury...
def scrape_wikinews(conn, project, articleset, query): """ Scrape wikinews articles from the given query @param conn: The AmcatAPI object @param articleset: The target articleset ID @param category: The wikinews category name """ url = "http://en.wikinews.org/w/index.php?search={}&limit=50"....
Scrape wikinews articles from the given query @param conn: The AmcatAPI object @param articleset: The target articleset ID @param category: The wikinews category name
Below is the the instruction that describes the task: ### Input: Scrape wikinews articles from the given query @param conn: The AmcatAPI object @param articleset: The target articleset ID @param category: The wikinews category name ### Response: def scrape_wikinews(conn, project, articleset, query): ...
def _send_textmetrics(metrics): ''' Format metrics for the carbon plaintext protocol ''' data = [' '.join(map(six.text_type, metric)) for metric in metrics] + [''] return '\n'.join(data)
Format metrics for the carbon plaintext protocol
Below is the the instruction that describes the task: ### Input: Format metrics for the carbon plaintext protocol ### Response: def _send_textmetrics(metrics): ''' Format metrics for the carbon plaintext protocol ''' data = [' '.join(map(six.text_type, metric)) for metric in metrics] + [''] r...
def get_citation_by_reference(self, type: str, reference: str) -> Optional[Citation]: """Get a citation object by its type and reference.""" citation_hash = hash_citation(type=type, reference=reference) return self.get_citation_by_hash(citation_hash)
Get a citation object by its type and reference.
Below is the the instruction that describes the task: ### Input: Get a citation object by its type and reference. ### Response: def get_citation_by_reference(self, type: str, reference: str) -> Optional[Citation]: """Get a citation object by its type and reference.""" citation_hash = hash_citation(...
def entropy(args): """ %prog entropy kmc_dump.out kmc_dump.out contains two columns: AAAAAAAAAAAGAAGAAAGAAA 34 """ p = OptionParser(entropy.__doc__) p.add_option("--threshold", default=0, type="int", help="Complexity needs to be above") opts, args = p.parse_args(args) ...
%prog entropy kmc_dump.out kmc_dump.out contains two columns: AAAAAAAAAAAGAAGAAAGAAA 34
Below is the the instruction that describes the task: ### Input: %prog entropy kmc_dump.out kmc_dump.out contains two columns: AAAAAAAAAAAGAAGAAAGAAA 34 ### Response: def entropy(args): """ %prog entropy kmc_dump.out kmc_dump.out contains two columns: AAAAAAAAAAAGAAGAAAGAAA 34 """ ...
def load_tabs(self): """Loads the tab group. It compiles the table instances for each table attached to any :class:`horizon.tabs.TableTab` instances on the tab group. This step is necessary before processing any tab or table actions. """ tab_group = self.get_tabs(self.re...
Loads the tab group. It compiles the table instances for each table attached to any :class:`horizon.tabs.TableTab` instances on the tab group. This step is necessary before processing any tab or table actions.
Below is the the instruction that describes the task: ### Input: Loads the tab group. It compiles the table instances for each table attached to any :class:`horizon.tabs.TableTab` instances on the tab group. This step is necessary before processing any tab or table actions. ### Response: d...
def abort(*args, **kwargs): """ Usage: return abort("...") => will sys.exit() by default return abort("...", fatal=True) => Will sys.exit() # Not fatal, but will log/print message: return abort("...", fatal=False) => Will return False return abort("...", fatal=(False, No...
Usage: return abort("...") => will sys.exit() by default return abort("...", fatal=True) => Will sys.exit() # Not fatal, but will log/print message: return abort("...", fatal=False) => Will return False return abort("...", fatal=(False, None)) => Will return None return ...
Below is the the instruction that describes the task: ### Input: Usage: return abort("...") => will sys.exit() by default return abort("...", fatal=True) => Will sys.exit() # Not fatal, but will log/print message: return abort("...", fatal=False) => Will return False return ...
def sigma_cached(self, psd): """ Cache sigma calculate for use in tandem with the FilterBank class """ if not hasattr(self, '_sigmasq'): from pycbc.opt import LimitedSizeDict self._sigmasq = LimitedSizeDict(size_limit=2**5) key = id(psd) if not hasattr(psd, '_sigma_cached_key'): ...
Cache sigma calculate for use in tandem with the FilterBank class
Below is the the instruction that describes the task: ### Input: Cache sigma calculate for use in tandem with the FilterBank class ### Response: def sigma_cached(self, psd): """ Cache sigma calculate for use in tandem with the FilterBank class """ if not hasattr(self, '_sigmasq'): from pycbc.op...
def depends (self, d): """ Adds additional instances of 'VirtualTarget' that this one depends on. """ self.dependencies_ = unique (self.dependencies_ + d).sort ()
Adds additional instances of 'VirtualTarget' that this one depends on.
Below is the the instruction that describes the task: ### Input: Adds additional instances of 'VirtualTarget' that this one depends on. ### Response: def depends (self, d): """ Adds additional instances of 'VirtualTarget' that this one depends on. """ self.dependenci...
def add_module(self, module, cython=False): """Add the given module, its members, and their submembers. The first examples are based on the site-package |numpy|: which is passed to method |Substituter.add_module|: >>> from hydpy.core.autodoctools import Substituter >>> substitu...
Add the given module, its members, and their submembers. The first examples are based on the site-package |numpy|: which is passed to method |Substituter.add_module|: >>> from hydpy.core.autodoctools import Substituter >>> substituter = Substituter() >>> import numpy >>...
Below is the the instruction that describes the task: ### Input: Add the given module, its members, and their submembers. The first examples are based on the site-package |numpy|: which is passed to method |Substituter.add_module|: >>> from hydpy.core.autodoctools import Substituter ...
def _hashable_bytes(data): """ Coerce strings to hashable bytes. """ if isinstance(data, bytes): return data elif isinstance(data, str): return data.encode('ascii') # Fail on anything non-ASCII. else: raise TypeError(data)
Coerce strings to hashable bytes.
Below is the the instruction that describes the task: ### Input: Coerce strings to hashable bytes. ### Response: def _hashable_bytes(data): """ Coerce strings to hashable bytes. """ if isinstance(data, bytes): return data elif isinstance(data, str): return data.encode('ascii') ...
def _set_least_batch_id(self, txn_signature): """Set the first batch id that doesn't have all results. Args: txn_signature (str): The txn identifier of the transaction with results being set. """ batch = self._batches_by_txn_id[txn_signature] least...
Set the first batch id that doesn't have all results. Args: txn_signature (str): The txn identifier of the transaction with results being set.
Below is the the instruction that describes the task: ### Input: Set the first batch id that doesn't have all results. Args: txn_signature (str): The txn identifier of the transaction with results being set. ### Response: def _set_least_batch_id(self, txn_signature): ""...
def with_reconnect(func): """ Handle when AutoReconnect is raised from pymongo. This is the standard error raised for everything from "host disconnected" to "couldn't connect to host" and more. The sleep handles the edge case when the state of a replica set changes, and the cursor raises AutoRe...
Handle when AutoReconnect is raised from pymongo. This is the standard error raised for everything from "host disconnected" to "couldn't connect to host" and more. The sleep handles the edge case when the state of a replica set changes, and the cursor raises AutoReconnect because the master may have ch...
Below is the the instruction that describes the task: ### Input: Handle when AutoReconnect is raised from pymongo. This is the standard error raised for everything from "host disconnected" to "couldn't connect to host" and more. The sleep handles the edge case when the state of a replica set changes, a...
def stats(self): """ Gets performance statistics and server information """ status, _, body = self._request('GET', self.stats_path(), {'Accept': 'application/json'}) if status == 200: return json.loads(bytes_to_str(body)) ...
Gets performance statistics and server information
Below is the the instruction that describes the task: ### Input: Gets performance statistics and server information ### Response: def stats(self): """ Gets performance statistics and server information """ status, _, body = self._request('GET', self.stats_path(), ...
def cysparse_real_type_from_real_cysparse_complex_type(cysparse_type): """ Returns the **real** type for the real or imaginary part of a **real** complex type. For instance: COMPLEX128_t -> FLOAT64_t Args: cysparse: """ r_type = None if cysparse_type in ['COMPLEX64_t']: ...
Returns the **real** type for the real or imaginary part of a **real** complex type. For instance: COMPLEX128_t -> FLOAT64_t Args: cysparse:
Below is the the instruction that describes the task: ### Input: Returns the **real** type for the real or imaginary part of a **real** complex type. For instance: COMPLEX128_t -> FLOAT64_t Args: cysparse: ### Response: def cysparse_real_type_from_real_cysparse_complex_type(cysparse_type...
def get_mysql_credentials(cfg_file): """Get the credentials and database name from options in config file.""" try: parser = ConfigParser.ConfigParser() cfg_fp = open(cfg_file) parser.readfp(cfg_fp) cfg_fp.close() except ConfigParser.NoOptionError: cfg_fp.close() ...
Get the credentials and database name from options in config file.
Below is the the instruction that describes the task: ### Input: Get the credentials and database name from options in config file. ### Response: def get_mysql_credentials(cfg_file): """Get the credentials and database name from options in config file.""" try: parser = ConfigParser.ConfigParser() ...
def show_grid(images, rows=None, cols=None): """ Converts the input images to a grid image and shows it in a new window. dtype support:: minimum of ( :func:`imgaug.imgaug.draw_grid`, :func:`imgaug.imgaug.imshow` ) Parameters ---------- images : (N,H,W,3...
Converts the input images to a grid image and shows it in a new window. dtype support:: minimum of ( :func:`imgaug.imgaug.draw_grid`, :func:`imgaug.imgaug.imshow` ) Parameters ---------- images : (N,H,W,3) ndarray or iterable of (H,W,3) array See :func:...
Below is the the instruction that describes the task: ### Input: Converts the input images to a grid image and shows it in a new window. dtype support:: minimum of ( :func:`imgaug.imgaug.draw_grid`, :func:`imgaug.imgaug.imshow` ) Parameters ---------- image...
def _make_grid_of_axes(self, bounding_rect=cfg.bounding_rect_default, num_rows=cfg.num_rows_per_view_default, num_cols=cfg.num_cols_grid_default, axis_pad=cfg.axis_pad_default, commn_an...
Creates a grid of axes bounded within a given rectangle.
Below is the the instruction that describes the task: ### Input: Creates a grid of axes bounded within a given rectangle. ### Response: def _make_grid_of_axes(self, bounding_rect=cfg.bounding_rect_default, num_rows=cfg.num_rows_per_view_default, ...
def from_kwargs(cls, **kwargs): """Creates a new instance of self from the given keyword arguments. Each argument will correspond to a field in the returned array, with the name of the field given by the keyword, and the value(s) whatever the keyword was set to. Each keyword may be set t...
Creates a new instance of self from the given keyword arguments. Each argument will correspond to a field in the returned array, with the name of the field given by the keyword, and the value(s) whatever the keyword was set to. Each keyword may be set to a single value or a list of value...
Below is the the instruction that describes the task: ### Input: Creates a new instance of self from the given keyword arguments. Each argument will correspond to a field in the returned array, with the name of the field given by the keyword, and the value(s) whatever the keyword was set to....
def web(connection, host, port): """Run a combine web interface.""" from bio2bel.web.application import create_application app = create_application(connection=connection) app.run(host=host, port=port)
Run a combine web interface.
Below is the the instruction that describes the task: ### Input: Run a combine web interface. ### Response: def web(connection, host, port): """Run a combine web interface.""" from bio2bel.web.application import create_application app = create_application(connection=connection) app.run(host=host, p...
def reflectance_from_tbs(self, sun_zenith, tb_near_ir, tb_thermal, **kwargs): """ The relfectance calculated is without units and should be between 0 and 1. Inputs: sun_zenith: Sun zenith angle for every pixel - in degrees tb_near_ir: The 3.7 (or 3.9 or equivalent) IR Tb's...
The relfectance calculated is without units and should be between 0 and 1. Inputs: sun_zenith: Sun zenith angle for every pixel - in degrees tb_near_ir: The 3.7 (or 3.9 or equivalent) IR Tb's at every pixel (Kelvin) tb_thermal: The 10.8 (or 11 or 12 or equ...
Below is the the instruction that describes the task: ### Input: The relfectance calculated is without units and should be between 0 and 1. Inputs: sun_zenith: Sun zenith angle for every pixel - in degrees tb_near_ir: The 3.7 (or 3.9 or equivalent) IR Tb's at every pixel ...
def password_change(self, wallet, password): """ Changes the password for **wallet** to **password** .. enable_control required :param wallet: Wallet to change password for :type wallet: str :param password: Password to set :type password: str :raises:...
Changes the password for **wallet** to **password** .. enable_control required :param wallet: Wallet to change password for :type wallet: str :param password: Password to set :type password: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.password_change...
Below is the the instruction that describes the task: ### Input: Changes the password for **wallet** to **password** .. enable_control required :param wallet: Wallet to change password for :type wallet: str :param password: Password to set :type password: str :rai...
def generate_classified_legend( analysis, exposure, hazard, use_rounding, debug_mode): """Generate an ordered python structure with the classified symbology. :param analysis: The analysis layer. :type analysis: QgsVectorLayer :param exposure: The exposure layer....
Generate an ordered python structure with the classified symbology. :param analysis: The analysis layer. :type analysis: QgsVectorLayer :param exposure: The exposure layer. :type exposure: QgsVectorLayer :param hazard: The hazard layer. :type hazard: QgsVectorLayer :param use_rounding: B...
Below is the the instruction that describes the task: ### Input: Generate an ordered python structure with the classified symbology. :param analysis: The analysis layer. :type analysis: QgsVectorLayer :param exposure: The exposure layer. :type exposure: QgsVectorLayer :param hazard: The hazar...
def _evaluate(self,R,z,phi=0.,t=0.): """ NAME: _evaluate PURPOSE: evaluate the potential at R,z INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: Phi(...
NAME: _evaluate PURPOSE: evaluate the potential at R,z INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: Phi(R,z) HISTORY: 2015-02-15 - Written - ...
Below is the the instruction that describes the task: ### Input: NAME: _evaluate PURPOSE: evaluate the potential at R,z INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: ...
def plotActivation(self, position=None, time=None, velocity=None): """ Plot the activation of the current cell populations. Assumes that two axes have already been created, ax1 and ax2. If done in a Jupyter notebook, this plotting will overwrite the old plot. :param position: The current location ...
Plot the activation of the current cell populations. Assumes that two axes have already been created, ax1 and ax2. If done in a Jupyter notebook, this plotting will overwrite the old plot. :param position: The current location of the animal :param time: The current time in the simulation :param ve...
Below is the the instruction that describes the task: ### Input: Plot the activation of the current cell populations. Assumes that two axes have already been created, ax1 and ax2. If done in a Jupyter notebook, this plotting will overwrite the old plot. :param position: The current location of the ani...
def get_dataset(self, key, info): """Read data from file and return the corresponding projectables.""" datadict = { 1000: ['EV_250_Aggr1km_RefSB', 'EV_500_Aggr1km_RefSB', 'EV_1KM_RefSB', 'EV_1KM_Emissive'], 500: ['EV_250_Ag...
Read data from file and return the corresponding projectables.
Below is the the instruction that describes the task: ### Input: Read data from file and return the corresponding projectables. ### Response: def get_dataset(self, key, info): """Read data from file and return the corresponding projectables.""" datadict = { 1000: ['EV_250_Aggr1km_RefSB'...
def _read_by_weight(self, F, att_weights, value): """Read from the value matrix given the attention weights. Parameters ---------- F : symbol or ndarray att_weights : Symbol or NDArray Attention weights. For single-head attention, Shape (b...
Read from the value matrix given the attention weights. Parameters ---------- F : symbol or ndarray att_weights : Symbol or NDArray Attention weights. For single-head attention, Shape (batch_size, query_length, memory_length). For mult...
Below is the the instruction that describes the task: ### Input: Read from the value matrix given the attention weights. Parameters ---------- F : symbol or ndarray att_weights : Symbol or NDArray Attention weights. For single-head attention, ...
def for_meters(cls, meter_x, meter_y, zoom): """Creates a tile from X Y meters in Spherical Mercator EPSG:900913""" point = Point.from_meters(meter_x=meter_x, meter_y=meter_y) pixel_x, pixel_y = point.pixels(zoom=zoom) return cls.for_pixels(pixel_x=pixel_x, pixel_y=pixel_y, zoom=zoom)
Creates a tile from X Y meters in Spherical Mercator EPSG:900913
Below is the the instruction that describes the task: ### Input: Creates a tile from X Y meters in Spherical Mercator EPSG:900913 ### Response: def for_meters(cls, meter_x, meter_y, zoom): """Creates a tile from X Y meters in Spherical Mercator EPSG:900913""" point = Point.from_meters(meter_x=meter...
def multiple_sequence_alignment(seqs_fp, threads=1): """Perform multiple sequence alignment on FASTA file using MAFFT. Parameters ---------- seqs_fp: string filepath to FASTA file for multiple sequence alignment threads: integer, optional number of threads to use. 0 to use all threa...
Perform multiple sequence alignment on FASTA file using MAFFT. Parameters ---------- seqs_fp: string filepath to FASTA file for multiple sequence alignment threads: integer, optional number of threads to use. 0 to use all threads Returns ------- msa_fp : str name of...
Below is the the instruction that describes the task: ### Input: Perform multiple sequence alignment on FASTA file using MAFFT. Parameters ---------- seqs_fp: string filepath to FASTA file for multiple sequence alignment threads: integer, optional number of threads to use. 0 to use ...
def contains(self, string): """Summary Returns: TYPE: Description """ # Check that self.weld_type is a string type vectype = self.weld_type if isinstance(vectype, WeldVec): elem_type = vectype.elemType if isinstance(elem_type, WeldChar): ...
Summary Returns: TYPE: Description
Below is the the instruction that describes the task: ### Input: Summary Returns: TYPE: Description ### Response: def contains(self, string): """Summary Returns: TYPE: Description """ # Check that self.weld_type is a string type vectype = self.weld_...
def flasher(msg, severity=None): """Flask's flash if available, logging call if not""" try: flash(msg, severity) except RuntimeError: if severity == 'danger': logging.error(msg) else: logging.info(msg)
Flask's flash if available, logging call if not
Below is the the instruction that describes the task: ### Input: Flask's flash if available, logging call if not ### Response: def flasher(msg, severity=None): """Flask's flash if available, logging call if not""" try: flash(msg, severity) except RuntimeError: if severity == 'danger': ...
def _fetch(self, key): """Helper function to fetch values from owning section. Returns a 2-tuple: the value, and the section where it was found. """ # switch off interpolation before we try and fetch anything ! save_interp = self.section.main.interpolation self.section.m...
Helper function to fetch values from owning section. Returns a 2-tuple: the value, and the section where it was found.
Below is the the instruction that describes the task: ### Input: Helper function to fetch values from owning section. Returns a 2-tuple: the value, and the section where it was found. ### Response: def _fetch(self, key): """Helper function to fetch values from owning section. Returns a 2-...
def url(self): """ Returns the rendered URL of the chart """ self.render() return self._apiurl + '&'.join(self._parts()).replace(' ','+')
Returns the rendered URL of the chart
Below is the the instruction that describes the task: ### Input: Returns the rendered URL of the chart ### Response: def url(self): """ Returns the rendered URL of the chart """ self.render() return self._apiurl + '&'.join(self._parts()).replace(' ','+')
def set_install_id(filename, install_id): """ Set install id for library named in `filename` Parameters ---------- filename : str filename of library install_id : str install id for library `filename` Raises ------ RuntimeError if `filename` has not install id """ ...
Set install id for library named in `filename` Parameters ---------- filename : str filename of library install_id : str install id for library `filename` Raises ------ RuntimeError if `filename` has not install id
Below is the the instruction that describes the task: ### Input: Set install id for library named in `filename` Parameters ---------- filename : str filename of library install_id : str install id for library `filename` Raises ------ RuntimeError if `filename` has not i...
def train(self): """Train the network using the training dataset. Parameters ---------- None Returns ------- None """ self.stamp_start = time.time() for iteration, batch in tqdm.tqdm(enumerate(self.iter_train), ...
Train the network using the training dataset. Parameters ---------- None Returns ------- None
Below is the the instruction that describes the task: ### Input: Train the network using the training dataset. Parameters ---------- None Returns ------- None ### Response: def train(self): """Train the network using the training dataset. Parameter...
def get_parameters(rq, variables, endpoint, query_metadata, auth=None): """ ?_name The variable specifies the API mandatory parameter name. The value is incorporated in the query as plain literal. ?__name The parameter name is optional. ?_name_iri The variable is substituted with the paramet...
?_name The variable specifies the API mandatory parameter name. The value is incorporated in the query as plain literal. ?__name The parameter name is optional. ?_name_iri The variable is substituted with the parameter value as a IRI (also: number or literal). ?_name_en The parameter value is co...
Below is the the instruction that describes the task: ### Input: ?_name The variable specifies the API mandatory parameter name. The value is incorporated in the query as plain literal. ?__name The parameter name is optional. ?_name_iri The variable is substituted with the parameter value as a IRI (...
def create_blueprint(endpoints): """Create Invenio-Records-UI blueprint. The factory installs one URL route per endpoint defined, and adds an error handler for rendering tombstones. :param endpoints: Dictionary of endpoints to be installed. See usage documentation for further details. :ret...
Create Invenio-Records-UI blueprint. The factory installs one URL route per endpoint defined, and adds an error handler for rendering tombstones. :param endpoints: Dictionary of endpoints to be installed. See usage documentation for further details. :returns: The initialized blueprint.
Below is the the instruction that describes the task: ### Input: Create Invenio-Records-UI blueprint. The factory installs one URL route per endpoint defined, and adds an error handler for rendering tombstones. :param endpoints: Dictionary of endpoints to be installed. See usage documentation ...
def stop(self): """ Stop the RpcConsumer. The RpcConsumer ordinary unregisters from the QueueConsumer when the last Rpc subclass unregisters from it. If no providers were registered, we should unregister from the QueueConsumer as soon as we're asked to stop. """ ...
Stop the RpcConsumer. The RpcConsumer ordinary unregisters from the QueueConsumer when the last Rpc subclass unregisters from it. If no providers were registered, we should unregister from the QueueConsumer as soon as we're asked to stop.
Below is the the instruction that describes the task: ### Input: Stop the RpcConsumer. The RpcConsumer ordinary unregisters from the QueueConsumer when the last Rpc subclass unregisters from it. If no providers were registered, we should unregister from the QueueConsumer as soon as we're as...
def get_object_or_child_by_type(self, *types): """ Get object if child already been read or get child. Use this method for fast access to objects in case of static configurations. :param types: requested object types. :return: all children of the specified types. """ o...
Get object if child already been read or get child. Use this method for fast access to objects in case of static configurations. :param types: requested object types. :return: all children of the specified types.
Below is the the instruction that describes the task: ### Input: Get object if child already been read or get child. Use this method for fast access to objects in case of static configurations. :param types: requested object types. :return: all children of the specified types. ### Response...
def answer(part, module='mlai2014.json'): """Returns the answers to the lab classes.""" marks = json.load(open(os.path.join(data_directory, module), 'rb')) return marks['Lab ' + str(part+1)]
Returns the answers to the lab classes.
Below is the the instruction that describes the task: ### Input: Returns the answers to the lab classes. ### Response: def answer(part, module='mlai2014.json'): """Returns the answers to the lab classes.""" marks = json.load(open(os.path.join(data_directory, module), 'rb')) return marks['Lab ' + str(p...
def import_medusa_data(mat_filename, config_file): """Import measurement data (a .mat file) of the FZJ EIT160 system. This data format is identified as 'FZJ-EZ-2017'. Parameters ---------- mat_filename: string filename to the .mat data file. Note that only MNU0 single-potentials are...
Import measurement data (a .mat file) of the FZJ EIT160 system. This data format is identified as 'FZJ-EZ-2017'. Parameters ---------- mat_filename: string filename to the .mat data file. Note that only MNU0 single-potentials are supported! config_file: string filename for c...
Below is the the instruction that describes the task: ### Input: Import measurement data (a .mat file) of the FZJ EIT160 system. This data format is identified as 'FZJ-EZ-2017'. Parameters ---------- mat_filename: string filename to the .mat data file. Note that only MNU0 single-potentials ...
def escape(identifier, ansi_quotes, should_quote): """ Escape identifiers. ANSI uses single quotes, but many databases use back quotes. """ if not should_quote(identifier): return identifier quote = '"' if ansi_quotes else '`' identifier = identifier.replace(quote, 2*quote) re...
Escape identifiers. ANSI uses single quotes, but many databases use back quotes.
Below is the the instruction that describes the task: ### Input: Escape identifiers. ANSI uses single quotes, but many databases use back quotes. ### Response: def escape(identifier, ansi_quotes, should_quote): """ Escape identifiers. ANSI uses single quotes, but many databases use back quotes. ...
def is_valid_ipv4 (ip): """ Return True if given ip is a valid IPv4 address. """ if not _ipv4_re.match(ip): return False a, b, c, d = [int(i) for i in ip.split(".")] return a <= 255 and b <= 255 and c <= 255 and d <= 255
Return True if given ip is a valid IPv4 address.
Below is the the instruction that describes the task: ### Input: Return True if given ip is a valid IPv4 address. ### Response: def is_valid_ipv4 (ip): """ Return True if given ip is a valid IPv4 address. """ if not _ipv4_re.match(ip): return False a, b, c, d = [int(i) for i in ip.split...
def get_api_id(self, lambda_name): """ Given a lambda_name, return the API id. """ try: response = self.cf_client.describe_stack_resource(StackName=lambda_name, LogicalResourceId='Api') return response[...
Given a lambda_name, return the API id.
Below is the the instruction that describes the task: ### Input: Given a lambda_name, return the API id. ### Response: def get_api_id(self, lambda_name): """ Given a lambda_name, return the API id. """ try: response = self.cf_client.describe_stack_resource(StackName=lamb...
def fromdict(dict): """Takes a dictionary as an argument and returns a new State object from the dictionary. :param dict: the dictionary to convert """ index = dict['index'] seed = hb_decode(dict['seed']) n = dict['n'] root = hb_decode(dict['root']) ...
Takes a dictionary as an argument and returns a new State object from the dictionary. :param dict: the dictionary to convert
Below is the the instruction that describes the task: ### Input: Takes a dictionary as an argument and returns a new State object from the dictionary. :param dict: the dictionary to convert ### Response: def fromdict(dict): """Takes a dictionary as an argument and returns a new State objec...
def group_add(self, name, restrict, repos, lces=[], assets=[], queries=[], policies=[], dashboards=[], credentials=[], description=''): '''group_add name, restrict, repos ''' return self.raw_query('group', 'add', data={ 'lces': [{'id': i} for i in lces], ...
group_add name, restrict, repos
Below is the the instruction that describes the task: ### Input: group_add name, restrict, repos ### Response: def group_add(self, name, restrict, repos, lces=[], assets=[], queries=[], policies=[], dashboards=[], credentials=[], description=''): '''group_add name, restrict, repos ...
def verify_connectivity(config): """ Verify connectivity to satellite server """ logger.debug("Verifying Connectivity") ic = InsightsConnection(config) try: branch_info = ic.get_branch_info() except requests.ConnectionError as e: logger.debug(e) logger.debug("Failed t...
Verify connectivity to satellite server
Below is the the instruction that describes the task: ### Input: Verify connectivity to satellite server ### Response: def verify_connectivity(config): """ Verify connectivity to satellite server """ logger.debug("Verifying Connectivity") ic = InsightsConnection(config) try: branch_...
def parse_response(self, resp): """ Parse the xmlrpc response. """ p, u = self.getparser() if hasattr(resp,'text'): # modern requests will do this for us text = resp.text # this is unicode(py2)/str(py3) else: encoding = requests.utils...
Parse the xmlrpc response.
Below is the the instruction that describes the task: ### Input: Parse the xmlrpc response. ### Response: def parse_response(self, resp): """ Parse the xmlrpc response. """ p, u = self.getparser() if hasattr(resp,'text'): # modern requests will do this for us ...
def validate_path(xj_path): """Validates XJ path. :param str xj_path: XJ Path :raise: XJPathError if validation fails. """ if not isinstance(xj_path, str): raise XJPathError('XJPath must be a string') for path in split(xj_path, '.'): if path == '*': continue ...
Validates XJ path. :param str xj_path: XJ Path :raise: XJPathError if validation fails.
Below is the the instruction that describes the task: ### Input: Validates XJ path. :param str xj_path: XJ Path :raise: XJPathError if validation fails. ### Response: def validate_path(xj_path): """Validates XJ path. :param str xj_path: XJ Path :raise: XJPathError if validation fails. """...
def next(self): """Returns the next input from this input reader as (ZipInfo, opener) tuple. Returns: The next input from this input reader, in the form of a 2-tuple. The first element of the tuple is a zipfile.ZipInfo object. The second element of the tuple is a zero-argument function that, ...
Returns the next input from this input reader as (ZipInfo, opener) tuple. Returns: The next input from this input reader, in the form of a 2-tuple. The first element of the tuple is a zipfile.ZipInfo object. The second element of the tuple is a zero-argument function that, when called, retu...
Below is the the instruction that describes the task: ### Input: Returns the next input from this input reader as (ZipInfo, opener) tuple. Returns: The next input from this input reader, in the form of a 2-tuple. The first element of the tuple is a zipfile.ZipInfo object. The second element o...
def find_enclosing_bracket_left(self, left_ch, right_ch, start_pos=None): """ Find the left bracket enclosing current position. Return the relative position to the cursor position. When `start_pos` is given, don't look past the position. """ if self.current_char == left_...
Find the left bracket enclosing current position. Return the relative position to the cursor position. When `start_pos` is given, don't look past the position.
Below is the the instruction that describes the task: ### Input: Find the left bracket enclosing current position. Return the relative position to the cursor position. When `start_pos` is given, don't look past the position. ### Response: def find_enclosing_bracket_left(self, left_ch, right_ch, st...
def cancel(batch_fn, cancel_fn, ops): """Cancel operations. Args: batch_fn: API-specific batch function. cancel_fn: API-specific cancel function. ops: A list of operations to cancel. Returns: A list of operations canceled and a list of error messages. """ # Canceling many operations one-by-...
Cancel operations. Args: batch_fn: API-specific batch function. cancel_fn: API-specific cancel function. ops: A list of operations to cancel. Returns: A list of operations canceled and a list of error messages.
Below is the the instruction that describes the task: ### Input: Cancel operations. Args: batch_fn: API-specific batch function. cancel_fn: API-specific cancel function. ops: A list of operations to cancel. Returns: A list of operations canceled and a list of error messages. ### Response: def...
def get_or_create(name=None, group=None, config=None, extra=0, verbose=0, backend_opts=None): """ Creates a virtual machine instance. """ require('vm_type', 'vm_group') backend_opts = backend_opts or {} verbose = int(verbose) extra = int(extra) if config: config_fn = common.fi...
Creates a virtual machine instance.
Below is the the instruction that describes the task: ### Input: Creates a virtual machine instance. ### Response: def get_or_create(name=None, group=None, config=None, extra=0, verbose=0, backend_opts=None): """ Creates a virtual machine instance. """ require('vm_type', 'vm_group') backend_op...
def SG(self): r'''Specific gravity of the chemical, [dimensionless]. For gas-phase conditions, this is calculated at 15.6 °C (60 °F) and 1 atm for the chemical and the reference fluid, air. For liquid and solid phase conditions, this is calculated based on a referenc...
r'''Specific gravity of the chemical, [dimensionless]. For gas-phase conditions, this is calculated at 15.6 °C (60 °F) and 1 atm for the chemical and the reference fluid, air. For liquid and solid phase conditions, this is calculated based on a reference fluid of water at 4°...
Below is the the instruction that describes the task: ### Input: r'''Specific gravity of the chemical, [dimensionless]. For gas-phase conditions, this is calculated at 15.6 °C (60 °F) and 1 atm for the chemical and the reference fluid, air. For liquid and solid phase conditions, ...
def xy(self): """CIE xy color space coordinates as array [x, y] of real values (0..1).""" if self._xy != (None, None): self._x, self._y = self._xy if self._x is not None and self._y is not None: x = self._x if self._x > 1: x = self._x / 65555 ...
CIE xy color space coordinates as array [x, y] of real values (0..1).
Below is the the instruction that describes the task: ### Input: CIE xy color space coordinates as array [x, y] of real values (0..1). ### Response: def xy(self): """CIE xy color space coordinates as array [x, y] of real values (0..1).""" if self._xy != (None, None): self._x, self._y = ...
def _client_run(self): """MessageReceiver Link is now open - start receiving messages. Will return True if operation successful and client can remain open for further work. :rtype: bool """ self._connection.work() now = self._counter.get_current_ms() if s...
MessageReceiver Link is now open - start receiving messages. Will return True if operation successful and client can remain open for further work. :rtype: bool
Below is the the instruction that describes the task: ### Input: MessageReceiver Link is now open - start receiving messages. Will return True if operation successful and client can remain open for further work. :rtype: bool ### Response: def _client_run(self): """MessageReceiver L...
def user_return(self, frame, return_value): """This function is called when a return trap is set here.""" # This is useful when debugging in an active interpreter (otherwise, # the debugger will stop before reaching the target file) if self._wait_for_mainpyfile: if (self.mainpyfile != self.canon...
This function is called when a return trap is set here.
Below is the the instruction that describes the task: ### Input: This function is called when a return trap is set here. ### Response: def user_return(self, frame, return_value): """This function is called when a return trap is set here.""" # This is useful when debugging in an active interpreter (otherwis...
def get_data_path(cls): """ Read data path from the following sources in order of priority: 1. Environment variable If not found raises an exception :return: str - datapath """ marvin_path = os.environ.get(cls._key) if not marvin_path: raise...
Read data path from the following sources in order of priority: 1. Environment variable If not found raises an exception :return: str - datapath
Below is the the instruction that describes the task: ### Input: Read data path from the following sources in order of priority: 1. Environment variable If not found raises an exception :return: str - datapath ### Response: def get_data_path(cls): """ Read data path from ...
def _parse_request_reply(self): "waiting for a reply to our request" # we need at least 6 bytes of data: 4 for the "header", such # as it is, and 2 more if it's DOMAINNAME (for the size) or 4 # or 16 more if it's an IPv4/6 address reply. plus there's 2 # bytes on the end for the ...
waiting for a reply to our request
Below is the the instruction that describes the task: ### Input: waiting for a reply to our request ### Response: def _parse_request_reply(self): "waiting for a reply to our request" # we need at least 6 bytes of data: 4 for the "header", such # as it is, and 2 more if it's DOMAINNAME (for ...
def bold(*content, sep=' '): """ Make bold text (Markdown) :param content: :param sep: :return: """ return _md(_join(*content, sep=sep), symbols=MD_SYMBOLS[0])
Make bold text (Markdown) :param content: :param sep: :return:
Below is the the instruction that describes the task: ### Input: Make bold text (Markdown) :param content: :param sep: :return: ### Response: def bold(*content, sep=' '): """ Make bold text (Markdown) :param content: :param sep: :return: """ return _md(_join(*content, sep=...
def matplotlib_to_ginga_cmap(cm, name=None): """Convert matplotlib colormap to Ginga's.""" if name is None: name = cm.name arr = cm(np.arange(0, min_cmap_len) / np.float(min_cmap_len - 1)) clst = arr[:, 0:3] return ColorMap(name, clst)
Convert matplotlib colormap to Ginga's.
Below is the the instruction that describes the task: ### Input: Convert matplotlib colormap to Ginga's. ### Response: def matplotlib_to_ginga_cmap(cm, name=None): """Convert matplotlib colormap to Ginga's.""" if name is None: name = cm.name arr = cm(np.arange(0, min_cmap_len) / np.float(min_cm...
def gather_data(registry): """Gathers the metrics""" # Get the host name of the machine host = socket.gethostname() # Create our collectors ram_metric = Gauge("memory_usage_bytes", "Memory usage in bytes.", {'host': host}) cpu_metric = Gauge("cpu_usage_percent", "CPU usa...
Gathers the metrics
Below is the the instruction that describes the task: ### Input: Gathers the metrics ### Response: def gather_data(registry): """Gathers the metrics""" # Get the host name of the machine host = socket.gethostname() # Create our collectors ram_metric = Gauge("memory_usage_bytes", "Memory usage...
def status(self, code=None): """Check status code in response returned by application. If ``code`` is not None, assert that ``code`` is returned by application, else simply return the status code. :param code: ``code`` to assert that application returns :type code: int ...
Check status code in response returned by application. If ``code`` is not None, assert that ``code`` is returned by application, else simply return the status code. :param code: ``code`` to assert that application returns :type code: int Example usage:: check50.fla...
Below is the the instruction that describes the task: ### Input: Check status code in response returned by application. If ``code`` is not None, assert that ``code`` is returned by application, else simply return the status code. :param code: ``code`` to assert that application returns ...
def get_ip_interface_output_interface_ip_address_ipv4(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_ip_interface = ET.Element("get_ip_interface") config = get_ip_interface output = ET.SubElement(get_ip_interface, "output") interface...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def get_ip_interface_output_interface_ip_address_ipv4(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_ip_interface = ET.Element("get_ip_interface") ...
def rename(args): """Supply two names: Existing instance name or ID, and new name to assign to the instance.""" old_name, new_name = args.names add_tags(resources.ec2.Instance(resolve_instance_id(old_name)), Name=new_name, dry_run=args.dry_run)
Supply two names: Existing instance name or ID, and new name to assign to the instance.
Below is the the instruction that describes the task: ### Input: Supply two names: Existing instance name or ID, and new name to assign to the instance. ### Response: def rename(args): """Supply two names: Existing instance name or ID, and new name to assign to the instance.""" old_name, new_name = args.na...
def _check_fact_ref_eval(cls, cpel_dom): """ Returns the result (True, False, Error) of performing the specified check, unless the check isn’t supported, in which case it returns False. Error is a catch-all for all results other than True and False. :param string cpel_do...
Returns the result (True, False, Error) of performing the specified check, unless the check isn’t supported, in which case it returns False. Error is a catch-all for all results other than True and False. :param string cpel_dom: XML infoset for the check_fact_ref element. :retur...
Below is the the instruction that describes the task: ### Input: Returns the result (True, False, Error) of performing the specified check, unless the check isn’t supported, in which case it returns False. Error is a catch-all for all results other than True and False. :param string...
def deserialize(self, data, fields=None): """ Deserializes msgpack bytes to OrderedDict (in the same sorted order as for serialize) :param data: the data in bytes :return: sorted OrderedDict """ # TODO: it can be that we returned data by `get_lines`, that is already deser...
Deserializes msgpack bytes to OrderedDict (in the same sorted order as for serialize) :param data: the data in bytes :return: sorted OrderedDict
Below is the the instruction that describes the task: ### Input: Deserializes msgpack bytes to OrderedDict (in the same sorted order as for serialize) :param data: the data in bytes :return: sorted OrderedDict ### Response: def deserialize(self, data, fields=None): """ Deserializes ...