code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def pkg_manager_init( self, package_names, overwrite=False, merge=False, callback=None, **kw): """ Note: default implementation calls for npm and package.json, please note that it may not be the case for this instance of Driver. If this class is initiated...
Note: default implementation calls for npm and package.json, please note that it may not be the case for this instance of Driver. If this class is initiated using standard procedures, this will emulate the functionality of ``npm init`` for the generation of a working ``package.j...
Below is the the instruction that describes the task: ### Input: Note: default implementation calls for npm and package.json, please note that it may not be the case for this instance of Driver. If this class is initiated using standard procedures, this will emulate the functionalit...
def update_config(self, cluster_config, login_config): """Update current configuration. This method is usually called after loading a `Cluster` instance from a persistent storage. Note that not all fields are actually updated, but only those that can be safely updated. "...
Update current configuration. This method is usually called after loading a `Cluster` instance from a persistent storage. Note that not all fields are actually updated, but only those that can be safely updated.
Below is the the instruction that describes the task: ### Input: Update current configuration. This method is usually called after loading a `Cluster` instance from a persistent storage. Note that not all fields are actually updated, but only those that can be safely updated. ### Re...
def _add_option(self, arg_parser, name, *args, **kwargs): """ Add an argument to the given arg_parser with the given name. :param argparse.ArgumentParser arg_parser: :param str name: The name of the option. """ arg_parser.add_argument('--' + name, *args, **kwargs)
Add an argument to the given arg_parser with the given name. :param argparse.ArgumentParser arg_parser: :param str name: The name of the option.
Below is the the instruction that describes the task: ### Input: Add an argument to the given arg_parser with the given name. :param argparse.ArgumentParser arg_parser: :param str name: The name of the option. ### Response: def _add_option(self, arg_parser, name, *args, **kwargs): """ ...
def get_all(cls): """ Returns an array with all databases :returns Database list """ api = Client.instance().api data = api.database.get() database_names = data['result'] databases = [] for name in database_names: db = Data...
Returns an array with all databases :returns Database list
Below is the the instruction that describes the task: ### Input: Returns an array with all databases :returns Database list ### Response: def get_all(cls): """ Returns an array with all databases :returns Database list """ api = Client.instance().api ...
def _push_entry(self, key): "Push entry onto our access log, invalidate the old entry if exists." self._invalidate_entry(key) new_entry = AccessEntry(key) self.access_lookup[key] = new_entry self.access_log_lock.acquire() self.access_log.appendleft(new_entry) se...
Push entry onto our access log, invalidate the old entry if exists.
Below is the the instruction that describes the task: ### Input: Push entry onto our access log, invalidate the old entry if exists. ### Response: def _push_entry(self, key): "Push entry onto our access log, invalidate the old entry if exists." self._invalidate_entry(key) new_entry = Acces...
def notify(self, n=1): """Wake up one or more threads waiting on this condition, if any. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. This method wakes up at most n of the threads waiting for the condition variable; it is...
Wake up one or more threads waiting on this condition, if any. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. This method wakes up at most n of the threads waiting for the condition variable; it is a no-op if no threads are waiting...
Below is the the instruction that describes the task: ### Input: Wake up one or more threads waiting on this condition, if any. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. This method wakes up at most n of the threads waiting for th...
def add_final_retrain_ops(class_count, final_tensor_name, bottleneck_tensor, quantize_layer, is_training): """Adds a new softmax and fully-connected layer for training and eval. We need to retrain the top layer to identify our new classes, so this function adds the right operations to t...
Adds a new softmax and fully-connected layer for training and eval. We need to retrain the top layer to identify our new classes, so this function adds the right operations to the graph, along with some variables to hold the weights, and then sets up all the gradients for the backward pass. The set up for the...
Below is the the instruction that describes the task: ### Input: Adds a new softmax and fully-connected layer for training and eval. We need to retrain the top layer to identify our new classes, so this function adds the right operations to the graph, along with some variables to hold the weights, and then s...
def destroy_comment(self, access_token, comment_id): """doc: http://open.youku.com/docs/doc?id=42 """ url = 'https://openapi.youku.com/v2/comments/destroy.json' data = { 'client_id': self.client_id, 'access_token': access_token, 'comment_id': comment_i...
doc: http://open.youku.com/docs/doc?id=42
Below is the the instruction that describes the task: ### Input: doc: http://open.youku.com/docs/doc?id=42 ### Response: def destroy_comment(self, access_token, comment_id): """doc: http://open.youku.com/docs/doc?id=42 """ url = 'https://openapi.youku.com/v2/comments/destroy.json' d...
def get_mentions(self, min_lp=None): ''' Get the list of mentions found. :param min_lp: if set, only get mentions with a link probability higher than this. ''' return (m for m in self.mentions if min_lp is None or m.linkprob > min_lp)
Get the list of mentions found. :param min_lp: if set, only get mentions with a link probability higher than this.
Below is the the instruction that describes the task: ### Input: Get the list of mentions found. :param min_lp: if set, only get mentions with a link probability higher than this. ### Response: def get_mentions(self, min_lp=None): ''' Get the list of mentions found. :param min_lp: i...
def pprint(self): """Print tag key=value pairs.""" strings = [] for key in sorted(self.keys()): values = self[key] for value in values: strings.append("%s=%s" % (key, value)) return "\n".join(strings)
Print tag key=value pairs.
Below is the the instruction that describes the task: ### Input: Print tag key=value pairs. ### Response: def pprint(self): """Print tag key=value pairs.""" strings = [] for key in sorted(self.keys()): values = self[key] for value in values: strings.a...
async def _base_request(self, battle_tag: str, endpoint_name: str, session: aiohttp.ClientSession, *, platform=None, handle_ratelimit=None, max_tries=None, request_timeout=None): """Does a request to some endpoint. This is also where ratelimit logic is handled.""" # We check ...
Does a request to some endpoint. This is also where ratelimit logic is handled.
Below is the the instruction that describes the task: ### Input: Does a request to some endpoint. This is also where ratelimit logic is handled. ### Response: async def _base_request(self, battle_tag: str, endpoint_name: str, session: aiohttp.ClientSession, *, platform=None, handle_rate...
def create(self): """Exclusively create a file, only if this file previously did not exist. """ fdint = os.open(self.path, (os.O_EXCL | os.O_CREAT | os.O_RDWR)) # XXX TODO: 'name' attribute of returned files is not ...
Exclusively create a file, only if this file previously did not exist.
Below is the the instruction that describes the task: ### Input: Exclusively create a file, only if this file previously did not exist. ### Response: def create(self): """Exclusively create a file, only if this file previously did not exist. """ fdint = os.open(self.path, (os.O_EXCL | ...
def run_itx_resistance_assessment(job, rsem_files, univ_options, reports_options): """ A wrapper for assess_itx_resistance. :param dict rsem_files: Results from running rsem :param dict univ_options: Dict of universal options used by almost all tools :param dict reports_options: Options specific to...
A wrapper for assess_itx_resistance. :param dict rsem_files: Results from running rsem :param dict univ_options: Dict of universal options used by almost all tools :param dict reports_options: Options specific to reporting modules :return: The results of running assess_itx_resistance :rtype: toil.f...
Below is the the instruction that describes the task: ### Input: A wrapper for assess_itx_resistance. :param dict rsem_files: Results from running rsem :param dict univ_options: Dict of universal options used by almost all tools :param dict reports_options: Options specific to reporting modules :re...
def replace_insensitive(string, target, replacement): """Similar to string.replace() but is case insensitive Code borrowed from: http://forums.devshed.com/python-programming-11/ case-insensitive-string-replace-490921.html """ no_case = string.lower() index = no_case.rfind(target.lower()) if ...
Similar to string.replace() but is case insensitive Code borrowed from: http://forums.devshed.com/python-programming-11/ case-insensitive-string-replace-490921.html
Below is the the instruction that describes the task: ### Input: Similar to string.replace() but is case insensitive Code borrowed from: http://forums.devshed.com/python-programming-11/ case-insensitive-string-replace-490921.html ### Response: def replace_insensitive(string, target, replacement): """Si...
def remove_work_item_type_field(self, process_id, wit_ref_name, field_ref_name): """RemoveWorkItemTypeField. [Preview API] Removes a field from a work item type. Does not permanently delete the field. :param str process_id: The ID of the process. :param str wit_ref_name: The reference na...
RemoveWorkItemTypeField. [Preview API] Removes a field from a work item type. Does not permanently delete the field. :param str process_id: The ID of the process. :param str wit_ref_name: The reference name of the work item type. :param str field_ref_name: The reference name of the field...
Below is the the instruction that describes the task: ### Input: RemoveWorkItemTypeField. [Preview API] Removes a field from a work item type. Does not permanently delete the field. :param str process_id: The ID of the process. :param str wit_ref_name: The reference name of the work item typ...
def eval(self, expression, vm='python'): """Evaluate an expression against the table columns. Parameters ---------- expression : string Expression to evaluate. vm : {'numexpr', 'python'} Virtual machine to use. Returns ------- res...
Evaluate an expression against the table columns. Parameters ---------- expression : string Expression to evaluate. vm : {'numexpr', 'python'} Virtual machine to use. Returns ------- result : ndarray
Below is the the instruction that describes the task: ### Input: Evaluate an expression against the table columns. Parameters ---------- expression : string Expression to evaluate. vm : {'numexpr', 'python'} Virtual machine to use. Returns --...
def find_out_pattern(self, pattern): """ This function will read the standard error of the program and return a matching pattern if found. EG. prog_obj.FindErrPattern("Update of mySQL failed") """ if self.wdir != '': stdout = "%s/%s"%(self.wdir, self.stdout) else: ...
This function will read the standard error of the program and return a matching pattern if found. EG. prog_obj.FindErrPattern("Update of mySQL failed")
Below is the the instruction that describes the task: ### Input: This function will read the standard error of the program and return a matching pattern if found. EG. prog_obj.FindErrPattern("Update of mySQL failed") ### Response: def find_out_pattern(self, pattern): """ This function wi...
def save(self, *args, **kwargs): """Override the default ``save`` method.""" if not self.status: self.status = self.DRAFT # Published pages should always have a publication date if self.publication_date is None and self.status == self.PUBLISHED: self.publication_d...
Override the default ``save`` method.
Below is the the instruction that describes the task: ### Input: Override the default ``save`` method. ### Response: def save(self, *args, **kwargs): """Override the default ``save`` method.""" if not self.status: self.status = self.DRAFT # Published pages should always have a p...
def _sampleRange(rng, start, end, step, k): """ Equivalent to: random.sample(xrange(start, end, step), k) except it uses our random number generator. This wouldn't need to create the arange if it were implemented in C. """ array = numpy.empty(k, dtype="uint32") rng.sample(numpy.arange(start, end, ste...
Equivalent to: random.sample(xrange(start, end, step), k) except it uses our random number generator. This wouldn't need to create the arange if it were implemented in C.
Below is the the instruction that describes the task: ### Input: Equivalent to: random.sample(xrange(start, end, step), k) except it uses our random number generator. This wouldn't need to create the arange if it were implemented in C. ### Response: def _sampleRange(rng, start, end, step, k): """ Equi...
def destroy(self, folder=None, as_coro=False): '''Destroy the environment. Does the following: 1. calls :py:meth:`~creamas.core.Environment.save_info` 2. for each agent: calls :py:meth:`close` 3. Shuts down its RPC-service. ''' async def _destroy(folder): ...
Destroy the environment. Does the following: 1. calls :py:meth:`~creamas.core.Environment.save_info` 2. for each agent: calls :py:meth:`close` 3. Shuts down its RPC-service.
Below is the the instruction that describes the task: ### Input: Destroy the environment. Does the following: 1. calls :py:meth:`~creamas.core.Environment.save_info` 2. for each agent: calls :py:meth:`close` 3. Shuts down its RPC-service. ### Response: def destroy(self, folder=Non...
def activate(ctx): """Activate the given ParseContext.""" if hasattr(ctx, '_on_context_exit'): raise ContextError( 'Context actions registered outside this ' 'parse context are active') try: ParseContext._active.append(ctx) ctx...
Activate the given ParseContext.
Below is the the instruction that describes the task: ### Input: Activate the given ParseContext. ### Response: def activate(ctx): """Activate the given ParseContext.""" if hasattr(ctx, '_on_context_exit'): raise ContextError( 'Context actions registered outside this ' ...
def update(self, unique_name=values.unset): """ Update the ModelBuildInstance :param unicode unique_name: An application-defined string that uniquely identifies the resource :returns: Updated ModelBuildInstance :rtype: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildIn...
Update the ModelBuildInstance :param unicode unique_name: An application-defined string that uniquely identifies the resource :returns: Updated ModelBuildInstance :rtype: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildInstance
Below is the the instruction that describes the task: ### Input: Update the ModelBuildInstance :param unicode unique_name: An application-defined string that uniquely identifies the resource :returns: Updated ModelBuildInstance :rtype: twilio.rest.autopilot.v1.assistant.model_build.ModelBu...
def make_range(clusters, extend=0): """ Convert to interval ends from a list of anchors extend modifies the xmax, ymax boundary of the box, which can be positive or negative very useful when we want to make the range as fuzzy as we specify """ eclusters = [] for cluster in clusters: ...
Convert to interval ends from a list of anchors extend modifies the xmax, ymax boundary of the box, which can be positive or negative very useful when we want to make the range as fuzzy as we specify
Below is the the instruction that describes the task: ### Input: Convert to interval ends from a list of anchors extend modifies the xmax, ymax boundary of the box, which can be positive or negative very useful when we want to make the range as fuzzy as we specify ### Response: def make_range(clusters,...
def estimate_entropy(X, epsilon=None): r"""Estimate a dataset's Shannon entropy. This function can take datasets of mixed discrete and continuous features, and uses a set of heuristics to determine which functions to apply to each. Because this function is a subroutine in a mutual information esti...
r"""Estimate a dataset's Shannon entropy. This function can take datasets of mixed discrete and continuous features, and uses a set of heuristics to determine which functions to apply to each. Because this function is a subroutine in a mutual information estimator, we employ the Kozachenko Estimat...
Below is the the instruction that describes the task: ### Input: r"""Estimate a dataset's Shannon entropy. This function can take datasets of mixed discrete and continuous features, and uses a set of heuristics to determine which functions to apply to each. Because this function is a subroutine in...
def add_package(pkg_type, pkg_name, working=None): """add_package Adds a package to the existing config.JSON file. This is a standalone function to handle this functionality. The existing config.JSON is read in and is left unchanged. """ kvp = {pkg_type: pkg_name} working = os.getcwd() if not working...
add_package Adds a package to the existing config.JSON file. This is a standalone function to handle this functionality. The existing config.JSON is read in and is left unchanged.
Below is the the instruction that describes the task: ### Input: add_package Adds a package to the existing config.JSON file. This is a standalone function to handle this functionality. The existing config.JSON is read in and is left unchanged. ### Response: def add_package(pkg_type, pkg_name, working=None): ...
def _cdf(self, xloc, dist, length, cache): """ Cumulative distribution function. Example: >>> print(chaospy.Iid(chaospy.Uniform(0, 2), 2).fwd( ... [[0.1, 0.2, 0.3], [0.2, 0.2, 0.3]])) [[0.05 0.1 0.15] [0.1 0.1 0.15]] """ ou...
Cumulative distribution function. Example: >>> print(chaospy.Iid(chaospy.Uniform(0, 2), 2).fwd( ... [[0.1, 0.2, 0.3], [0.2, 0.2, 0.3]])) [[0.05 0.1 0.15] [0.1 0.1 0.15]]
Below is the the instruction that describes the task: ### Input: Cumulative distribution function. Example: >>> print(chaospy.Iid(chaospy.Uniform(0, 2), 2).fwd( ... [[0.1, 0.2, 0.3], [0.2, 0.2, 0.3]])) [[0.05 0.1 0.15] [0.1 0.1 0.15]] ### Response: d...
def key(self, *path_args, **kwargs): """Proxy to :class:`google.cloud.datastore.key.Key`. Passes our ``project``. """ if "project" in kwargs: raise TypeError("Cannot pass project") kwargs["project"] = self.project if "namespace" not in kwargs: kwa...
Proxy to :class:`google.cloud.datastore.key.Key`. Passes our ``project``.
Below is the the instruction that describes the task: ### Input: Proxy to :class:`google.cloud.datastore.key.Key`. Passes our ``project``. ### Response: def key(self, *path_args, **kwargs): """Proxy to :class:`google.cloud.datastore.key.Key`. Passes our ``project``. """ if...
def next_row(self): """Move to next row from currently selected row.""" row = self.currentIndex().row() rows = self.source_model.rowCount() if row + 1 == rows: row = -1 self.selectRow(row + 1)
Move to next row from currently selected row.
Below is the the instruction that describes the task: ### Input: Move to next row from currently selected row. ### Response: def next_row(self): """Move to next row from currently selected row.""" row = self.currentIndex().row() rows = self.source_model.rowCount() if row + 1 == rows...
def setComplete(self, basepath): """Set complete flag for this comic, ie. all comics are downloaded.""" if self.endOfLife: filename = self.getCompleteFile(basepath) if not os.path.exists(filename): with open(filename, 'w') as f: f.write('All co...
Set complete flag for this comic, ie. all comics are downloaded.
Below is the the instruction that describes the task: ### Input: Set complete flag for this comic, ie. all comics are downloaded. ### Response: def setComplete(self, basepath): """Set complete flag for this comic, ie. all comics are downloaded.""" if self.endOfLife: filename = self.getC...
def run(self): """Start the consumer""" if self.profile_file: LOGGER.info('Profiling to %s', self.profile_file) profile.runctx('self._run()', globals(), locals(), self.profile_file) else: self._run() LOGGER.debug('Exiting %s ...
Start the consumer
Below is the the instruction that describes the task: ### Input: Start the consumer ### Response: def run(self): """Start the consumer""" if self.profile_file: LOGGER.info('Profiling to %s', self.profile_file) profile.runctx('self._run()', globals(), locals(), ...
def py2json(py_obj): """ Converts the inputted python object to JSON format. :param py_obj | <variant> """ method = getattr(py_obj, '__json__', None) if method: return method() elif type(py_obj) == datetime.datetime: return py_obj.isoformat() elif type(py_obj) ...
Converts the inputted python object to JSON format. :param py_obj | <variant>
Below is the the instruction that describes the task: ### Input: Converts the inputted python object to JSON format. :param py_obj | <variant> ### Response: def py2json(py_obj): """ Converts the inputted python object to JSON format. :param py_obj | <variant> """ method ...
def data_to_dict(self, sysbase=False): """ Return the loaded model parameters as one dictionary. Each key of the dictionary is a parameter name, and the value is a list of all the parameter values. :param sysbase: use system base quantities :type sysbase: bool "...
Return the loaded model parameters as one dictionary. Each key of the dictionary is a parameter name, and the value is a list of all the parameter values. :param sysbase: use system base quantities :type sysbase: bool
Below is the the instruction that describes the task: ### Input: Return the loaded model parameters as one dictionary. Each key of the dictionary is a parameter name, and the value is a list of all the parameter values. :param sysbase: use system base quantities :type sysbase: bool...
def find_line(self): """第一次载入时查找歌词""" for now_time in reversed(range(self.data.time)): locate = [index for index, i in enumerate(self._sort_lrc_dict) if i[0] == now_time] # 查找歌词在self.sort_lrc_dict中的位置 if locate: return locate[0] + self.lrc_o...
第一次载入时查找歌词
Below is the the instruction that describes the task: ### Input: 第一次载入时查找歌词 ### Response: def find_line(self): """第一次载入时查找歌词""" for now_time in reversed(range(self.data.time)): locate = [index for index, i in enumerate(self._sort_lrc_dict) if i[0] == now_time] # 查...
def prep_vectors_for_gradient(nest_coefs, index_coefs, design, choice_vec, rows_to_obs, rows_to_nests, *args, ...
Parameters ---------- nest_coefs : 1D or 2D ndarray. All elements should by ints, floats, or longs. If 1D, should have 1 element for each nesting coefficient being estimated. If 2D, should have 1 column for each set of nesting coefficients being used to predict the probabilities ...
Below is the the instruction that describes the task: ### Input: Parameters ---------- nest_coefs : 1D or 2D ndarray. All elements should by ints, floats, or longs. If 1D, should have 1 element for each nesting coefficient being estimated. If 2D, should have 1 column for each set of ...
def _function(self): """ Waits until stopped to keep script live. Gui must handle calling of Toggle_NV function on mouse click. """ start_time = datetime.datetime.now() # calculate stop time if self.settings['wait_mode'] == 'absolute': stop_time = start_time...
Waits until stopped to keep script live. Gui must handle calling of Toggle_NV function on mouse click.
Below is the the instruction that describes the task: ### Input: Waits until stopped to keep script live. Gui must handle calling of Toggle_NV function on mouse click. ### Response: def _function(self): """ Waits until stopped to keep script live. Gui must handle calling of Toggle_NV function on mo...
def get_songs(self, cache=True, results=15, start=0): """Get the songs associated with an artist Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. results (int):...
Get the songs associated with an artist Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. results (int): An integer number of results to return ...
Below is the the instruction that describes the task: ### Input: Get the songs associated with an artist Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. results (i...
def extract_dicommetadata(self, token, item_id): """ Extract DICOM metadata from the given item :param token: A valid token for the user in question. :type token: string :param item_id: id of the item to be extracted :type item_id: int | long :return: the item re...
Extract DICOM metadata from the given item :param token: A valid token for the user in question. :type token: string :param item_id: id of the item to be extracted :type item_id: int | long :return: the item revision DAO :rtype: dict
Below is the the instruction that describes the task: ### Input: Extract DICOM metadata from the given item :param token: A valid token for the user in question. :type token: string :param item_id: id of the item to be extracted :type item_id: int | long :return: the item re...
def filter_query(self, query, field, value): """Filter a query.""" return query.where(field ** "%{}%".format(value.lower()))
Filter a query.
Below is the the instruction that describes the task: ### Input: Filter a query. ### Response: def filter_query(self, query, field, value): """Filter a query.""" return query.where(field ** "%{}%".format(value.lower()))
def uuid1(node=None, clock_seq=None): """Generate a UUID from a host ID, sequence number, and the current time. If 'node' is not given, getnode() is used to obtain the hardware address. If 'clock_seq' is given, it is used as the sequence number; otherwise a random 14-bit sequence number is chosen.""" ...
Generate a UUID from a host ID, sequence number, and the current time. If 'node' is not given, getnode() is used to obtain the hardware address. If 'clock_seq' is given, it is used as the sequence number; otherwise a random 14-bit sequence number is chosen.
Below is the the instruction that describes the task: ### Input: Generate a UUID from a host ID, sequence number, and the current time. If 'node' is not given, getnode() is used to obtain the hardware address. If 'clock_seq' is given, it is used as the sequence number; otherwise a random 14-bit sequenc...
def _prepareSObjects(sObjects): '''Prepare a SObject''' sObjectsCopy = copy.deepcopy(sObjects) if isinstance(sObjectsCopy, dict): # If root element is a dict, then this is a single object not an array _doPrep(sObjectsCopy) else: # else this is an array, and each elelment should b...
Prepare a SObject
Below is the the instruction that describes the task: ### Input: Prepare a SObject ### Response: def _prepareSObjects(sObjects): '''Prepare a SObject''' sObjectsCopy = copy.deepcopy(sObjects) if isinstance(sObjectsCopy, dict): # If root element is a dict, then this is a single object not an arr...
def normalizeURL(url): """Normalize a URL, converting normalization failures to DiscoveryFailure""" try: normalized = urinorm.urinorm(url) except ValueError, why: raise DiscoveryFailure('Normalizing identifier: %s' % (why[0],), None) else: return urlparse.urldefrag(normalized...
Normalize a URL, converting normalization failures to DiscoveryFailure
Below is the the instruction that describes the task: ### Input: Normalize a URL, converting normalization failures to DiscoveryFailure ### Response: def normalizeURL(url): """Normalize a URL, converting normalization failures to DiscoveryFailure""" try: normalized = urinorm.urinorm(url) ...
def rdl_decomposition_rev(T, k, norm='reversible', ncv=None, mu=None): r"""Compute the decomposition into left and right eigenvectors. Parameters ---------- T : sparse matrix Transition matrix k : int Number of eigenvector/eigenvalue pairs norm: {'standard', 'reversible'} ...
r"""Compute the decomposition into left and right eigenvectors. Parameters ---------- T : sparse matrix Transition matrix k : int Number of eigenvector/eigenvalue pairs norm: {'standard', 'reversible'} standard: (L'R) = Id, L[:,0] is a probability distribution, t...
Below is the the instruction that describes the task: ### Input: r"""Compute the decomposition into left and right eigenvectors. Parameters ---------- T : sparse matrix Transition matrix k : int Number of eigenvector/eigenvalue pairs norm: {'standard', 'reversible'} stan...
def power(self, n): """The matrix power of the channel. Args: n (int): compute the matrix power of the superoperator matrix. Returns: PTM: the matrix power of the SuperOp converted to a PTM channel. Raises: QiskitError: if the input and output dimen...
The matrix power of the channel. Args: n (int): compute the matrix power of the superoperator matrix. Returns: PTM: the matrix power of the SuperOp converted to a PTM channel. Raises: QiskitError: if the input and output dimensions of the Quantu...
Below is the the instruction that describes the task: ### Input: The matrix power of the channel. Args: n (int): compute the matrix power of the superoperator matrix. Returns: PTM: the matrix power of the SuperOp converted to a PTM channel. Raises: Qisk...
def is_all_field_none(self): """ :rtype: bool """ if self._country is not None: return False if self._tax_number is not None: return False if self._status is not None: return False return True
:rtype: bool
Below is the the instruction that describes the task: ### Input: :rtype: bool ### Response: def is_all_field_none(self): """ :rtype: bool """ if self._country is not None: return False if self._tax_number is not None: return False if self._...
def right_complement(clr): """ Returns the right half of the split complement. """ right = split_complementary(clr)[2] colors = complementary(clr) colors[3].h = right.h colors[4].h = right.h colors[5].h = right.h colors = colorlist( colors[0], colors[2], colors[1], colors[5]...
Returns the right half of the split complement.
Below is the the instruction that describes the task: ### Input: Returns the right half of the split complement. ### Response: def right_complement(clr): """ Returns the right half of the split complement. """ right = split_complementary(clr)[2] colors = complementary(clr) colors[3].h = rig...
def process_node(node): """Process a node in result.json structure""" value = node['value'] mname = node['name'] typeid = node['typeid'] if typeid == 52: # StructDataValue obj = {} for el in value['elements']: key, val = process_node(el) obj[key] = val ...
Process a node in result.json structure
Below is the the instruction that describes the task: ### Input: Process a node in result.json structure ### Response: def process_node(node): """Process a node in result.json structure""" value = node['value'] mname = node['name'] typeid = node['typeid'] if typeid == 52: # StructDataValue ...
def run(self, data, results=None, mask=None, positions=None): """ Run a fit for each galaxy from the previous phase. Parameters ---------- data: LensData results: ResultsCollection Results from all previous phases mask: Mask The mask ...
Run a fit for each galaxy from the previous phase. Parameters ---------- data: LensData results: ResultsCollection Results from all previous phases mask: Mask The mask positions Returns ------- results: HyperGalaxyResults ...
Below is the the instruction that describes the task: ### Input: Run a fit for each galaxy from the previous phase. Parameters ---------- data: LensData results: ResultsCollection Results from all previous phases mask: Mask The mask positions ...
def __resize_surface_extents(self): """Handles surface cleanup once a scale or rotation operation has been performed.""" #Set the new location of the origin, as the surface size may increase with rotation self.__origin.X = self.image.get_width() * self.__untransformed_nor_origin.X self._...
Handles surface cleanup once a scale or rotation operation has been performed.
Below is the the instruction that describes the task: ### Input: Handles surface cleanup once a scale or rotation operation has been performed. ### Response: def __resize_surface_extents(self): """Handles surface cleanup once a scale or rotation operation has been performed.""" #Set the new locatio...
def trigger (self, event, *args, **kwargs): """ Cause the callbacks associated with the event to be called :param event: the event that occurred :type event: str :param data: optional data to pass to the callback :type data: anything that should be passed to the callback ...
Cause the callbacks associated with the event to be called :param event: the event that occurred :type event: str :param data: optional data to pass to the callback :type data: anything that should be passed to the callback
Below is the the instruction that describes the task: ### Input: Cause the callbacks associated with the event to be called :param event: the event that occurred :type event: str :param data: optional data to pass to the callback :type data: anything that should be passed to the call...
def unpack_archive(archive_format, archive_path, source_path): """Extract a .zip/.tar.gz archive to a folder.""" if archive_format not in ('zip', 'tar'): raise ValueError('Unknown archive format "%s".' % archive_format) if archive_format == 'zip': with zipfile.ZipFile(archive_path) as archiv...
Extract a .zip/.tar.gz archive to a folder.
Below is the the instruction that describes the task: ### Input: Extract a .zip/.tar.gz archive to a folder. ### Response: def unpack_archive(archive_format, archive_path, source_path): """Extract a .zip/.tar.gz archive to a folder.""" if archive_format not in ('zip', 'tar'): raise ValueError('Unkn...
def keypoint_flip(bbox, d, rows, cols): """Flip a keypoint either vertically, horizontally or both depending on the value of `d`. Raises: ValueError: if value of `d` is not -1, 0 or 1. """ if d == 0: bbox = keypoint_vflip(bbox, rows, cols) elif d == 1: bbox = keypoint_hflip...
Flip a keypoint either vertically, horizontally or both depending on the value of `d`. Raises: ValueError: if value of `d` is not -1, 0 or 1.
Below is the the instruction that describes the task: ### Input: Flip a keypoint either vertically, horizontally or both depending on the value of `d`. Raises: ValueError: if value of `d` is not -1, 0 or 1. ### Response: def keypoint_flip(bbox, d, rows, cols): """Flip a keypoint either vertically,...
def readint2dnorm(filename): """Read corrected intensity and error matrices (Matlab mat or numpy npz format for Beamline B1 (HASYLAB/DORISIII)) Input ----- filename: string the name of the file Outputs ------- two ``np.ndarray``-s, the Intensity and the Error matrices File...
Read corrected intensity and error matrices (Matlab mat or numpy npz format for Beamline B1 (HASYLAB/DORISIII)) Input ----- filename: string the name of the file Outputs ------- two ``np.ndarray``-s, the Intensity and the Error matrices File formats supported: ------------...
Below is the the instruction that describes the task: ### Input: Read corrected intensity and error matrices (Matlab mat or numpy npz format for Beamline B1 (HASYLAB/DORISIII)) Input ----- filename: string the name of the file Outputs ------- two ``np.ndarray``-s, the Intensity...
def post_gist(content, description='', filename='file', auth=False): """Post some text to a Gist, and return the URL.""" post_data = json.dumps({ "description": description, "public": True, "files": { filename: { "content": content } } }).encode('utf-8') ...
Post some text to a Gist, and return the URL.
Below is the the instruction that describes the task: ### Input: Post some text to a Gist, and return the URL. ### Response: def post_gist(content, description='', filename='file', auth=False): """Post some text to a Gist, and return the URL.""" post_data = json.dumps({ "description": description, ...
def load_grouped_actions(spec, default_group=None, key_prefix="actions", pop_keys=False, expr_parser=None): """Instanciates actions from a dict. Will look for a key name key_prefix and for key starting with key_prefix followed by a dot and a group name. A group name can be any string and will can be used la...
Instanciates actions from a dict. Will look for a key name key_prefix and for key starting with key_prefix followed by a dot and a group name. A group name can be any string and will can be used later to filter actions. Values associated to these keys should be lists that will be loaded using load_actions()
Below is the the instruction that describes the task: ### Input: Instanciates actions from a dict. Will look for a key name key_prefix and for key starting with key_prefix followed by a dot and a group name. A group name can be any string and will can be used later to filter actions. Values associated t...
def __IsFlagFileDirective(self, flag_string): """Checks whether flag_string contain a --flagfile=<foo> directive.""" if isinstance(flag_string, type('')): if flag_string.startswith('--flagfile='): return 1 elif flag_string == '--flagfile': return 1 elif flag_string.startswith('...
Checks whether flag_string contain a --flagfile=<foo> directive.
Below is the the instruction that describes the task: ### Input: Checks whether flag_string contain a --flagfile=<foo> directive. ### Response: def __IsFlagFileDirective(self, flag_string): """Checks whether flag_string contain a --flagfile=<foo> directive.""" if isinstance(flag_string, type('')): if...
def selected(self, new): """Set selected from list or instance of object or name. Over-writes existing selection """ def preprocess(item): if isinstance(item, str): return self.options[item] return item items = coerce_to_list(new, preproce...
Set selected from list or instance of object or name. Over-writes existing selection
Below is the the instruction that describes the task: ### Input: Set selected from list or instance of object or name. Over-writes existing selection ### Response: def selected(self, new): """Set selected from list or instance of object or name. Over-writes existing selection """ ...
def sqrt_shannon_entropy(filename): """ Calculates Shannon entropy based on square root of phenotype count. This might account for relationship between population size and evolvability. """ data = load_grid_data(filename, "int") data = agg_grid(data, mode) phenotypes = {} for r in da...
Calculates Shannon entropy based on square root of phenotype count. This might account for relationship between population size and evolvability.
Below is the the instruction that describes the task: ### Input: Calculates Shannon entropy based on square root of phenotype count. This might account for relationship between population size and evolvability. ### Response: def sqrt_shannon_entropy(filename): """ Calculates Shannon entropy based o...
def load_image(name, n, m=None, gpu=None, square=None): """Function to load images with certain size.""" if m is None: m = n if gpu is None: gpu = 0 if square is None: square = 0 command = ('Shearlab.load_image("{}", {}, {}, {}, {})'.format(name, n, m, gpu, squ...
Function to load images with certain size.
Below is the the instruction that describes the task: ### Input: Function to load images with certain size. ### Response: def load_image(name, n, m=None, gpu=None, square=None): """Function to load images with certain size.""" if m is None: m = n if gpu is None: gpu = 0 if square is...
def predict_median(self, X, ancillary_X=None): """ Returns the median lifetimes for the individuals. If the survival curve of an individual does not cross 0.5, then the result is infinity. http://stats.stackexchange.com/questions/102986/percentile-loss-functions Parameters ...
Returns the median lifetimes for the individuals. If the survival curve of an individual does not cross 0.5, then the result is infinity. http://stats.stackexchange.com/questions/102986/percentile-loss-functions Parameters ---------- X: numpy array or DataFrame a (n...
Below is the the instruction that describes the task: ### Input: Returns the median lifetimes for the individuals. If the survival curve of an individual does not cross 0.5, then the result is infinity. http://stats.stackexchange.com/questions/102986/percentile-loss-functions Parameters ...
def get_smokedetector_by_name(self, name): """Retrieves a smokedetector object by its name :param name: The name of the smokedetector to return :return: A smokedetector object """ return next((smokedetector for smokedetector in self.smokedetectors if smokede...
Retrieves a smokedetector object by its name :param name: The name of the smokedetector to return :return: A smokedetector object
Below is the the instruction that describes the task: ### Input: Retrieves a smokedetector object by its name :param name: The name of the smokedetector to return :return: A smokedetector object ### Response: def get_smokedetector_by_name(self, name): """Retrieves a smokedetector object by...
def load(self, instance, xblock): """ Get the filesystem for the field specified in 'instance' and the xblock in 'xblock' It is locally scoped. """ # TODO: Get xblock from context, once the plumbing is piped through if djpyfs: return djpyfs.get_filesystem(sco...
Get the filesystem for the field specified in 'instance' and the xblock in 'xblock' It is locally scoped.
Below is the the instruction that describes the task: ### Input: Get the filesystem for the field specified in 'instance' and the xblock in 'xblock' It is locally scoped. ### Response: def load(self, instance, xblock): """ Get the filesystem for the field specified in 'instance' and the ...
def heapreplace(heap, item): """Pop and return the current smallest value, and add the new item. This is more efficient than heappop() followed by heappush(), and can be more appropriate when using a fixed-size heap. Note that the value returned may be larger than item! That constrains reasonable use...
Pop and return the current smallest value, and add the new item. This is more efficient than heappop() followed by heappush(), and can be more appropriate when using a fixed-size heap. Note that the value returned may be larger than item! That constrains reasonable uses of this routine unless written...
Below is the the instruction that describes the task: ### Input: Pop and return the current smallest value, and add the new item. This is more efficient than heappop() followed by heappush(), and can be more appropriate when using a fixed-size heap. Note that the value returned may be larger than item...
def create_from_lambda_arn(cls, client, lambda_arn): # type: (TypedAWSClient, str) -> LogRetriever """Create a LogRetriever from a client and lambda arn. :type client: botocore.client.Logs :param client: A ``logs`` client. :type lambda_arn: str :param lambda_arn: The AR...
Create a LogRetriever from a client and lambda arn. :type client: botocore.client.Logs :param client: A ``logs`` client. :type lambda_arn: str :param lambda_arn: The ARN of the lambda function. :return: An instance of ``LogRetriever``.
Below is the the instruction that describes the task: ### Input: Create a LogRetriever from a client and lambda arn. :type client: botocore.client.Logs :param client: A ``logs`` client. :type lambda_arn: str :param lambda_arn: The ARN of the lambda function. :return: An in...
def run_node(cls, node, # type: NodeProto inputs, # type: Any device='CPU', # type: Text outputs_info=None, # type: Optional[Sequence[Tuple[numpy.dtype, Tuple[int, ...]]]] **kwargs # type: Dict[Text, Any] ): # ty...
Simple run one operator and return the results. Args: outputs_info: a list of tuples, which contains the element type and shape of each output. First element of the tuple is the dtype, and the second element is the shape. More use case can be found in https://gith...
Below is the the instruction that describes the task: ### Input: Simple run one operator and return the results. Args: outputs_info: a list of tuples, which contains the element type and shape of each output. First element of the tuple is the dtype, and the second element...
def Images(self, run, tag): """Retrieve the image events associated with a run and tag. Args: run: A string name of the run for which values are retrieved. tag: A string name of the tag for which values are retrieved. Raises: KeyError: If the run is not found, or the tag is not available...
Retrieve the image events associated with a run and tag. Args: run: A string name of the run for which values are retrieved. tag: A string name of the tag for which values are retrieved. Raises: KeyError: If the run is not found, or the tag is not available for the given run. Re...
Below is the the instruction that describes the task: ### Input: Retrieve the image events associated with a run and tag. Args: run: A string name of the run for which values are retrieved. tag: A string name of the tag for which values are retrieved. Raises: KeyError: If the run is not ...
def compute_upper_limit(mu_in, post, alpha=0.9): """ Returns the upper limit mu_high of confidence level alpha for a posterior distribution post on the given parameter mu. The posterior need not be normalized. """ if 0 < alpha < 1: dp = integral_element(mu_in, post) high_idx = bi...
Returns the upper limit mu_high of confidence level alpha for a posterior distribution post on the given parameter mu. The posterior need not be normalized.
Below is the the instruction that describes the task: ### Input: Returns the upper limit mu_high of confidence level alpha for a posterior distribution post on the given parameter mu. The posterior need not be normalized. ### Response: def compute_upper_limit(mu_in, post, alpha=0.9): """ Returns th...
def status(self, pk=None, detail=False, **kwargs): """Print the current job status. This is used to check a running job. You can look up the job with the same parameters used for a get request. =====API DOCS===== Retrieve the current job status. :param pk: Primary key of the re...
Print the current job status. This is used to check a running job. You can look up the job with the same parameters used for a get request. =====API DOCS===== Retrieve the current job status. :param pk: Primary key of the resource to retrieve status from. :type pk: int ...
Below is the the instruction that describes the task: ### Input: Print the current job status. This is used to check a running job. You can look up the job with the same parameters used for a get request. =====API DOCS===== Retrieve the current job status. :param pk: Primary key of...
def get_bios(self): """ Gets the list of BIOS/UEFI values currently set on the physical server. Returns: dict: Dictionary of BIOS/UEFI values. """ uri = "{}/bios".format(self.data["uri"]) return self._helper.do_get(uri)
Gets the list of BIOS/UEFI values currently set on the physical server. Returns: dict: Dictionary of BIOS/UEFI values.
Below is the the instruction that describes the task: ### Input: Gets the list of BIOS/UEFI values currently set on the physical server. Returns: dict: Dictionary of BIOS/UEFI values. ### Response: def get_bios(self): """ Gets the list of BIOS/UEFI values currently set on the p...
def register_to_ldbd(client, program, paramdict, version = u'0', cvs_repository = u'-', cvs_entry_time = 0, comment = u'-', is_online = False, jobid = 0, domain = None, ifos = u'-'): """ Register the current process and params to a database via a LDBDClient. The program and paramdict arguments and any additional k...
Register the current process and params to a database via a LDBDClient. The program and paramdict arguments and any additional keyword arguments are the same as those for register_to_xmldoc(). Returns the new row from the process table.
Below is the the instruction that describes the task: ### Input: Register the current process and params to a database via a LDBDClient. The program and paramdict arguments and any additional keyword arguments are the same as those for register_to_xmldoc(). Returns the new row from the process table. ### Respon...
def rotate(img, angle, resample=False, expand=False, center=None): """Rotate the image by angle. Args: img (PIL Image): PIL Image to be rotated. angle (float or int): In degrees degrees counter clockwise order. resample (``PIL.Image.NEAREST`` or ``PIL.Image.BILINEAR`` or ``PIL.Image.BI...
Rotate the image by angle. Args: img (PIL Image): PIL Image to be rotated. angle (float or int): In degrees degrees counter clockwise order. resample (``PIL.Image.NEAREST`` or ``PIL.Image.BILINEAR`` or ``PIL.Image.BICUBIC``, optional): An optional resampling filter. See `filter...
Below is the the instruction that describes the task: ### Input: Rotate the image by angle. Args: img (PIL Image): PIL Image to be rotated. angle (float or int): In degrees degrees counter clockwise order. resample (``PIL.Image.NEAREST`` or ``PIL.Image.BILINEAR`` or ``PIL.Image.BICUBIC...
def append(self, *args, **kwargs): """ Base method for appending data. Applies a plot-type specific cleaning operation, then appends data to the visualization. """ data = self._clean_data(*args, **kwargs) if 'images' in data: images = data['images'] ...
Base method for appending data. Applies a plot-type specific cleaning operation, then appends data to the visualization.
Below is the the instruction that describes the task: ### Input: Base method for appending data. Applies a plot-type specific cleaning operation, then appends data to the visualization. ### Response: def append(self, *args, **kwargs): """ Base method for appending data. Ap...
def make_isotropic_source(name, Spectrum_Filename, spectrum): """Construct and return a `fermipy.roi_model.IsoSource` object """ data = dict(Spectrum_Filename=Spectrum_Filename) if spectrum is not None: data.update(spectrum) return roi_model.IsoSource(name, data)
Construct and return a `fermipy.roi_model.IsoSource` object
Below is the the instruction that describes the task: ### Input: Construct and return a `fermipy.roi_model.IsoSource` object ### Response: def make_isotropic_source(name, Spectrum_Filename, spectrum): """Construct and return a `fermipy.roi_model.IsoSource` object """ data = dict(Spectrum_Filename=Spect...
def size(self): """Total number of grid points.""" # Since np.prod(()) == 1.0 we need to handle that by ourselves return (0 if self.shape == () else int(np.prod(self.shape, dtype='int64')))
Total number of grid points.
Below is the the instruction that describes the task: ### Input: Total number of grid points. ### Response: def size(self): """Total number of grid points.""" # Since np.prod(()) == 1.0 we need to handle that by ourselves return (0 if self.shape == () else int(np.prod(self.s...
def type(self, mpath): """Return the manta type for the given manta path. @param mpath {str} The manta path for which to get the type. @returns {str|None} The manta type, e.g. "object" or "directory", or None if the path doesn't exist. """ try: return sel...
Return the manta type for the given manta path. @param mpath {str} The manta path for which to get the type. @returns {str|None} The manta type, e.g. "object" or "directory", or None if the path doesn't exist.
Below is the the instruction that describes the task: ### Input: Return the manta type for the given manta path. @param mpath {str} The manta path for which to get the type. @returns {str|None} The manta type, e.g. "object" or "directory", or None if the path doesn't exist. ### Response...
async def _get_input_dialog(self, dialog): """ Returns a :tl:`InputDialogPeer`. This is a bit tricky because it may or not need access to the client to convert what's given into an input entity. """ try: if dialog.SUBCLASS_OF_ID == 0xa21c9795: # crc32(b'Input...
Returns a :tl:`InputDialogPeer`. This is a bit tricky because it may or not need access to the client to convert what's given into an input entity.
Below is the the instruction that describes the task: ### Input: Returns a :tl:`InputDialogPeer`. This is a bit tricky because it may or not need access to the client to convert what's given into an input entity. ### Response: async def _get_input_dialog(self, dialog): """ Returns a...
def __parse_affiliations_json(self, affiliations, uuid): """Parse identity's affiliations from a json dict""" enrollments = [] for affiliation in affiliations.values(): name = self.__encode(affiliation['name']) try: start_date = str_to_datetime(affiliat...
Parse identity's affiliations from a json dict
Below is the the instruction that describes the task: ### Input: Parse identity's affiliations from a json dict ### Response: def __parse_affiliations_json(self, affiliations, uuid): """Parse identity's affiliations from a json dict""" enrollments = [] for affiliation in affiliations.valu...
def _check_valid_translation(self, translation): """Checks that the translation vector is valid. """ if not isinstance(translation, np.ndarray) or not np.issubdtype(translation.dtype, np.number): raise ValueError('Translation must be specified as numeric numpy array') t = tr...
Checks that the translation vector is valid.
Below is the the instruction that describes the task: ### Input: Checks that the translation vector is valid. ### Response: def _check_valid_translation(self, translation): """Checks that the translation vector is valid. """ if not isinstance(translation, np.ndarray) or not np.issubdtype(tr...
def percentOverlap(x1, x2, size): """ Computes the percentage of overlap between vectors x1 and x2. @param x1 (array) binary vector @param x2 (array) binary vector @param size (int) length of binary vectors @return percentOverlap (float) percentage overlap between x1 and x2 """ nonZeroX1 = np.co...
Computes the percentage of overlap between vectors x1 and x2. @param x1 (array) binary vector @param x2 (array) binary vector @param size (int) length of binary vectors @return percentOverlap (float) percentage overlap between x1 and x2
Below is the the instruction that describes the task: ### Input: Computes the percentage of overlap between vectors x1 and x2. @param x1 (array) binary vector @param x2 (array) binary vector @param size (int) length of binary vectors @return percentOverlap (float) percentage overlap between x1 and x...
def buildType(valtype, extra=[], display=False, control=False, valueAlarm=False): """Build a Type :param str valtype: A type code to be used with the 'value' field. See :ref:`valuecodes` :param list extra: A list of tuples describing additional non-standard fields :param bool display: ...
Build a Type :param str valtype: A type code to be used with the 'value' field. See :ref:`valuecodes` :param list extra: A list of tuples describing additional non-standard fields :param bool display: Include optional fields for display meta-data :param bool control: Include optional f...
Below is the the instruction that describes the task: ### Input: Build a Type :param str valtype: A type code to be used with the 'value' field. See :ref:`valuecodes` :param list extra: A list of tuples describing additional non-standard fields :param bool display: Include optional fields ...
def calculate(self, calc, formula_reg, data_reg, out_reg, timestep=None, idx=None): """ Calculate looping over specified repeat arguments. :param calc: Calculation to loop over. :param formula_reg: Formula registry :param data_reg: Data registry :param ...
Calculate looping over specified repeat arguments. :param calc: Calculation to loop over. :param formula_reg: Formula registry :param data_reg: Data registry :param out_reg: Outputs registry :param timestep: timestep used for dynamic calcs :param idx: index used in dynam...
Below is the the instruction that describes the task: ### Input: Calculate looping over specified repeat arguments. :param calc: Calculation to loop over. :param formula_reg: Formula registry :param data_reg: Data registry :param out_reg: Outputs registry :param timestep: ti...
def get_token(self): """Performs Neurio API token authentication using provided key and secret. Note: This method is generally not called by hand; rather it is usually called as-needed by a Neurio Client object. Returns: string: the access token """ if self.__token is not None: ...
Performs Neurio API token authentication using provided key and secret. Note: This method is generally not called by hand; rather it is usually called as-needed by a Neurio Client object. Returns: string: the access token
Below is the the instruction that describes the task: ### Input: Performs Neurio API token authentication using provided key and secret. Note: This method is generally not called by hand; rather it is usually called as-needed by a Neurio Client object. Returns: string: the access token #...
def fetch(self): """ Fetch a SampleInstance :returns: Fetched SampleInstance :rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance """ params = values.of({}) payload = self._version.fetch( 'GET', self._uri, par...
Fetch a SampleInstance :returns: Fetched SampleInstance :rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance
Below is the the instruction that describes the task: ### Input: Fetch a SampleInstance :returns: Fetched SampleInstance :rtype: twilio.rest.autopilot.v1.assistant.task.sample.SampleInstance ### Response: def fetch(self): """ Fetch a SampleInstance :returns: Fetched Sample...
def create_channel( self, name, values=None, *, shape=None, units=None, dtype=None, **kwargs ) -> Channel: """Append a new channel. Parameters ---------- name : string Unique name for this channel. values : array (optional) Array. If None, an ...
Append a new channel. Parameters ---------- name : string Unique name for this channel. values : array (optional) Array. If None, an empty array equaling the data shape is created. Default is None. shape : tuple of int Shape to use...
Below is the the instruction that describes the task: ### Input: Append a new channel. Parameters ---------- name : string Unique name for this channel. values : array (optional) Array. If None, an empty array equaling the data shape is created. D...
def simplex_search(self, source, component_nr): ''' API: simplex_search(self, source, component_nr) Description: Searches graph starting from source. Its difference from usual search is we can also go backwards along an arc. When the graph is a spa...
API: simplex_search(self, source, component_nr) Description: Searches graph starting from source. Its difference from usual search is we can also go backwards along an arc. When the graph is a spanning tree it computes predecessor, thread and depth ind...
Below is the the instruction that describes the task: ### Input: API: simplex_search(self, source, component_nr) Description: Searches graph starting from source. Its difference from usual search is we can also go backwards along an arc. When the graph is a sp...
def configure_uwsgi(configurator_func): """Allows configuring uWSGI using Configuration objects returned by the given configuration function. .. code-block: python # In configuration module, e.g `uwsgicfg.py` from uwsgiconf.config import configure_uwsgi configure_uwsgi(get_config...
Allows configuring uWSGI using Configuration objects returned by the given configuration function. .. code-block: python # In configuration module, e.g `uwsgicfg.py` from uwsgiconf.config import configure_uwsgi configure_uwsgi(get_configurations) :param callable configurator_fu...
Below is the the instruction that describes the task: ### Input: Allows configuring uWSGI using Configuration objects returned by the given configuration function. .. code-block: python # In configuration module, e.g `uwsgicfg.py` from uwsgiconf.config import configure_uwsgi conf...
def _get_gecos(name): ''' Retrieve GECOS field info and return it in dictionary form ''' try: gecos_field = pwd.getpwnam(name).pw_gecos.split(',', 3) except KeyError: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if not gecos_field:...
Retrieve GECOS field info and return it in dictionary form
Below is the the instruction that describes the task: ### Input: Retrieve GECOS field info and return it in dictionary form ### Response: def _get_gecos(name): ''' Retrieve GECOS field info and return it in dictionary form ''' try: gecos_field = pwd.getpwnam(name).pw_gecos.split(',', 3) ...
def _make_attr_element_from_resourceattr(parent, resource_attr_i): """ General function to add an attribute element to a resource element. """ attr = _make_attr_element(parent, resource_attr_i.attr) attr_is_var = etree.SubElement(attr, 'is_var') attr_is_var.text = resource_attr_i.attr_i...
General function to add an attribute element to a resource element.
Below is the the instruction that describes the task: ### Input: General function to add an attribute element to a resource element. ### Response: def _make_attr_element_from_resourceattr(parent, resource_attr_i): """ General function to add an attribute element to a resource element. """ attr...
def peek_step(self, val: ArrayValue, sn: "DataNode") -> Tuple[ObjectValue, "DataNode"]: """Return the entry addressed by the receiver + its schema node. Args: val: Current value (array). sn: Current schema node. """ keys = self.parse_keys(sn) ...
Return the entry addressed by the receiver + its schema node. Args: val: Current value (array). sn: Current schema node.
Below is the the instruction that describes the task: ### Input: Return the entry addressed by the receiver + its schema node. Args: val: Current value (array). sn: Current schema node. ### Response: def peek_step(self, val: ArrayValue, sn: "DataNode") -> Tuple[O...
async def play(self, *uris: SomeURIs, offset: Optional[Offset] = 0, device: Optional[SomeDevice] = None): """Start a new context or resume current playback on the user’s active device. The method treats a single argument as a Spotify context, such as a Artist, Album and playlist objects/URI. Wh...
Start a new context or resume current playback on the user’s active device. The method treats a single argument as a Spotify context, such as a Artist, Album and playlist objects/URI. When called with multiple positional arguments they are interpreted as a array of Spotify Track objects/URIs. ...
Below is the the instruction that describes the task: ### Input: Start a new context or resume current playback on the user’s active device. The method treats a single argument as a Spotify context, such as a Artist, Album and playlist objects/URI. When called with multiple positional arguments the...
def add_string_pairs_from_button_element(xib_file, results, button, special_ui_components_prefix): """ Adds strings pairs from a button xib element. Args: xib_file (str): Path to the xib file. results (list): The list to add the results to. button(element): The button element from the x...
Adds strings pairs from a button xib element. Args: xib_file (str): Path to the xib file. results (list): The list to add the results to. button(element): The button element from the xib, to extract the string pairs from. special_ui_components_prefix(str): A custom prefix for intern...
Below is the the instruction that describes the task: ### Input: Adds strings pairs from a button xib element. Args: xib_file (str): Path to the xib file. results (list): The list to add the results to. button(element): The button element from the xib, to extract the string pairs from. ...
def textwrap_body(body, *, subsequent_indent=''): """ Accepts either a string or an iterable of strings. (Iterable is assumed to be individual lines.) Returns a string. """ if isinstance(body, str): text = body else: text = "\n".join(body).rstrip() # textwrap merges para...
Accepts either a string or an iterable of strings. (Iterable is assumed to be individual lines.) Returns a string.
Below is the the instruction that describes the task: ### Input: Accepts either a string or an iterable of strings. (Iterable is assumed to be individual lines.) Returns a string. ### Response: def textwrap_body(body, *, subsequent_indent=''): """ Accepts either a string or an iterable of strings. ...
def import_product_sets( self, parent, input_config, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Asynchronous API that imports a list of reference images to specified pro...
Asynchronous API that imports a list of reference images to specified product sets based on a list of image information. The ``google.longrunning.Operation`` API can be used to keep track of the progress and results of the request. ``Operation.metadata`` contains ``BatchOperationMetadat...
Below is the the instruction that describes the task: ### Input: Asynchronous API that imports a list of reference images to specified product sets based on a list of image information. The ``google.longrunning.Operation`` API can be used to keep track of the progress and results of the req...
def apply_scaling(self, copy=True): """Scale pixel values to there true DN. :param copy: whether to apply the scalling to a copy of the pixel data and leave the orginial unaffected :returns: a scalled version of the pixel data """ if copy: return self.mu...
Scale pixel values to there true DN. :param copy: whether to apply the scalling to a copy of the pixel data and leave the orginial unaffected :returns: a scalled version of the pixel data
Below is the the instruction that describes the task: ### Input: Scale pixel values to there true DN. :param copy: whether to apply the scalling to a copy of the pixel data and leave the orginial unaffected :returns: a scalled version of the pixel data ### Response: def apply_scaling(...
def daylight_saving_end_day(self, value=None): """Corresponds to IDD Field `daylight_saving_end_day` Args: value (str): value for IDD Field `daylight_saving_end_day` if `value` is None it will not be checked against the specification and is assumed to be a mi...
Corresponds to IDD Field `daylight_saving_end_day` Args: value (str): value for IDD Field `daylight_saving_end_day` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `v...
Below is the the instruction that describes the task: ### Input: Corresponds to IDD Field `daylight_saving_end_day` Args: value (str): value for IDD Field `daylight_saving_end_day` if `value` is None it will not be checked against the specification and is assumed...
def from_object(self, obj): """Update the values from the given object. Objects are usually either modules or classes. Just the uppercase variables in that object are stored in the config. Example usage:: from yourapplication import default_config app.config.fro...
Update the values from the given object. Objects are usually either modules or classes. Just the uppercase variables in that object are stored in the config. Example usage:: from yourapplication import default_config app.config.from_object(default_config) You s...
Below is the the instruction that describes the task: ### Input: Update the values from the given object. Objects are usually either modules or classes. Just the uppercase variables in that object are stored in the config. Example usage:: from yourapplication import default_con...
def construct(args): '''Construct a queue-name from a set of arguments and a delimiter''' # make everything unicode name = u'' delimiter, encodeseq = delimiter_encodeseq(_c.FSQ_DELIMITER, _c.FSQ_ENCODE, _c.FSQ_CHARSET) if len(args) == 0: return ...
Construct a queue-name from a set of arguments and a delimiter
Below is the the instruction that describes the task: ### Input: Construct a queue-name from a set of arguments and a delimiter ### Response: def construct(args): '''Construct a queue-name from a set of arguments and a delimiter''' # make everything unicode name = u'' delimiter, encodeseq = delimit...
def delete_cli(access_token, project_member_id, base_url=OH_BASE_URL, file_basename=None, file_id=None, all_files=False): """ Command line function for deleting files. For more information visit :func:`delete_file<ohapi.api.delete_file>`. """ response = delete_file(access_token, p...
Command line function for deleting files. For more information visit :func:`delete_file<ohapi.api.delete_file>`.
Below is the the instruction that describes the task: ### Input: Command line function for deleting files. For more information visit :func:`delete_file<ohapi.api.delete_file>`. ### Response: def delete_cli(access_token, project_member_id, base_url=OH_BASE_URL, file_basename=None, file_id=No...
def copyFile(src, dest): """Copies a source file to a destination whose path may not yet exist. Keyword arguments: src -- Source path to a file (string) dest -- Path for destination file (also a string) """ #Src Exists? try: if os.path.isfile(src): dpath, dfile = os.path...
Copies a source file to a destination whose path may not yet exist. Keyword arguments: src -- Source path to a file (string) dest -- Path for destination file (also a string)
Below is the the instruction that describes the task: ### Input: Copies a source file to a destination whose path may not yet exist. Keyword arguments: src -- Source path to a file (string) dest -- Path for destination file (also a string) ### Response: def copyFile(src, dest): """Copies a source ...
def tables_insert(self, table_name, schema=None, query=None, friendly_name=None, description=None): """Issues a request to create a table or view in the specified dataset with the specified id. A schema must be provided to create a Table, or a query must be provided to create a View. ...
Issues a request to create a table or view in the specified dataset with the specified id. A schema must be provided to create a Table, or a query must be provided to create a View. Args: table_name: the name of the table as a tuple of components. schema: the schema, if this is a Table creation....
Below is the the instruction that describes the task: ### Input: Issues a request to create a table or view in the specified dataset with the specified id. A schema must be provided to create a Table, or a query must be provided to create a View. Args: table_name: the name of the table as a tuple ...
def reset_placeholder_dropdown(cls, input_el): """ Reset the element back to default. """ text = cls.get_placeholder_text(input_el) cls.set_placeholder_text( input_el=input_el, text=text.replace(cls._dropdown_text, "") )
Reset the element back to default.
Below is the the instruction that describes the task: ### Input: Reset the element back to default. ### Response: def reset_placeholder_dropdown(cls, input_el): """ Reset the element back to default. """ text = cls.get_placeholder_text(input_el) cls.set_placeholder_text( ...