code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def get_job_class(job_class=None): """ Return job class from RQ settings, otherwise return Job. If `job_class` is not None, it is used as an override (can be python import path as string). """ RQ = getattr(settings, 'RQ', {}) if job_class is None: job_class = RQ.get('JOB_CLASS', Job...
Return job class from RQ settings, otherwise return Job. If `job_class` is not None, it is used as an override (can be python import path as string).
Below is the the instruction that describes the task: ### Input: Return job class from RQ settings, otherwise return Job. If `job_class` is not None, it is used as an override (can be python import path as string). ### Response: def get_job_class(job_class=None): """ Return job class from RQ settin...
def mk_mopheader(expnum, ccd, version, dry_run=False, prefix=""): """Run the OSSOS mopheader script. """ ## confirm destination directory exists. destdir = os.path.dirname( storage.dbimages_uri(expnum, ccd, prefix=prefix, version=version, ext='fits')) if not dry_run: storage.mkdir(d...
Run the OSSOS mopheader script.
Below is the the instruction that describes the task: ### Input: Run the OSSOS mopheader script. ### Response: def mk_mopheader(expnum, ccd, version, dry_run=False, prefix=""): """Run the OSSOS mopheader script. """ ## confirm destination directory exists. destdir = os.path.dirname( storag...
def get_categories(self): """ Return a list of categories that a safe deposit box can belong to""" sdb_resp = get_with_retry(self.cerberus_url + '/v1/category', headers=self.HEADERS) throw_if_bad_response(sdb_resp) return sdb_resp.json()
Return a list of categories that a safe deposit box can belong to
Below is the the instruction that describes the task: ### Input: Return a list of categories that a safe deposit box can belong to ### Response: def get_categories(self): """ Return a list of categories that a safe deposit box can belong to""" sdb_resp = get_with_retry(self.cerberus_url + '/v1/cate...
def sample_cleanup(data, sample): """ stats, cleanup, and link to samples """ ## get maxlen and depths array from clusters maxlens, depths = get_quick_depths(data, sample) try: depths.max() except ValueError: ## If depths is an empty array max() will raise print(" no clu...
stats, cleanup, and link to samples
Below is the the instruction that describes the task: ### Input: stats, cleanup, and link to samples ### Response: def sample_cleanup(data, sample): """ stats, cleanup, and link to samples """ ## get maxlen and depths array from clusters maxlens, depths = get_quick_depths(data, sample) try: ...
def _register_renderers(self, attrs): """ Go through the passed in list of attributes and register those renderers in the render map. """ for method in attrs: func = getattr(self, method) mimetypes = getattr(func, 'mimetypes', []) for mimetype ...
Go through the passed in list of attributes and register those renderers in the render map.
Below is the the instruction that describes the task: ### Input: Go through the passed in list of attributes and register those renderers in the render map. ### Response: def _register_renderers(self, attrs): """ Go through the passed in list of attributes and register those renderers ...
def image_cache(article_cache, img_dir): """ The method to be used by get_images() for copying images out of the cache. """ log.debug('Looking for image directory in the cache') if os.path.isdir(article_cache): log.info('Cached image directory found: {0}'.format(article_cache)) shuti...
The method to be used by get_images() for copying images out of the cache.
Below is the the instruction that describes the task: ### Input: The method to be used by get_images() for copying images out of the cache. ### Response: def image_cache(article_cache, img_dir): """ The method to be used by get_images() for copying images out of the cache. """ log.debug('Looking fo...
def _notin(expr, values): """ Return a boolean sequence or scalar showing whether each element is not contained in the passed `values`. :param expr: sequence or scalar :param values: `list` object or sequence :return: boolean sequence or scalar """ if isinstance(expr, SequenceExpr): ...
Return a boolean sequence or scalar showing whether each element is not contained in the passed `values`. :param expr: sequence or scalar :param values: `list` object or sequence :return: boolean sequence or scalar
Below is the the instruction that describes the task: ### Input: Return a boolean sequence or scalar showing whether each element is not contained in the passed `values`. :param expr: sequence or scalar :param values: `list` object or sequence :return: boolean sequence or scalar ### Response: def ...
def modify(name, bin_path=None, exe_args=None, display_name=None, description=None, service_type=None, start_type=None, start_delayed=None, error_control=None, load_order_group=None, dependencies=None, ...
Modify a service's parameters. Changes will not be made for parameters that are not passed. .. versionadded:: 2016.11.0 Args: name (str): The name of the service. Can be found using the ``service.get_service_name`` function bin_path (str): The path to t...
Below is the the instruction that describes the task: ### Input: Modify a service's parameters. Changes will not be made for parameters that are not passed. .. versionadded:: 2016.11.0 Args: name (str): The name of the service. Can be found using the ``service.get_servi...
def run_mapper(self, stdin=sys.stdin, stdout=sys.stdout): """ Run the mapper on the hadoop node. """ self.init_hadoop() self.init_mapper() outputs = self._map_input((line[:-1] for line in stdin)) if self.reducer == NotImplemented: self.writer(outputs, ...
Run the mapper on the hadoop node.
Below is the the instruction that describes the task: ### Input: Run the mapper on the hadoop node. ### Response: def run_mapper(self, stdin=sys.stdin, stdout=sys.stdout): """ Run the mapper on the hadoop node. """ self.init_hadoop() self.init_mapper() outputs = self...
def read(self, size=-1): """Read bytes from the buffer and advance the read position. Returns the bytes in a bytestring. Parameters ---------- size: int, optional Maximum number of bytes to read. If negative or not supplied, read all unread bytes in the b...
Read bytes from the buffer and advance the read position. Returns the bytes in a bytestring. Parameters ---------- size: int, optional Maximum number of bytes to read. If negative or not supplied, read all unread bytes in the buffer. Returns ----...
Below is the the instruction that describes the task: ### Input: Read bytes from the buffer and advance the read position. Returns the bytes in a bytestring. Parameters ---------- size: int, optional Maximum number of bytes to read. If negative or not supplied, read ...
def validate_rmq_ssl_enabled_units(self, sentry_units, port=None): """Check that ssl is enabled on rmq juju sentry units. :param sentry_units: list of all rmq sentry units :param port: optional ssl port override to validate :returns: None if successful, otherwise return error message ...
Check that ssl is enabled on rmq juju sentry units. :param sentry_units: list of all rmq sentry units :param port: optional ssl port override to validate :returns: None if successful, otherwise return error message
Below is the the instruction that describes the task: ### Input: Check that ssl is enabled on rmq juju sentry units. :param sentry_units: list of all rmq sentry units :param port: optional ssl port override to validate :returns: None if successful, otherwise return error message ### Respons...
def load(name, split=None, data_dir=None, batch_size=1, download=True, as_supervised=False, with_info=False, builder_kwargs=None, download_and_prepare_kwargs=None, as_dataset_kwargs=None, try_gcs=False): """Loads the named datas...
Loads the named dataset into a `tf.data.Dataset`. If `split=None` (the default), returns all splits for the dataset. Otherwise, returns the specified split. `load` is a convenience method that fetches the `tfds.core.DatasetBuilder` by string name, optionally calls `DatasetBuilder.download_and_prepare` (if `...
Below is the the instruction that describes the task: ### Input: Loads the named dataset into a `tf.data.Dataset`. If `split=None` (the default), returns all splits for the dataset. Otherwise, returns the specified split. `load` is a convenience method that fetches the `tfds.core.DatasetBuilder` by string...
def parse_args(argv=()): """Parse command line arguments, and return a dict. """ _p, _args, argv = base_argparser(argv) config_files = [] if not _args.no_config: # process config files # extra config file specified with --config <fname> has highest precedence if _args.config: ...
Parse command line arguments, and return a dict.
Below is the the instruction that describes the task: ### Input: Parse command line arguments, and return a dict. ### Response: def parse_args(argv=()): """Parse command line arguments, and return a dict. """ _p, _args, argv = base_argparser(argv) config_files = [] if not _args.no_config: # ...
def _set_get_vnetwork_portgroups(self, v, load=False): """ Setter method for get_vnetwork_portgroups, mapped from YANG variable /brocade_vswitch_rpc/get_vnetwork_portgroups (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_get_vnetwork_portgroups is considered as a p...
Setter method for get_vnetwork_portgroups, mapped from YANG variable /brocade_vswitch_rpc/get_vnetwork_portgroups (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_get_vnetwork_portgroups is considered as a private method. Backends looking to populate this variable shoul...
Below is the the instruction that describes the task: ### Input: Setter method for get_vnetwork_portgroups, mapped from YANG variable /brocade_vswitch_rpc/get_vnetwork_portgroups (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_get_vnetwork_portgroups is considered as a...
def get_random_value(field): """ Calls the dispatch method (``get_factory_func``) and passes the field obj argument to the callable returned. Returns: random value depending on field type and constraints in the field object """ func = get_factory_func(field) if field.de...
Calls the dispatch method (``get_factory_func``) and passes the field obj argument to the callable returned. Returns: random value depending on field type and constraints in the field object
Below is the the instruction that describes the task: ### Input: Calls the dispatch method (``get_factory_func``) and passes the field obj argument to the callable returned. Returns: random value depending on field type and constraints in the field object ### Response: def get_random_v...
def get_shard_by_num(self, shard_num): """ get_shard_by_num returns the shard at index shard_num. Keyword arguments: shard_num -- The shard index Returns a redis.StrictRedis connection or raises a ValueError. """ if shard_num < 0 or shard_num >= self.num_shards(...
get_shard_by_num returns the shard at index shard_num. Keyword arguments: shard_num -- The shard index Returns a redis.StrictRedis connection or raises a ValueError.
Below is the the instruction that describes the task: ### Input: get_shard_by_num returns the shard at index shard_num. Keyword arguments: shard_num -- The shard index Returns a redis.StrictRedis connection or raises a ValueError. ### Response: def get_shard_by_num(self, shard_num): ...
def return_item(self, item, priority): """Complete work on an item from ``check_out_item()``. If this instance no longer owns ``item``, raise ``LostLease``. If ``priority`` is None, the item is removed from the queue; otherwise it is re-added with the specified priority. Any lo...
Complete work on an item from ``check_out_item()``. If this instance no longer owns ``item``, raise ``LostLease``. If ``priority`` is None, the item is removed from the queue; otherwise it is re-added with the specified priority. Any locked items associated with this item are unlocked.
Below is the the instruction that describes the task: ### Input: Complete work on an item from ``check_out_item()``. If this instance no longer owns ``item``, raise ``LostLease``. If ``priority`` is None, the item is removed from the queue; otherwise it is re-added with the specified priori...
def view_from_url(named_url): # noqa """ Finds and returns the view class from a named url """ # code below is `stolen` from django's reverse method. resolver = get_resolver(get_urlconf()) if type(named_url) in (list, tuple): named_url = named_url[0] parts = named_url.split(":") ...
Finds and returns the view class from a named url
Below is the the instruction that describes the task: ### Input: Finds and returns the view class from a named url ### Response: def view_from_url(named_url): # noqa """ Finds and returns the view class from a named url """ # code below is `stolen` from django's reverse method. resolver = get_...
def _decode_response(response): """ Strip off Gerrit's magic prefix and decode a response. :returns: Decoded JSON content as a dict, or raw text if content could not be decoded as JSON. :raises: requests.HTTPError if the response contains an HTTP error status code. """ con...
Strip off Gerrit's magic prefix and decode a response. :returns: Decoded JSON content as a dict, or raw text if content could not be decoded as JSON. :raises: requests.HTTPError if the response contains an HTTP error status code.
Below is the the instruction that describes the task: ### Input: Strip off Gerrit's magic prefix and decode a response. :returns: Decoded JSON content as a dict, or raw text if content could not be decoded as JSON. :raises: requests.HTTPError if the response contains an HTTP error ...
def _put_resource(self, url, body): """ When I Work PUT method. """ headers = {"Content-Type": "application/json", "Accept": "application/json"} if self.token: headers["W-Token"] = "%s" % self.token response = WhenIWork_DAO().putURL(url, hea...
When I Work PUT method.
Below is the the instruction that describes the task: ### Input: When I Work PUT method. ### Response: def _put_resource(self, url, body): """ When I Work PUT method. """ headers = {"Content-Type": "application/json", "Accept": "application/json"} if self....
def GE(classical_reg1, classical_reg2, classical_reg3): """ Produce an GE instruction. :param classical_reg1: Memory address to which to store the comparison result. :param classical_reg2: Left comparison operand. :param classical_reg3: Right comparison operand. :return: A ClassicalGreaterEqual...
Produce an GE instruction. :param classical_reg1: Memory address to which to store the comparison result. :param classical_reg2: Left comparison operand. :param classical_reg3: Right comparison operand. :return: A ClassicalGreaterEqual instance.
Below is the the instruction that describes the task: ### Input: Produce an GE instruction. :param classical_reg1: Memory address to which to store the comparison result. :param classical_reg2: Left comparison operand. :param classical_reg3: Right comparison operand. :return: A ClassicalGreaterEqua...
def init_with_instance(self, instance): """Initialize with an instance object """ self._uid = api.get_uid(instance) self._brain = None self._catalog = self.get_catalog_for(instance) self._instance = instance
Initialize with an instance object
Below is the the instruction that describes the task: ### Input: Initialize with an instance object ### Response: def init_with_instance(self, instance): """Initialize with an instance object """ self._uid = api.get_uid(instance) self._brain = None self._catalog = self.get_c...
def extract_concepts(self, sentences=None, ids=None, composite_phrase=4, filename=None, file_format='sldi', allow_acronym_variants=False, word_sense_disambiguation=False, allow_large_n=False, strict_model=False, relaxed_...
extract_concepts takes a list of sentences and ids(optional) then returns a list of Concept objects extracted via MetaMap. Supported Options: Composite Phrase -Q Word Sense Disambiguation -y use strict model -A use rela...
Below is the the instruction that describes the task: ### Input: extract_concepts takes a list of sentences and ids(optional) then returns a list of Concept objects extracted via MetaMap. Supported Options: Composite Phrase -Q Word Sense Disambigu...
def create_blueprint(state, import_name): """Creates the security extension blueprint""" bp = Blueprint(state.blueprint_name, import_name, url_prefix=state.url_prefix, subdomain=state.subdomain, template_folder='templates') bp.route(state.logout_url...
Creates the security extension blueprint
Below is the the instruction that describes the task: ### Input: Creates the security extension blueprint ### Response: def create_blueprint(state, import_name): """Creates the security extension blueprint""" bp = Blueprint(state.blueprint_name, import_name, url_prefix=state.url_prefix,...
def is_byte_range_valid(start, stop, length): """Checks if a given byte content range is valid for the given length. .. versionadded:: 0.7 """ if (start is None) != (stop is None): return False elif start is None: return length is None or length >= 0 elif length is None: ...
Checks if a given byte content range is valid for the given length. .. versionadded:: 0.7
Below is the the instruction that describes the task: ### Input: Checks if a given byte content range is valid for the given length. .. versionadded:: 0.7 ### Response: def is_byte_range_valid(start, stop, length): """Checks if a given byte content range is valid for the given length. .. versionadded...
def MOVS(cpu, dest, src): """ Moves data from string to string. Moves the byte, word, or doubleword specified with the second operand (source operand) to the location specified with the first operand (destination operand). Both the source and destination operands are located in memory. ...
Moves data from string to string. Moves the byte, word, or doubleword specified with the second operand (source operand) to the location specified with the first operand (destination operand). Both the source and destination operands are located in memory. The address of the source operand is r...
Below is the the instruction that describes the task: ### Input: Moves data from string to string. Moves the byte, word, or doubleword specified with the second operand (source operand) to the location specified with the first operand (destination operand). Both the source and destination operands ...
def pop(self, index=None): """ This method only works for extensible fields. It allows to remove a value and shift all other values to fill the gap. Parameters ---------- index: int, default None index of field to remove. Returns ------- ...
This method only works for extensible fields. It allows to remove a value and shift all other values to fill the gap. Parameters ---------- index: int, default None index of field to remove. Returns ------- serialize value of popped field
Below is the the instruction that describes the task: ### Input: This method only works for extensible fields. It allows to remove a value and shift all other values to fill the gap. Parameters ---------- index: int, default None index of field to remove. Return...
def to_dict(self): """ Returns a Python dictionary of the TDigest and internal Centroid values. Or use centroids_to_list() for a list of only the Centroid values. """ return {'n':self.n, 'delta':self.delta, 'K':self.K, 'centroids':self.centroids_to_list()}
Returns a Python dictionary of the TDigest and internal Centroid values. Or use centroids_to_list() for a list of only the Centroid values.
Below is the the instruction that describes the task: ### Input: Returns a Python dictionary of the TDigest and internal Centroid values. Or use centroids_to_list() for a list of only the Centroid values. ### Response: def to_dict(self): """ Returns a Python dictionary of the TDigest and in...
def _convert_types(self): """ convert lists and dictionaries that are useful for users to np vectors that are usable by machines """ self.fars = np.array(self.fars) self.parking_rates = np.array([self.parking_rates[use] for use in self.uses]) self.res_ratios = {}...
convert lists and dictionaries that are useful for users to np vectors that are usable by machines
Below is the the instruction that describes the task: ### Input: convert lists and dictionaries that are useful for users to np vectors that are usable by machines ### Response: def _convert_types(self): """ convert lists and dictionaries that are useful for users to np vectors that...
def may_be_emitted(self): """return True if message may be emitted using the current interpreter""" if self.minversion is not None and self.minversion > sys.version_info: return False if self.maxversion is not None and self.maxversion <= sys.version_info: return False ...
return True if message may be emitted using the current interpreter
Below is the the instruction that describes the task: ### Input: return True if message may be emitted using the current interpreter ### Response: def may_be_emitted(self): """return True if message may be emitted using the current interpreter""" if self.minversion is not None and self.minversion >...
def get_workflow_id_and_project(path): ''' :param path: a path or ID to a workflow object :type path: string :returns: tuple of (workflow ID, project ID) Returns the workflow and project IDs from the given path if available; otherwise, exits with an appropriate error message. ''' projec...
:param path: a path or ID to a workflow object :type path: string :returns: tuple of (workflow ID, project ID) Returns the workflow and project IDs from the given path if available; otherwise, exits with an appropriate error message.
Below is the the instruction that describes the task: ### Input: :param path: a path or ID to a workflow object :type path: string :returns: tuple of (workflow ID, project ID) Returns the workflow and project IDs from the given path if available; otherwise, exits with an appropriate error message. ...
def set_cache( self, instance=None, translation=None, language=None, field_name=None, field_value=None, ): """ Add a new translation into the cache. """ if instance is not None and translation is not None: cached_obj = Cache...
Add a new translation into the cache.
Below is the the instruction that describes the task: ### Input: Add a new translation into the cache. ### Response: def set_cache( self, instance=None, translation=None, language=None, field_name=None, field_value=None, ): """ Add a new translati...
def __setUserMinimumSize( self, section, oldSize, newSize ): """ Records the user minimum size for a column. :param section | <int> oldSize | <int> newSize | <int> """ if self.isVisible(): self._columnMini...
Records the user minimum size for a column. :param section | <int> oldSize | <int> newSize | <int>
Below is the the instruction that describes the task: ### Input: Records the user minimum size for a column. :param section | <int> oldSize | <int> newSize | <int> ### Response: def __setUserMinimumSize( self, section, oldSize, newSize ): "...
def get_parameter(self, name): """ Gets a single parameter by its name. :param str name: Either a fully-qualified XTCE name or an alias in the format ``NAMESPACE/NAME``. :rtype: .Parameter """ name = adapt_name_for_rest(name) url = '/mdb/...
Gets a single parameter by its name. :param str name: Either a fully-qualified XTCE name or an alias in the format ``NAMESPACE/NAME``. :rtype: .Parameter
Below is the the instruction that describes the task: ### Input: Gets a single parameter by its name. :param str name: Either a fully-qualified XTCE name or an alias in the format ``NAMESPACE/NAME``. :rtype: .Parameter ### Response: def get_parameter(self, name): "...
def gettree(self, key, create = False): """ Get a subtree node from the key (path relative to this node) """ tree, _ = self._getsubitem(key + '.tmp', create) return tree
Get a subtree node from the key (path relative to this node)
Below is the the instruction that describes the task: ### Input: Get a subtree node from the key (path relative to this node) ### Response: def gettree(self, key, create = False): """ Get a subtree node from the key (path relative to this node) """ tree, _ = self._getsubitem(key + '...
def insertData(self, tablename, list_value_pairs, list_SQLCMD_pairs=None): """insert data into table - ID: identifier of the updated value - list_value_pairs: contains the table field ID and the according value - list_SQLCMD_pairs: contains the table field ID and a SQL command """ fields = self._getF...
insert data into table - ID: identifier of the updated value - list_value_pairs: contains the table field ID and the according value - list_SQLCMD_pairs: contains the table field ID and a SQL command
Below is the the instruction that describes the task: ### Input: insert data into table - ID: identifier of the updated value - list_value_pairs: contains the table field ID and the according value - list_SQLCMD_pairs: contains the table field ID and a SQL command ### Response: def insertData(self, tablen...
def write(self, msg): """ This method the debugger uses to write. In contrast to writeline, no newline is added to the end to `str'. """ if self.state == 'active': if not self.output: self.output = open(self.out_name, 'w') pass pass...
This method the debugger uses to write. In contrast to writeline, no newline is added to the end to `str'.
Below is the the instruction that describes the task: ### Input: This method the debugger uses to write. In contrast to writeline, no newline is added to the end to `str'. ### Response: def write(self, msg): """ This method the debugger uses to write. In contrast to writeline, no newline is...
def allPolygons(self): """ Return a list of all polygons in this BSP tree. """ polygons = self.polygons[:] if self.front: polygons.extend(self.front.allPolygons()) if self.back: polygons.extend(self.back.allPolygons()) return polygons
Return a list of all polygons in this BSP tree.
Below is the the instruction that describes the task: ### Input: Return a list of all polygons in this BSP tree. ### Response: def allPolygons(self): """ Return a list of all polygons in this BSP tree. """ polygons = self.polygons[:] if self.front: polygons.exte...
def create_channels_for_related_fields_in_model(model_class): """ Create channel for the fields of the model, the channel name can be got by calling get_ajax_config_for_relation_fields :param model_class: :return: """ need_to_create_channel = [] for field in enum_model_fields(model_class): ...
Create channel for the fields of the model, the channel name can be got by calling get_ajax_config_for_relation_fields :param model_class: :return:
Below is the the instruction that describes the task: ### Input: Create channel for the fields of the model, the channel name can be got by calling get_ajax_config_for_relation_fields :param model_class: :return: ### Response: def create_channels_for_related_fields_in_model(model_class): """ Create...
def log(self, level, msg, *args, **kwargs): """Log a message and inform all clients. Parameters ---------- level : logging level constant The level to log the message at. msg : str The text format for the log message. args : list of objects ...
Log a message and inform all clients. Parameters ---------- level : logging level constant The level to log the message at. msg : str The text format for the log message. args : list of objects Arguments to pass to log format string. Final mes...
Below is the the instruction that describes the task: ### Input: Log a message and inform all clients. Parameters ---------- level : logging level constant The level to log the message at. msg : str The text format for the log message. args : list of ...
def mw(self): """Molecular weight""" m = P_TAB[self.symbol].get('std_weight') mh = P_TAB['H'].get('std_weight') return m + mh * self.H_count
Molecular weight
Below is the the instruction that describes the task: ### Input: Molecular weight ### Response: def mw(self): """Molecular weight""" m = P_TAB[self.symbol].get('std_weight') mh = P_TAB['H'].get('std_weight') return m + mh * self.H_count
def ReadLine(self, file_object): """Reads a line. Args: file_object (dfvfs.FileIO): file-like object. Returns: str: line read from the lines buffer. """ line, _, self.lines = self.lines.partition('\n') if not line: self.ReadLines(file_object) line, _, self.lines = self....
Reads a line. Args: file_object (dfvfs.FileIO): file-like object. Returns: str: line read from the lines buffer.
Below is the the instruction that describes the task: ### Input: Reads a line. Args: file_object (dfvfs.FileIO): file-like object. Returns: str: line read from the lines buffer. ### Response: def ReadLine(self, file_object): """Reads a line. Args: file_object (dfvfs.FileIO): fi...
def ranked_attributes(self): """ Returns the matrix of ranked attributes from the last run. :return: the Numpy matrix :rtype: ndarray """ matrix = javabridge.call(self.jobject, "rankedAttributes", "()[[D") if matrix is None: return None else: ...
Returns the matrix of ranked attributes from the last run. :return: the Numpy matrix :rtype: ndarray
Below is the the instruction that describes the task: ### Input: Returns the matrix of ranked attributes from the last run. :return: the Numpy matrix :rtype: ndarray ### Response: def ranked_attributes(self): """ Returns the matrix of ranked attributes from the last run. :...
def load_pointings(self, filename=None): """Load some pointings""" filename = ( filename is None and tkFileDialog.askopenfilename() or filename) if filename is None: return f = storage.open_vos_or_local(filename) lines = f.readlines() f.close() poin...
Load some pointings
Below is the the instruction that describes the task: ### Input: Load some pointings ### Response: def load_pointings(self, filename=None): """Load some pointings""" filename = ( filename is None and tkFileDialog.askopenfilename() or filename) if filename is None: return ...
def temp_shell_task(cls, inp, ddb_node, mpi_procs=1, gkk_node=None, md_node=None, ddk_node=None, workdir=None, manager=None): """ Build a :class:`AnaddbTask` with a temporary workdir. The task is executed via the shell with 1 MPI proc. Mainly used for post-processing the ...
Build a :class:`AnaddbTask` with a temporary workdir. The task is executed via the shell with 1 MPI proc. Mainly used for post-processing the DDB files. Args: mpi_procs: Number of MPI processes to use. anaddb_input: string with the anaddb variables. ddb_node: The nod...
Below is the the instruction that describes the task: ### Input: Build a :class:`AnaddbTask` with a temporary workdir. The task is executed via the shell with 1 MPI proc. Mainly used for post-processing the DDB files. Args: mpi_procs: Number of MPI processes to use. anaddb_i...
def execute(self): """Deploys and executes the physical dataflow.""" self._collect_garbage() # Make sure everything is clean # TODO (john): Check if dataflow has any 'logical inconsistencies' # For example, if there is a forward partitioning strategy but # the number of downstre...
Deploys and executes the physical dataflow.
Below is the the instruction that describes the task: ### Input: Deploys and executes the physical dataflow. ### Response: def execute(self): """Deploys and executes the physical dataflow.""" self._collect_garbage() # Make sure everything is clean # TODO (john): Check if dataflow has any '...
def _examine_key(self, key_name, key_val, p, i, option_parsing): """ Examine the current matching key Extracts information, such as function to execute and command options, from the current key (passed to function as 'key_name' and 'key_val'). """ # if the e...
Examine the current matching key Extracts information, such as function to execute and command options, from the current key (passed to function as 'key_name' and 'key_val').
Below is the the instruction that describes the task: ### Input: Examine the current matching key Extracts information, such as function to execute and command options, from the current key (passed to function as 'key_name' and 'key_val'). ### Response: def _examine_key(self, k...
def mappedPolygon(self, polygon, path=None, percent=0.5): """ Maps the inputed polygon to the inputed path \ used when drawing items along the path. If no \ specific path is supplied, then this object's own \ path will be used. It will rotate and move the \ polygon acco...
Maps the inputed polygon to the inputed path \ used when drawing items along the path. If no \ specific path is supplied, then this object's own \ path will be used. It will rotate and move the \ polygon according to the inputed percentage. :param polygon <QPo...
Below is the the instruction that describes the task: ### Input: Maps the inputed polygon to the inputed path \ used when drawing items along the path. If no \ specific path is supplied, then this object's own \ path will be used. It will rotate and move the \ polygon according to ...
def create_import_marking(self, args, options): """ This function parses the `--marking_json` and `--marking_pfill` arguments and creates a marking object if these parameters are specified. Look into 'dingos/management/commands/dingos_generic_xml_import.py to see how this is use...
This function parses the `--marking_json` and `--marking_pfill` arguments and creates a marking object if these parameters are specified. Look into 'dingos/management/commands/dingos_generic_xml_import.py to see how this is used to specify a Django command line argument 'dingos_generic_xml_impo...
Below is the the instruction that describes the task: ### Input: This function parses the `--marking_json` and `--marking_pfill` arguments and creates a marking object if these parameters are specified. Look into 'dingos/management/commands/dingos_generic_xml_import.py to see how this is us...
def add_task(self, func, *args, **kargs): """ Add a task to the queue. """ self.tasks.put((func, args, kargs))
Add a task to the queue.
Below is the the instruction that describes the task: ### Input: Add a task to the queue. ### Response: def add_task(self, func, *args, **kargs): """ Add a task to the queue. """ self.tasks.put((func, args, kargs))
def trends_closest(self, lat, lon): """ Returns the closest regions for the supplied lat/lon. """ url = 'https://api.twitter.com/1.1/trends/closest.json' params = {'lat': lat, 'long': lon} try: resp = self.get(url, params=params) except requests.except...
Returns the closest regions for the supplied lat/lon.
Below is the the instruction that describes the task: ### Input: Returns the closest regions for the supplied lat/lon. ### Response: def trends_closest(self, lat, lon): """ Returns the closest regions for the supplied lat/lon. """ url = 'https://api.twitter.com/1.1/trends/closest.js...
def current(self): # type: () -> Hub """Returns the current instance of the hub.""" rv = _local.get(None) if rv is None: rv = Hub(GLOBAL_HUB) _local.set(rv) return rv
Returns the current instance of the hub.
Below is the the instruction that describes the task: ### Input: Returns the current instance of the hub. ### Response: def current(self): # type: () -> Hub """Returns the current instance of the hub.""" rv = _local.get(None) if rv is None: rv = Hub(GLOBAL_HUB) ...
def _setup_storage_dir(self): """Setup the storage directory path value and ensure the path exists. :rtype: str :raises: tinman.exceptions.ConfigurationException """ dir_path = self._settings.get(config.DIRECTORY) if dir_path is None: dir_path = self._defaul...
Setup the storage directory path value and ensure the path exists. :rtype: str :raises: tinman.exceptions.ConfigurationException
Below is the the instruction that describes the task: ### Input: Setup the storage directory path value and ensure the path exists. :rtype: str :raises: tinman.exceptions.ConfigurationException ### Response: def _setup_storage_dir(self): """Setup the storage directory path value and ensure...
def _delete_msg(self, conn, queue_url, receipt_handle): """ Delete the message specified by ``receipt_handle`` in the queue specified by ``queue_url``. :param conn: SQS API connection :type conn: :py:class:`botocore:SQS.Client` :param queue_url: queue URL to delete the m...
Delete the message specified by ``receipt_handle`` in the queue specified by ``queue_url``. :param conn: SQS API connection :type conn: :py:class:`botocore:SQS.Client` :param queue_url: queue URL to delete the message from :type queue_url: str :param receipt_handle: mess...
Below is the the instruction that describes the task: ### Input: Delete the message specified by ``receipt_handle`` in the queue specified by ``queue_url``. :param conn: SQS API connection :type conn: :py:class:`botocore:SQS.Client` :param queue_url: queue URL to delete the message ...
def add_changes_markup(dom, ins_nodes, del_nodes): """ Add <ins> and <del> tags to the dom to show changes. """ # add markup for inserted and deleted sections for node in reversed(del_nodes): # diff algorithm deletes nodes in reverse order, so un-reverse the # order for this iteratio...
Add <ins> and <del> tags to the dom to show changes.
Below is the the instruction that describes the task: ### Input: Add <ins> and <del> tags to the dom to show changes. ### Response: def add_changes_markup(dom, ins_nodes, del_nodes): """ Add <ins> and <del> tags to the dom to show changes. """ # add markup for inserted and deleted sections for ...
def set_int(bytearray_, byte_index, _int): """ Set value in bytearray to int """ # make sure were dealing with an int _int = int(_int) _bytes = struct.unpack('2B', struct.pack('>h', _int)) bytearray_[byte_index:byte_index + 2] = _bytes return bytearray_
Set value in bytearray to int
Below is the the instruction that describes the task: ### Input: Set value in bytearray to int ### Response: def set_int(bytearray_, byte_index, _int): """ Set value in bytearray to int """ # make sure were dealing with an int _int = int(_int) _bytes = struct.unpack('2B', struct.pack('>h', ...
def check_stripe_api_host(app_configs=None, **kwargs): """ Check that STRIPE_API_HOST is not being used in production. """ from django.conf import settings messages = [] if not settings.DEBUG and hasattr(settings, "STRIPE_API_HOST"): messages.append( checks.Warning( "STRIPE_API_HOST should not be set i...
Check that STRIPE_API_HOST is not being used in production.
Below is the the instruction that describes the task: ### Input: Check that STRIPE_API_HOST is not being used in production. ### Response: def check_stripe_api_host(app_configs=None, **kwargs): """ Check that STRIPE_API_HOST is not being used in production. """ from django.conf import settings messages = [] ...
def authorization_code(self, client_id, client_secret, code, redirect_uri, grant_type='authorization_code'): """Authorization code grant This is the OAuth 2.0 grant that regular web apps utilize in order to access an API. Use this endpoint to exchange an Authorization...
Authorization code grant This is the OAuth 2.0 grant that regular web apps utilize in order to access an API. Use this endpoint to exchange an Authorization Code for a Token. Args: grant_type (str): Denotes the flow you're using. For authorization code use autho...
Below is the the instruction that describes the task: ### Input: Authorization code grant This is the OAuth 2.0 grant that regular web apps utilize in order to access an API. Use this endpoint to exchange an Authorization Code for a Token. Args: grant_type (str): Denote...
def run(self, ipyclient=None, ): """ Run a batch of dstat tests on a list of tests, where each test is a dictionary mapping sample names to {p1 - p4} (and sometimes p5). Parameters modifying the behavior of the run, such as the number of bootstrap replicates (n...
Run a batch of dstat tests on a list of tests, where each test is a dictionary mapping sample names to {p1 - p4} (and sometimes p5). Parameters modifying the behavior of the run, such as the number of bootstrap replicates (nboots) or the minimum coverage for loci (mincov) can be set i...
Below is the the instruction that describes the task: ### Input: Run a batch of dstat tests on a list of tests, where each test is a dictionary mapping sample names to {p1 - p4} (and sometimes p5). Parameters modifying the behavior of the run, such as the number of bootstrap replicates (nb...
def create_buffer(self, ignore_unsupported=False): """ Create this tree's TreeBuffer """ bufferdict = OrderedDict() for branch in self.iterbranches(): # only include activated branches if not self.GetBranchStatus(branch.GetName()): continue...
Create this tree's TreeBuffer
Below is the the instruction that describes the task: ### Input: Create this tree's TreeBuffer ### Response: def create_buffer(self, ignore_unsupported=False): """ Create this tree's TreeBuffer """ bufferdict = OrderedDict() for branch in self.iterbranches(): # o...
def recarraydifference(X,Y): """ Records of a numpy recarray (or ndarray with structured dtype) that do not appear in another. Fast routine for determining which records in numpy array `X` do not appear in numpy recarray `Y`. Record array version of func:`tabular.fast.arraydifference`. **...
Records of a numpy recarray (or ndarray with structured dtype) that do not appear in another. Fast routine for determining which records in numpy array `X` do not appear in numpy recarray `Y`. Record array version of func:`tabular.fast.arraydifference`. **Parameters** **X** : numpy ...
Below is the the instruction that describes the task: ### Input: Records of a numpy recarray (or ndarray with structured dtype) that do not appear in another. Fast routine for determining which records in numpy array `X` do not appear in numpy recarray `Y`. Record array version of func:`tabular.fa...
def compute_full_connections(self, config, direct): """ Compute connections for a fully-connected feed-forward genome--each input connected to all hidden nodes (and output nodes if ``direct`` is set or there are no hidden nodes), each hidden node connected to all output nodes. ...
Compute connections for a fully-connected feed-forward genome--each input connected to all hidden nodes (and output nodes if ``direct`` is set or there are no hidden nodes), each hidden node connected to all output nodes. (Recurrent genomes will also include node self-connections.)
Below is the the instruction that describes the task: ### Input: Compute connections for a fully-connected feed-forward genome--each input connected to all hidden nodes (and output nodes if ``direct`` is set or there are no hidden nodes), each hidden node connected to all output nodes. ...
def parse_options(options): """ :type options: list of str :rtype: list of dict """ if options is None: return [] else: return [ convert_single_option(key.strip(), value.strip()) for key, value in [option.split('=', 1) for option in options] ...
:type options: list of str :rtype: list of dict
Below is the the instruction that describes the task: ### Input: :type options: list of str :rtype: list of dict ### Response: def parse_options(options): """ :type options: list of str :rtype: list of dict """ if options is None: return [] else: return [ con...
def dump_environment(self): """ Try to dump memory Not currently implemented feature :return: None """ # Dump the Alignak configuration to a temporary ini file path = os.path.join(tempfile.gettempdir(), 'dump-env-%s-%s-%d.ini' % (self.type, s...
Try to dump memory Not currently implemented feature :return: None
Below is the the instruction that describes the task: ### Input: Try to dump memory Not currently implemented feature :return: None ### Response: def dump_environment(self): """ Try to dump memory Not currently implemented feature :return: None """ # Dump...
def saliency_map(output, input, name="saliency_map"): """ Produce a saliency map as described in the paper: `Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps <https://arxiv.org/abs/1312.6034>`_. The saliency map is the gradient of the max element in outpu...
Produce a saliency map as described in the paper: `Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps <https://arxiv.org/abs/1312.6034>`_. The saliency map is the gradient of the max element in output w.r.t input. Returns: tf.Tensor: the saliency map. ...
Below is the the instruction that describes the task: ### Input: Produce a saliency map as described in the paper: `Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps <https://arxiv.org/abs/1312.6034>`_. The saliency map is the gradient of the max element in ou...
def _set_intf_ipv6_router_isis(self, v, load=False): """ Setter method for intf_ipv6_router_isis, mapped from YANG variable /interface/ethernet/ipv6/intf_ipv6_router_isis (container) If this variable is read-only (config: false) in the source YANG file, then _set_intf_ipv6_router_isis is considered as a...
Setter method for intf_ipv6_router_isis, mapped from YANG variable /interface/ethernet/ipv6/intf_ipv6_router_isis (container) If this variable is read-only (config: false) in the source YANG file, then _set_intf_ipv6_router_isis is considered as a private method. Backends looking to populate this variable s...
Below is the the instruction that describes the task: ### Input: Setter method for intf_ipv6_router_isis, mapped from YANG variable /interface/ethernet/ipv6/intf_ipv6_router_isis (container) If this variable is read-only (config: false) in the source YANG file, then _set_intf_ipv6_router_isis is considered ...
def process_result_value(self, value, dialect): """ Processes DateTimes from the DB making sure it is always returning UTC. Not using timezone.convert_to_utc as that converts to configured TIMEZONE while the DB might be running with some other setting. We assume UTC datetimes ...
Processes DateTimes from the DB making sure it is always returning UTC. Not using timezone.convert_to_utc as that converts to configured TIMEZONE while the DB might be running with some other setting. We assume UTC datetimes in the database.
Below is the the instruction that describes the task: ### Input: Processes DateTimes from the DB making sure it is always returning UTC. Not using timezone.convert_to_utc as that converts to configured TIMEZONE while the DB might be running with some other setting. We assume UTC datetimes ...
def _slice(attrs, inputs, proto_obj): """Returns a slice of the input tensor along multiple axes.""" new_attrs = translation_utils._fix_attribute_names(attrs, {'axes' : 'axis', 'ends' : 'end', ...
Returns a slice of the input tensor along multiple axes.
Below is the the instruction that describes the task: ### Input: Returns a slice of the input tensor along multiple axes. ### Response: def _slice(attrs, inputs, proto_obj): """Returns a slice of the input tensor along multiple axes.""" new_attrs = translation_utils._fix_attribute_names(attrs, ...
def generate_heightmap(self, buffer=False, as_array=False): """Return a heightmap, representing the highest solid blocks in this chunk.""" non_solids = [0, 8, 9, 10, 11, 38, 37, 32, 31] if buffer: return BytesIO(pack(">i", 256)+self.generate_heightmap()) # Length + Heightmap, ready f...
Return a heightmap, representing the highest solid blocks in this chunk.
Below is the the instruction that describes the task: ### Input: Return a heightmap, representing the highest solid blocks in this chunk. ### Response: def generate_heightmap(self, buffer=False, as_array=False): """Return a heightmap, representing the highest solid blocks in this chunk.""" non_soli...
def _get_opus_maximum(self): """Instantiate an opus maximum type.""" label = """The opux maximum of a given author that is, the only preserved work by that author or the most known one.""" opmax = self.session.get_resource( BASE_URI_TYPES % "o...
Instantiate an opus maximum type.
Below is the the instruction that describes the task: ### Input: Instantiate an opus maximum type. ### Response: def _get_opus_maximum(self): """Instantiate an opus maximum type.""" label = """The opux maximum of a given author that is, the only preserved work by that ...
def ecdh(self, identity, pubkey): """Get shared session key using Elliptic Curve Diffie-Hellman.""" curve_name = identity.get_curve_name(ecdh=True) log.debug('"%s" shared session key (%s) for %r from %s', identity.to_string(), curve_name, pubkey, self) try: ...
Get shared session key using Elliptic Curve Diffie-Hellman.
Below is the the instruction that describes the task: ### Input: Get shared session key using Elliptic Curve Diffie-Hellman. ### Response: def ecdh(self, identity, pubkey): """Get shared session key using Elliptic Curve Diffie-Hellman.""" curve_name = identity.get_curve_name(ecdh=True) log....
def strel_pair(x, y): """Create a structing element composed of the origin and another pixel x, y - x and y offsets of the other pixel returns a structuring element """ x_center = int(np.abs(x)) y_center = int(np.abs(y)) result = np.zeros((y_center * 2 + 1, x_center * 2 + 1), bool...
Create a structing element composed of the origin and another pixel x, y - x and y offsets of the other pixel returns a structuring element
Below is the the instruction that describes the task: ### Input: Create a structing element composed of the origin and another pixel x, y - x and y offsets of the other pixel returns a structuring element ### Response: def strel_pair(x, y): """Create a structing element composed of the origin...
def _parse_expression(s): """Parse boolean expression containing and/or operators""" # Converters for opeartor clauses operators = { 'and': And, 'or': Or, None: lambda *args: args[0] } # Pairing of end group symbols with start group symbols group_pairs = { ')': ...
Parse boolean expression containing and/or operators
Below is the the instruction that describes the task: ### Input: Parse boolean expression containing and/or operators ### Response: def _parse_expression(s): """Parse boolean expression containing and/or operators""" # Converters for opeartor clauses operators = { 'and': And, 'or': Or,...
def decode(cls, line): """ Remove backslash escaping from line.value, then split on commas. """ if line.encoded: line.value = stringToTextValues(line.value, listSeparator=cls.listSeparator) line.encoded=False
Remove backslash escaping from line.value, then split on commas.
Below is the the instruction that describes the task: ### Input: Remove backslash escaping from line.value, then split on commas. ### Response: def decode(cls, line): """ Remove backslash escaping from line.value, then split on commas. """ if line.encoded: line.value = s...
def writePatternLine(self, step_milliseconds, color, pos, led_number=0): """Write a color & step time color pattern line to RAM :param step_milliseconds: how long for this pattern line to take :param color: LED color :param pos: color pattern line number (0-15) :param led_number...
Write a color & step time color pattern line to RAM :param step_milliseconds: how long for this pattern line to take :param color: LED color :param pos: color pattern line number (0-15) :param led_number: LED to adjust, 0=all, 1=LEDA, 2=LEDB
Below is the the instruction that describes the task: ### Input: Write a color & step time color pattern line to RAM :param step_milliseconds: how long for this pattern line to take :param color: LED color :param pos: color pattern line number (0-15) :param led_number: LED to adjust...
def using(self, keyspace=None, connection=None): """ Change the context on-the-fly of the Model class (keyspace, connection) """ if connection and self._batch: raise CQLEngineException("Cannot specify a connection on model in batch mode.") clone = copy.deepcopy(self...
Change the context on-the-fly of the Model class (keyspace, connection)
Below is the the instruction that describes the task: ### Input: Change the context on-the-fly of the Model class (keyspace, connection) ### Response: def using(self, keyspace=None, connection=None): """ Change the context on-the-fly of the Model class (keyspace, connection) """ if...
def fft_coefficient(x, param): """ Calculates the fourier coefficients of the one-dimensional discrete Fourier Transform for real input by fast fourier transformation algorithm .. math:: A_k = \\sum_{m=0}^{n-1} a_m \\exp \\left \\{ -2 \\pi i \\frac{m k}{n} \\right \\}, \\qquad k = 0, \...
Calculates the fourier coefficients of the one-dimensional discrete Fourier Transform for real input by fast fourier transformation algorithm .. math:: A_k = \\sum_{m=0}^{n-1} a_m \\exp \\left \\{ -2 \\pi i \\frac{m k}{n} \\right \\}, \\qquad k = 0, \\ldots , n-1. The resulting coefficien...
Below is the the instruction that describes the task: ### Input: Calculates the fourier coefficients of the one-dimensional discrete Fourier Transform for real input by fast fourier transformation algorithm .. math:: A_k = \\sum_{m=0}^{n-1} a_m \\exp \\left \\{ -2 \\pi i \\frac{m k}{n} \\right \\}...
def section(self, section_title): ''' Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that ha...
Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that has subheadings will NOT return the f...
Below is the the instruction that describes the task: ### Input: Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `sectio...
def render_template(self): """Render and save API doc in openapi.yml.""" self._parse_paths() context = dict(napp=self._napp.__dict__, paths=self._paths) self._save(context)
Render and save API doc in openapi.yml.
Below is the the instruction that describes the task: ### Input: Render and save API doc in openapi.yml. ### Response: def render_template(self): """Render and save API doc in openapi.yml.""" self._parse_paths() context = dict(napp=self._napp.__dict__, paths=self._paths) self._save(...
def worktree_prune(cwd, dry_run=False, verbose=True, expire=None, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encodi...
.. versionadded:: 2015.8.0 Interface to `git-worktree(1)`_, prunes stale worktree administrative data from the gitdir cwd The path to the main git checkout or a linked worktree dry_run : False If ``True``, then this function will report what would have been pruned, but no chan...
Below is the the instruction that describes the task: ### Input: .. versionadded:: 2015.8.0 Interface to `git-worktree(1)`_, prunes stale worktree administrative data from the gitdir cwd The path to the main git checkout or a linked worktree dry_run : False If ``True``, then this ...
def qos(self, prefetch_size, prefetch_count, apply_global=False): """Request specific Quality of Service.""" self.channel.basic_qos(prefetch_size, prefetch_count, apply_global)
Request specific Quality of Service.
Below is the the instruction that describes the task: ### Input: Request specific Quality of Service. ### Response: def qos(self, prefetch_size, prefetch_count, apply_global=False): """Request specific Quality of Service.""" self.channel.basic_qos(prefetch_size, prefetch_count, ...
def first(self, limit=1, columns=None): """ Execute the query and get the first results :param limit: The number of results to get :type limit: int :param columns: The columns to get :type columns: list :return: The result :rtype: mixed """ ...
Execute the query and get the first results :param limit: The number of results to get :type limit: int :param columns: The columns to get :type columns: list :return: The result :rtype: mixed
Below is the the instruction that describes the task: ### Input: Execute the query and get the first results :param limit: The number of results to get :type limit: int :param columns: The columns to get :type columns: list :return: The result :rtype: mixed ### Res...
def show_zoning_enabled_configuration_input_request_type_get_next_request_last_rcvd_zone_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_zoning_enabled_configuration = ET.Element("show_zoning_enabled_configuration") config = show_zoning_enabled...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def show_zoning_enabled_configuration_input_request_type_get_next_request_last_rcvd_zone_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_zoning_enab...
def _validate_codeblock_size(self, cparams): """ Code block dimensions must satisfy certain restrictions. They must both be a power of 2 and the total area defined by the width and height cannot be either too great or too small for the codec. """ if cparams.cblockw_init ...
Code block dimensions must satisfy certain restrictions. They must both be a power of 2 and the total area defined by the width and height cannot be either too great or too small for the codec.
Below is the the instruction that describes the task: ### Input: Code block dimensions must satisfy certain restrictions. They must both be a power of 2 and the total area defined by the width and height cannot be either too great or too small for the codec. ### Response: def _validate_codeblock_s...
def _point_in_tectonic_region(self, polygon): ''' Returns the region type and area according to the tectonic region :param polygon: Dictionary containing the following attributes - 'long_lims' - Longitude limits (West, East) 'lat_lims' - Latitude limits (South, No...
Returns the region type and area according to the tectonic region :param polygon: Dictionary containing the following attributes - 'long_lims' - Longitude limits (West, East) 'lat_lims' - Latitude limits (South, North) 'region_type' - Tectonic region type (str) ...
Below is the the instruction that describes the task: ### Input: Returns the region type and area according to the tectonic region :param polygon: Dictionary containing the following attributes - 'long_lims' - Longitude limits (West, East) 'lat_lims' - Latitude limits (South,...
def _nonzero(self): """ Equivalent numpy's nonzero but returns a tuple of Varibles. """ # TODO we should replace dask's native nonzero # after https://github.com/dask/dask/issues/1076 is implemented. nonzeros = np.nonzero(self.data) return tuple(Variable((dim), nz) for nz, dim ...
Equivalent numpy's nonzero but returns a tuple of Varibles.
Below is the the instruction that describes the task: ### Input: Equivalent numpy's nonzero but returns a tuple of Varibles. ### Response: def _nonzero(self): """ Equivalent numpy's nonzero but returns a tuple of Varibles. """ # TODO we should replace dask's native nonzero # after https://g...
def from_doi(doi): """ Get the arXiv eprint id for a given DOI. .. note:: Uses arXiv API. Will not return anything if arXiv is not aware of the associated DOI. :param doi: The DOI of the resource to look for. :returns: The arXiv eprint id, or ``None`` if not found. >>> from_d...
Get the arXiv eprint id for a given DOI. .. note:: Uses arXiv API. Will not return anything if arXiv is not aware of the associated DOI. :param doi: The DOI of the resource to look for. :returns: The arXiv eprint id, or ``None`` if not found. >>> from_doi('10.1209/0295-5075/111/40005...
Below is the the instruction that describes the task: ### Input: Get the arXiv eprint id for a given DOI. .. note:: Uses arXiv API. Will not return anything if arXiv is not aware of the associated DOI. :param doi: The DOI of the resource to look for. :returns: The arXiv eprint id, or ...
def write_to_file(chats, chatfile): """called every time chats are modified""" with open(chatfile, 'w') as handler: handler.write('\n'.join((str(id_) for id_ in chats)))
called every time chats are modified
Below is the the instruction that describes the task: ### Input: called every time chats are modified ### Response: def write_to_file(chats, chatfile): """called every time chats are modified""" with open(chatfile, 'w') as handler: handler.write('\n'.join((str(id_) for id_ in chats)))
def simulate(batch_env, algo, log=True, reset=False): """Simulation step of a vectorized algorithm with in-graph environments. Integrates the operations implemented by the algorithm and the environments into a combined operation. Args: batch_env: In-graph batch environment. algo: Algorithm instance im...
Simulation step of a vectorized algorithm with in-graph environments. Integrates the operations implemented by the algorithm and the environments into a combined operation. Args: batch_env: In-graph batch environment. algo: Algorithm instance implementing required operations. log: Tensor indicating ...
Below is the the instruction that describes the task: ### Input: Simulation step of a vectorized algorithm with in-graph environments. Integrates the operations implemented by the algorithm and the environments into a combined operation. Args: batch_env: In-graph batch environment. algo: Algorithm i...
def on_ujson_dumps(self, ujson, config, dictionary, **kwargs): """ The `ujson <https://pypi.org/project/ujson/>`_ dumps method. :param module ujson: The ``ujson`` module :param class config: The instance's config class :param dict dictionary: The dictionary instance to serialize ...
The `ujson <https://pypi.org/project/ujson/>`_ dumps method. :param module ujson: The ``ujson`` module :param class config: The instance's config class :param dict dictionary: The dictionary instance to serialize :param int indent: The amount of spaces to use for indentation, ...
Below is the the instruction that describes the task: ### Input: The `ujson <https://pypi.org/project/ujson/>`_ dumps method. :param module ujson: The ``ujson`` module :param class config: The instance's config class :param dict dictionary: The dictionary instance to serialize :para...
def unique(seq): """Helper function to include only unique monomials in a basis.""" seen = {} result = [] for item in seq: marker = item if marker in seen: continue seen[marker] = 1 result.append(item) return result
Helper function to include only unique monomials in a basis.
Below is the the instruction that describes the task: ### Input: Helper function to include only unique monomials in a basis. ### Response: def unique(seq): """Helper function to include only unique monomials in a basis.""" seen = {} result = [] for item in seq: marker = item if mar...
def fit_richness(self, atol=1.e-3, maxiter=50): """ Maximize the log-likelihood as a function of richness. ADW 2018-06-04: Does it make sense to set the richness to the mle? Parameters: ----------- atol : absolute tolerence for conversion maxiter : maximum numbe...
Maximize the log-likelihood as a function of richness. ADW 2018-06-04: Does it make sense to set the richness to the mle? Parameters: ----------- atol : absolute tolerence for conversion maxiter : maximum number of iterations Returns: -------- loglike, ...
Below is the the instruction that describes the task: ### Input: Maximize the log-likelihood as a function of richness. ADW 2018-06-04: Does it make sense to set the richness to the mle? Parameters: ----------- atol : absolute tolerence for conversion maxiter : maximum numb...
def receive_bytes(self, data): """Process bytes received from the network. Arguments: data (bytes): any length bytes received from a network connection to a kafka broker. Returns: responses (list of (correlation_id, response)): any/all completed ...
Process bytes received from the network. Arguments: data (bytes): any length bytes received from a network connection to a kafka broker. Returns: responses (list of (correlation_id, response)): any/all completed responses, decoded from bytes to p...
Below is the the instruction that describes the task: ### Input: Process bytes received from the network. Arguments: data (bytes): any length bytes received from a network connection to a kafka broker. Returns: responses (list of (correlation_id, response)):...
def setup_sfr_pars(self, par_cols=None, include_temporal_pars=False): """setup multiplier parameters for sfr segment data Adding support for reachinput (and isfropt = 1)""" assert self.m.sfr is not None, "can't find sfr package..." if isinstance(par_cols, str): par_cols = [pa...
setup multiplier parameters for sfr segment data Adding support for reachinput (and isfropt = 1)
Below is the the instruction that describes the task: ### Input: setup multiplier parameters for sfr segment data Adding support for reachinput (and isfropt = 1) ### Response: def setup_sfr_pars(self, par_cols=None, include_temporal_pars=False): """setup multiplier parameters for sfr segment data ...
def _pkcs1imify(self, data): """ turn a 20-byte SHA1 hash into a blob of data as large as the key's N, using PKCS1's \"emsa-pkcs1-v1_5\" encoding. totally bizarre. """ SHA1_DIGESTINFO = '\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14' size = len(util.deflat...
turn a 20-byte SHA1 hash into a blob of data as large as the key's N, using PKCS1's \"emsa-pkcs1-v1_5\" encoding. totally bizarre.
Below is the the instruction that describes the task: ### Input: turn a 20-byte SHA1 hash into a blob of data as large as the key's N, using PKCS1's \"emsa-pkcs1-v1_5\" encoding. totally bizarre. ### Response: def _pkcs1imify(self, data): """ turn a 20-byte SHA1 hash into a blob of data as...
def __geo_point(lat, lon, elev): """ GeoJSON standard: Create a geoJson Point-type dictionary :param list lat: :param list lon: :return dict: """ logger_noaa_lpd.info("enter geo_point") coordinates = [] geo_dict = OrderedDict() geom...
GeoJSON standard: Create a geoJson Point-type dictionary :param list lat: :param list lon: :return dict:
Below is the the instruction that describes the task: ### Input: GeoJSON standard: Create a geoJson Point-type dictionary :param list lat: :param list lon: :return dict: ### Response: def __geo_point(lat, lon, elev): """ GeoJSON standard: Create a geoJson Poi...
def add_callback(self, callback): """ Add a callback function to the listener. The callback function will be called for each indication this listener receives from any WBEM server. If the callback function is already known to the listener, it will not be added. ...
Add a callback function to the listener. The callback function will be called for each indication this listener receives from any WBEM server. If the callback function is already known to the listener, it will not be added. Parameters: callback (:func:`~pywbem.callb...
Below is the the instruction that describes the task: ### Input: Add a callback function to the listener. The callback function will be called for each indication this listener receives from any WBEM server. If the callback function is already known to the listener, it will not be ...
def with_params(self, params): """Create a new request with added query parameters Parameters ---------- params: Mapping the query parameters to add """ return self.replace(params=_merge_maps(self.params, params))
Create a new request with added query parameters Parameters ---------- params: Mapping the query parameters to add
Below is the the instruction that describes the task: ### Input: Create a new request with added query parameters Parameters ---------- params: Mapping the query parameters to add ### Response: def with_params(self, params): """Create a new request with added query para...
def leaves(self): """ Returns a :class:`QuerySet` of all leaf nodes (nodes with no children). :return: A :class:`QuerySet` of all leaf nodes (nodes with no children). """ # We need to read the _cte_node_children attribute, so ensure it exists. sel...
Returns a :class:`QuerySet` of all leaf nodes (nodes with no children). :return: A :class:`QuerySet` of all leaf nodes (nodes with no children).
Below is the the instruction that describes the task: ### Input: Returns a :class:`QuerySet` of all leaf nodes (nodes with no children). :return: A :class:`QuerySet` of all leaf nodes (nodes with no children). ### Response: def leaves(self): """ Returns a :class:`Qu...
def _computeSky(image, skypars, memmap=False): """ Compute the sky value for the data array passed to the function image is a fits object which contains the data and the header for one image extension skypars is passed in as paramDict """ #this object contains the returned values from the...
Compute the sky value for the data array passed to the function image is a fits object which contains the data and the header for one image extension skypars is passed in as paramDict
Below is the the instruction that describes the task: ### Input: Compute the sky value for the data array passed to the function image is a fits object which contains the data and the header for one image extension skypars is passed in as paramDict ### Response: def _computeSky(image, skypars, memmap=...