code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
async def first(self): """Fetch the first row and then close the result set unconditionally. Returns None if no row is present. """ if self._metadata is None: self._non_result() try: return (await self.fetchone()) finally: await self.c...
Fetch the first row and then close the result set unconditionally. Returns None if no row is present.
Below is the the instruction that describes the task: ### Input: Fetch the first row and then close the result set unconditionally. Returns None if no row is present. ### Response: async def first(self): """Fetch the first row and then close the result set unconditionally. Returns None if...
def json_to_csv(json_input): ''' Convert simple JSON to CSV Accepts a JSON string or JSON object ''' try: json_input = json.loads(json_input) except: pass # If loads fails, it's probably already parsed headers = set() for json_row in json_input: headers.update(jso...
Convert simple JSON to CSV Accepts a JSON string or JSON object
Below is the the instruction that describes the task: ### Input: Convert simple JSON to CSV Accepts a JSON string or JSON object ### Response: def json_to_csv(json_input): ''' Convert simple JSON to CSV Accepts a JSON string or JSON object ''' try: json_input = json.loads(json_input...
def save(self): """ Deletes the selected files from storage """ storage = get_media_storage() for storage_name in self.cleaned_data['selected_files']: full_path = storage.path(storage_name) try: storage.delete(storage_name) ...
Deletes the selected files from storage
Below is the the instruction that describes the task: ### Input: Deletes the selected files from storage ### Response: def save(self): """ Deletes the selected files from storage """ storage = get_media_storage() for storage_name in self.cleaned_data['selected_files']: ...
def disable_script(zap_helper, script_name): """Disable a script.""" with zap_error_handler(): console.debug('Disabling script "{0}"'.format(script_name)) result = zap_helper.zap.script.disable(script_name) if result != 'OK': raise ZAPError('Error disabling script: {0}'.form...
Disable a script.
Below is the the instruction that describes the task: ### Input: Disable a script. ### Response: def disable_script(zap_helper, script_name): """Disable a script.""" with zap_error_handler(): console.debug('Disabling script "{0}"'.format(script_name)) result = zap_helper.zap.script.disable(...
def turn_on(self): """Turn bulb on (full brightness).""" command = "C {},,,,100,\r\n".format(self._zid) response = self._hub.send_command(command) _LOGGER.debug("Turn on %s: %s", repr(command), response) return response
Turn bulb on (full brightness).
Below is the the instruction that describes the task: ### Input: Turn bulb on (full brightness). ### Response: def turn_on(self): """Turn bulb on (full brightness).""" command = "C {},,,,100,\r\n".format(self._zid) response = self._hub.send_command(command) _LOGGER.debug("Turn on %s...
def ashraeiam(self, aoi): """ Determine the incidence angle modifier using ``self.module_parameters['b']``, ``aoi``, and the :py:func:`ashraeiam` function. Uses default arguments if keys not in module_parameters. Parameters ---------- aoi : numeric ...
Determine the incidence angle modifier using ``self.module_parameters['b']``, ``aoi``, and the :py:func:`ashraeiam` function. Uses default arguments if keys not in module_parameters. Parameters ---------- aoi : numeric The angle of incidence in degrees. ...
Below is the the instruction that describes the task: ### Input: Determine the incidence angle modifier using ``self.module_parameters['b']``, ``aoi``, and the :py:func:`ashraeiam` function. Uses default arguments if keys not in module_parameters. Parameters ---------- ...
def teetext(table, source=None, encoding=None, errors='strict', template=None, prologue=None, epilogue=None): """ Return a table that writes rows to a text file as they are iterated over. """ assert template is not None, 'template is required' return TeeTextView(table, source=source, e...
Return a table that writes rows to a text file as they are iterated over.
Below is the the instruction that describes the task: ### Input: Return a table that writes rows to a text file as they are iterated over. ### Response: def teetext(table, source=None, encoding=None, errors='strict', template=None, prologue=None, epilogue=None): """ Return a table that writes r...
def plot_periodbase_lsp(lspinfo, outfile=None, plotdpi=100): '''Makes a plot of periodograms obtained from `periodbase` functions. This takes the output dict produced by any `astrobase.periodbase` period-finder function or a pickle filename containing such a dict and makes a periodogram plot. Par...
Makes a plot of periodograms obtained from `periodbase` functions. This takes the output dict produced by any `astrobase.periodbase` period-finder function or a pickle filename containing such a dict and makes a periodogram plot. Parameters ---------- lspinfo : dict or str If lspinfo ...
Below is the the instruction that describes the task: ### Input: Makes a plot of periodograms obtained from `periodbase` functions. This takes the output dict produced by any `astrobase.periodbase` period-finder function or a pickle filename containing such a dict and makes a periodogram plot. Par...
def feed_eof(self): """Send a potentially "ragged" EOF. This method will raise an SSL_ERROR_EOF exception if the EOF is unexpected. """ self._incoming.write_eof() ssldata, appdata = self.feed_ssldata(b'') assert appdata == [] or appdata == [b'']
Send a potentially "ragged" EOF. This method will raise an SSL_ERROR_EOF exception if the EOF is unexpected.
Below is the the instruction that describes the task: ### Input: Send a potentially "ragged" EOF. This method will raise an SSL_ERROR_EOF exception if the EOF is unexpected. ### Response: def feed_eof(self): """Send a potentially "ragged" EOF. This method will raise an SSL_ERROR_E...
def uniform_crossover(parents): """Perform uniform crossover on two parent chromosomes. Randomly take genes from one parent or the other. Ex. p1 = xxxxx, p2 = yyyyy, child = xyxxy """ chromosome_length = len(parents[0]) children = [[], []] for i in range(chromosome_length): select...
Perform uniform crossover on two parent chromosomes. Randomly take genes from one parent or the other. Ex. p1 = xxxxx, p2 = yyyyy, child = xyxxy
Below is the the instruction that describes the task: ### Input: Perform uniform crossover on two parent chromosomes. Randomly take genes from one parent or the other. Ex. p1 = xxxxx, p2 = yyyyy, child = xyxxy ### Response: def uniform_crossover(parents): """Perform uniform crossover on two parent chr...
def async_(self, cbl, fun): """ return a pair (pipe, process) so that the process writes `fun(a)` to the pipe for each element `a` in the iterable returned by the callable `cbl`. :param cbl: a function returning something iterable :type cbl: callable :param fun: ...
return a pair (pipe, process) so that the process writes `fun(a)` to the pipe for each element `a` in the iterable returned by the callable `cbl`. :param cbl: a function returning something iterable :type cbl: callable :param fun: an unary translation function :type fun:...
Below is the the instruction that describes the task: ### Input: return a pair (pipe, process) so that the process writes `fun(a)` to the pipe for each element `a` in the iterable returned by the callable `cbl`. :param cbl: a function returning something iterable :type cbl: callable...
def round(cls, x: 'TensorFluent') -> 'TensorFluent': '''Returns a TensorFluent for the round function. Args: x: The input fluent. Returns: A TensorFluent wrapping the round function. ''' return cls._unary_op(x, tf.round, tf.float32)
Returns a TensorFluent for the round function. Args: x: The input fluent. Returns: A TensorFluent wrapping the round function.
Below is the the instruction that describes the task: ### Input: Returns a TensorFluent for the round function. Args: x: The input fluent. Returns: A TensorFluent wrapping the round function. ### Response: def round(cls, x: 'TensorFluent') -> 'TensorFluent': '''Ret...
def get_date_range(self, periodicity=PERIODICITY_WEEKLY): """Returns a date range (date from, date to) that suits with the passed in periodicity. :param periodicity: string that represents the periodicity :type periodicity: str :return: A date range :rtype: [(DateTime, D...
Returns a date range (date from, date to) that suits with the passed in periodicity. :param periodicity: string that represents the periodicity :type periodicity: str :return: A date range :rtype: [(DateTime, DateTime)]
Below is the the instruction that describes the task: ### Input: Returns a date range (date from, date to) that suits with the passed in periodicity. :param periodicity: string that represents the periodicity :type periodicity: str :return: A date range :rtype: [(DateTime, D...
def refactor_froms_to_imports(self, offset): """Converting imports of the form "from ..." to "import ...".""" refactor = ImportOrganizer(self.project) changes = refactor.froms_to_imports(self.resource, offset) return translate_changes(changes)
Converting imports of the form "from ..." to "import ...".
Below is the the instruction that describes the task: ### Input: Converting imports of the form "from ..." to "import ...". ### Response: def refactor_froms_to_imports(self, offset): """Converting imports of the form "from ..." to "import ...".""" refactor = ImportOrganizer(self.project) ch...
def _run(self): # pylint: disable=method-hidden """ Runnable main method, perform wait on long-running subtasks """ try: self.event_stop.wait() except gevent.GreenletExit: # killed without exception self.event_stop.set() gevent.killall(self.greenlets) # kil...
Runnable main method, perform wait on long-running subtasks
Below is the the instruction that describes the task: ### Input: Runnable main method, perform wait on long-running subtasks ### Response: def _run(self): # pylint: disable=method-hidden """ Runnable main method, perform wait on long-running subtasks """ try: self.event_stop.wait() ...
def set_basic_auth(self, username, password): """Manually set basic auth in the header when normal method does not work.""" credentials = str(b64encode('{}:{}'.format(username, password).encode('utf-8')), 'utf-8') self.authorization = 'Basic {}'.format(credentials)
Manually set basic auth in the header when normal method does not work.
Below is the the instruction that describes the task: ### Input: Manually set basic auth in the header when normal method does not work. ### Response: def set_basic_auth(self, username, password): """Manually set basic auth in the header when normal method does not work.""" credentials = str(b64enc...
def run(self): """ Run the command with supplied configuration """ device = self.model_config.torch_device() learner = api.Learner(device, self.model_factory.instantiate(), self.max_grad_norm) optimizer = self.optimizer_factory.instantiate(learner.model) # All callbacks used fo...
Run the command with supplied configuration
Below is the the instruction that describes the task: ### Input: Run the command with supplied configuration ### Response: def run(self): """ Run the command with supplied configuration """ device = self.model_config.torch_device() learner = api.Learner(device, self.model_factory.instantia...
def close(self): """ Close (destroy) this USB context, and all related instances. When this method has been called, methods on its instance will become mosty no-ops, returning None until explicitly re-opened (by calling open() or __enter__()). Note: "exit" is a deprecat...
Close (destroy) this USB context, and all related instances. When this method has been called, methods on its instance will become mosty no-ops, returning None until explicitly re-opened (by calling open() or __enter__()). Note: "exit" is a deprecated alias of "close".
Below is the the instruction that describes the task: ### Input: Close (destroy) this USB context, and all related instances. When this method has been called, methods on its instance will become mosty no-ops, returning None until explicitly re-opened (by calling open() or __enter__()). ...
def is_floating(self): """Returns whether this is a (non-quantized, real) floating point type.""" return ( self.is_numpy_compatible and np.issubdtype(self.as_numpy_dtype, np.floating) ) or self.base_dtype == bfloat16
Returns whether this is a (non-quantized, real) floating point type.
Below is the the instruction that describes the task: ### Input: Returns whether this is a (non-quantized, real) floating point type. ### Response: def is_floating(self): """Returns whether this is a (non-quantized, real) floating point type.""" return ( self.is_numpy_compatible and np....
def add_comment(self, body, allow_create=False, allow_hashes=False, summary=None): "Implement as required by parent to store comment in CSV file." if allow_hashes: raise ValueError('allow_hashes not implemented for %s yet' % ( self.__class__.__name__)) ...
Implement as required by parent to store comment in CSV file.
Below is the the instruction that describes the task: ### Input: Implement as required by parent to store comment in CSV file. ### Response: def add_comment(self, body, allow_create=False, allow_hashes=False, summary=None): "Implement as required by parent to store comment in CSV file."...
def transformer_base_v1(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.norm_type = "layer" hparams.hidden_size = 512 hparams.batch_size = 4096 hparams.max_length = 256 hparams.clip_grad_norm = 0. # i.e. no gradient clipping hparams.optimizer_adam_epsilon = 1e-9 hpar...
Set of hyperparameters.
Below is the the instruction that describes the task: ### Input: Set of hyperparameters. ### Response: def transformer_base_v1(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.norm_type = "layer" hparams.hidden_size = 512 hparams.batch_size = 4096 hparams.max_length = 2...
def deserializeEc(x, compress=True): """ Deserialize binary string @x into an EC element. """ return _deserialize(x, ec1Element, compress, librelic.ec_read_bin_abi)
Deserialize binary string @x into an EC element.
Below is the the instruction that describes the task: ### Input: Deserialize binary string @x into an EC element. ### Response: def deserializeEc(x, compress=True): """ Deserialize binary string @x into an EC element. """ return _deserialize(x, ec1Element, compress, librelic.ec_read_bin_abi)
def _init_coord_properties(self): """ Generates combinations of named coordinate values, mapping them to the internal array. For Example: x, xy, xyz, y, yy, zyx, etc """ def gen_getter_setter_funs(*args): indices = [self.coords[coord] for coord in args] d...
Generates combinations of named coordinate values, mapping them to the internal array. For Example: x, xy, xyz, y, yy, zyx, etc
Below is the the instruction that describes the task: ### Input: Generates combinations of named coordinate values, mapping them to the internal array. For Example: x, xy, xyz, y, yy, zyx, etc ### Response: def _init_coord_properties(self): """ Generates combinations of named coordinate val...
def defgate(self, name, matrix, parameters=None): """ Define a new static gate. .. note:: The matrix elements along each axis are ordered by bitstring. For two qubits the order is ``00, 01, 10, 11``, where the the bits **are ordered in reverse** by the qubit index, ...
Define a new static gate. .. note:: The matrix elements along each axis are ordered by bitstring. For two qubits the order is ``00, 01, 10, 11``, where the the bits **are ordered in reverse** by the qubit index, i.e., for qubits 0 and 1 the bitstring ``01`` indicates that q...
Below is the the instruction that describes the task: ### Input: Define a new static gate. .. note:: The matrix elements along each axis are ordered by bitstring. For two qubits the order is ``00, 01, 10, 11``, where the the bits **are ordered in reverse** by the qubit index, ...
def addSiInfo(self, msrunContainer, specfiles=None, attributes=['obsMz', 'rt', 'charge']): """Transfer attributes to :class:`Sii` elements from the corresponding :class`Si` in :class:`MsrunContainer.sic <MsrunContainer>`. If an attribute is not present in the ``Si`` the attribu...
Transfer attributes to :class:`Sii` elements from the corresponding :class`Si` in :class:`MsrunContainer.sic <MsrunContainer>`. If an attribute is not present in the ``Si`` the attribute value in the ``Sii``is set to ``None``. Attribute examples: 'obsMz', 'rt', 'charge', 'tic', 'iit', '...
Below is the the instruction that describes the task: ### Input: Transfer attributes to :class:`Sii` elements from the corresponding :class`Si` in :class:`MsrunContainer.sic <MsrunContainer>`. If an attribute is not present in the ``Si`` the attribute value in the ``Sii``is set to ``None``. ...
def fetch(self, ui_version=values.unset): """ Fetch a ConfigurationInstance :param unicode ui_version: Pinned UI version :returns: Fetched ConfigurationInstance :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationInstance """ return self._proxy.fetch(ui_v...
Fetch a ConfigurationInstance :param unicode ui_version: Pinned UI version :returns: Fetched ConfigurationInstance :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationInstance
Below is the the instruction that describes the task: ### Input: Fetch a ConfigurationInstance :param unicode ui_version: Pinned UI version :returns: Fetched ConfigurationInstance :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationInstance ### Response: def fetch(self, ui_version=...
def __diff_set(self, level): """Difference of sets""" t1_hashtable = self.__create_hashtable(level.t1, level) t2_hashtable = self.__create_hashtable(level.t2, level) t1_hashes = set(t1_hashtable.keys()) t2_hashes = set(t2_hashtable.keys()) hashes_added = t2_hashes - t1_...
Difference of sets
Below is the the instruction that describes the task: ### Input: Difference of sets ### Response: def __diff_set(self, level): """Difference of sets""" t1_hashtable = self.__create_hashtable(level.t1, level) t2_hashtable = self.__create_hashtable(level.t2, level) t1_hashes = set(t1...
def join(self): """Wait for transfer to exit, raising errors as necessary.""" self.closed = True while self.expect > 0: val = self.wait_change.get() self.expect -= 1 if val is not None: # Wait a while for all running greenlets to exit, and ...
Wait for transfer to exit, raising errors as necessary.
Below is the the instruction that describes the task: ### Input: Wait for transfer to exit, raising errors as necessary. ### Response: def join(self): """Wait for transfer to exit, raising errors as necessary.""" self.closed = True while self.expect > 0: val = self.wait_change....
def cena_tau(imt, mag, params): """ Returns the inter-event standard deviation, tau, for the CENA case """ if imt.name == "PGV": C = params["PGV"] else: C = params["SA"] if mag > 6.5: return C["tau3"] elif (mag > 5.5) and (mag <= 6.5): return ITPL(mag, C["tau3...
Returns the inter-event standard deviation, tau, for the CENA case
Below is the the instruction that describes the task: ### Input: Returns the inter-event standard deviation, tau, for the CENA case ### Response: def cena_tau(imt, mag, params): """ Returns the inter-event standard deviation, tau, for the CENA case """ if imt.name == "PGV": C = params["PGV"...
def _parse_access_token(self, resp_text): ' parse access token from urlencoded str like access_token=abcxyz&expires_in=123000&other=true ' r = self._qs2dict(resp_text) access_token = r.pop('access_token') expires = time.time() + float(r.pop('expires_in')) return JsonDict(access_t...
parse access token from urlencoded str like access_token=abcxyz&expires_in=123000&other=true
Below is the the instruction that describes the task: ### Input: parse access token from urlencoded str like access_token=abcxyz&expires_in=123000&other=true ### Response: def _parse_access_token(self, resp_text): ' parse access token from urlencoded str like access_token=abcxyz&expires_in=123000&other=tru...
def deserialize_transaction(tx_hex): """ Given a serialized transaction, return its inputs, outputs, locktime, and version Each input will have: * transaction_hash: string * output_index: int * [optional] sequence: int * [optional] script_sig: string ...
Given a serialized transaction, return its inputs, outputs, locktime, and version Each input will have: * transaction_hash: string * output_index: int * [optional] sequence: int * [optional] script_sig: string Each output will have: * value: int ...
Below is the the instruction that describes the task: ### Input: Given a serialized transaction, return its inputs, outputs, locktime, and version Each input will have: * transaction_hash: string * output_index: int * [optional] sequence: int * [optional] script_sig:...
def load(cls, sc, path): """ Load a model from the given path. """ jmodel = sc._jvm.org.apache.spark.mllib.feature \ .Word2VecModel.load(sc._jsc.sc(), path) model = sc._jvm.org.apache.spark.mllib.api.python.Word2VecModelWrapper(jmodel) return Word2VecModel(mod...
Load a model from the given path.
Below is the the instruction that describes the task: ### Input: Load a model from the given path. ### Response: def load(cls, sc, path): """ Load a model from the given path. """ jmodel = sc._jvm.org.apache.spark.mllib.feature \ .Word2VecModel.load(sc._jsc.sc(), path) ...
def path_distance(points): """ Compute the path distance from given set of points """ vecs = np.diff(points, axis=0)[:, :3] d2 = [np.dot(p, p) for p in vecs] return np.sum(np.sqrt(d2))
Compute the path distance from given set of points
Below is the the instruction that describes the task: ### Input: Compute the path distance from given set of points ### Response: def path_distance(points): """ Compute the path distance from given set of points """ vecs = np.diff(points, axis=0)[:, :3] d2 = [np.dot(p, p) for p in vecs] ret...
def load_data(self, pdbid): """Loads and parses an XML resource and saves it as a tree if successful""" f = urlopen("http://projects.biotec.tu-dresden.de/plip-rest/pdb/%s?format=xml" % pdbid.lower()) self.doc = etree.parse(f)
Loads and parses an XML resource and saves it as a tree if successful
Below is the the instruction that describes the task: ### Input: Loads and parses an XML resource and saves it as a tree if successful ### Response: def load_data(self, pdbid): """Loads and parses an XML resource and saves it as a tree if successful""" f = urlopen("http://projects.biotec.tu-dresden...
def sample_truncated_gaussian_vector(data, uncertainties, bounds=None): ''' Samples a Gaussian distribution subject to boundaries on the data :param numpy.ndarray data: Vector of N data values :param numpy.ndarray uncertainties: Vector of N data uncertainties :param int number_boots...
Samples a Gaussian distribution subject to boundaries on the data :param numpy.ndarray data: Vector of N data values :param numpy.ndarray uncertainties: Vector of N data uncertainties :param int number_bootstraps: Number of bootstrap samples :param tuple bounds: (Lower, ...
Below is the the instruction that describes the task: ### Input: Samples a Gaussian distribution subject to boundaries on the data :param numpy.ndarray data: Vector of N data values :param numpy.ndarray uncertainties: Vector of N data uncertainties :param int number_bootstraps: ...
def get_effective_member_count(self, group_id): """ Returns a count of effective members for the group identified by the passed group ID. """ self._valid_group_id(group_id) url = "{}/group/{}/effective_member?view=count".format(self.API, ...
Returns a count of effective members for the group identified by the passed group ID.
Below is the the instruction that describes the task: ### Input: Returns a count of effective members for the group identified by the passed group ID. ### Response: def get_effective_member_count(self, group_id): """ Returns a count of effective members for the group identified by the ...
def save(self, data): """Save the config data Args: data: any serializable config data Raises: ConfigLoaderException: if the ConfigLoader.load not called, so there is no config file name, or the data is not serializable or the loader i...
Save the config data Args: data: any serializable config data Raises: ConfigLoaderException: if the ConfigLoader.load not called, so there is no config file name, or the data is not serializable or the loader is nested
Below is the the instruction that describes the task: ### Input: Save the config data Args: data: any serializable config data Raises: ConfigLoaderException: if the ConfigLoader.load not called, so there is no config file name, or the data...
def as_view(url=None, methods=None, view_class=ActionsView, name=None, url_rules=None, **kwargs): """Decorator to transform a function into a view class. Be warned that this will replace the function with the view class. """ def decorator(f): if url is not None: f = expose(url, metho...
Decorator to transform a function into a view class. Be warned that this will replace the function with the view class.
Below is the the instruction that describes the task: ### Input: Decorator to transform a function into a view class. Be warned that this will replace the function with the view class. ### Response: def as_view(url=None, methods=None, view_class=ActionsView, name=None, url_rules=None, **kwargs): """Decorat...
def group_by(self, *args): """ This method lets you specify the grouping fields explicitly. The `args` must be names of grouping fields or calculated fields that this queryset was created with. """ for name in args: assert name in self._fields or name in self....
This method lets you specify the grouping fields explicitly. The `args` must be names of grouping fields or calculated fields that this queryset was created with.
Below is the the instruction that describes the task: ### Input: This method lets you specify the grouping fields explicitly. The `args` must be names of grouping fields or calculated fields that this queryset was created with. ### Response: def group_by(self, *args): """ This metho...
def _get_team_abbreviation(self, team): """ Retrieve team's abbreviation. The team's abbreviation is embedded within the 'school_name' tag and requires special parsing as it is located in the middle of a URI. The abbreviation is returned for the requested school. Parame...
Retrieve team's abbreviation. The team's abbreviation is embedded within the 'school_name' tag and requires special parsing as it is located in the middle of a URI. The abbreviation is returned for the requested school. Parameters ---------- team : PyQuery object ...
Below is the the instruction that describes the task: ### Input: Retrieve team's abbreviation. The team's abbreviation is embedded within the 'school_name' tag and requires special parsing as it is located in the middle of a URI. The abbreviation is returned for the requested school. ...
def to_xml(self): ''' Returns a DOM representation of the deliveries method @returns: Element ''' for n, v in { "method": self.method, "status": self.status, "date":self.date}.items(): if is_empty_or_none(v): raise DeliveryMethodEr...
Returns a DOM representation of the deliveries method @returns: Element
Below is the the instruction that describes the task: ### Input: Returns a DOM representation of the deliveries method @returns: Element ### Response: def to_xml(self): ''' Returns a DOM representation of the deliveries method @returns: Element ''' for n, v in { "met...
def matrix_representation(op): """Return a matrix representation of a linear operator. Parameters ---------- op : `Operator` The linear operator of which one wants a matrix representation. If the domain or range is a `ProductSpace`, it must be a power-space. Returns ------- ...
Return a matrix representation of a linear operator. Parameters ---------- op : `Operator` The linear operator of which one wants a matrix representation. If the domain or range is a `ProductSpace`, it must be a power-space. Returns ------- matrix : `numpy.ndarray` The ...
Below is the the instruction that describes the task: ### Input: Return a matrix representation of a linear operator. Parameters ---------- op : `Operator` The linear operator of which one wants a matrix representation. If the domain or range is a `ProductSpace`, it must be a power-spac...
def toposort_flatten(data, sort=True): """Returns a single list of dependencies. For any set returned by toposort(), those items are sorted and appended to the result (just to make the results deterministic).""" result = [] for d in toposort(data): try: result.extend((sorted if sort els...
Returns a single list of dependencies. For any set returned by toposort(), those items are sorted and appended to the result (just to make the results deterministic).
Below is the the instruction that describes the task: ### Input: Returns a single list of dependencies. For any set returned by toposort(), those items are sorted and appended to the result (just to make the results deterministic). ### Response: def toposort_flatten(data, sort=True): """Returns a single list o...
def perceptual_weighting(S, frequencies, **kwargs): '''Perceptual weighting of a power spectrogram: `S_p[f] = A_weighting(f) + 10*log(S[f] / ref)` Parameters ---------- S : np.ndarray [shape=(d, t)] Power spectrogram frequencies : np.ndarray [shape=(d,)] Center frequency for e...
Perceptual weighting of a power spectrogram: `S_p[f] = A_weighting(f) + 10*log(S[f] / ref)` Parameters ---------- S : np.ndarray [shape=(d, t)] Power spectrogram frequencies : np.ndarray [shape=(d,)] Center frequency for each row of `S` kwargs : additional keyword arguments ...
Below is the the instruction that describes the task: ### Input: Perceptual weighting of a power spectrogram: `S_p[f] = A_weighting(f) + 10*log(S[f] / ref)` Parameters ---------- S : np.ndarray [shape=(d, t)] Power spectrogram frequencies : np.ndarray [shape=(d,)] Center frequ...
def replace_blocks(self, blocks): """Replace multiple blocks. blocks must be a list of tuples where each tuple consists of (namespace, offset, key, data)""" start = 0 bulk_insert = self.bulk_insert blocks_len = len(blocks) row = '(%s,%s,%s,%s,%s)' query = 'REPLACE...
Replace multiple blocks. blocks must be a list of tuples where each tuple consists of (namespace, offset, key, data)
Below is the the instruction that describes the task: ### Input: Replace multiple blocks. blocks must be a list of tuples where each tuple consists of (namespace, offset, key, data) ### Response: def replace_blocks(self, blocks): """Replace multiple blocks. blocks must be a list of tuples where ...
def get_appliance_stats_by_location(self, location_id, start, end, granularity=None, per_page=None, page=None, min_power=None): """Get appliance usage data for a given location within a given time range. Stats are generated by fetching appliance events that match the suppli...
Get appliance usage data for a given location within a given time range. Stats are generated by fetching appliance events that match the supplied criteria and then aggregating them together based on the granularity specified with the request. Note: This endpoint uses the location's time zone when...
Below is the the instruction that describes the task: ### Input: Get appliance usage data for a given location within a given time range. Stats are generated by fetching appliance events that match the supplied criteria and then aggregating them together based on the granularity specified with the reque...
def fht(zsrc, zrec, lsrc, lrec, off, factAng, depth, ab, etaH, etaV, zetaH, zetaV, xdirect, fhtarg, use_ne_eval, msrc, mrec): r"""Hankel Transform using the Digital Linear Filter method. The *Digital Linear Filter* method was introduced to geophysics by [Ghos70]_, and made popular and wide-spread b...
r"""Hankel Transform using the Digital Linear Filter method. The *Digital Linear Filter* method was introduced to geophysics by [Ghos70]_, and made popular and wide-spread by [Ande75]_, [Ande79]_, [Ande82]_. The DLF is sometimes referred to as the *Fast Hankel Transform* FHT, from which this routine ha...
Below is the the instruction that describes the task: ### Input: r"""Hankel Transform using the Digital Linear Filter method. The *Digital Linear Filter* method was introduced to geophysics by [Ghos70]_, and made popular and wide-spread by [Ande75]_, [Ande79]_, [Ande82]_. The DLF is sometimes referred ...
def _readline(self): """Read exactly one line from the device, nonblocking. Returns: None on no data """ if len(self.lines) > 1: return self.lines.pop(0) tail = '' if len(self.lines): tail = self.lines.pop() try: ...
Read exactly one line from the device, nonblocking. Returns: None on no data
Below is the the instruction that describes the task: ### Input: Read exactly one line from the device, nonblocking. Returns: None on no data ### Response: def _readline(self): """Read exactly one line from the device, nonblocking. Returns: None on no data ...
def load_json_object(file_name, default=None): """ Deserialized <file_name> into a Python object :param str|unicode file_name: The name of the file to read :param default: The value to return if the file is not found """ if not os.path.isfile(file_name): return default # use utf-8-s...
Deserialized <file_name> into a Python object :param str|unicode file_name: The name of the file to read :param default: The value to return if the file is not found
Below is the the instruction that describes the task: ### Input: Deserialized <file_name> into a Python object :param str|unicode file_name: The name of the file to read :param default: The value to return if the file is not found ### Response: def load_json_object(file_name, default=None): """ Des...
def decode_chain_list(in_bytes): """Convert a list of bytes to a list of strings. Each string is of length mmtf.CHAIN_LEN :param in_bytes: the input bytes :return the decoded list of strings""" bstrings = numpy.frombuffer(in_bytes, numpy.dtype('S' + str(mmtf.utils.constants.CHAIN_LEN))) return [s.d...
Convert a list of bytes to a list of strings. Each string is of length mmtf.CHAIN_LEN :param in_bytes: the input bytes :return the decoded list of strings
Below is the the instruction that describes the task: ### Input: Convert a list of bytes to a list of strings. Each string is of length mmtf.CHAIN_LEN :param in_bytes: the input bytes :return the decoded list of strings ### Response: def decode_chain_list(in_bytes): """Convert a list of bytes to a lis...
def update_aliases(self): """Get aliases information from room state. Returns: boolean: True if the aliases changed, False if not """ try: response = self.client.api.get_room_state(self.room_id) for chunk in response: if "content" in c...
Get aliases information from room state. Returns: boolean: True if the aliases changed, False if not
Below is the the instruction that describes the task: ### Input: Get aliases information from room state. Returns: boolean: True if the aliases changed, False if not ### Response: def update_aliases(self): """Get aliases information from room state. Returns: boolea...
def insert(self, table_name, record, attr_names=None): """ Send an INSERT query to the database. :param str table_name: Table name of executing the query. :param record: Record to be inserted. :type record: |dict|/|namedtuple|/|list|/|tuple| :raises IOError: |raises_writ...
Send an INSERT query to the database. :param str table_name: Table name of executing the query. :param record: Record to be inserted. :type record: |dict|/|namedtuple|/|list|/|tuple| :raises IOError: |raises_write_permission| :raises simplesqlite.NullDatabaseConnectionError: ...
Below is the the instruction that describes the task: ### Input: Send an INSERT query to the database. :param str table_name: Table name of executing the query. :param record: Record to be inserted. :type record: |dict|/|namedtuple|/|list|/|tuple| :raises IOError: |raises_write_perm...
def find(self, text, magicKey=None, sourceCountry=None, bbox=None, location=None, distance=3218.69, outSR=102100, category=None, outFields="*", maxLocations=20, forStorage=False...
The find operation geocodes one location per request; the input address is specified in a single parameter. Inputs: text - Specifies the location to be geocoded. This can be a street address, place name, postal code, or POI. magicKey - The find operation retrieves resu...
Below is the the instruction that describes the task: ### Input: The find operation geocodes one location per request; the input address is specified in a single parameter. Inputs: text - Specifies the location to be geocoded. This can be a street address, place name, postal ...
def savepoint(cr): """return a context manager wrapping postgres savepoints""" if hasattr(cr, 'savepoint'): with cr.savepoint(): yield else: name = uuid.uuid1().hex cr.execute('SAVEPOINT "%s"' % name) try: yield cr.execute('RELEASE SAVEPOIN...
return a context manager wrapping postgres savepoints
Below is the the instruction that describes the task: ### Input: return a context manager wrapping postgres savepoints ### Response: def savepoint(cr): """return a context manager wrapping postgres savepoints""" if hasattr(cr, 'savepoint'): with cr.savepoint(): yield else: n...
def list_processed_parameter_group_histogram(self, group=None, start=None, stop=None, merge_time=20): """ Reads index records related to processed parameter groups between the specified start and stop time. Each iteration returns a chunk of chronologically-sorted records. :para...
Reads index records related to processed parameter groups between the specified start and stop time. Each iteration returns a chunk of chronologically-sorted records. :param float merge_time: Maximum gap in seconds before two consecutive index records are merged together. :rtype: ~coll...
Below is the the instruction that describes the task: ### Input: Reads index records related to processed parameter groups between the specified start and stop time. Each iteration returns a chunk of chronologically-sorted records. :param float merge_time: Maximum gap in seconds before two...
def hook_fn(self, module:nn.Module, input:Tensors, output:Tensors): "Applies `hook_func` to `module`, `input`, `output`." if self.detach: input = (o.detach() for o in input ) if is_listy(input ) else input.detach() output = (o.detach() for o in output) if is_listy(output) else o...
Applies `hook_func` to `module`, `input`, `output`.
Below is the the instruction that describes the task: ### Input: Applies `hook_func` to `module`, `input`, `output`. ### Response: def hook_fn(self, module:nn.Module, input:Tensors, output:Tensors): "Applies `hook_func` to `module`, `input`, `output`." if self.detach: input = (o.detach...
def is_maximal_matching(G, matching): """Determines whether the given set of edges is a maximal matching. A matching is a subset of edges in which no node occurs more than once. The cardinality of a matching is the number of matched edges. A maximal matching is one where one cannot add any more edges ...
Determines whether the given set of edges is a maximal matching. A matching is a subset of edges in which no node occurs more than once. The cardinality of a matching is the number of matched edges. A maximal matching is one where one cannot add any more edges without violating the matching rule. ...
Below is the the instruction that describes the task: ### Input: Determines whether the given set of edges is a maximal matching. A matching is a subset of edges in which no node occurs more than once. The cardinality of a matching is the number of matched edges. A maximal matching is one where one can...
def _set_implicit_commit(self, v, load=False): """ Setter method for implicit_commit, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/policy/implicit_commit (container) If this variable is read-only (config: false) in the source YANG file, then _set_implicit_commit is considered as a...
Setter method for implicit_commit, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/policy/implicit_commit (container) If this variable is read-only (config: false) in the source YANG file, then _set_implicit_commit is considered as a private method. Backends looking to populate this vari...
Below is the the instruction that describes the task: ### Input: Setter method for implicit_commit, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/policy/implicit_commit (container) If this variable is read-only (config: false) in the source YANG file, then _set_implicit_commit is consi...
def stitch_images(images, margin=5, cols=5): """Utility function to stitch images together with a `margin`. Args: images: The array of 2D images to stitch. margin: The black border margin size between images (Default value = 5) cols: Max number of image cols. New row is created when num...
Utility function to stitch images together with a `margin`. Args: images: The array of 2D images to stitch. margin: The black border margin size between images (Default value = 5) cols: Max number of image cols. New row is created when number of images exceed the column size. (D...
Below is the the instruction that describes the task: ### Input: Utility function to stitch images together with a `margin`. Args: images: The array of 2D images to stitch. margin: The black border margin size between images (Default value = 5) cols: Max number of image cols. New row is...
def link(self, other): """ Link (associate) this object with anI{other} properties object to create a network of properties. Links are bidirectional. @param other: The object to link. @type other: L{Properties} @return: self @rtype: L{Properties} """ ...
Link (associate) this object with anI{other} properties object to create a network of properties. Links are bidirectional. @param other: The object to link. @type other: L{Properties} @return: self @rtype: L{Properties}
Below is the the instruction that describes the task: ### Input: Link (associate) this object with anI{other} properties object to create a network of properties. Links are bidirectional. @param other: The object to link. @type other: L{Properties} @return: self @rtype: L{Pr...
def _lookup_vpc_count_min_max(session=None, **bfilter): """Look up count/min/max Nexus VPC Allocs for given switch. :param session: db session :param bfilter: filter for mappings query :returns: number of VPCs and min value if query gave a result, else raise NexusVPCAllocNotFound. """ ...
Look up count/min/max Nexus VPC Allocs for given switch. :param session: db session :param bfilter: filter for mappings query :returns: number of VPCs and min value if query gave a result, else raise NexusVPCAllocNotFound.
Below is the the instruction that describes the task: ### Input: Look up count/min/max Nexus VPC Allocs for given switch. :param session: db session :param bfilter: filter for mappings query :returns: number of VPCs and min value if query gave a result, else raise NexusVPCAllocNotFound. ##...
def get_authorization_lookup_session(self): """Gets the ``OsidSession`` associated with the authorization lookup service. return: (osid.authorization.AuthorizationLookupSession) - an ``AuthorizationLookupSession`` raise: OperationFailed - unable to complete request rais...
Gets the ``OsidSession`` associated with the authorization lookup service. return: (osid.authorization.AuthorizationLookupSession) - an ``AuthorizationLookupSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_authorization_lookup()``...
Below is the the instruction that describes the task: ### Input: Gets the ``OsidSession`` associated with the authorization lookup service. return: (osid.authorization.AuthorizationLookupSession) - an ``AuthorizationLookupSession`` raise: OperationFailed - unable to complete reques...
async def wait_for_all_empty(self, *queues): """ Wait for multiple queues to be empty at the same time. Require delegate when calling from coroutines running in other containers """ matchers = [m for m in (q.waitForEmpty() for q in queues) if m is not None] while matcher...
Wait for multiple queues to be empty at the same time. Require delegate when calling from coroutines running in other containers
Below is the the instruction that describes the task: ### Input: Wait for multiple queues to be empty at the same time. Require delegate when calling from coroutines running in other containers ### Response: async def wait_for_all_empty(self, *queues): """ Wait for multiple queues to be em...
def until_state(self, state, timeout=None): """Future that resolves when a certain client state is attained Parameters ---------- state : str Desired state, one of ("disconnected", "syncing", "synced") timeout: float Timeout for operation in seconds. ...
Future that resolves when a certain client state is attained Parameters ---------- state : str Desired state, one of ("disconnected", "syncing", "synced") timeout: float Timeout for operation in seconds.
Below is the the instruction that describes the task: ### Input: Future that resolves when a certain client state is attained Parameters ---------- state : str Desired state, one of ("disconnected", "syncing", "synced") timeout: float Timeout for operation i...
def chunker(l, n): """ Generates n-sized chunks from the list l """ for i in ranger(0, len(l), n): yield l[i:i + n]
Generates n-sized chunks from the list l
Below is the the instruction that describes the task: ### Input: Generates n-sized chunks from the list l ### Response: def chunker(l, n): """ Generates n-sized chunks from the list l """ for i in ranger(0, len(l), n): yield l[i:i + n]
def base_warfare(name, bases, attributes): """ Adds any number of attributes to an existing class. :param name: Name. :type name: unicode :param bases: Bases. :type bases: list :param attributes: Attributes. :type attributes: dict :return: Base. :rtype: object """ asser...
Adds any number of attributes to an existing class. :param name: Name. :type name: unicode :param bases: Bases. :type bases: list :param attributes: Attributes. :type attributes: dict :return: Base. :rtype: object
Below is the the instruction that describes the task: ### Input: Adds any number of attributes to an existing class. :param name: Name. :type name: unicode :param bases: Bases. :type bases: list :param attributes: Attributes. :type attributes: dict :return: Base. :rtype: object ### ...
def show_weights(self, **kwargs): """ Call :func:`eli5.show_weights` for the locally-fit classification pipeline. Keyword arguments are passed to :func:`eli5.show_weights`. :func:`fit` must be called before using this method. """ self._fix_target_names(kwargs) ...
Call :func:`eli5.show_weights` for the locally-fit classification pipeline. Keyword arguments are passed to :func:`eli5.show_weights`. :func:`fit` must be called before using this method.
Below is the the instruction that describes the task: ### Input: Call :func:`eli5.show_weights` for the locally-fit classification pipeline. Keyword arguments are passed to :func:`eli5.show_weights`. :func:`fit` must be called before using this method. ### Response: def show_weights(self, ...
def build_single_handler_applications(paths, argvs=None): ''' Return a dictionary mapping routes to Bokeh applications built using single handlers, for specified files or directories. This function iterates over ``paths`` and ``argvs`` and calls :func:`~bokeh.command.util.build_single_handler_applicati...
Return a dictionary mapping routes to Bokeh applications built using single handlers, for specified files or directories. This function iterates over ``paths`` and ``argvs`` and calls :func:`~bokeh.command.util.build_single_handler_application` on each to generate the mapping. Args: path (...
Below is the the instruction that describes the task: ### Input: Return a dictionary mapping routes to Bokeh applications built using single handlers, for specified files or directories. This function iterates over ``paths`` and ``argvs`` and calls :func:`~bokeh.command.util.build_single_handler_applic...
def parse(self, string): '''Parse some string to the Grammar. Returns a nodeResult with the following attributes: - is_valid: True when the string is successfully parsed by the Grammar. - pos: position in the string where parsing ended. (this is th...
Parse some string to the Grammar. Returns a nodeResult with the following attributes: - is_valid: True when the string is successfully parsed by the Grammar. - pos: position in the string where parsing ended. (this is the end of the string when is_valid is...
Below is the the instruction that describes the task: ### Input: Parse some string to the Grammar. Returns a nodeResult with the following attributes: - is_valid: True when the string is successfully parsed by the Grammar. - pos: position in the string where parsing e...
def set_t(self, value): ''' setter Time. ''' if isinstance(value, int) is False: raise TypeError("The type of __t must be int.") self.__t = value
setter Time.
Below is the the instruction that describes the task: ### Input: setter Time. ### Response: def set_t(self, value): ''' setter Time. ''' if isinstance(value, int) is False: raise TypeError("The type of __t must be int.") self.__t = value
def _conf_packages(args): """Runs custom configuration steps for the packages that ship with support in acorn. """ from acorn.config import config_dir from os import path from acorn.base import testmode target = config_dir(True) alternate = path.join(path.abspath(path.expanduser("~")), "...
Runs custom configuration steps for the packages that ship with support in acorn.
Below is the the instruction that describes the task: ### Input: Runs custom configuration steps for the packages that ship with support in acorn. ### Response: def _conf_packages(args): """Runs custom configuration steps for the packages that ship with support in acorn. """ from acorn.config i...
def str_wrap(arr, width, **kwargs): r""" Wrap long strings in the Series/Index to be formatted in paragraphs with length less than a given width. This method has the same keyword parameters and defaults as :class:`textwrap.TextWrapper`. Parameters ---------- width : int Maximum...
r""" Wrap long strings in the Series/Index to be formatted in paragraphs with length less than a given width. This method has the same keyword parameters and defaults as :class:`textwrap.TextWrapper`. Parameters ---------- width : int Maximum line width. expand_tabs : bool, opt...
Below is the the instruction that describes the task: ### Input: r""" Wrap long strings in the Series/Index to be formatted in paragraphs with length less than a given width. This method has the same keyword parameters and defaults as :class:`textwrap.TextWrapper`. Parameters ---------- ...
def scramble_native_password(password, message): """Scramble used for mysql_native_password""" if not password: return b'' stage1 = sha1_new(password).digest() stage2 = sha1_new(stage1).digest() s = sha1_new() s.update(message[:SCRAMBLE_LENGTH]) s.update(stage2) result = s.diges...
Scramble used for mysql_native_password
Below is the the instruction that describes the task: ### Input: Scramble used for mysql_native_password ### Response: def scramble_native_password(password, message): """Scramble used for mysql_native_password""" if not password: return b'' stage1 = sha1_new(password).digest() stage2 = sh...
def _verify_same_spaces(self): """Verifies that all the envs have the same observation and action space.""" # Pre-conditions: self._envs is initialized. if self._envs is None: raise ValueError("Environments not initialized.") if not isinstance(self._envs, list): tf.logging.warning("Not ch...
Verifies that all the envs have the same observation and action space.
Below is the the instruction that describes the task: ### Input: Verifies that all the envs have the same observation and action space. ### Response: def _verify_same_spaces(self): """Verifies that all the envs have the same observation and action space.""" # Pre-conditions: self._envs is initialized. ...
def node_hist_fig( node_color_distribution, title="Graph Node Distribution", width=400, height=300, top=60, left=25, bottom=60, right=25, bgcolor="rgb(240,240,240)", y_gridcolor="white", ): """Define the plotly plot representing the node histogram Param...
Define the plotly plot representing the node histogram Parameters ---------- node_color_distribution: list of dicts describing the build_histogram width, height: integers - width and height of the histogram FigureWidget left, top, right, bottom: ints; number of pixels around the FigureWi...
Below is the the instruction that describes the task: ### Input: Define the plotly plot representing the node histogram Parameters ---------- node_color_distribution: list of dicts describing the build_histogram width, height: integers - width and height of the histogram FigureWidget ...
def targetOffset(self, dx, dy): """ Returns a new Pattern with the given target offset """ pattern = Pattern(self.path) pattern.similarity = self.similarity pattern.offset = Location(dx, dy) return pattern
Returns a new Pattern with the given target offset
Below is the the instruction that describes the task: ### Input: Returns a new Pattern with the given target offset ### Response: def targetOffset(self, dx, dy): """ Returns a new Pattern with the given target offset """ pattern = Pattern(self.path) pattern.similarity = self.similarity ...
def paragraph(separator='\n\n', wrap_start='', wrap_end='', html=False, sentences_quantity=3): """Return a random paragraph.""" return paragraphs(quantity=1, separator=separator, wrap_start=wrap_start, wrap_end=wrap_end, html=html, sentences_quantity=sen...
Return a random paragraph.
Below is the the instruction that describes the task: ### Input: Return a random paragraph. ### Response: def paragraph(separator='\n\n', wrap_start='', wrap_end='', html=False, sentences_quantity=3): """Return a random paragraph.""" return paragraphs(quantity=1, separator=separator, wrap_sta...
def OnPasteFormat(self, event): """Paste format event handler""" with undo.group(_("Paste format")): self.grid.actions.paste_format() self.grid.ForceRefresh() self.grid.update_attribute_toolbar() self.grid.actions.zoom()
Paste format event handler
Below is the the instruction that describes the task: ### Input: Paste format event handler ### Response: def OnPasteFormat(self, event): """Paste format event handler""" with undo.group(_("Paste format")): self.grid.actions.paste_format() self.grid.ForceRefresh() self...
def switch(poi): """ Zaps into a specific product specified by switch context to the product of interest(poi) A poi is: sdox:dev - for product "dev" located in container "sdox" If poi does not contain a ":" it is interpreted as product name implying that a product within this container is a...
Zaps into a specific product specified by switch context to the product of interest(poi) A poi is: sdox:dev - for product "dev" located in container "sdox" If poi does not contain a ":" it is interpreted as product name implying that a product within this container is already active. So if this tas...
Below is the the instruction that describes the task: ### Input: Zaps into a specific product specified by switch context to the product of interest(poi) A poi is: sdox:dev - for product "dev" located in container "sdox" If poi does not contain a ":" it is interpreted as product name implying that ...
def join_tokens_to_sentences(tokens): """ Correctly joins tokens to multiple sentences Instead of always placing white-space between the tokens, it will distinguish between the next symbol and *not* insert whitespace if it is a sentence symbol (e.g. '.', or '?') Args: tokens: array of stri...
Correctly joins tokens to multiple sentences Instead of always placing white-space between the tokens, it will distinguish between the next symbol and *not* insert whitespace if it is a sentence symbol (e.g. '.', or '?') Args: tokens: array of string tokens Returns: Joint sentences...
Below is the the instruction that describes the task: ### Input: Correctly joins tokens to multiple sentences Instead of always placing white-space between the tokens, it will distinguish between the next symbol and *not* insert whitespace if it is a sentence symbol (e.g. '.', or '?') Args: ...
def fit1d(samples, e, remove_zeros = False, **kw): """Fits a 1D distribution with splines. Input: samples: Array Array of samples from a probability distribution e: Array Edges that define the events in the probability distribution. For example, e[0] < x <= ...
Fits a 1D distribution with splines. Input: samples: Array Array of samples from a probability distribution e: Array Edges that define the events in the probability distribution. For example, e[0] < x <= e[1] is the range of values that are associate...
Below is the the instruction that describes the task: ### Input: Fits a 1D distribution with splines. Input: samples: Array Array of samples from a probability distribution e: Array Edges that define the events in the probability distribution. For example, e...
def get_mongo_version(self): """ Gets mongo version of the server if it is running. Otherwise return version configured in mongoVersion property """ if self._mongo_version: return self._mongo_version mongo_version = self.read_current_mongo_version() ...
Gets mongo version of the server if it is running. Otherwise return version configured in mongoVersion property
Below is the the instruction that describes the task: ### Input: Gets mongo version of the server if it is running. Otherwise return version configured in mongoVersion property ### Response: def get_mongo_version(self): """ Gets mongo version of the server if it is running. Otherwise retur...
def exclude_types(self, *objs): '''Exclude the specified object instances and types from sizing. All instances and types of the given objects are excluded, even objects specified as positional arguments in subsequent calls to methods **asizeof** and **asizesof**. ''' ...
Exclude the specified object instances and types from sizing. All instances and types of the given objects are excluded, even objects specified as positional arguments in subsequent calls to methods **asizeof** and **asizesof**.
Below is the the instruction that describes the task: ### Input: Exclude the specified object instances and types from sizing. All instances and types of the given objects are excluded, even objects specified as positional arguments in subsequent calls to methods **asizeof** and **...
def _affine_inv_mult(c, m): "Applies the inverse affine transform described in `m` to `c`." size = c.flow.size() h,w = c.size m[0,1] *= h/w m[1,0] *= w/h c.flow = c.flow.view(-1,2) a = torch.inverse(m[:2,:2].t()) c.flow = torch.mm(c.flow - m[:2,2], a).view(size) return c
Applies the inverse affine transform described in `m` to `c`.
Below is the the instruction that describes the task: ### Input: Applies the inverse affine transform described in `m` to `c`. ### Response: def _affine_inv_mult(c, m): "Applies the inverse affine transform described in `m` to `c`." size = c.flow.size() h,w = c.size m[0,1] *= h/w m[1,0] *= w/h ...
def _process_coref_span_annotations_for_word(label: str, word_index: int, clusters: DefaultDict[int, List[Tuple[int, int]]], coref_stacks: DefaultDict[int, List[int]]) -> No...
For a given coref label, add it to a currently open span(s), complete a span(s) or ignore it, if it is outside of all spans. This method mutates the clusters and coref_stacks dictionaries. Parameters ---------- label : ``str`` The coref label for this word. w...
Below is the the instruction that describes the task: ### Input: For a given coref label, add it to a currently open span(s), complete a span(s) or ignore it, if it is outside of all spans. This method mutates the clusters and coref_stacks dictionaries. Parameters ---------- ...
def apply_classifier(self, name, samples=None, subset=None): """ Apply a clustering classifier based on all samples, or a subset. Parameters ---------- name : str The name of the classifier to apply. subset : str The subset of samples to apply the...
Apply a clustering classifier based on all samples, or a subset. Parameters ---------- name : str The name of the classifier to apply. subset : str The subset of samples to apply the classifier to. Returns ------- name : str
Below is the the instruction that describes the task: ### Input: Apply a clustering classifier based on all samples, or a subset. Parameters ---------- name : str The name of the classifier to apply. subset : str The subset of samples to apply the classifier ...
def files(self, path="/", **kwargs): # type: (Text, **Any) -> Iterator[Text] """Walk a filesystem, yielding absolute paths to files. Arguments: path (str): A path to a directory. Keyword Arguments: ignore_errors (bool): If `True`, any errors reading a ...
Walk a filesystem, yielding absolute paths to files. Arguments: path (str): A path to a directory. Keyword Arguments: ignore_errors (bool): If `True`, any errors reading a directory will be ignored, otherwise exceptions will be raised. ...
Below is the the instruction that describes the task: ### Input: Walk a filesystem, yielding absolute paths to files. Arguments: path (str): A path to a directory. Keyword Arguments: ignore_errors (bool): If `True`, any errors reading a directory will be ign...
def lower_coerce_type_blocks(ir_blocks): """Lower CoerceType blocks into Filter blocks with a type-check predicate.""" new_ir_blocks = [] for block in ir_blocks: new_block = block if isinstance(block, CoerceType): predicate = BinaryComposition( u'contains', Liter...
Lower CoerceType blocks into Filter blocks with a type-check predicate.
Below is the the instruction that describes the task: ### Input: Lower CoerceType blocks into Filter blocks with a type-check predicate. ### Response: def lower_coerce_type_blocks(ir_blocks): """Lower CoerceType blocks into Filter blocks with a type-check predicate.""" new_ir_blocks = [] for block in ...
def filter_variance(matrix, top): """Filter genes in an expression matrix by variance. Parameters ---------- matrix: ExpMatrix The expression matrix. top: int The number of genes to retain. Returns ------- ExpMatrix The filtered expression matrix. """ as...
Filter genes in an expression matrix by variance. Parameters ---------- matrix: ExpMatrix The expression matrix. top: int The number of genes to retain. Returns ------- ExpMatrix The filtered expression matrix.
Below is the the instruction that describes the task: ### Input: Filter genes in an expression matrix by variance. Parameters ---------- matrix: ExpMatrix The expression matrix. top: int The number of genes to retain. Returns ------- ExpMatrix The filtered expre...
def parse_descedant_elements(self, element): '''parses all descendants of an etree element''' for descendant in element.iterdescendants(): self.parsers[descendant.tag](descendant)
parses all descendants of an etree element
Below is the the instruction that describes the task: ### Input: parses all descendants of an etree element ### Response: def parse_descedant_elements(self, element): '''parses all descendants of an etree element''' for descendant in element.iterdescendants(): self.parsers[descendant.ta...
def iterclass(cls): """Iterates over (valid) attributes of a class. Args: cls (object): the class to iterate over Yields: (str, obj) tuples: the class-level attributes. """ for field in dir(cls): if hasattr(cls, field): value = getattr(cls, field) yi...
Iterates over (valid) attributes of a class. Args: cls (object): the class to iterate over Yields: (str, obj) tuples: the class-level attributes.
Below is the the instruction that describes the task: ### Input: Iterates over (valid) attributes of a class. Args: cls (object): the class to iterate over Yields: (str, obj) tuples: the class-level attributes. ### Response: def iterclass(cls): """Iterates over (valid) attributes of a...
def sigma_filter(filename, region, step_size, box_size, shape, domask, sid): """ Calculate the background and rms for a sub region of an image. The results are written to shared memory - irms and ibkg. Parameters ---------- filename : string Fits file to open region : list ...
Calculate the background and rms for a sub region of an image. The results are written to shared memory - irms and ibkg. Parameters ---------- filename : string Fits file to open region : list Region within the fits file that is to be processed. (row_min, row_max). step_size :...
Below is the the instruction that describes the task: ### Input: Calculate the background and rms for a sub region of an image. The results are written to shared memory - irms and ibkg. Parameters ---------- filename : string Fits file to open region : list Region within the fi...
def get_pane_index(self, pane): " Return the index of the given pane. ValueError if not found. " assert isinstance(pane, Pane) return self.panes.index(pane)
Return the index of the given pane. ValueError if not found.
Below is the the instruction that describes the task: ### Input: Return the index of the given pane. ValueError if not found. ### Response: def get_pane_index(self, pane): " Return the index of the given pane. ValueError if not found. " assert isinstance(pane, Pane) return self.panes.index(...
def forward(self, inputs, states=None): # pylint: disable=arguments-differ """Defines the forward computation. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`.""" batch_size = inputs.shape[self._batch_axis] skip_states = states is None if skip_states: ...
Defines the forward computation. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`.
Below is the the instruction that describes the task: ### Input: Defines the forward computation. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`. ### Response: def forward(self, inputs, states=None): # pylint: disable=arguments-differ """Defines the forward computation. Arguments...
def meta_set(self, key, metafield, value): """ Set the meta field for a key to a new value. """ self._meta.setdefault(key, {})[metafield] = value
Set the meta field for a key to a new value.
Below is the the instruction that describes the task: ### Input: Set the meta field for a key to a new value. ### Response: def meta_set(self, key, metafield, value): """ Set the meta field for a key to a new value. """ self._meta.setdefault(key, {})[metafield] = value
def to_string(self, other): """String representation with addtional information""" arg = "%s/%s,%s" % ( self.ttl, self.get_remaining_ttl(current_time_millis()), other) return DNSEntry.to_string(self, "record", arg)
String representation with addtional information
Below is the the instruction that describes the task: ### Input: String representation with addtional information ### Response: def to_string(self, other): """String representation with addtional information""" arg = "%s/%s,%s" % ( self.ttl, self.get_remaining_ttl(current_time_milli...
def append(self, item: TransItem): """ Append an item to the list. If there is not enough sentences in the list, then the list is extended as needed. There is no control made to make sure that the key is consistent. """ if not (1 <= item.index <= settings.I18N_MAX_SENTE...
Append an item to the list. If there is not enough sentences in the list, then the list is extended as needed. There is no control made to make sure that the key is consistent.
Below is the the instruction that describes the task: ### Input: Append an item to the list. If there is not enough sentences in the list, then the list is extended as needed. There is no control made to make sure that the key is consistent. ### Response: def append(self, item: TransItem): ...
def compose(self, mapping): """Apply the ``compose`` method to all functions. Returns a new farray. """ items = [f.compose(mapping) for f in self._items] return self.__class__(items, self.shape, self.ftype)
Apply the ``compose`` method to all functions. Returns a new farray.
Below is the the instruction that describes the task: ### Input: Apply the ``compose`` method to all functions. Returns a new farray. ### Response: def compose(self, mapping): """Apply the ``compose`` method to all functions. Returns a new farray. """ items = [f.compose(ma...
def metapolicy(self, permitted): """ Sets metapolicy to ``permitted``. (only applicable to master policy files). Acceptable values correspond to those listed in Section 3(b)(i) of the crossdomain.xml specification, and are also available as a set of constants defined in this modu...
Sets metapolicy to ``permitted``. (only applicable to master policy files). Acceptable values correspond to those listed in Section 3(b)(i) of the crossdomain.xml specification, and are also available as a set of constants defined in this module. By default, Flash assumes a value of ``m...
Below is the the instruction that describes the task: ### Input: Sets metapolicy to ``permitted``. (only applicable to master policy files). Acceptable values correspond to those listed in Section 3(b)(i) of the crossdomain.xml specification, and are also available as a set of constants defi...
def log_player_trades_with_port(self, player, to_port, port, to_player): """ :param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.T...
:param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)]
Below is the the instruction that describes the task: ### Input: :param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.Terrain), (int, game.boar...