code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def Morlet (sampr, freq, width=7.0): """ Morlet's wavelet for frequency f and time t Wavelet normalized so total energy is 1 freq: specific frequency (Hz) width: number of cycles for the Morlet wavelet output returned: final units are 1/s """ dt = 1. / sampr sf = freq / width # sf in Hz ...
Morlet's wavelet for frequency f and time t Wavelet normalized so total energy is 1 freq: specific frequency (Hz) width: number of cycles for the Morlet wavelet output returned: final units are 1/s
Below is the the instruction that describes the task: ### Input: Morlet's wavelet for frequency f and time t Wavelet normalized so total energy is 1 freq: specific frequency (Hz) width: number of cycles for the Morlet wavelet output returned: final units are 1/s ### Response: def Morlet (sa...
def update(self, data): """ New data will only contain the changed attributes. """ if not data.get('status', []): return status_data = data['status'][0] media_data = status_data.get('media') or {} volume_data = status_data.get('volume', {}) self.current_time...
New data will only contain the changed attributes.
Below is the the instruction that describes the task: ### Input: New data will only contain the changed attributes. ### Response: def update(self, data): """ New data will only contain the changed attributes. """ if not data.get('status', []): return status_data = data['status'...
def plot (data, pconfig=None): """ Plot a scatter plot with X,Y data. :param data: 2D dict, first keys as sample names, then x:y data pairs :param pconfig: optional dict with config key:value pairs. See CONTRIBUTING.md :return: HTML and JS, ready to be inserted into the page """ if pconfig is No...
Plot a scatter plot with X,Y data. :param data: 2D dict, first keys as sample names, then x:y data pairs :param pconfig: optional dict with config key:value pairs. See CONTRIBUTING.md :return: HTML and JS, ready to be inserted into the page
Below is the the instruction that describes the task: ### Input: Plot a scatter plot with X,Y data. :param data: 2D dict, first keys as sample names, then x:y data pairs :param pconfig: optional dict with config key:value pairs. See CONTRIBUTING.md :return: HTML and JS, ready to be inserted into the pag...
def qasm(self, prec=15): """Return the corresponding OPENQASM string.""" if self.value == pi: return "pi" return ccode(self.value, precision=prec)
Return the corresponding OPENQASM string.
Below is the the instruction that describes the task: ### Input: Return the corresponding OPENQASM string. ### Response: def qasm(self, prec=15): """Return the corresponding OPENQASM string.""" if self.value == pi: return "pi" return ccode(self.value, precision=prec)
def get_item_template(self): '''returns template for signle object from queryset If you have a template name my_list_template.html then template for a single object will be _my_list_template.html Now only for default generates _item.html _item.html is obsolete use _defau...
returns template for signle object from queryset If you have a template name my_list_template.html then template for a single object will be _my_list_template.html Now only for default generates _item.html _item.html is obsolete use _default.html
Below is the the instruction that describes the task: ### Input: returns template for signle object from queryset If you have a template name my_list_template.html then template for a single object will be _my_list_template.html Now only for default generates _item.html _ite...
def from_yaml(cls, yaml_str=None, str_or_buffer=None): """ Create a RegressionModel instance from a saved YAML configuration. Arguments are mutually exclusive. Parameters ---------- yaml_str : str, optional A YAML string from which to load model. str_...
Create a RegressionModel instance from a saved YAML configuration. Arguments are mutually exclusive. Parameters ---------- yaml_str : str, optional A YAML string from which to load model. str_or_buffer : str or file like, optional File name or buffer from...
Below is the the instruction that describes the task: ### Input: Create a RegressionModel instance from a saved YAML configuration. Arguments are mutually exclusive. Parameters ---------- yaml_str : str, optional A YAML string from which to load model. str_or_buf...
def parse_log(log, url_pattern): """Parse ``log`` buffer based on ``url_pattern``. Given a buffer as ``log``, parse the log buffer into a mapping of ident-hashes to a hit count, the timestamp of the initial log, and the last timestamp in the log. """ hits = {} initial_timestamp = None ...
Parse ``log`` buffer based on ``url_pattern``. Given a buffer as ``log``, parse the log buffer into a mapping of ident-hashes to a hit count, the timestamp of the initial log, and the last timestamp in the log.
Below is the the instruction that describes the task: ### Input: Parse ``log`` buffer based on ``url_pattern``. Given a buffer as ``log``, parse the log buffer into a mapping of ident-hashes to a hit count, the timestamp of the initial log, and the last timestamp in the log. ### Response: def pars...
def on_frame(self, frame_in): """Handle frame sent to this specific channel. :param pamqp.Frame frame_in: Amqp frame. :return: """ if self.rpc.on_frame(frame_in): return if frame_in.name in CONTENT_FRAME: self._inbound.append(frame_in) el...
Handle frame sent to this specific channel. :param pamqp.Frame frame_in: Amqp frame. :return:
Below is the the instruction that describes the task: ### Input: Handle frame sent to this specific channel. :param pamqp.Frame frame_in: Amqp frame. :return: ### Response: def on_frame(self, frame_in): """Handle frame sent to this specific channel. :param pamqp.Frame frame_in: Am...
def build_includes(cls, include_packages): """ cx_freeze doesn't support the star (*) method of sub-module inclusion, so all submodules must be included explicitly. Example (From SaltStack 2014.7): salt salt.fileserver salt.fileserver.gitfs ...
cx_freeze doesn't support the star (*) method of sub-module inclusion, so all submodules must be included explicitly. Example (From SaltStack 2014.7): salt salt.fileserver salt.fileserver.gitfs salt.fileserver.hgfs salt.fileserver.minionfs ...
Below is the the instruction that describes the task: ### Input: cx_freeze doesn't support the star (*) method of sub-module inclusion, so all submodules must be included explicitly. Example (From SaltStack 2014.7): salt salt.fileserver salt.fileserver.gitfs ...
def roles(self): """gets user groups""" result = AuthGroup.objects(creator=self.client).only('role') return json.loads(result.to_json())
gets user groups
Below is the the instruction that describes the task: ### Input: gets user groups ### Response: def roles(self): """gets user groups""" result = AuthGroup.objects(creator=self.client).only('role') return json.loads(result.to_json())
def crash_handler_lite(etype, evalue, tb): """a light excepthook, adding a small message to the usual traceback""" traceback.print_exception(etype, evalue, tb) from IPython.core.interactiveshell import InteractiveShell if InteractiveShell.initialized(): # we are in a Shell environment, give...
a light excepthook, adding a small message to the usual traceback
Below is the the instruction that describes the task: ### Input: a light excepthook, adding a small message to the usual traceback ### Response: def crash_handler_lite(etype, evalue, tb): """a light excepthook, adding a small message to the usual traceback""" traceback.print_exception(etype, evalue, tb) ...
def get_field_names(self): """ Different field names depending on self.add setting (see load_data) For BaseIO """ if self.add: return ['date', 'elem', 'value'] + [flag for flag in self.add] else: field_names = ['date'] for elem in self....
Different field names depending on self.add setting (see load_data) For BaseIO
Below is the the instruction that describes the task: ### Input: Different field names depending on self.add setting (see load_data) For BaseIO ### Response: def get_field_names(self): """ Different field names depending on self.add setting (see load_data) For BaseIO """ ...
def process_bib_files(local_dir): """Run the refresh-lsst-bib program's logic: iterates through bib URLs, downloads the file from GitHub, and writes it to a local directory. Parameters ---------- local_dir : `str` Directory to write bib files into. Returns ------- error_count :...
Run the refresh-lsst-bib program's logic: iterates through bib URLs, downloads the file from GitHub, and writes it to a local directory. Parameters ---------- local_dir : `str` Directory to write bib files into. Returns ------- error_count : `int` Number of download errors.
Below is the the instruction that describes the task: ### Input: Run the refresh-lsst-bib program's logic: iterates through bib URLs, downloads the file from GitHub, and writes it to a local directory. Parameters ---------- local_dir : `str` Directory to write bib files into. Returns ...
def detect(byte_str): """ Detect the encoding of the given byte string. :param byte_str: The byte sequence to examine. :type byte_str: ``bytes`` or ``bytearray`` """ if not isinstance(byte_str, bytearray): if not isinstance(byte_str, bytes): raise TypeError('Expecte...
Detect the encoding of the given byte string. :param byte_str: The byte sequence to examine. :type byte_str: ``bytes`` or ``bytearray``
Below is the the instruction that describes the task: ### Input: Detect the encoding of the given byte string. :param byte_str: The byte sequence to examine. :type byte_str: ``bytes`` or ``bytearray`` ### Response: def detect(byte_str): """ Detect the encoding of the given byte string. ...
def _metadata_fetch(self, metadata_fields, label=None): """Takes a list of metadata fields, some of which can contain taxon names or taxon IDs, and returns a DataFrame with transformed data that can be used for plotting. Parameters ---------- metadata_fields : `list` of `string`...
Takes a list of metadata fields, some of which can contain taxon names or taxon IDs, and returns a DataFrame with transformed data that can be used for plotting. Parameters ---------- metadata_fields : `list` of `string` A list of metadata fields, taxon names, or taxon IDs t...
Below is the the instruction that describes the task: ### Input: Takes a list of metadata fields, some of which can contain taxon names or taxon IDs, and returns a DataFrame with transformed data that can be used for plotting. Parameters ---------- metadata_fields : `list` of `strin...
def rtc_as_set(self): """Returns current RTC AS configured for current neighbors. """ rtc_as_set = set() for neigh in self._neighbors.values(): rtc_as_set.add(neigh.rtc_as) return rtc_as_set
Returns current RTC AS configured for current neighbors.
Below is the the instruction that describes the task: ### Input: Returns current RTC AS configured for current neighbors. ### Response: def rtc_as_set(self): """Returns current RTC AS configured for current neighbors. """ rtc_as_set = set() for neigh in self._neighbors.values(): ...
def to_dict(self): """ Returns: dict: Concise represented as a dictionary. """ final_res = { "param": self._param, "unused_param": self.unused_param, "execution_time": self._exec_time, "output": {"accuracy": self.get_accuracy(),...
Returns: dict: Concise represented as a dictionary.
Below is the the instruction that describes the task: ### Input: Returns: dict: Concise represented as a dictionary. ### Response: def to_dict(self): """ Returns: dict: Concise represented as a dictionary. """ final_res = { "param": self._param, ...
def get_difference_model(self, category): """ Get the equation corresponding to a variation wrt category. For example if:: modelstr = { 'full' :'H(I) + B', 'dH' : 'dH(I)', 'dI' : 'H(dI)', 'dB' : 'dB' } ...
Get the equation corresponding to a variation wrt category. For example if:: modelstr = { 'full' :'H(I) + B', 'dH' : 'dH(I)', 'dI' : 'H(dI)', 'dB' : 'dB' } varmap = {'H': 'psf', 'I': 'obj', 'B': 'bkg'} ...
Below is the the instruction that describes the task: ### Input: Get the equation corresponding to a variation wrt category. For example if:: modelstr = { 'full' :'H(I) + B', 'dH' : 'dH(I)', 'dI' : 'H(dI)', 'dB' : 'dB' ...
def update_record(cls, fqdn, name, type, value, ttl, content): """Update all records for a domain.""" data = { "rrset_name": name, "rrset_type": type, "rrset_values": value, } if ttl: data['rrset_ttl'] = int(ttl) meta = cls.get_fqdn...
Update all records for a domain.
Below is the the instruction that describes the task: ### Input: Update all records for a domain. ### Response: def update_record(cls, fqdn, name, type, value, ttl, content): """Update all records for a domain.""" data = { "rrset_name": name, "rrset_type": type, ...
def _finalize_batch(self): """ Method to finalize the batch, this will iterate over the _batches dict and create a PmtInf node for each batch. The correct information (from the batch_key and batch_totals) will be inserted and the batch transaction nodes will be folded. Finally, t...
Method to finalize the batch, this will iterate over the _batches dict and create a PmtInf node for each batch. The correct information (from the batch_key and batch_totals) will be inserted and the batch transaction nodes will be folded. Finally, the batches will be added to the main XM...
Below is the the instruction that describes the task: ### Input: Method to finalize the batch, this will iterate over the _batches dict and create a PmtInf node for each batch. The correct information (from the batch_key and batch_totals) will be inserted and the batch transaction nodes will...
def validate_srec_checksum(srec): """ Validate if the checksum of the supplied s-record is valid Returns: True if valid, False if not """ checksum = srec[len(srec)-2:] # Strip the original checksum and compare with the computed one if compute_srec_checksum(srec[:len(srec) - 2]) == i...
Validate if the checksum of the supplied s-record is valid Returns: True if valid, False if not
Below is the the instruction that describes the task: ### Input: Validate if the checksum of the supplied s-record is valid Returns: True if valid, False if not ### Response: def validate_srec_checksum(srec): """ Validate if the checksum of the supplied s-record is valid Returns: True i...
def _query_mssql(self): """ Queries MSSQL and returns a cursor of results. :return: mssql cursor """ mssql = MsSqlHook(mssql_conn_id=self.mssql_conn_id) conn = mssql.get_conn() cursor = conn.cursor() cursor.execute(self.sql) return cursor
Queries MSSQL and returns a cursor of results. :return: mssql cursor
Below is the the instruction that describes the task: ### Input: Queries MSSQL and returns a cursor of results. :return: mssql cursor ### Response: def _query_mssql(self): """ Queries MSSQL and returns a cursor of results. :return: mssql cursor """ mssql = MsSqlHoo...
def load_matrix_sparse(filename): coo = np.load(filename) """Check if coo is (M, 3) ndarray""" if len(coo.shape) == 2 and coo.shape[1] == 3: row = coo[:, 0] col = coo[:, 1] values = coo[:, 2] """Check if imaginary part of row and col is zero""" if np.all(np.isreal(r...
Check if coo is (M, 3) ndarray
Below is the the instruction that describes the task: ### Input: Check if coo is (M, 3) ndarray ### Response: def load_matrix_sparse(filename): coo = np.load(filename) """Check if coo is (M, 3) ndarray""" if len(coo.shape) == 2 and coo.shape[1] == 3: row = coo[:, 0] col = coo[:, 1] ...
def get_rest_apis(self, project_name): """ Generator that allows to iterate per every available apis. """ all_apis = self.apigateway_client.get_rest_apis( limit=500 ) for api in all_apis['items']: if api['name'] != project_name: co...
Generator that allows to iterate per every available apis.
Below is the the instruction that describes the task: ### Input: Generator that allows to iterate per every available apis. ### Response: def get_rest_apis(self, project_name): """ Generator that allows to iterate per every available apis. """ all_apis = self.apigateway_client.get_r...
def _pack_with_tf_ops(dataset, keys, length): """Helper-function for packing a dataset which has already been batched. See pack_dataset() Uses tf.while_loop. Slow. Args: dataset: a dataset containing padded batches of examples. keys: a list of strings length: an integer Returns: a dataset...
Helper-function for packing a dataset which has already been batched. See pack_dataset() Uses tf.while_loop. Slow. Args: dataset: a dataset containing padded batches of examples. keys: a list of strings length: an integer Returns: a dataset.
Below is the the instruction that describes the task: ### Input: Helper-function for packing a dataset which has already been batched. See pack_dataset() Uses tf.while_loop. Slow. Args: dataset: a dataset containing padded batches of examples. keys: a list of strings length: an integer Retu...
def get_objects_by_type_in_subtree(self, *types): """ :param types: requested object types. :return: all children of the specified types. """ typed_objects = self.get_objects_by_type(*types) for child in self.objects.values(): typed_objects += child.get_objec...
:param types: requested object types. :return: all children of the specified types.
Below is the the instruction that describes the task: ### Input: :param types: requested object types. :return: all children of the specified types. ### Response: def get_objects_by_type_in_subtree(self, *types): """ :param types: requested object types. :return: all children of the...
def earth_accel2_df(IMU,IMU2,ATT): '''return earth frame acceleration vector from df log''' r = rotation_df(ATT) accel1 = Vector3(IMU.AccX, IMU.AccY, IMU.AccZ) accel2 = Vector3(IMU2.AccX, IMU2.AccY, IMU2.AccZ) accel = 0.5 * (accel1 + accel2) return r * accel
return earth frame acceleration vector from df log
Below is the the instruction that describes the task: ### Input: return earth frame acceleration vector from df log ### Response: def earth_accel2_df(IMU,IMU2,ATT): '''return earth frame acceleration vector from df log''' r = rotation_df(ATT) accel1 = Vector3(IMU.AccX, IMU.AccY, IMU.AccZ) accel2 = ...
def strip_xss(html, whitelist=None, replacement="(removed)"): """ This function returns a tuple containing: * *html* with all non-whitelisted HTML tags replaced with *replacement*. * A `set()` containing the tags that were removed. Any tags that contain JavaScript, VBScript, or other known...
This function returns a tuple containing: * *html* with all non-whitelisted HTML tags replaced with *replacement*. * A `set()` containing the tags that were removed. Any tags that contain JavaScript, VBScript, or other known XSS/executable functions will also be removed. If *whitelist* is...
Below is the the instruction that describes the task: ### Input: This function returns a tuple containing: * *html* with all non-whitelisted HTML tags replaced with *replacement*. * A `set()` containing the tags that were removed. Any tags that contain JavaScript, VBScript, or other known XSS/...
def get_dict_to_print(field_to_obs): """Transform the field-to-obs mapping into a printable dictionary. Args: field_to_obs: Dict that maps string field to `Observation` list. Returns: A dict with the keys and values to print to console. """ def compressed_steps(steps): return {'num_steps': len(...
Transform the field-to-obs mapping into a printable dictionary. Args: field_to_obs: Dict that maps string field to `Observation` list. Returns: A dict with the keys and values to print to console.
Below is the the instruction that describes the task: ### Input: Transform the field-to-obs mapping into a printable dictionary. Args: field_to_obs: Dict that maps string field to `Observation` list. Returns: A dict with the keys and values to print to console. ### Response: def get_dict_to_print(fie...
def make_association_id(definedby, sub, pred, obj, attributes=None): """ A method to create unique identifiers for OBAN-style associations, based on all the parts of the association If any of the items is empty or None, it will convert it to blank. It effectively digests the str...
A method to create unique identifiers for OBAN-style associations, based on all the parts of the association If any of the items is empty or None, it will convert it to blank. It effectively digests the string of concatonated values. Subclasses of Assoc can submit an additional array of...
Below is the the instruction that describes the task: ### Input: A method to create unique identifiers for OBAN-style associations, based on all the parts of the association If any of the items is empty or None, it will convert it to blank. It effectively digests the string of concatonated ...
def sqrt( data: AnnData, copy: bool = False, chunked: bool = False, chunk_size: Optional[int] = None, ) -> Optional[AnnData]: """Square root the data matrix. Computes :math:`X = \\sqrt(X)`. Parameters ---------- data The (annotated) data matrix of shape ``n_obs`` × ``n_vars...
Square root the data matrix. Computes :math:`X = \\sqrt(X)`. Parameters ---------- data The (annotated) data matrix of shape ``n_obs`` × ``n_vars``. Rows correspond to cells and columns to genes. copy If an :class:`~scanpy.api.AnnData` is passed, determines whether ...
Below is the the instruction that describes the task: ### Input: Square root the data matrix. Computes :math:`X = \\sqrt(X)`. Parameters ---------- data The (annotated) data matrix of shape ``n_obs`` × ``n_vars``. Rows correspond to cells and columns to genes. copy If a...
def _winsorize_wrapper(x, limits): """ Wraps scipy winsorize function to drop na's """ if isinstance(x, pd.Series): if x.count() == 0: return x notnanx = ~np.isnan(x) x[notnanx] = scipy.stats.mstats.winsorize(x[notnanx], ...
Wraps scipy winsorize function to drop na's
Below is the the instruction that describes the task: ### Input: Wraps scipy winsorize function to drop na's ### Response: def _winsorize_wrapper(x, limits): """ Wraps scipy winsorize function to drop na's """ if isinstance(x, pd.Series): if x.count() == 0: return x not...
def storageLevel(self): """Get the :class:`DataFrame`'s current storage level. >>> df.storageLevel StorageLevel(False, False, False, False, 1) >>> df.cache().storageLevel StorageLevel(True, True, False, True, 1) >>> df2.persist(StorageLevel.DISK_ONLY_2).storageLevel ...
Get the :class:`DataFrame`'s current storage level. >>> df.storageLevel StorageLevel(False, False, False, False, 1) >>> df.cache().storageLevel StorageLevel(True, True, False, True, 1) >>> df2.persist(StorageLevel.DISK_ONLY_2).storageLevel StorageLevel(True, False, False...
Below is the the instruction that describes the task: ### Input: Get the :class:`DataFrame`'s current storage level. >>> df.storageLevel StorageLevel(False, False, False, False, 1) >>> df.cache().storageLevel StorageLevel(True, True, False, True, 1) >>> df2.persist(StorageLe...
def get_nowait(self): """Remove and return an item from the queue. Return an item if one is immediately available, else raise QueueEmpty. """ self._parent._check_closing() with self._parent._sync_mutex: if self._parent._qsize() == 0: raise AsyncQueueE...
Remove and return an item from the queue. Return an item if one is immediately available, else raise QueueEmpty.
Below is the the instruction that describes the task: ### Input: Remove and return an item from the queue. Return an item if one is immediately available, else raise QueueEmpty. ### Response: def get_nowait(self): """Remove and return an item from the queue. Return an item if one is immed...
def unflat_unique_rowid_map(func, unflat_rowids, **kwargs): """ performs only one call to the underlying func with unique rowids the func must be some lookup function TODO: move this to a better place. CommandLine: python -m utool.util_list --test-unflat_unique_rowid_map:0 python -...
performs only one call to the underlying func with unique rowids the func must be some lookup function TODO: move this to a better place. CommandLine: python -m utool.util_list --test-unflat_unique_rowid_map:0 python -m utool.util_list --test-unflat_unique_rowid_map:1 Example0: ...
Below is the the instruction that describes the task: ### Input: performs only one call to the underlying func with unique rowids the func must be some lookup function TODO: move this to a better place. CommandLine: python -m utool.util_list --test-unflat_unique_rowid_map:0 python -m u...
def pivoted_cholesky(matrix, max_rank, diag_rtol=1e-3, name=None): """Computes the (partial) pivoted cholesky decomposition of `matrix`. The pivoted Cholesky is a low rank approximation of the Cholesky decomposition of `matrix`, i.e. as described in [(Harbrecht et al., 2012)][1]. The currently-worst-approximat...
Computes the (partial) pivoted cholesky decomposition of `matrix`. The pivoted Cholesky is a low rank approximation of the Cholesky decomposition of `matrix`, i.e. as described in [(Harbrecht et al., 2012)][1]. The currently-worst-approximated diagonal element is selected as the pivot at each iteration. This y...
Below is the the instruction that describes the task: ### Input: Computes the (partial) pivoted cholesky decomposition of `matrix`. The pivoted Cholesky is a low rank approximation of the Cholesky decomposition of `matrix`, i.e. as described in [(Harbrecht et al., 2012)][1]. The currently-worst-approximated ...
def _process_packet(self, sequence): """ Check packet list for acks. """ if self._packets: with self._packet_lock: self._packets[:] = [packet for packet in self._packets if self._packet_ack(packet, sequence)]
Check packet list for acks.
Below is the the instruction that describes the task: ### Input: Check packet list for acks. ### Response: def _process_packet(self, sequence): """ Check packet list for acks. """ if self._packets: with self._packet_lock: self._packets[:] = [packet for packet in self._pa...
def getAnalysisServiceSettings(self, uid): """Returns a dictionary with the settings for the analysis service that match with the uid provided. If there are no settings for the analysis service and template, returns a dictionary with the key 'uid' """ settings = self....
Returns a dictionary with the settings for the analysis service that match with the uid provided. If there are no settings for the analysis service and template, returns a dictionary with the key 'uid'
Below is the the instruction that describes the task: ### Input: Returns a dictionary with the settings for the analysis service that match with the uid provided. If there are no settings for the analysis service and template, returns a dictionary with the key 'uid' ### Response: def ge...
def revoke_security_group(self, group_name=None, src_security_group_name=None, src_security_group_owner_id=None, ip_protocol=None, from_port=None, to_port=None, cidr_ip=None, group_id=None, src_securi...
Remove an existing rule from an existing security group. You need to pass in either src_security_group_name and src_security_group_owner_id OR ip_protocol, from_port, to_port, and cidr_ip. In other words, either you are revoking another group or you are revoking some ip-based rule. ...
Below is the the instruction that describes the task: ### Input: Remove an existing rule from an existing security group. You need to pass in either src_security_group_name and src_security_group_owner_id OR ip_protocol, from_port, to_port, and cidr_ip. In other words, either you are revoki...
def wait(self, milliseconds, **options): """ Allows the thread to sleep for a given amount of time in milliseconds Argument: milliseconds is an Integer Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/wait """ self._steps.append(...
Allows the thread to sleep for a given amount of time in milliseconds Argument: milliseconds is an Integer Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/wait
Below is the the instruction that describes the task: ### Input: Allows the thread to sleep for a given amount of time in milliseconds Argument: milliseconds is an Integer Argument: **options is a set of optional keyword arguments. See https://www.tropo.com/docs/webapi/wait ### Response: def wait...
def get_session(): """Gets a session. If there's no yet, creates one. :returns: a session """ if hasattr(g, 'session'): return g.session sess = create_session(bind=current_app.config['DATABASE_ENGINE']) try: g.session = sess except RuntimeError: pass return sess
Gets a session. If there's no yet, creates one. :returns: a session
Below is the the instruction that describes the task: ### Input: Gets a session. If there's no yet, creates one. :returns: a session ### Response: def get_session(): """Gets a session. If there's no yet, creates one. :returns: a session """ if hasattr(g, 'session'): return g.session...
def get_block_statistics(cls, block_id): """ Get block statistics. Only works in test mode. """ if not os.environ.get("BLOCKSTACK_TEST"): raise Exception("This method is only available in the test framework") global STATISTICS return STATISTICS.get(bl...
Get block statistics. Only works in test mode.
Below is the the instruction that describes the task: ### Input: Get block statistics. Only works in test mode. ### Response: def get_block_statistics(cls, block_id): """ Get block statistics. Only works in test mode. """ if not os.environ.get("BLOCKSTACK_TEST"): ...
def _parse(template): """Parse a top-level template string Expression. Any extraneous text is considered literal text. """ parser = Parser(template) parser.parse_expression() parts = parser.parts remainder = parser.string[parser.pos:] if remainder: parts.append(remainder) re...
Parse a top-level template string Expression. Any extraneous text is considered literal text.
Below is the the instruction that describes the task: ### Input: Parse a top-level template string Expression. Any extraneous text is considered literal text. ### Response: def _parse(template): """Parse a top-level template string Expression. Any extraneous text is considered literal text. """ ...
def _set_asn1_time(boundary, when): """ The the time value of an ASN1 time object. @param boundary: An ASN1_TIME pointer (or an object safely castable to that type) which will have its value set. @param when: A string representation of the desired time value. @raise TypeError: If C{when} i...
The the time value of an ASN1 time object. @param boundary: An ASN1_TIME pointer (or an object safely castable to that type) which will have its value set. @param when: A string representation of the desired time value. @raise TypeError: If C{when} is not a L{bytes} string. @raise ValueError: ...
Below is the the instruction that describes the task: ### Input: The the time value of an ASN1 time object. @param boundary: An ASN1_TIME pointer (or an object safely castable to that type) which will have its value set. @param when: A string representation of the desired time value. @raise Ty...
def extract_path_info( environ_or_baseurl, path_or_url, charset="utf-8", errors="werkzeug.url_quote", collapse_http_schemes=True, ): """Extracts the path info from the given URL (or WSGI environment) and path. The path info returned is a unicode string, not a bytestring suitable for a W...
Extracts the path info from the given URL (or WSGI environment) and path. The path info returned is a unicode string, not a bytestring suitable for a WSGI environment. The URLs might also be IRIs. If the path info could not be determined, `None` is returned. Some examples: >>> extract_path_info...
Below is the the instruction that describes the task: ### Input: Extracts the path info from the given URL (or WSGI environment) and path. The path info returned is a unicode string, not a bytestring suitable for a WSGI environment. The URLs might also be IRIs. If the path info could not be determine...
def BuildArtifactsRegistry( cls, artifact_definitions_path, custom_artifacts_path): """Build Find Specs from artifacts or filter file if available. Args: artifact_definitions_path (str): path to artifact definitions file. custom_artifacts_path (str): path to custom artifact definitions file...
Build Find Specs from artifacts or filter file if available. Args: artifact_definitions_path (str): path to artifact definitions file. custom_artifacts_path (str): path to custom artifact definitions file. Returns: artifacts.ArtifactDefinitionsRegistry: artifact definitions registry. ...
Below is the the instruction that describes the task: ### Input: Build Find Specs from artifacts or filter file if available. Args: artifact_definitions_path (str): path to artifact definitions file. custom_artifacts_path (str): path to custom artifact definitions file. Returns: artifa...
def save_state_recursively(state, base_path, parent_path, as_copy=False): """Recursively saves a state to a json file It calls this method on all its substates. :param state: State to be stored :param base_path: Path to the state machine :param parent_path: Path to the parent state :param bool...
Recursively saves a state to a json file It calls this method on all its substates. :param state: State to be stored :param base_path: Path to the state machine :param parent_path: Path to the parent state :param bool as_copy: Temporary storage flag to signal that the given path is not the new fil...
Below is the the instruction that describes the task: ### Input: Recursively saves a state to a json file It calls this method on all its substates. :param state: State to be stored :param base_path: Path to the state machine :param parent_path: Path to the parent state :param bool as_copy: Te...
def send_to_contact(self, obj_id, contact_id): """ Send email to a specific contact :param obj_id: int :param contact_id: int :return: dict|str """ response = self._client.session.post( '{url}/{id}/send/contact/{contact_id}'.format( ur...
Send email to a specific contact :param obj_id: int :param contact_id: int :return: dict|str
Below is the the instruction that describes the task: ### Input: Send email to a specific contact :param obj_id: int :param contact_id: int :return: dict|str ### Response: def send_to_contact(self, obj_id, contact_id): """ Send email to a specific contact :param ob...
def build_transaction_for_function( address, web3, function_name=None, transaction=None, contract_abi=None, fn_abi=None, *args, **kwargs): """Builds a dictionary with the fields required to make the given transaction Don't call this directly, inst...
Builds a dictionary with the fields required to make the given transaction Don't call this directly, instead use :meth:`Contract.buildTransaction` on your contract instance.
Below is the the instruction that describes the task: ### Input: Builds a dictionary with the fields required to make the given transaction Don't call this directly, instead use :meth:`Contract.buildTransaction` on your contract instance. ### Response: def build_transaction_for_function( address, ...
def get_setupcfg_version(): """As get_setup_version(), but configure via setup.cfg. If your project uses setup.cfg to configure setuptools, and hence has at least a "name" key in the [metadata] section, you can set the version as follows: ``` [metadata] name = mypackage version = attr: ...
As get_setup_version(), but configure via setup.cfg. If your project uses setup.cfg to configure setuptools, and hence has at least a "name" key in the [metadata] section, you can set the version as follows: ``` [metadata] name = mypackage version = attr: autover.version.get_setup_version2 ...
Below is the the instruction that describes the task: ### Input: As get_setup_version(), but configure via setup.cfg. If your project uses setup.cfg to configure setuptools, and hence has at least a "name" key in the [metadata] section, you can set the version as follows: ``` [metadata] nam...
def submit_rpc(self, rpc_name, params, flags=0): """ Sends an RPC request. This call will transition session into pending state. If some operation is currently pending on the session, it will be cancelled before sending this request. Spec: http://msdn.microsoft.com/en-us/librar...
Sends an RPC request. This call will transition session into pending state. If some operation is currently pending on the session, it will be cancelled before sending this request. Spec: http://msdn.microsoft.com/en-us/library/dd357576.aspx :param rpc_name: Name of the RPC to ...
Below is the the instruction that describes the task: ### Input: Sends an RPC request. This call will transition session into pending state. If some operation is currently pending on the session, it will be cancelled before sending this request. Spec: http://msdn.microsoft.com/en-u...
def assemble_rom_code(self, asm): """ assemble the given code and program the ROM """ stream = StringIO(asm) worker = assembler.Assembler(self.processor, stream) try: result = worker.assemble() except BaseException as e: return e, None self.rom.program(result) return None, result
assemble the given code and program the ROM
Below is the the instruction that describes the task: ### Input: assemble the given code and program the ROM ### Response: def assemble_rom_code(self, asm): """ assemble the given code and program the ROM """ stream = StringIO(asm) worker = assembler.Assembler(self.processor, stream) try: result = ...
def primeSieve(k): """return a list with length k + 1, showing if list[i] == 1, i is a prime else if list[i] == 0, i is a composite, if list[i] == -1, not defined""" def isPrime(n): """return True is given number n is absolutely prime, return False is otherwise.""" for i in range(2,...
return a list with length k + 1, showing if list[i] == 1, i is a prime else if list[i] == 0, i is a composite, if list[i] == -1, not defined
Below is the the instruction that describes the task: ### Input: return a list with length k + 1, showing if list[i] == 1, i is a prime else if list[i] == 0, i is a composite, if list[i] == -1, not defined ### Response: def primeSieve(k): """return a list with length k + 1, showing if list[i] == 1, i is a ...
def do_status(self, subcmd, opts, *args): """Print the status of working copy files and directories. usage: status [PATH...] With no args, print only locally modified items (no network access). With -u, add working revision and server out-of-date information. ...
Print the status of working copy files and directories. usage: status [PATH...] With no args, print only locally modified items (no network access). With -u, add working revision and server out-of-date information. With -v, print full revision information on every i...
Below is the the instruction that describes the task: ### Input: Print the status of working copy files and directories. usage: status [PATH...] With no args, print only locally modified items (no network access). With -u, add working revision and server out-of-date inf...
def accuracy(self): """ Calculates the accuracy of the tree by comparing the model predictions to the dataset (TP + TN) / (TP + TN + FP + FN) == (T / (T + F)) """ sub_observed = np.array([self.observed.metadata[i] for i in self.observed.arr]) return float((self.mo...
Calculates the accuracy of the tree by comparing the model predictions to the dataset (TP + TN) / (TP + TN + FP + FN) == (T / (T + F))
Below is the the instruction that describes the task: ### Input: Calculates the accuracy of the tree by comparing the model predictions to the dataset (TP + TN) / (TP + TN + FP + FN) == (T / (T + F)) ### Response: def accuracy(self): """ Calculates the accuracy of the tree by compar...
def _parse_paginated_members(self, direction="children"): """ Launch parsing of children """ page = self._last_page_parsed[direction] if not page: page = 1 else: page = int(page) while page: if page > 1: response = self...
Launch parsing of children
Below is the the instruction that describes the task: ### Input: Launch parsing of children ### Response: def _parse_paginated_members(self, direction="children"): """ Launch parsing of children """ page = self._last_page_parsed[direction] if not page: page = 1 ...
def get_asset(self): """ Returns an instance of the Asset Service. """ import predix.data.asset asset = predix.data.asset.Asset() return asset
Returns an instance of the Asset Service.
Below is the the instruction that describes the task: ### Input: Returns an instance of the Asset Service. ### Response: def get_asset(self): """ Returns an instance of the Asset Service. """ import predix.data.asset asset = predix.data.asset.Asset() return asset
def real(prompt=None, empty=False): """Prompt a real number. Parameters ---------- prompt : str, optional Use an alternative prompt. empty : bool, optional Allow an empty response. Returns ------- float or None A float if the user entered a valid real number. ...
Prompt a real number. Parameters ---------- prompt : str, optional Use an alternative prompt. empty : bool, optional Allow an empty response. Returns ------- float or None A float if the user entered a valid real number. None if the user pressed only Enter a...
Below is the the instruction that describes the task: ### Input: Prompt a real number. Parameters ---------- prompt : str, optional Use an alternative prompt. empty : bool, optional Allow an empty response. Returns ------- float or None A float if the user enter...
def data_from_dict(self, data): """ Populate model parameters from a dictionary of parameters Parameters ---------- data : dict List of parameter dictionaries Returns ------- None """ nvars = [] for key, val in data.i...
Populate model parameters from a dictionary of parameters Parameters ---------- data : dict List of parameter dictionaries Returns ------- None
Below is the the instruction that describes the task: ### Input: Populate model parameters from a dictionary of parameters Parameters ---------- data : dict List of parameter dictionaries Returns ------- None ### Response: def data_from_dict(self, data)...
def candidates(word): "Generate possible spelling corrections for word." return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word])
Generate possible spelling corrections for word.
Below is the the instruction that describes the task: ### Input: Generate possible spelling corrections for word. ### Response: def candidates(word): "Generate possible spelling corrections for word." return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word])
def pix2ang(nside, pix): r"""Convert pixel to angle :math:`\theta` :math:`\phi`. nside and pix are broadcast with numpy rules. Returns: theta, phi This is translated from chealpix.c; but refer to Section 4.1 of http://adsabs.harvard.edu/abs/2005ApJ...622..759G """ nside, p...
r"""Convert pixel to angle :math:`\theta` :math:`\phi`. nside and pix are broadcast with numpy rules. Returns: theta, phi This is translated from chealpix.c; but refer to Section 4.1 of http://adsabs.harvard.edu/abs/2005ApJ...622..759G
Below is the the instruction that describes the task: ### Input: r"""Convert pixel to angle :math:`\theta` :math:`\phi`. nside and pix are broadcast with numpy rules. Returns: theta, phi This is translated from chealpix.c; but refer to Section 4.1 of http://adsabs.harvard.edu/abs/...
def get_SQL(self, schema, query, **sql_options): """ convert the query instance into SQL this is the glue method that translates the generic Query() instance to the SQL specific query, this is where the magic happens **sql_options -- dict count_query -- boolean -- t...
convert the query instance into SQL this is the glue method that translates the generic Query() instance to the SQL specific query, this is where the magic happens **sql_options -- dict count_query -- boolean -- true if this is a count query SELECT only_where_clause -- ...
Below is the the instruction that describes the task: ### Input: convert the query instance into SQL this is the glue method that translates the generic Query() instance to the SQL specific query, this is where the magic happens **sql_options -- dict count_query -- boolean -- t...
def get_from_clause(self): """ Add the JOINS for related multilingual fields filtering. """ result = super(MultilingualSQLCompiler, self).get_from_clause() if not self.query.include_translation_data: return result from_ = result[0] for join in self.q...
Add the JOINS for related multilingual fields filtering.
Below is the the instruction that describes the task: ### Input: Add the JOINS for related multilingual fields filtering. ### Response: def get_from_clause(self): """ Add the JOINS for related multilingual fields filtering. """ result = super(MultilingualSQLCompiler, self).get_from_...
def execute(self, command=None, container_id=None, sudo=False, stream=False): '''execute a command to a container instance based on container_id Parameters ========== container_id: the container_id to delete command: the command to execute to the container sudo: whether to issue ...
execute a command to a container instance based on container_id Parameters ========== container_id: the container_id to delete command: the command to execute to the container sudo: whether to issue the command with sudo (or not) a container started with sudo will belong...
Below is the the instruction that describes the task: ### Input: execute a command to a container instance based on container_id Parameters ========== container_id: the container_id to delete command: the command to execute to the container sudo: whether to issue the command with...
def fit_texture(layer): """Fits a layer into a texture by scaling each axis to (0, 1). Does not preserve aspect ratio (TODO: make this an option). Args: layer (layer): the layer to scale Returns: texture: A texture. """ x, y = layer x = (x - np.nanmin(x)) / (np.nanmax(x) -...
Fits a layer into a texture by scaling each axis to (0, 1). Does not preserve aspect ratio (TODO: make this an option). Args: layer (layer): the layer to scale Returns: texture: A texture.
Below is the the instruction that describes the task: ### Input: Fits a layer into a texture by scaling each axis to (0, 1). Does not preserve aspect ratio (TODO: make this an option). Args: layer (layer): the layer to scale Returns: texture: A texture. ### Response: def fit_texture(...
def build_task(current_target): """ Build a target. Arguments target - The target to build. """ target = current_target.config try: builder = _make_builder(target, current_target) build_path = _get_build_path(target, builder) if not os.path.exists(build_path): ...
Build a target. Arguments target - The target to build.
Below is the the instruction that describes the task: ### Input: Build a target. Arguments target - The target to build. ### Response: def build_task(current_target): """ Build a target. Arguments target - The target to build. """ target = current_target.config try: b...
def between(value, min=None, max=None): """ Validate that a number is between minimum and/or maximum value. This will work with any comparable type, such as floats, decimals and dates not just integers. This validator is originally based on `WTForms NumberRange validator`_. .. _WTForms Number...
Validate that a number is between minimum and/or maximum value. This will work with any comparable type, such as floats, decimals and dates not just integers. This validator is originally based on `WTForms NumberRange validator`_. .. _WTForms NumberRange validator: https://github.com/wtforms/w...
Below is the the instruction that describes the task: ### Input: Validate that a number is between minimum and/or maximum value. This will work with any comparable type, such as floats, decimals and dates not just integers. This validator is originally based on `WTForms NumberRange validator`_. ....
def modify_password(self, username, newpwd, oldpwd): """ Params: username - user name newpwd - new password oldpwd - old password """ ret = self.command( 'userManager.cgi?action=modifyPassword&name={0}&pwd={1}' '&pwdOld={2}'.for...
Params: username - user name newpwd - new password oldpwd - old password
Below is the the instruction that describes the task: ### Input: Params: username - user name newpwd - new password oldpwd - old password ### Response: def modify_password(self, username, newpwd, oldpwd): """ Params: username - user name n...
def extract_text(self, node): """Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list. """ if...
Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore list.
Below is the the instruction that describes the task: ### Input: Return the string representation of the node or list of nodes by parsing the subnodes, but returning the result as a string instead of adding it to `self.pieces`. Note that this allows extracting text even if the node is in the ignore ...
def get_rule(self, field_id): """ Returns the rule for the field identified by the id. If it is set as not being compulsory, the rule will be adapted to accept string composed only of white characters. :param field_id: unique id in the system for the field :return: the ...
Returns the rule for the field identified by the id. If it is set as not being compulsory, the rule will be adapted to accept string composed only of white characters. :param field_id: unique id in the system for the field :return: the rule of a field
Below is the the instruction that describes the task: ### Input: Returns the rule for the field identified by the id. If it is set as not being compulsory, the rule will be adapted to accept string composed only of white characters. :param field_id: unique id in the system for the field ...
def Deserialize(self, reader): """ Deserialize full object. Args: reader (neo.IO.BinaryReader): """ usage = reader.ReadByte() self.Usage = usage if usage == TransactionAttributeUsage.ContractHash or usage == TransactionAttributeUsage.Vote or \ ...
Deserialize full object. Args: reader (neo.IO.BinaryReader):
Below is the the instruction that describes the task: ### Input: Deserialize full object. Args: reader (neo.IO.BinaryReader): ### Response: def Deserialize(self, reader): """ Deserialize full object. Args: reader (neo.IO.BinaryReader): """ u...
def by_group_name(cls, group_name, db_session=None): """ fetch group by name :param group_name: :param db_session: :return: """ db_session = get_db_session(db_session) query = db_session.query(cls.model).filter(cls.model.group_name == group_name) ...
fetch group by name :param group_name: :param db_session: :return:
Below is the the instruction that describes the task: ### Input: fetch group by name :param group_name: :param db_session: :return: ### Response: def by_group_name(cls, group_name, db_session=None): """ fetch group by name :param group_name: :param db_sessi...
def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method will invoke ``receiver._document_patched`` if it exists. ''' super(DocumentPatchedEvent, self).dispatch(receiver) if hasattr(receiver, '_document_patched'): receiver._docume...
Dispatch handling of this event to a receiver. This method will invoke ``receiver._document_patched`` if it exists.
Below is the the instruction that describes the task: ### Input: Dispatch handling of this event to a receiver. This method will invoke ``receiver._document_patched`` if it exists. ### Response: def dispatch(self, receiver): ''' Dispatch handling of this event to a receiver. This method w...
def get(self, aid): """ Get manga information by id. :param int aid: ID of the manga. :return: Dictionary or None (for not found) :rtype: Dictionary or None :raises: :class:`Pymoe.errors.ServerError` """ r = requests.get(self.apiurl + "/manga/{}".format(a...
Get manga information by id. :param int aid: ID of the manga. :return: Dictionary or None (for not found) :rtype: Dictionary or None :raises: :class:`Pymoe.errors.ServerError`
Below is the the instruction that describes the task: ### Input: Get manga information by id. :param int aid: ID of the manga. :return: Dictionary or None (for not found) :rtype: Dictionary or None :raises: :class:`Pymoe.errors.ServerError` ### Response: def get(self, aid): ...
def fetch_project(self, project_id): """Fetch an existing project and it's relevant metadata by ID. .. note:: If the project does not exist, this will raise a :class:`NotFound <google.cloud.exceptions.NotFound>` error. :type project_id: str :param project_id: T...
Fetch an existing project and it's relevant metadata by ID. .. note:: If the project does not exist, this will raise a :class:`NotFound <google.cloud.exceptions.NotFound>` error. :type project_id: str :param project_id: The ID for this project. :rtype: :class:...
Below is the the instruction that describes the task: ### Input: Fetch an existing project and it's relevant metadata by ID. .. note:: If the project does not exist, this will raise a :class:`NotFound <google.cloud.exceptions.NotFound>` error. :type project_id: str ...
def unzoom(self,event=None): """zoom out 1 level, or to full data range """ if self.panel is not None: self.panel.unzoom(event=event)
zoom out 1 level, or to full data range
Below is the the instruction that describes the task: ### Input: zoom out 1 level, or to full data range ### Response: def unzoom(self,event=None): """zoom out 1 level, or to full data range """ if self.panel is not None: self.panel.unzoom(event=event)
def get_start_date_metadata(self): """Gets the metadata for a start date. return: (osid.Metadata) - metadata for the date *compliance: mandatory -- This method must be implemented.* """ metadata = dict(self._mdata['start_date']) metadata.update({'existing_date_time_valu...
Gets the metadata for a start date. return: (osid.Metadata) - metadata for the date *compliance: mandatory -- This method must be implemented.*
Below is the the instruction that describes the task: ### Input: Gets the metadata for a start date. return: (osid.Metadata) - metadata for the date *compliance: mandatory -- This method must be implemented.* ### Response: def get_start_date_metadata(self): """Gets the metadata for a start...
def attrdict_middleware(make_request, web3): """ Converts any result which is a dictionary into an a """ def middleware(method, params): response = make_request(method, params) if 'result' in response: result = response['result'] if is_dict(result) and not isinst...
Converts any result which is a dictionary into an a
Below is the the instruction that describes the task: ### Input: Converts any result which is a dictionary into an a ### Response: def attrdict_middleware(make_request, web3): """ Converts any result which is a dictionary into an a """ def middleware(method, params): response = make_request...
def get_MD_VDS(tail_check_max, vds): """ input: tail_check_max, vector difference sum output: MD_VDS """ if tail_check_max == 0 or numpy.isnan(tail_check_max): return float('nan') MD_VDS = (old_div(tail_check_max, vds)) * 100 return MD_VDS
input: tail_check_max, vector difference sum output: MD_VDS
Below is the the instruction that describes the task: ### Input: input: tail_check_max, vector difference sum output: MD_VDS ### Response: def get_MD_VDS(tail_check_max, vds): """ input: tail_check_max, vector difference sum output: MD_VDS """ if tail_check_max == 0 or numpy.isnan(tail_chec...
def get_terminal_size(): '''Finds the width of the terminal, or returns a suitable default value.''' def read_terminal_size_by_ioctl(fd): try: import struct, fcntl, termios cr = struct.unpack('hh', fcntl.ioctl(1, termios.TIOCGWINSZ, ...
Finds the width of the terminal, or returns a suitable default value.
Below is the the instruction that describes the task: ### Input: Finds the width of the terminal, or returns a suitable default value. ### Response: def get_terminal_size(): '''Finds the width of the terminal, or returns a suitable default value.''' def read_terminal_size_by_ioctl(fd): try: ...
def get_group_offsets(self, group, topic=None): """Fetch group offsets for given topic and partition otherwise all topics and partitions otherwise. { 'topic': { 'partition': offset-value, ... ... } } ...
Fetch group offsets for given topic and partition otherwise all topics and partitions otherwise. { 'topic': { 'partition': offset-value, ... ... } }
Below is the the instruction that describes the task: ### Input: Fetch group offsets for given topic and partition otherwise all topics and partitions otherwise. { 'topic': { 'partition': offset-value, ... ... } ...
def cylinders_from_ellipses(ellipses): """Create 3d cylinders from ellipses.""" ellipses = np.asarray(ellipses) ellipsoids = np.zeros((ellipses.shape[0], 10)) ellipsoids[:, [0, 1, 2, 4, 5, 7]] = ellipses ellipsoids[:, 3] = 100000.0 return ellipsoids
Create 3d cylinders from ellipses.
Below is the the instruction that describes the task: ### Input: Create 3d cylinders from ellipses. ### Response: def cylinders_from_ellipses(ellipses): """Create 3d cylinders from ellipses.""" ellipses = np.asarray(ellipses) ellipsoids = np.zeros((ellipses.shape[0], 10)) ellipsoids[:, [0, 1, 2, 4,...
def as_status(cls, obj): """Convert obj into Status.""" if obj is None: return None return obj if isinstance(obj, cls) else cls.from_string(obj)
Convert obj into Status.
Below is the the instruction that describes the task: ### Input: Convert obj into Status. ### Response: def as_status(cls, obj): """Convert obj into Status.""" if obj is None: return None return obj if isinstance(obj, cls) else cls.from_string(obj)
def find_datafile(name, search_path, codecs=get_codecs()): """ find all matching data files in search_path search_path: path of directories to load from codecs: allow to override from list of installed returns array of tuples (codec_object, filename) """ return munge.find_datafile(name, sear...
find all matching data files in search_path search_path: path of directories to load from codecs: allow to override from list of installed returns array of tuples (codec_object, filename)
Below is the the instruction that describes the task: ### Input: find all matching data files in search_path search_path: path of directories to load from codecs: allow to override from list of installed returns array of tuples (codec_object, filename) ### Response: def find_datafile(name, search_path,...
def _check_inputs(self): """Check the inputs to ensure they are valid. Returns ------- status : bool True if all inputs are valid, False if one is not. """ valid_detector = True valid_filter = True valid_date = True # Determine the su...
Check the inputs to ensure they are valid. Returns ------- status : bool True if all inputs are valid, False if one is not.
Below is the the instruction that describes the task: ### Input: Check the inputs to ensure they are valid. Returns ------- status : bool True if all inputs are valid, False if one is not. ### Response: def _check_inputs(self): """Check the inputs to ensure they are val...
def img2img_transformer2d_n31(): """Set of hyperparameters.""" hparams = img2img_transformer2d_base() hparams.batch_size = 1 hparams.num_encoder_layers = 6 hparams.num_decoder_layers = 12 hparams.num_heads = 8 hparams.query_shape = (16, 32) hparams.memory_flange = (16, 32) return hparams
Set of hyperparameters.
Below is the the instruction that describes the task: ### Input: Set of hyperparameters. ### Response: def img2img_transformer2d_n31(): """Set of hyperparameters.""" hparams = img2img_transformer2d_base() hparams.batch_size = 1 hparams.num_encoder_layers = 6 hparams.num_decoder_layers = 12 hparams.num_...
def can_fetch(self, url_info: URLInfo, user_agent: str): '''Return whether the URL can be fetched.''' key = self.url_info_key(url_info) parser = self._parsers[key] return parser.is_allowed(user_agent, url_info.url)
Return whether the URL can be fetched.
Below is the the instruction that describes the task: ### Input: Return whether the URL can be fetched. ### Response: def can_fetch(self, url_info: URLInfo, user_agent: str): '''Return whether the URL can be fetched.''' key = self.url_info_key(url_info) parser = self._parsers[key] ...
def _set_BC(self, pores, bctype, bcvalues=None, mode='merge'): r""" Apply boundary conditions to specified pores if no source terms are already assigned to these pores. Otherwise, raise an error. Parameters ---------- pores : array_like The pores where the bo...
r""" Apply boundary conditions to specified pores if no source terms are already assigned to these pores. Otherwise, raise an error. Parameters ---------- pores : array_like The pores where the boundary conditions should be applied bctype : string ...
Below is the the instruction that describes the task: ### Input: r""" Apply boundary conditions to specified pores if no source terms are already assigned to these pores. Otherwise, raise an error. Parameters ---------- pores : array_like The pores where the boun...
def ReflexVacuumAgent(): "A reflex agent for the two-state vacuum environment. [Fig. 2.8]" def program((location, status)): if status == 'Dirty': return 'Suck' elif location == loc_A: return 'Right' elif location == loc_B: return 'Left' return Agent(program)
A reflex agent for the two-state vacuum environment. [Fig. 2.8]
Below is the the instruction that describes the task: ### Input: A reflex agent for the two-state vacuum environment. [Fig. 2.8] ### Response: def ReflexVacuumAgent(): "A reflex agent for the two-state vacuum environment. [Fig. 2.8]" def program((location, status)): if status == 'Dirty': return 'Su...
def _set_nameserver_cos(self, v, load=False): """ Setter method for nameserver_cos, mapped from YANG variable /brocade_nameserver_rpc/get_nameserver_detail/output/show_nameserver/nameserver_cos (nameserver-cos-type) If this variable is read-only (config: false) in the source YANG file, then _set_nameser...
Setter method for nameserver_cos, mapped from YANG variable /brocade_nameserver_rpc/get_nameserver_detail/output/show_nameserver/nameserver_cos (nameserver-cos-type) If this variable is read-only (config: false) in the source YANG file, then _set_nameserver_cos is considered as a private method. Backends lo...
Below is the the instruction that describes the task: ### Input: Setter method for nameserver_cos, mapped from YANG variable /brocade_nameserver_rpc/get_nameserver_detail/output/show_nameserver/nameserver_cos (nameserver-cos-type) If this variable is read-only (config: false) in the source YANG file, then _...
def remove_edge(self, u, v, key=None): """Version of remove_edge that's much like normal networkx but only deletes once, since the database doesn't keep separate adj and succ mappings """ try: d = self.adj[u][v] except KeyError: raise NetworkXErro...
Version of remove_edge that's much like normal networkx but only deletes once, since the database doesn't keep separate adj and succ mappings
Below is the the instruction that describes the task: ### Input: Version of remove_edge that's much like normal networkx but only deletes once, since the database doesn't keep separate adj and succ mappings ### Response: def remove_edge(self, u, v, key=None): """Version of remove_edge that'...
def to_nnf(self): """Return an equivalent expression is negation normal form.""" node = self.node.to_nnf() if node is self.node: return self else: return _expr(node)
Return an equivalent expression is negation normal form.
Below is the the instruction that describes the task: ### Input: Return an equivalent expression is negation normal form. ### Response: def to_nnf(self): """Return an equivalent expression is negation normal form.""" node = self.node.to_nnf() if node is self.node: return self ...
def _backwards_search(self, start_node, split_name, max_depth=float('inf'), shortcuts=True): """ Performs a backwards search from the terminal node back to the start node :param start_node: The node from where search starts, or here better way where backwards search should end....
Performs a backwards search from the terminal node back to the start node :param start_node: The node from where search starts, or here better way where backwards search should end. :param split_name: List of names :param max_depth: Maximum s...
Below is the the instruction that describes the task: ### Input: Performs a backwards search from the terminal node back to the start node :param start_node: The node from where search starts, or here better way where backwards search should end. :param split_name: ...
def evaluator(self, candidates, args): """Return the fitness values for the given candidates.""" fitness = [] if self._use_ants: for candidate in candidates: total = 0 for c in candidate: total += c.value fitness.app...
Return the fitness values for the given candidates.
Below is the the instruction that describes the task: ### Input: Return the fitness values for the given candidates. ### Response: def evaluator(self, candidates, args): """Return the fitness values for the given candidates.""" fitness = [] if self._use_ants: for candidate in ca...
def create_download_specifications(ctx_cli_options, config): # type: (dict, dict) -> List[blobxfer.models.download.Specification] """Create a list of Download Specification objects from configuration :param dict ctx_cli_options: cli options :param dict config: config dict :rtype: list :return: l...
Create a list of Download Specification objects from configuration :param dict ctx_cli_options: cli options :param dict config: config dict :rtype: list :return: list of Download Specification objects
Below is the the instruction that describes the task: ### Input: Create a list of Download Specification objects from configuration :param dict ctx_cli_options: cli options :param dict config: config dict :rtype: list :return: list of Download Specification objects ### Response: def create_download...
def extract_grid(self, longmin, longmax, latmin, latmax): ''' Extract part of the image ``img`` Args: longmin (float): Minimum longitude of the window longmax (float): Maximum longitude of the window latmin (float): Minimum latitude of the window latmax (...
Extract part of the image ``img`` Args: longmin (float): Minimum longitude of the window longmax (float): Maximum longitude of the window latmin (float): Minimum latitude of the window latmax (float): Maximum latitude of the window Returns: A...
Below is the the instruction that describes the task: ### Input: Extract part of the image ``img`` Args: longmin (float): Minimum longitude of the window longmax (float): Maximum longitude of the window latmin (float): Minimum latitude of the window latmax (f...
def min(self, axis=None, dtype=None, out=None, keepdims=False): """Return the minimum of ``self``. See Also -------- numpy.amin max """ return self.elem.__array_ufunc__( np.minimum, 'reduce', self.elem, axis=axis, dtype=dtype, out=(out,), ...
Return the minimum of ``self``. See Also -------- numpy.amin max
Below is the the instruction that describes the task: ### Input: Return the minimum of ``self``. See Also -------- numpy.amin max ### Response: def min(self, axis=None, dtype=None, out=None, keepdims=False): """Return the minimum of ``self``. See Also -----...
def default_mp_batchify_fn(data): """Collate data into batch. Use shared memory for stacking.""" if isinstance(data[0], nd.NDArray): out = nd.empty((len(data),) + data[0].shape, dtype=data[0].dtype, ctx=context.Context('cpu_shared', 0)) return nd.stack(*data, out=out) ...
Collate data into batch. Use shared memory for stacking.
Below is the the instruction that describes the task: ### Input: Collate data into batch. Use shared memory for stacking. ### Response: def default_mp_batchify_fn(data): """Collate data into batch. Use shared memory for stacking.""" if isinstance(data[0], nd.NDArray): out = nd.empty((len(data),) + ...
def show_task(successful_transfers, task_id): """ Executor for `globus task show` """ client = get_client() if successful_transfers: print_successful_transfers(client, task_id) else: print_task_detail(client, task_id)
Executor for `globus task show`
Below is the the instruction that describes the task: ### Input: Executor for `globus task show` ### Response: def show_task(successful_transfers, task_id): """ Executor for `globus task show` """ client = get_client() if successful_transfers: print_successful_transfers(client, task_id...
def _ReadMakefileAm(self): """Reads Makefile.am to initialize the project information.""" if not self.library_name: raise RuntimeError("Missing library name") file_object = open("Makefile.am", "rb") if not file_object: raise IOError("Unable to open: Makefile.am") found_subdirs = False ...
Reads Makefile.am to initialize the project information.
Below is the the instruction that describes the task: ### Input: Reads Makefile.am to initialize the project information. ### Response: def _ReadMakefileAm(self): """Reads Makefile.am to initialize the project information.""" if not self.library_name: raise RuntimeError("Missing library name") f...