code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def append_sources_from(self, other):
"""Merge the source alias lists of two CatDicts."""
# Get aliases lists from this `CatDict` and other
self_aliases = self[self._KEYS.SOURCE].split(',')
other_aliases = other[self._KEYS.SOURCE].split(',')
# Store alias to `self`
self[... | Merge the source alias lists of two CatDicts. | Below is the the instruction that describes the task:
### Input:
Merge the source alias lists of two CatDicts.
### Response:
def append_sources_from(self, other):
"""Merge the source alias lists of two CatDicts."""
# Get aliases lists from this `CatDict` and other
self_aliases = self[self._... |
def _parse_tile_url(tile_url):
""" Extracts tile name, data and AWS index from tile URL
:param tile_url: Location of tile at AWS
:type: tile_url: str
:return: Tuple in a form (tile_name, date, aws_index)
:rtype: (str, str, int)
"""
props = tile_url.rsplit('/', 7)... | Extracts tile name, data and AWS index from tile URL
:param tile_url: Location of tile at AWS
:type: tile_url: str
:return: Tuple in a form (tile_name, date, aws_index)
:rtype: (str, str, int) | Below is the the instruction that describes the task:
### Input:
Extracts tile name, data and AWS index from tile URL
:param tile_url: Location of tile at AWS
:type: tile_url: str
:return: Tuple in a form (tile_name, date, aws_index)
:rtype: (str, str, int)
### Response:
def _parse... |
async def remove(self) -> bool:
"""
Remove serialized wallet, best effort, if it exists. Return whether wallet absent after operation
(removal successful or else not present a priori).
Raise WalletState if wallet is open.
:return: whether wallet gone from persistent storage
... | Remove serialized wallet, best effort, if it exists. Return whether wallet absent after operation
(removal successful or else not present a priori).
Raise WalletState if wallet is open.
:return: whether wallet gone from persistent storage | Below is the the instruction that describes the task:
### Input:
Remove serialized wallet, best effort, if it exists. Return whether wallet absent after operation
(removal successful or else not present a priori).
Raise WalletState if wallet is open.
:return: whether wallet gone from persi... |
def get_ir(cfg_func):
"""
Converts the given CFG function into IR entities
"""
ir_func = ir.Function()
ir_var_list = []
cfg_var_list = []
ir_bb_label_list = []
for cfg_var in cfg_func.variable_list:
ir_var = ir.Variable(cfg_var.name)
ir_var_list.append(ir_var)
cfg... | Converts the given CFG function into IR entities | Below is the the instruction that describes the task:
### Input:
Converts the given CFG function into IR entities
### Response:
def get_ir(cfg_func):
"""
Converts the given CFG function into IR entities
"""
ir_func = ir.Function()
ir_var_list = []
cfg_var_list = []
ir_bb_label_list = []... |
def avail_images(kwargs=None, call=None):
'''
Return a dict of all available VM images on the cloud provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
... | Return a dict of all available VM images on the cloud provider. | Below is the the instruction that describes the task:
### Input:
Return a dict of all available VM images on the cloud provider.
### Response:
def avail_images(kwargs=None, call=None):
'''
Return a dict of all available VM images on the cloud provider.
'''
if call == 'action':
raise SaltClo... |
def delete(self, url=None, post_data={}, parse_data=False, key=None, parameters=None):
""" Issue a PUT request.
Kwargs:
url (str): Destination URL
post_data (dict): Dictionary of parameter and values
parse_data (bool): If true, parse response data
key (st... | Issue a PUT request.
Kwargs:
url (str): Destination URL
post_data (dict): Dictionary of parameter and values
parse_data (bool): If true, parse response data
key (string): If parse_data==True, look for this key when parsing data
parameters (dict): Addi... | Below is the the instruction that describes the task:
### Input:
Issue a PUT request.
Kwargs:
url (str): Destination URL
post_data (dict): Dictionary of parameter and values
parse_data (bool): If true, parse response data
key (string): If parse_data==True, lo... |
def __setup_fileserver(self):
'''
Set the local file objects from the file server interface
'''
# Avoid circular import
import salt.fileserver
self.fs_ = salt.fileserver.Fileserver(self.opts)
self._serve_file = self.fs_.serve_file
self._file_find = self.fs... | Set the local file objects from the file server interface | Below is the the instruction that describes the task:
### Input:
Set the local file objects from the file server interface
### Response:
def __setup_fileserver(self):
'''
Set the local file objects from the file server interface
'''
# Avoid circular import
import salt.filese... |
def _from_jd_schematic(jd, method):
'''Convert from JD using various leap-year calculation methods'''
if jd < EPOCH:
raise ValueError("Can't convert days before the French Revolution")
# days since Epoch
J = trunc(jd) + 0.5 - EPOCH
y0, y1, y2, y3, y4, y5 = 0, 0, 0, 0, 0, 0
intercal_cyc... | Convert from JD using various leap-year calculation methods | Below is the the instruction that describes the task:
### Input:
Convert from JD using various leap-year calculation methods
### Response:
def _from_jd_schematic(jd, method):
'''Convert from JD using various leap-year calculation methods'''
if jd < EPOCH:
raise ValueError("Can't convert days before... |
def filename(self):
"""
Filename from which this image part was originally created. A generic
name, e.g. 'image.png', is substituted if no name is available, for
example when the image was loaded from an unnamed stream. In that
case a default extension is applied based on the det... | Filename from which this image part was originally created. A generic
name, e.g. 'image.png', is substituted if no name is available, for
example when the image was loaded from an unnamed stream. In that
case a default extension is applied based on the detected MIME type
of the image. | Below is the the instruction that describes the task:
### Input:
Filename from which this image part was originally created. A generic
name, e.g. 'image.png', is substituted if no name is available, for
example when the image was loaded from an unnamed stream. In that
case a default extensio... |
def formula(self, atom_sequence):
'''
Constructs standardized chemical formula
NB: this is the PUBLIC method
@returns formula_str
'''
labels = {}
types = []
y = 0
for k, atomi in enumerate(atom_sequence):
lbl = re.sub("[0-9]+", "", atom... | Constructs standardized chemical formula
NB: this is the PUBLIC method
@returns formula_str | Below is the the instruction that describes the task:
### Input:
Constructs standardized chemical formula
NB: this is the PUBLIC method
@returns formula_str
### Response:
def formula(self, atom_sequence):
'''
Constructs standardized chemical formula
NB: this is the PUBLIC me... |
def _flush(self):
"""Purges the buffer and commits all pending values into the estimator."""
self._buffer.sort()
self._replace_batch()
self._buffer = []
self._compress() | Purges the buffer and commits all pending values into the estimator. | Below is the the instruction that describes the task:
### Input:
Purges the buffer and commits all pending values into the estimator.
### Response:
def _flush(self):
"""Purges the buffer and commits all pending values into the estimator."""
self._buffer.sort()
self._replace_batch()
... |
def match(self, filename, isdir=False):
"""
Match all the #IgnoreList#s` in this collection. Returns one of
- #MATCH_DEFAULT
- #MATCH_IGNORE
- #MATCH_INCLUDE
"""
for lst in self:
result = lst.match(filename, isdir)
if result != MATCH_DEFAULT:
return result
return MA... | Match all the #IgnoreList#s` in this collection. Returns one of
- #MATCH_DEFAULT
- #MATCH_IGNORE
- #MATCH_INCLUDE | Below is the the instruction that describes the task:
### Input:
Match all the #IgnoreList#s` in this collection. Returns one of
- #MATCH_DEFAULT
- #MATCH_IGNORE
- #MATCH_INCLUDE
### Response:
def match(self, filename, isdir=False):
"""
Match all the #IgnoreList#s` in this collection. Returns ... |
def get_asm_uids(taxon_uid):
"""Returns a set of NCBI UIDs associated with the passed taxon.
This query at NCBI returns all assemblies for the taxon subtree
rooted at the passed taxon_uid.
"""
query = "txid%s[Organism:exp]" % taxon_uid
logger.info("Entrez ESearch with query: %s", query)
# ... | Returns a set of NCBI UIDs associated with the passed taxon.
This query at NCBI returns all assemblies for the taxon subtree
rooted at the passed taxon_uid. | Below is the the instruction that describes the task:
### Input:
Returns a set of NCBI UIDs associated with the passed taxon.
This query at NCBI returns all assemblies for the taxon subtree
rooted at the passed taxon_uid.
### Response:
def get_asm_uids(taxon_uid):
"""Returns a set of NCBI UIDs associa... |
def discoverable(dev):
'''
Enable this bluetooth device to be discoverable.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.discoverable hci0
'''
if dev not in address_():
raise CommandExecutionError(
'Invalid dev passed to bluetooth.discoverable'
)
... | Enable this bluetooth device to be discoverable.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.discoverable hci0 | Below is the the instruction that describes the task:
### Input:
Enable this bluetooth device to be discoverable.
CLI Example:
.. code-block:: bash
salt '*' bluetooth.discoverable hci0
### Response:
def discoverable(dev):
'''
Enable this bluetooth device to be discoverable.
CLI Exam... |
def duration(self):
"""
Return a timedelta for this task.
Measure the time between this task's start and end time, or "now"
if the task has not yet finished.
:returns: timedelta object, or None if the task has not even started.
"""
if not self.started:
... | Return a timedelta for this task.
Measure the time between this task's start and end time, or "now"
if the task has not yet finished.
:returns: timedelta object, or None if the task has not even started. | Below is the the instruction that describes the task:
### Input:
Return a timedelta for this task.
Measure the time between this task's start and end time, or "now"
if the task has not yet finished.
:returns: timedelta object, or None if the task has not even started.
### Response:
def du... |
def download_vod(self, video_id):
"""
This will return a byte string of the M3U8 playlist data
(which contains more links to segments of the vod)
"""
vod_id = video_id[1:]
token = self._request_get(
'vods/{}/access_token'.format(vod_id), url='https://api.twitc... | This will return a byte string of the M3U8 playlist data
(which contains more links to segments of the vod) | Below is the the instruction that describes the task:
### Input:
This will return a byte string of the M3U8 playlist data
(which contains more links to segments of the vod)
### Response:
def download_vod(self, video_id):
"""
This will return a byte string of the M3U8 playlist data
(... |
def _read_next(ctx: ReaderContext) -> LispReaderForm: # noqa: C901
"""Read the next full form from the input stream."""
reader = ctx.reader
token = reader.peek()
if token == "(":
return _read_list(ctx)
elif token == "[":
return _read_vector(ctx)
elif token == "{":
return... | Read the next full form from the input stream. | Below is the the instruction that describes the task:
### Input:
Read the next full form from the input stream.
### Response:
def _read_next(ctx: ReaderContext) -> LispReaderForm: # noqa: C901
"""Read the next full form from the input stream."""
reader = ctx.reader
token = reader.peek()
if token =... |
def insert_fft_options(optgroup):
"""
Inserts the options that affect the behavior of this backend
Parameters
----------
optgroup: fft_option
OptionParser argument group whose options are extended
"""
optgroup.add_argument("--fftw-measure-level",
help="Determine... | Inserts the options that affect the behavior of this backend
Parameters
----------
optgroup: fft_option
OptionParser argument group whose options are extended | Below is the the instruction that describes the task:
### Input:
Inserts the options that affect the behavior of this backend
Parameters
----------
optgroup: fft_option
OptionParser argument group whose options are extended
### Response:
def insert_fft_options(optgroup):
"""
Inserts the... |
def relative_position_of(self, other):
"""
Return the position of the given other time interval,
relative to this time interval,
as a ``RELATIVE_POSITION_*`` constant.
:param other: the other interval
:type other: :class:`~aeneas.exacttiming.TimeInterval`
:rtype... | Return the position of the given other time interval,
relative to this time interval,
as a ``RELATIVE_POSITION_*`` constant.
:param other: the other interval
:type other: :class:`~aeneas.exacttiming.TimeInterval`
:rtype: int | Below is the the instruction that describes the task:
### Input:
Return the position of the given other time interval,
relative to this time interval,
as a ``RELATIVE_POSITION_*`` constant.
:param other: the other interval
:type other: :class:`~aeneas.exacttiming.TimeInterval`
... |
def list(self, **kwargs):
"""
List secrets. Similar to the ``docker secret ls`` command.
Args:
filters (dict): Server-side list filtering options.
Returns:
(list of :py:class:`Secret`): The secrets.
Raises:
:py:class:`docker.errors.APIError`... | List secrets. Similar to the ``docker secret ls`` command.
Args:
filters (dict): Server-side list filtering options.
Returns:
(list of :py:class:`Secret`): The secrets.
Raises:
:py:class:`docker.errors.APIError`
If the server returns an erro... | Below is the the instruction that describes the task:
### Input:
List secrets. Similar to the ``docker secret ls`` command.
Args:
filters (dict): Server-side list filtering options.
Returns:
(list of :py:class:`Secret`): The secrets.
Raises:
:py:class:`... |
def shutdown(self, prompt=False):
"""
Shut down the server.
This method checks if the H2O cluster is still running, and if it does shuts it down (via a REST API call).
:param prompt: A logical value indicating whether to prompt the user before shutting down the H2O server.
"""
... | Shut down the server.
This method checks if the H2O cluster is still running, and if it does shuts it down (via a REST API call).
:param prompt: A logical value indicating whether to prompt the user before shutting down the H2O server. | Below is the the instruction that describes the task:
### Input:
Shut down the server.
This method checks if the H2O cluster is still running, and if it does shuts it down (via a REST API call).
:param prompt: A logical value indicating whether to prompt the user before shutting down the H2O serve... |
def parse(self):
"""Apply search template."""
self.verbose = bool(self.re_verbose)
self.version = self.re_version if self.re_version else _regex.DEFAULT_VERSION
self.global_flag_swap = {
"version": self.re_version != 0,
"verbose": False
}
self.tem... | Apply search template. | Below is the the instruction that describes the task:
### Input:
Apply search template.
### Response:
def parse(self):
"""Apply search template."""
self.verbose = bool(self.re_verbose)
self.version = self.re_version if self.re_version else _regex.DEFAULT_VERSION
self.global_flag_sw... |
def _authenticate(self):
"""
Authenticate with the API and return an authentication token.
"""
auth_url = BASE_URL + "/auth/token"
payload = {'username': self.email, 'password': self.password, 'grant_type': 'password'}
arequest = requests.post(auth_url, data=payload, head... | Authenticate with the API and return an authentication token. | Below is the the instruction that describes the task:
### Input:
Authenticate with the API and return an authentication token.
### Response:
def _authenticate(self):
"""
Authenticate with the API and return an authentication token.
"""
auth_url = BASE_URL + "/auth/token"
pay... |
def CheckPrintf(filename, clean_lines, linenum, error):
"""Check for printf related issues.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
l... | Check for printf related issues.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found. | Below is the the instruction that describes the task:
### Input:
Check for printf related issues.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
#... |
def set_pubkey(self, pkey):
"""
Set the public key of the certificate signing request.
:param pkey: The public key to use.
:type pkey: :py:class:`PKey`
:return: ``None``
"""
set_result = _lib.X509_REQ_set_pubkey(self._req, pkey._pkey)
_openssl_assert(set... | Set the public key of the certificate signing request.
:param pkey: The public key to use.
:type pkey: :py:class:`PKey`
:return: ``None`` | Below is the the instruction that describes the task:
### Input:
Set the public key of the certificate signing request.
:param pkey: The public key to use.
:type pkey: :py:class:`PKey`
:return: ``None``
### Response:
def set_pubkey(self, pkey):
"""
Set the public key of th... |
def disambiguate(self, words):
"""Disambiguate previously analyzed words.
Parameters
----------
words: list of dict
A sentence of words.
Returns
-------
list of dict
Sentence of disambiguated words.
"""
words = vm.Sentence... | Disambiguate previously analyzed words.
Parameters
----------
words: list of dict
A sentence of words.
Returns
-------
list of dict
Sentence of disambiguated words. | Below is the the instruction that describes the task:
### Input:
Disambiguate previously analyzed words.
Parameters
----------
words: list of dict
A sentence of words.
Returns
-------
list of dict
Sentence of disambiguated words.
### Response... |
def sg_float(tensor, opt):
r"""Casts a tensor to floatx.
See `tf.cast()` in tensorflow.
Args:
tensor: A `Tensor` or `SparseTensor` (automatically given by chain).
opt:
name : If provided, it replaces current tensor's name
Returns:
A `Tensor` or `SparseTensor` with same s... | r"""Casts a tensor to floatx.
See `tf.cast()` in tensorflow.
Args:
tensor: A `Tensor` or `SparseTensor` (automatically given by chain).
opt:
name : If provided, it replaces current tensor's name
Returns:
A `Tensor` or `SparseTensor` with same shape as `tensor`. | Below is the the instruction that describes the task:
### Input:
r"""Casts a tensor to floatx.
See `tf.cast()` in tensorflow.
Args:
tensor: A `Tensor` or `SparseTensor` (automatically given by chain).
opt:
name : If provided, it replaces current tensor's name
Returns:
A ... |
def _toSKLGLM(self, model, is_classifier):
""" Private method for converting a GLM to a scikit-learn model
TODO: Add model parameters as well.
"""
py_cls = type(model)
skl_cls = self._spark2skl_classes[py_cls]
intercept = model.intercept
weights = model.coefficien... | Private method for converting a GLM to a scikit-learn model
TODO: Add model parameters as well. | Below is the the instruction that describes the task:
### Input:
Private method for converting a GLM to a scikit-learn model
TODO: Add model parameters as well.
### Response:
def _toSKLGLM(self, model, is_classifier):
""" Private method for converting a GLM to a scikit-learn model
TODO: Add... |
def redirect_resolver(resolver, path):
'''Resolves environment from .cpenv file...recursively walks up the tree
in attempt to find a .cpenv file'''
if not os.path.exists(path):
raise ResolveError
if os.path.isfile(path):
path = os.path.dirname(path)
for root, _, _ in walk_up(path)... | Resolves environment from .cpenv file...recursively walks up the tree
in attempt to find a .cpenv file | Below is the the instruction that describes the task:
### Input:
Resolves environment from .cpenv file...recursively walks up the tree
in attempt to find a .cpenv file
### Response:
def redirect_resolver(resolver, path):
'''Resolves environment from .cpenv file...recursively walks up the tree
in attemp... |
def reduce(self, func, **kwargs):
"""Reduce the items in this group by applying `func` along some
dimension(s).
Parameters
----------
func : function
Function which can be called in the form
`func(x, **kwargs)` to return the result of collapsing an
... | Reduce the items in this group by applying `func` along some
dimension(s).
Parameters
----------
func : function
Function which can be called in the form
`func(x, **kwargs)` to return the result of collapsing an
np.ndarray over an the rolling dimensio... | Below is the the instruction that describes the task:
### Input:
Reduce the items in this group by applying `func` along some
dimension(s).
Parameters
----------
func : function
Function which can be called in the form
`func(x, **kwargs)` to return the result... |
def contains(self, index: Union[SchemaKey, int, str]) -> bool:
"""
Return whether the cache contains a schema for the input key, sequence number, or schema identifier.
:param index: schema key, sequence number, or sequence identifier
:return: whether the cache contains a schema for the ... | Return whether the cache contains a schema for the input key, sequence number, or schema identifier.
:param index: schema key, sequence number, or sequence identifier
:return: whether the cache contains a schema for the input index | Below is the the instruction that describes the task:
### Input:
Return whether the cache contains a schema for the input key, sequence number, or schema identifier.
:param index: schema key, sequence number, or sequence identifier
:return: whether the cache contains a schema for the input index
##... |
def select_row(self, steps):
"""Select row in list widget based on a number of steps with direction.
Steps can be positive (next rows) or negative (previous rows).
"""
row = self.current_row() + steps
if 0 <= row < self.count():
self.set_current_row(row) | Select row in list widget based on a number of steps with direction.
Steps can be positive (next rows) or negative (previous rows). | Below is the the instruction that describes the task:
### Input:
Select row in list widget based on a number of steps with direction.
Steps can be positive (next rows) or negative (previous rows).
### Response:
def select_row(self, steps):
"""Select row in list widget based on a number of steps wi... |
def get_group_name_nonetrick(self, group_name = None):
""" In all getter function in case of single payment group, group_name can be None """
groups = self.m["groups"]
if (len(groups) == 0):
raise Exception("Cannot find any groups in metadata")
if (not group_name):
... | In all getter function in case of single payment group, group_name can be None | Below is the the instruction that describes the task:
### Input:
In all getter function in case of single payment group, group_name can be None
### Response:
def get_group_name_nonetrick(self, group_name = None):
""" In all getter function in case of single payment group, group_name can be None """
... |
def represent_bool(self, data):
"""Represent bool as 'yes' or 'no' instead of 'true' or 'false'.
"""
if data:
value = u'yes'
else:
value = u'no'
return self.represent_scalar('tag:yaml.org,2002:bool', value) | Represent bool as 'yes' or 'no' instead of 'true' or 'false'. | Below is the the instruction that describes the task:
### Input:
Represent bool as 'yes' or 'no' instead of 'true' or 'false'.
### Response:
def represent_bool(self, data):
"""Represent bool as 'yes' or 'no' instead of 'true' or 'false'.
"""
if data:
value = u'yes'
else:... |
def execute(self, try_limit=5, try_interval=0.5, timeout=30):
"""
Execute this query, retrying based on the supplied parameters.
Keyword Args:
try_limit (int): The number of times to retry the query.
try_interval (float): The number of seconds to wait between each try (f... | Execute this query, retrying based on the supplied parameters.
Keyword Args:
try_limit (int): The number of times to retry the query.
try_interval (float): The number of seconds to wait between each try (float).
timeout (float): The maximum number of seconds to spend retryin... | Below is the the instruction that describes the task:
### Input:
Execute this query, retrying based on the supplied parameters.
Keyword Args:
try_limit (int): The number of times to retry the query.
try_interval (float): The number of seconds to wait between each try (float).
... |
def render_template(request, app, template_name, context=None, subdir="templates", def_name=None):
'''
Convenience method that directly renders a template, given the app and template names.
'''
return get_template(app, template_name, subdir).render(context, request, def_name) | Convenience method that directly renders a template, given the app and template names. | Below is the the instruction that describes the task:
### Input:
Convenience method that directly renders a template, given the app and template names.
### Response:
def render_template(request, app, template_name, context=None, subdir="templates", def_name=None):
'''
Convenience method that directly rende... |
def parse_arguments(lexer: Lexer, is_const: bool) -> List[ArgumentNode]:
"""Arguments[Const]: (Argument[?Const]+)"""
item = parse_const_argument if is_const else parse_argument
return (
cast(
List[ArgumentNode],
many_nodes(lexer, TokenKind.PAREN_L, item, TokenKind.PAREN_R),
... | Arguments[Const]: (Argument[?Const]+) | Below is the the instruction that describes the task:
### Input:
Arguments[Const]: (Argument[?Const]+)
### Response:
def parse_arguments(lexer: Lexer, is_const: bool) -> List[ArgumentNode]:
"""Arguments[Const]: (Argument[?Const]+)"""
item = parse_const_argument if is_const else parse_argument
return (
... |
def add_sitemap_urls(self, rp, url_data, roboturl):
"""Add sitemap URLs to queue."""
if not rp.sitemap_urls or not url_data.allows_simple_recursion():
return
for sitemap_url, line in rp.sitemap_urls:
url_data.add_url(sitemap_url, line=line) | Add sitemap URLs to queue. | Below is the the instruction that describes the task:
### Input:
Add sitemap URLs to queue.
### Response:
def add_sitemap_urls(self, rp, url_data, roboturl):
"""Add sitemap URLs to queue."""
if not rp.sitemap_urls or not url_data.allows_simple_recursion():
return
for sitemap_url... |
def _build_sectors_and_pages(self, keep_unwritten):
"""! @brief Converts the list of flash operations to flash sectors and pages.
@param self
@param keep_unwritten If true, unwritten pages in an erased sector and unwritten
contents of a modified page will be read from the ta... | ! @brief Converts the list of flash operations to flash sectors and pages.
@param self
@param keep_unwritten If true, unwritten pages in an erased sector and unwritten
contents of a modified page will be read from the target and added to the data to be
programmed.
... | Below is the the instruction that describes the task:
### Input:
! @brief Converts the list of flash operations to flash sectors and pages.
@param self
@param keep_unwritten If true, unwritten pages in an erased sector and unwritten
contents of a modified page will be read from ... |
def prospective_prov(self, job):
# type: (Any) -> None
"""Create prospective prov recording as wfdesc prov:Plan."""
if not hasattr(job, "steps"):
# direct command line tool execution
self.document.entity(
"wf:main", {provM.PROV_TYPE: WFDESC["Process"],
... | Create prospective prov recording as wfdesc prov:Plan. | Below is the the instruction that describes the task:
### Input:
Create prospective prov recording as wfdesc prov:Plan.
### Response:
def prospective_prov(self, job):
# type: (Any) -> None
"""Create prospective prov recording as wfdesc prov:Plan."""
if not hasattr(job, "steps"):
... |
def read(self, key, array=False, embedded=True):
"""Read method of CRUD operation for working with KeyValue DB.
This method will automatically check to see if a single variable is passed
or if "mixed" data is passed and return the results from the DB. It will also
automatically determin... | Read method of CRUD operation for working with KeyValue DB.
This method will automatically check to see if a single variable is passed
or if "mixed" data is passed and return the results from the DB. It will also
automatically determine the variable type to read.
Args:
key ... | Below is the the instruction that describes the task:
### Input:
Read method of CRUD operation for working with KeyValue DB.
This method will automatically check to see if a single variable is passed
or if "mixed" data is passed and return the results from the DB. It will also
automatically... |
def plot_iv_curve(a, hold_v, i, *plt_args, **plt_kwargs):
"""A single IV curve"""
grid = plt_kwargs.pop('grid',True)
same_fig = plt_kwargs.pop('same_fig',False)
if not len(plt_args):
plt_args = ('ko-',)
if 'label' not in plt_kwargs:
plt_kwargs['label'] = 'Current'
if not sa... | A single IV curve | Below is the the instruction that describes the task:
### Input:
A single IV curve
### Response:
def plot_iv_curve(a, hold_v, i, *plt_args, **plt_kwargs):
"""A single IV curve"""
grid = plt_kwargs.pop('grid',True)
same_fig = plt_kwargs.pop('same_fig',False)
if not len(plt_args):
plt_ar... |
def run_query(
self, project_id, partition_id, read_options=None, query=None, gql_query=None
):
"""Perform a ``runQuery`` request.
:type project_id: str
:param project_id: The project to connect to. This is
usually your project name in the cloud console.
... | Perform a ``runQuery`` request.
:type project_id: str
:param project_id: The project to connect to. This is
usually your project name in the cloud console.
:type partition_id: :class:`.entity_pb2.PartitionId`
:param partition_id: Partition ID corresponding to... | Below is the the instruction that describes the task:
### Input:
Perform a ``runQuery`` request.
:type project_id: str
:param project_id: The project to connect to. This is
usually your project name in the cloud console.
:type partition_id: :class:`.entity_pb2.Pa... |
def Heartbeat(self):
"""Writes a heartbeat to the registry."""
service_key = _GetServiceKey()
try:
winreg.SetValueEx(service_key, "Nanny.heartbeat", 0, winreg.REG_DWORD,
int(time.time()))
except OSError as e:
logging.debug("Failed to heartbeat nanny at %s: %s", servic... | Writes a heartbeat to the registry. | Below is the the instruction that describes the task:
### Input:
Writes a heartbeat to the registry.
### Response:
def Heartbeat(self):
"""Writes a heartbeat to the registry."""
service_key = _GetServiceKey()
try:
winreg.SetValueEx(service_key, "Nanny.heartbeat", 0, winreg.REG_DWORD,
... |
def package(self):
"""Packages lambda data for deployment into a zip"""
logger.info('Packaging lambda {}'.format(self.lambda_name))
zfh = io.BytesIO()
if os.path.exists(os.path.join(self.lambda_dir, '.env')):
logger.warn(
'A .env file exists in your Lambda di... | Packages lambda data for deployment into a zip | Below is the the instruction that describes the task:
### Input:
Packages lambda data for deployment into a zip
### Response:
def package(self):
"""Packages lambda data for deployment into a zip"""
logger.info('Packaging lambda {}'.format(self.lambda_name))
zfh = io.BytesIO()
if os... |
def run_forever(
lcdproc='', mpd='', lcdproc_screen=DEFAULT_LCD_SCREEN_NAME,
lcdproc_charset=DEFAULT_LCDPROC_CHARSET,
lcdd_debug=False,
pattern='', patterns=[],
refresh=DEFAULT_REFRESH,
backlight_on=DEFAULT_BACKLIGHT_ON,
priority_playing=DEFAULT_PRIORITY,
... | Run the server.
Args:
lcdproc (str): the target connection (host:port) for lcdproc
mpd (str): the target connection ([pwd@]host:port) for mpd
lcdproc_screen (str): the name of the screen to use for lcdproc
lcdproc_charset (str): the charset to use with lcdproc
lcdd_debug (bo... | Below is the the instruction that describes the task:
### Input:
Run the server.
Args:
lcdproc (str): the target connection (host:port) for lcdproc
mpd (str): the target connection ([pwd@]host:port) for mpd
lcdproc_screen (str): the name of the screen to use for lcdproc
lcdproc_... |
def shell(self):
"""
Spawn a debug shell.
"""
click.echo(click.style("NOTICE!", fg="yellow", bold=True) + " This is a " + click.style("local", fg="green", bold=True) + " shell, inside a " + click.style("Zappa", bold=True) + " object!")
self.zappa.shell()
return | Spawn a debug shell. | Below is the the instruction that describes the task:
### Input:
Spawn a debug shell.
### Response:
def shell(self):
"""
Spawn a debug shell.
"""
click.echo(click.style("NOTICE!", fg="yellow", bold=True) + " This is a " + click.style("local", fg="green", bold=True) + " shell, inside... |
def set_group_info(self, group_name, group_number, insertion_code,
group_type, atom_count, bond_count, single_letter_code,
sequence_index, secondary_structure_type):
"""Set the information for a group
:param group_name: the name of this group,e.g. LYS
... | Set the information for a group
:param group_name: the name of this group,e.g. LYS
:param group_number: the residue number of this group
:param insertion_code: the insertion code for this group
:param group_type: a string indicating the type of group (as found in the chemcomp dictionary.... | Below is the the instruction that describes the task:
### Input:
Set the information for a group
:param group_name: the name of this group,e.g. LYS
:param group_number: the residue number of this group
:param insertion_code: the insertion code for this group
:param group_type: a stri... |
def ResetHandler(self, name):
'''
Method which assigns handler to the tag encountered before the current, or else
sets it to None
:param name: name of the latest tag
:return:
'''
if name in self.tags:
if len(self.tags) > 1:
key = len(... | Method which assigns handler to the tag encountered before the current, or else
sets it to None
:param name: name of the latest tag
:return: | Below is the the instruction that describes the task:
### Input:
Method which assigns handler to the tag encountered before the current, or else
sets it to None
:param name: name of the latest tag
:return:
### Response:
def ResetHandler(self, name):
'''
Method which assign... |
def _onKeyUp(self, evt):
"""Release key."""
key = self._get_key(evt)
#print 'release key', key
evt.Skip()
FigureCanvasBase.key_release_event(self, key, guiEvent=evt) | Release key. | Below is the the instruction that describes the task:
### Input:
Release key.
### Response:
def _onKeyUp(self, evt):
"""Release key."""
key = self._get_key(evt)
#print 'release key', key
evt.Skip()
FigureCanvasBase.key_release_event(self, key, guiEvent=evt) |
def value(self):
"""
A tuple of values. This attribute can be set with any iterable; the
iterable is then evaluated into a tuple and stored at the bound field.
Whenever values are written to this attribute, they are passed through
the :meth:`~.AbstractCDataType.coerce` method of... | A tuple of values. This attribute can be set with any iterable; the
iterable is then evaluated into a tuple and stored at the bound field.
Whenever values are written to this attribute, they are passed through
the :meth:`~.AbstractCDataType.coerce` method of the
:attr:`~.AbstractField.t... | Below is the the instruction that describes the task:
### Input:
A tuple of values. This attribute can be set with any iterable; the
iterable is then evaluated into a tuple and stored at the bound field.
Whenever values are written to this attribute, they are passed through
the :meth:`~.Abs... |
def select_lasso(self, expression_x, expression_y, xsequence, ysequence, mode="replace", name="default", executor=None):
"""For performance reasons, a lasso selection is handled differently.
:param str expression_x: Name/expression for the x coordinate
:param str expression_y: Name/expression f... | For performance reasons, a lasso selection is handled differently.
:param str expression_x: Name/expression for the x coordinate
:param str expression_y: Name/expression for the y coordinate
:param xsequence: list of x numbers defining the lasso, together with y
:param ysequence:
... | Below is the the instruction that describes the task:
### Input:
For performance reasons, a lasso selection is handled differently.
:param str expression_x: Name/expression for the x coordinate
:param str expression_y: Name/expression for the y coordinate
:param xsequence: list of x numbers... |
def calc_structured_append_parity(content):
"""\
Calculates the parity data for the Structured Append mode.
:param str content: The content.
:rtype: int
"""
if not isinstance(content, str_type):
content = str(content)
try:
data = content.encode('iso-8859-1')
except Unico... | \
Calculates the parity data for the Structured Append mode.
:param str content: The content.
:rtype: int | Below is the the instruction that describes the task:
### Input:
\
Calculates the parity data for the Structured Append mode.
:param str content: The content.
:rtype: int
### Response:
def calc_structured_append_parity(content):
"""\
Calculates the parity data for the Structured Append mode.
... |
def deselect_by_visible_text(self, text):
"""Deselect all options that display text matching the argument. That is, when given "Bar" this
would deselect an option like:
<option value="foo">Bar</option>
:Args:
- text - The visible text to match against
"""
... | Deselect all options that display text matching the argument. That is, when given "Bar" this
would deselect an option like:
<option value="foo">Bar</option>
:Args:
- text - The visible text to match against | Below is the the instruction that describes the task:
### Input:
Deselect all options that display text matching the argument. That is, when given "Bar" this
would deselect an option like:
<option value="foo">Bar</option>
:Args:
- text - The visible text to match again... |
def set_vo(vo):
"""
NAME:
set_vo
PURPOSE:
set the global configuration value of vo (velocity scale)
INPUT:
vo - scale in km/s or astropy Quantity
OUTPUT:
(none)
HISTORY:
2016-01-05 - Written - Bovy (UofT)
"""
if _APY_LOADED and isinstance(vo,units.Quant... | NAME:
set_vo
PURPOSE:
set the global configuration value of vo (velocity scale)
INPUT:
vo - scale in km/s or astropy Quantity
OUTPUT:
(none)
HISTORY:
2016-01-05 - Written - Bovy (UofT) | Below is the the instruction that describes the task:
### Input:
NAME:
set_vo
PURPOSE:
set the global configuration value of vo (velocity scale)
INPUT:
vo - scale in km/s or astropy Quantity
OUTPUT:
(none)
HISTORY:
2016-01-05 - Written - Bovy (UofT)
### Response:
... |
def backward(self, y):
r"""
Inverse of the softplus transform:
.. math::
x = \log( \exp(y) - 1)
The bound for the input y is [self._lower. inf[, self._lower is
subtracted prior to any calculations. The implementation avoids overflow
explicitly by applying the... | r"""
Inverse of the softplus transform:
.. math::
x = \log( \exp(y) - 1)
The bound for the input y is [self._lower. inf[, self._lower is
subtracted prior to any calculations. The implementation avoids overflow
explicitly by applying the log sum exp trick:
.. ... | Below is the the instruction that describes the task:
### Input:
r"""
Inverse of the softplus transform:
.. math::
x = \log( \exp(y) - 1)
The bound for the input y is [self._lower. inf[, self._lower is
subtracted prior to any calculations. The implementation avoids overf... |
def interactive_login():
"""
Force an interactive login via the command line.
Sets the global API key and updates the client auth.
"""
solvebio.access_token = None
solvebio.api_key = None
client.set_token()
domain, email, password = _ask_for_credentials()
if not all([domain, email, ... | Force an interactive login via the command line.
Sets the global API key and updates the client auth. | Below is the the instruction that describes the task:
### Input:
Force an interactive login via the command line.
Sets the global API key and updates the client auth.
### Response:
def interactive_login():
"""
Force an interactive login via the command line.
Sets the global API key and updates the ... |
def recv(self, x=BPF_BUFFER_LENGTH):
"""Receive a frame from the network"""
if self.buffered_frames():
# Get a frame from the buffer
return self.get_frame()
# Get data from BPF
try:
bpf_buffer = os.read(self.ins, x)
except EnvironmentError as... | Receive a frame from the network | Below is the the instruction that describes the task:
### Input:
Receive a frame from the network
### Response:
def recv(self, x=BPF_BUFFER_LENGTH):
"""Receive a frame from the network"""
if self.buffered_frames():
# Get a frame from the buffer
return self.get_frame()
... |
def on_before_transform_template(self, template_dict):
"""
Hook method that gets called before the SAM template is processed.
The template has pass the validation and is guaranteed to contain a non-empty "Resources" section.
:param dict template_dict: Dictionary of the SAM template
... | Hook method that gets called before the SAM template is processed.
The template has pass the validation and is guaranteed to contain a non-empty "Resources" section.
:param dict template_dict: Dictionary of the SAM template
:return: Nothing | Below is the the instruction that describes the task:
### Input:
Hook method that gets called before the SAM template is processed.
The template has pass the validation and is guaranteed to contain a non-empty "Resources" section.
:param dict template_dict: Dictionary of the SAM template
:r... |
def create_router(self, context, router):
"""Create a new router entry in DB, and create it Arista HW."""
# Add router to the DB
new_router = super(AristaL3ServicePlugin, self).create_router(
context,
router)
# create router on the Arista Hw
try:
... | Create a new router entry in DB, and create it Arista HW. | Below is the the instruction that describes the task:
### Input:
Create a new router entry in DB, and create it Arista HW.
### Response:
def create_router(self, context, router):
"""Create a new router entry in DB, and create it Arista HW."""
# Add router to the DB
new_router = super(Arist... |
def flipped(self):
"""Return the flipped version of this direction."""
forward, reverse = self.value
return self.__class__((reverse, forward)) | Return the flipped version of this direction. | Below is the the instruction that describes the task:
### Input:
Return the flipped version of this direction.
### Response:
def flipped(self):
"""Return the flipped version of this direction."""
forward, reverse = self.value
return self.__class__((reverse, forward)) |
def remove_ancestors_of(self, node):
"""Remove all of the ancestor operation nodes of node."""
if isinstance(node, int):
warnings.warn('Calling remove_ancestors_of() with a node id is deprecated,'
' use a DAGNode instead',
DeprecationWarnin... | Remove all of the ancestor operation nodes of node. | Below is the the instruction that describes the task:
### Input:
Remove all of the ancestor operation nodes of node.
### Response:
def remove_ancestors_of(self, node):
"""Remove all of the ancestor operation nodes of node."""
if isinstance(node, int):
warnings.warn('Calling remove_ances... |
def process_request(self, request):
"""
Lazy set user and token
"""
request.token = get_token(request)
request.user = SimpleLazyObject(lambda: get_user(request))
request._dont_enforce_csrf_checks = dont_enforce_csrf_checks(request) | Lazy set user and token | Below is the the instruction that describes the task:
### Input:
Lazy set user and token
### Response:
def process_request(self, request):
"""
Lazy set user and token
"""
request.token = get_token(request)
request.user = SimpleLazyObject(lambda: get_user(request))
re... |
def prune_influence_map(self):
"""Remove edges between rules causing problematic non-transitivity.
First, all self-loops are removed. After this initial step, edges are
removed between rules when they share *all* child nodes except for each
other; that is, they have a mutual relationshi... | Remove edges between rules causing problematic non-transitivity.
First, all self-loops are removed. After this initial step, edges are
removed between rules when they share *all* child nodes except for each
other; that is, they have a mutual relationship with each other and
share all of... | Below is the the instruction that describes the task:
### Input:
Remove edges between rules causing problematic non-transitivity.
First, all self-loops are removed. After this initial step, edges are
removed between rules when they share *all* child nodes except for each
other; that is, the... |
def request_examples(self, attack_config, criteria, run_counts, batch_size):
"""
Returns a numpy array of integer example indices to run in the next batch.
"""
raise NotImplementedError(str(type(self)) +
"needs to implement request_examples") | Returns a numpy array of integer example indices to run in the next batch. | Below is the the instruction that describes the task:
### Input:
Returns a numpy array of integer example indices to run in the next batch.
### Response:
def request_examples(self, attack_config, criteria, run_counts, batch_size):
"""
Returns a numpy array of integer example indices to run in the next batc... |
def do_rpc(self, name: str, rpc_function: Callable[..., Awaitable[None]]) -> Callable[..., Awaitable[None]]:
"""
Wraps a given RPC function by producing an awaitable function suitable to be run in the asyncio
event loop. The wrapped function catches all unhandled exceptions and reports them to t... | Wraps a given RPC function by producing an awaitable function suitable to be run in the asyncio
event loop. The wrapped function catches all unhandled exceptions and reports them to the exception
future, which consumers can await upon to listen for unhandled exceptions.
The wrapped function als... | Below is the the instruction that describes the task:
### Input:
Wraps a given RPC function by producing an awaitable function suitable to be run in the asyncio
event loop. The wrapped function catches all unhandled exceptions and reports them to the exception
future, which consumers can await upon ... |
def get_input_peer(entity, allow_self=True, check_hash=True):
"""
Gets the input peer for the given "entity" (user, chat or channel).
A ``TypeError`` is raised if the given entity isn't a supported type
or if ``check_hash is True`` but the entity's ``access_hash is None``.
Note that ``check_hash``... | Gets the input peer for the given "entity" (user, chat or channel).
A ``TypeError`` is raised if the given entity isn't a supported type
or if ``check_hash is True`` but the entity's ``access_hash is None``.
Note that ``check_hash`` **is ignored** if an input peer is already
passed since in that case ... | Below is the the instruction that describes the task:
### Input:
Gets the input peer for the given "entity" (user, chat or channel).
A ``TypeError`` is raised if the given entity isn't a supported type
or if ``check_hash is True`` but the entity's ``access_hash is None``.
Note that ``check_hash`` **is... |
def acceleration(self):
"""Return the acceleration in G's
:returns: Acceleration for every axis as a tuple
:Example:
>>> sensor = MPU6050I2C(gw)
>>> sensor.wakeup()
>>> sensor.acceleration()
(0.6279296875, 0.87890625, 1.1298828125)
"""
if not se... | Return the acceleration in G's
:returns: Acceleration for every axis as a tuple
:Example:
>>> sensor = MPU6050I2C(gw)
>>> sensor.wakeup()
>>> sensor.acceleration()
(0.6279296875, 0.87890625, 1.1298828125) | Below is the the instruction that describes the task:
### Input:
Return the acceleration in G's
:returns: Acceleration for every axis as a tuple
:Example:
>>> sensor = MPU6050I2C(gw)
>>> sensor.wakeup()
>>> sensor.acceleration()
(0.6279296875, 0.87890625, 1.1298828... |
def obtain_access_token(self):
"""Returns an OAuth 2 access token to make OAuth 2 authenticated
read-only calls.
:rtype: string
"""
if self.oauth_version != 2:
raise TwythonError('This method can only be called when your \
OAuth version... | Returns an OAuth 2 access token to make OAuth 2 authenticated
read-only calls.
:rtype: string | Below is the the instruction that describes the task:
### Input:
Returns an OAuth 2 access token to make OAuth 2 authenticated
read-only calls.
:rtype: string
### Response:
def obtain_access_token(self):
"""Returns an OAuth 2 access token to make OAuth 2 authenticated
read-only cal... |
def degree(self, degree_number, direction='a'):
"""Return the asked scale degree.
The direction of the scale is 'a' for ascending (default) and 'd'
for descending.
"""
if degree_number < 1:
raise RangeError("degree '%s' out of range" % degree_number)
if direc... | Return the asked scale degree.
The direction of the scale is 'a' for ascending (default) and 'd'
for descending. | Below is the the instruction that describes the task:
### Input:
Return the asked scale degree.
The direction of the scale is 'a' for ascending (default) and 'd'
for descending.
### Response:
def degree(self, degree_number, direction='a'):
"""Return the asked scale degree.
The dir... |
def get_utm_zone(longitude):
"""Return utm zone."""
zone = int((math.floor((longitude + 180.0) / 6.0) + 1) % 60)
if zone == 0:
zone = 60
return zone | Return utm zone. | Below is the the instruction that describes the task:
### Input:
Return utm zone.
### Response:
def get_utm_zone(longitude):
"""Return utm zone."""
zone = int((math.floor((longitude + 180.0) / 6.0) + 1) % 60)
if zone == 0:
zone = 60
return zone |
def make_valid_pyclipper(shape):
"""
Use the pyclipper library to "union" a polygon on its own. This operation
uses the even-odd rule to determine which points are in the interior of
the polygon, and can reconstruct the orientation of the polygon from that.
The pyclipper library is robust, and uses ... | Use the pyclipper library to "union" a polygon on its own. This operation
uses the even-odd rule to determine which points are in the interior of
the polygon, and can reconstruct the orientation of the polygon from that.
The pyclipper library is robust, and uses integer coordinates, so should
not produc... | Below is the the instruction that describes the task:
### Input:
Use the pyclipper library to "union" a polygon on its own. This operation
uses the even-odd rule to determine which points are in the interior of
the polygon, and can reconstruct the orientation of the polygon from that.
The pyclipper libr... |
def conc_err_plot(fname):
"""Plots the error in the CE data.
This plots the error in the CE predictions within a ternary concentration diagram.
Parameters
----------
fname : string containing the input file name.
"""
energies = _read_data(fname)
enthalpy = _energy_to_enthalpy(ener... | Plots the error in the CE data.
This plots the error in the CE predictions within a ternary concentration diagram.
Parameters
----------
fname : string containing the input file name. | Below is the the instruction that describes the task:
### Input:
Plots the error in the CE data.
This plots the error in the CE predictions within a ternary concentration diagram.
Parameters
----------
fname : string containing the input file name.
### Response:
def conc_err_plot(fname):
... |
def getCell(self, row, column):
""" Returns the specified cell (if a raster is set for the region) """
row = int(row)
column = int(column)
if self._raster[0] == 0 or self._raster[1] == 0:
return self
rowHeight = self.h / self._raster[0]
columnWidth = self.h / ... | Returns the specified cell (if a raster is set for the region) | Below is the the instruction that describes the task:
### Input:
Returns the specified cell (if a raster is set for the region)
### Response:
def getCell(self, row, column):
""" Returns the specified cell (if a raster is set for the region) """
row = int(row)
column = int(column)
if... |
def updateEditor( self ):
"""
Updates the editor based on the current selection.
"""
# assignt the rule operators to the choice list
rule = self.currentRule()
operator = self.currentOperator()
widget = self.uiWidgetAREA.widget()
edi... | Updates the editor based on the current selection. | Below is the the instruction that describes the task:
### Input:
Updates the editor based on the current selection.
### Response:
def updateEditor( self ):
"""
Updates the editor based on the current selection.
"""
# assignt the rule operators to the choice list
rul... |
def get_or_none(cls, **filter_kwargs):
"""
Returns a video or None.
"""
try:
video = cls.objects.get(**filter_kwargs)
except cls.DoesNotExist:
video = None
return video | Returns a video or None. | Below is the the instruction that describes the task:
### Input:
Returns a video or None.
### Response:
def get_or_none(cls, **filter_kwargs):
"""
Returns a video or None.
"""
try:
video = cls.objects.get(**filter_kwargs)
except cls.DoesNotExist:
vide... |
def toDict(datastorage_obj, recursive=True):
""" convert a DataStorage object to a dictionary (useful for saving); it should work for other objects too
"""
# if not a DataStorage, convert to it first
if "items" not in dir(datastorage_obj): datastorage_obj = DataStorage(datastorage_obj)
return _toDi... | convert a DataStorage object to a dictionary (useful for saving); it should work for other objects too | Below is the the instruction that describes the task:
### Input:
convert a DataStorage object to a dictionary (useful for saving); it should work for other objects too
### Response:
def toDict(datastorage_obj, recursive=True):
""" convert a DataStorage object to a dictionary (useful for saving); it should work... |
def transform(self, X, y=None, sample_weight=None):
'''
Transforms the time series data into segments (temporal tensor)
Note this transformation changes the number of samples in the data
If y and sample_weight are provided, they are transformed to align to the new samples
Param... | Transforms the time series data into segments (temporal tensor)
Note this transformation changes the number of samples in the data
If y and sample_weight are provided, they are transformed to align to the new samples
Parameters
----------
X : array-like, shape [n_series, ...]
... | Below is the the instruction that describes the task:
### Input:
Transforms the time series data into segments (temporal tensor)
Note this transformation changes the number of samples in the data
If y and sample_weight are provided, they are transformed to align to the new samples
Paramete... |
def list_users(self, objectmask=None, objectfilter=None):
"""Lists all users on an account
:param string objectmask: Used to overwrite the default objectmask.
:param dictionary objectfilter: If you want to use an objectfilter.
:returns: A list of dictionaries that describe each user
... | Lists all users on an account
:param string objectmask: Used to overwrite the default objectmask.
:param dictionary objectfilter: If you want to use an objectfilter.
:returns: A list of dictionaries that describe each user
Example::
result = mgr.list_users() | Below is the the instruction that describes the task:
### Input:
Lists all users on an account
:param string objectmask: Used to overwrite the default objectmask.
:param dictionary objectfilter: If you want to use an objectfilter.
:returns: A list of dictionaries that describe each user
... |
def parse_args():
"""
Parse the command line arguments
"""
parser = argparse.ArgumentParser(description = 'Decrypt AEADs',
add_help = True,
formatter_class = argparse.ArgumentDefaultsHelpFormatter,
... | Parse the command line arguments | Below is the the instruction that describes the task:
### Input:
Parse the command line arguments
### Response:
def parse_args():
"""
Parse the command line arguments
"""
parser = argparse.ArgumentParser(description = 'Decrypt AEADs',
add_help = True,
... |
def magic(adata,
name_list=None,
k=10,
a=15,
t='auto',
n_pca=100,
knn_dist='euclidean',
random_state=None,
n_jobs=None,
verbose=False,
copy=None,
**kwargs):
"""Markov Affinity-based Graph Imputation of Cell... | Markov Affinity-based Graph Imputation of Cells (MAGIC) API [vanDijk18]_.
MAGIC is an algorithm for denoising and transcript recover of single cells
applied to single-cell sequencing data. MAGIC builds a graph from the data
and uses diffusion to smooth out noise and recover the data manifold.
More inf... | Below is the the instruction that describes the task:
### Input:
Markov Affinity-based Graph Imputation of Cells (MAGIC) API [vanDijk18]_.
MAGIC is an algorithm for denoising and transcript recover of single cells
applied to single-cell sequencing data. MAGIC builds a graph from the data
and uses diffu... |
def process(inFile,force=False,newpath=None, inmemory=False, num_cores=None,
headerlets=True, align_to_gaia=True):
""" Run astrodrizzle on input file/ASN table
using default values for astrodrizzle parameters.
"""
# We only need to import this package if a user run the task
import dr... | Run astrodrizzle on input file/ASN table
using default values for astrodrizzle parameters. | Below is the the instruction that describes the task:
### Input:
Run astrodrizzle on input file/ASN table
using default values for astrodrizzle parameters.
### Response:
def process(inFile,force=False,newpath=None, inmemory=False, num_cores=None,
headerlets=True, align_to_gaia=True):
""" Ru... |
def ParseOptions(cls, options, configuration_object):
"""Parses and validates options.
Args:
options (argparse.Namespace): parser options.
configuration_object (CLITool): object to be configured by the argument
helper.
Raises:
BadConfigObject: when the configuration object is o... | Parses and validates options.
Args:
options (argparse.Namespace): parser options.
configuration_object (CLITool): object to be configured by the argument
helper.
Raises:
BadConfigObject: when the configuration object is of the wrong type. | Below is the the instruction that describes the task:
### Input:
Parses and validates options.
Args:
options (argparse.Namespace): parser options.
configuration_object (CLITool): object to be configured by the argument
helper.
Raises:
BadConfigObject: when the configuration obj... |
def geckoboard_pie_chart(request):
"""
Shows a pie chart of the metrics in the uids[] GET variable array.
"""
params = get_gecko_params(request, cumulative=True)
from_date = datetime.now()-timedelta(days=params['days_back'])
metrics = Metric.objects.filter(uid__in=params['uids'])
results =... | Shows a pie chart of the metrics in the uids[] GET variable array. | Below is the the instruction that describes the task:
### Input:
Shows a pie chart of the metrics in the uids[] GET variable array.
### Response:
def geckoboard_pie_chart(request):
"""
Shows a pie chart of the metrics in the uids[] GET variable array.
"""
params = get_gecko_params(request, cumulat... |
def events(self):
""" All events in calendar within specified time range """
if self._events is None:
self._events = self.parent.calendar.events(
calendarId="primary", singleEvents=True, orderBy="startTime",
timeMin=self.since, timeMax=self.until)
retu... | All events in calendar within specified time range | Below is the the instruction that describes the task:
### Input:
All events in calendar within specified time range
### Response:
def events(self):
""" All events in calendar within specified time range """
if self._events is None:
self._events = self.parent.calendar.events(
... |
def get_merge(self, path, local_destination):
"""
Using snakebite getmerge to implement this.
:param path: HDFS directory
:param local_destination: path on the system running Luigi
:return: merge of the directory
"""
return list(self.get_bite().getmerge(path=path,... | Using snakebite getmerge to implement this.
:param path: HDFS directory
:param local_destination: path on the system running Luigi
:return: merge of the directory | Below is the the instruction that describes the task:
### Input:
Using snakebite getmerge to implement this.
:param path: HDFS directory
:param local_destination: path on the system running Luigi
:return: merge of the directory
### Response:
def get_merge(self, path, local_destination):
... |
def batch_slice(dist, params_event_ndims, params_overrides, slices):
"""Slices `dist` along its batch dimensions. Helper for tfd.Distribution.
Args:
dist: A `tfd.Distribution` instance.
params_event_ndims: A `dict` of `str->int` indicating the number of
dimensions of a given parameter required to par... | Slices `dist` along its batch dimensions. Helper for tfd.Distribution.
Args:
dist: A `tfd.Distribution` instance.
params_event_ndims: A `dict` of `str->int` indicating the number of
dimensions of a given parameter required to parameterize a single event.
params_overrides: A `dict` of parameter over... | Below is the the instruction that describes the task:
### Input:
Slices `dist` along its batch dimensions. Helper for tfd.Distribution.
Args:
dist: A `tfd.Distribution` instance.
params_event_ndims: A `dict` of `str->int` indicating the number of
dimensions of a given parameter required to paramete... |
def setup_cmd_parser(cls):
"""Returns the RSS argument parser."""
parser = BackendCommandArgumentParser(cls.BACKEND.CATEGORIES,
archive=True)
# Required arguments
parser.parser.add_argument('url',
help="UR... | Returns the RSS argument parser. | Below is the the instruction that describes the task:
### Input:
Returns the RSS argument parser.
### Response:
def setup_cmd_parser(cls):
"""Returns the RSS argument parser."""
parser = BackendCommandArgumentParser(cls.BACKEND.CATEGORIES,
archive=True... |
def add_env(parser):
"""Add an `env` flag to the _parser_."""
parser.add_argument(
'-e', '--env', choices=ENVS, default=os.getenv('ENV', default='dev'), help='Deploy environment, overrides $ENV') | Add an `env` flag to the _parser_. | Below is the the instruction that describes the task:
### Input:
Add an `env` flag to the _parser_.
### Response:
def add_env(parser):
"""Add an `env` flag to the _parser_."""
parser.add_argument(
'-e', '--env', choices=ENVS, default=os.getenv('ENV', default='dev'), help='Deploy environment, overri... |
def try_value_to_bool(value, strict_mode=True):
"""Tries to convert value into boolean.
strict_mode is True:
- Only string representation of str(True) and str(False)
are converted into booleans;
- Otherwise unchanged incoming value is returned;
strict_mode is False:
- Anything that looks... | Tries to convert value into boolean.
strict_mode is True:
- Only string representation of str(True) and str(False)
are converted into booleans;
- Otherwise unchanged incoming value is returned;
strict_mode is False:
- Anything that looks like True or False is converted into booleans.
Val... | Below is the the instruction that describes the task:
### Input:
Tries to convert value into boolean.
strict_mode is True:
- Only string representation of str(True) and str(False)
are converted into booleans;
- Otherwise unchanged incoming value is returned;
strict_mode is False:
- Anyth... |
def load_library_permanently(filename):
"""
Load an external library
"""
with ffi.OutputString() as outerr:
if ffi.lib.LLVMPY_LoadLibraryPermanently(
_encode_string(filename), outerr):
raise RuntimeError(str(outerr)) | Load an external library | Below is the the instruction that describes the task:
### Input:
Load an external library
### Response:
def load_library_permanently(filename):
"""
Load an external library
"""
with ffi.OutputString() as outerr:
if ffi.lib.LLVMPY_LoadLibraryPermanently(
_encode_string(filena... |
def reset(self):
"""
Clears `nick` and `own_ids`, sets `center` to `world.center`,
and then calls `cells_changed()`.
"""
self.own_ids.clear()
self.nick = ''
self.center = self.world.center
self.cells_changed() | Clears `nick` and `own_ids`, sets `center` to `world.center`,
and then calls `cells_changed()`. | Below is the the instruction that describes the task:
### Input:
Clears `nick` and `own_ids`, sets `center` to `world.center`,
and then calls `cells_changed()`.
### Response:
def reset(self):
"""
Clears `nick` and `own_ids`, sets `center` to `world.center`,
and then calls `cells_cha... |
def setup_method_options(method, tuning_options):
""" prepare method specific options """
kwargs = {}
#pass size of parameter space as max iterations to methods that support it
#it seems not all methods iterpret this value in the same manner
maxiter = numpy.prod([len(v) for v in tuning_options.tune... | prepare method specific options | Below is the the instruction that describes the task:
### Input:
prepare method specific options
### Response:
def setup_method_options(method, tuning_options):
""" prepare method specific options """
kwargs = {}
#pass size of parameter space as max iterations to methods that support it
#it seems ... |
def _loadKSubcatRelations( inputFile ):
''' Laeb sisendfailist (inputFile) kaassõnade rektsiooniseoste mustrid.
Iga muster peab olema failis eraldi real, kujul:
(sõnalemma);(sõnaliik);(post|pre);(nõutud_käänete_regexp)
nt
ees;_K_;post;g
eest;_K_;post;g
enn... | Laeb sisendfailist (inputFile) kaassõnade rektsiooniseoste mustrid.
Iga muster peab olema failis eraldi real, kujul:
(sõnalemma);(sõnaliik);(post|pre);(nõutud_käänete_regexp)
nt
ees;_K_;post;g
eest;_K_;post;g
enne;_K_;pre;p
Tagastab laetud andmed sõnas... | Below is the the instruction that describes the task:
### Input:
Laeb sisendfailist (inputFile) kaassõnade rektsiooniseoste mustrid.
Iga muster peab olema failis eraldi real, kujul:
(sõnalemma);(sõnaliik);(post|pre);(nõutud_käänete_regexp)
nt
ees;_K_;post;g
eest;_K_;p... |
def box(self):
"""Return the bounding box as a new ``Actor``.
.. hint:: |latex.py|_
"""
b = self.GetBounds()
from vtkplotter.shapes import Box
pos = (b[0]+b[1])/2, (b[3]+b[2])/2, (b[5]+b[4])/2
length, width, height = b[1]-b[0], b[3]-b[2], b[5]-b[4]
... | Return the bounding box as a new ``Actor``.
.. hint:: |latex.py|_ | Below is the the instruction that describes the task:
### Input:
Return the bounding box as a new ``Actor``.
.. hint:: |latex.py|_
### Response:
def box(self):
"""Return the bounding box as a new ``Actor``.
.. hint:: |latex.py|_
"""
b = self.GetBounds()
... |
def sanitize_metadata(self, metadata, replace_hyphen_with="-"):
"""Convert non-string metadata values to strings and drop null values"""
return {str(k).replace("-", replace_hyphen_with): str(v)
for k, v in (metadata or {}).items() if v is not None} | Convert non-string metadata values to strings and drop null values | Below is the the instruction that describes the task:
### Input:
Convert non-string metadata values to strings and drop null values
### Response:
def sanitize_metadata(self, metadata, replace_hyphen_with="-"):
"""Convert non-string metadata values to strings and drop null values"""
return {str(k).r... |
def pyramid_analysis(Gs, f, **kwargs):
r"""Compute the graph pyramid transform coefficients.
Parameters
----------
Gs : list of graphs
A multiresolution sequence of graph structures.
f : ndarray
Graph signal to analyze.
h_filters : list
A list of filter that will be used... | r"""Compute the graph pyramid transform coefficients.
Parameters
----------
Gs : list of graphs
A multiresolution sequence of graph structures.
f : ndarray
Graph signal to analyze.
h_filters : list
A list of filter that will be used for the analysis and sythesis operator.
... | Below is the the instruction that describes the task:
### Input:
r"""Compute the graph pyramid transform coefficients.
Parameters
----------
Gs : list of graphs
A multiresolution sequence of graph structures.
f : ndarray
Graph signal to analyze.
h_filters : list
A list o... |
def list_groups(
self,
name,
children_of_group=None,
ancestors_of_group=None,
descendants_of_group=None,
page_size=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"... | Lists the existing groups.
Example:
>>> from google.cloud import monitoring_v3
>>>
>>> client = monitoring_v3.GroupServiceClient()
>>>
>>> name = client.project_path('[PROJECT]')
>>>
>>> # Iterate over all results
>... | Below is the the instruction that describes the task:
### Input:
Lists the existing groups.
Example:
>>> from google.cloud import monitoring_v3
>>>
>>> client = monitoring_v3.GroupServiceClient()
>>>
>>> name = client.project_path('[PROJECT]')
... |
def get_timeseries(self, child_agg_count=0, dataframe=False):
"""
Get time series data for the specified fields and period of analysis
:param child_agg_count: the child aggregation count to be used
default = 0
:param dataframe: if dataframe=True, return a... | Get time series data for the specified fields and period of analysis
:param child_agg_count: the child aggregation count to be used
default = 0
:param dataframe: if dataframe=True, return a pandas.DataFrame object
:returns: dictionary containing "date", "value" a... | Below is the the instruction that describes the task:
### Input:
Get time series data for the specified fields and period of analysis
:param child_agg_count: the child aggregation count to be used
default = 0
:param dataframe: if dataframe=True, return a pandas.DataF... |
async def on_raw_privmsg(self, message):
""" PRIVMSG command. """
nick, metadata = self._parse_user(message.source)
target, message = message.params
self._sync_user(nick, metadata)
await self.on_message(target, nick, message)
if self.is_channel(target):
awai... | PRIVMSG command. | Below is the the instruction that describes the task:
### Input:
PRIVMSG command.
### Response:
async def on_raw_privmsg(self, message):
""" PRIVMSG command. """
nick, metadata = self._parse_user(message.source)
target, message = message.params
self._sync_user(nick, metadata)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.