code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def generate_annotations_json_string(source_path, only_simple=False):
# type: (str, bool) -> List[FunctionData]
"""Produce annotation data JSON file from a JSON file with runtime-collected types.
Data formats:
* The source JSON is a list of pyannotate_tools.annotations.parse.RawEntry items.
* The ... | Produce annotation data JSON file from a JSON file with runtime-collected types.
Data formats:
* The source JSON is a list of pyannotate_tools.annotations.parse.RawEntry items.
* The output JSON is a list of FunctionData items. | Below is the the instruction that describes the task:
### Input:
Produce annotation data JSON file from a JSON file with runtime-collected types.
Data formats:
* The source JSON is a list of pyannotate_tools.annotations.parse.RawEntry items.
* The output JSON is a list of FunctionData items.
### Respo... |
def slice(dataset, normal='x', origin=None, generate_triangles=False,
contour=False):
"""Slice a dataset by a plane at the specified origin and normal vector
orientation. If no origin is specified, the center of the input dataset will
be used.
Parameters
----------... | Slice a dataset by a plane at the specified origin and normal vector
orientation. If no origin is specified, the center of the input dataset will
be used.
Parameters
----------
normal : tuple(float) or str
Length 3 tuple for the normal vector direction. Can also be
... | Below is the the instruction that describes the task:
### Input:
Slice a dataset by a plane at the specified origin and normal vector
orientation. If no origin is specified, the center of the input dataset will
be used.
Parameters
----------
normal : tuple(float) or str
... |
def _determine_beacon_config(self, current_beacon_config, key):
'''
Process a beacon configuration to determine its interval
'''
interval = False
if isinstance(current_beacon_config, dict):
interval = current_beacon_config.get(key, False)
return interval | Process a beacon configuration to determine its interval | Below is the the instruction that describes the task:
### Input:
Process a beacon configuration to determine its interval
### Response:
def _determine_beacon_config(self, current_beacon_config, key):
'''
Process a beacon configuration to determine its interval
'''
interval = False
... |
def vibrational_internal_energy(self, temperature, volume):
"""
Vibrational internal energy, U_vib(V, T).
Eq(4) in doi.org/10.1016/j.comphy.2003.12.001
Args:
temperature (float): temperature in K
volume (float): in Ang^3
Returns:
float: vibra... | Vibrational internal energy, U_vib(V, T).
Eq(4) in doi.org/10.1016/j.comphy.2003.12.001
Args:
temperature (float): temperature in K
volume (float): in Ang^3
Returns:
float: vibrational internal energy in eV | Below is the the instruction that describes the task:
### Input:
Vibrational internal energy, U_vib(V, T).
Eq(4) in doi.org/10.1016/j.comphy.2003.12.001
Args:
temperature (float): temperature in K
volume (float): in Ang^3
Returns:
float: vibrational inte... |
def enable_llama_ha(self, new_llama_host_id, zk_service_name=None,
new_llama_role_name=None):
"""
Enable high availability for an Impala Llama ApplicationMaster.
This command only applies to CDH 5.1+ Impala services.
@param new_llama_host_id: id of the host where the second Llama... | Enable high availability for an Impala Llama ApplicationMaster.
This command only applies to CDH 5.1+ Impala services.
@param new_llama_host_id: id of the host where the second Llama role
will be added.
@param zk_service_name: Name of the ZooKeeper service to use for
... | Below is the the instruction that describes the task:
### Input:
Enable high availability for an Impala Llama ApplicationMaster.
This command only applies to CDH 5.1+ Impala services.
@param new_llama_host_id: id of the host where the second Llama role
will be added.
@par... |
def get_pulls_list(project, auth=False, **params):
"""get pull request list"""
params.setdefault("state", "closed")
url = "https://api.github.com/repos/{project}/pulls".format(project=project)
if auth:
headers = make_auth_header()
else:
headers = None
pages = get_paged_request(ur... | get pull request list | Below is the the instruction that describes the task:
### Input:
get pull request list
### Response:
def get_pulls_list(project, auth=False, **params):
"""get pull request list"""
params.setdefault("state", "closed")
url = "https://api.github.com/repos/{project}/pulls".format(project=project)
if au... |
def copy_subtree(self, source_node, dest_node): # noqa: D302
r"""
Copy a sub-tree from one sub-node to another.
Data is added if some nodes of the source sub-tree exist in the
destination sub-tree
:param source_name: Root node of the sub-tree to copy from
:type source... | r"""
Copy a sub-tree from one sub-node to another.
Data is added if some nodes of the source sub-tree exist in the
destination sub-tree
:param source_name: Root node of the sub-tree to copy from
:type source_name: :ref:`NodeName`
:param dest_name: Root node of the sub... | Below is the the instruction that describes the task:
### Input:
r"""
Copy a sub-tree from one sub-node to another.
Data is added if some nodes of the source sub-tree exist in the
destination sub-tree
:param source_name: Root node of the sub-tree to copy from
:type source_... |
def main():
"""Main Function"""
num_blocks = int(sys.argv[1]) if len(sys.argv) == 2 else 3
clear_db()
for block_id in generate_scheduling_block_id(num_blocks=num_blocks,
project='sip'):
config = {
"id": block_id,
"sub_array... | Main Function | Below is the the instruction that describes the task:
### Input:
Main Function
### Response:
def main():
"""Main Function"""
num_blocks = int(sys.argv[1]) if len(sys.argv) == 2 else 3
clear_db()
for block_id in generate_scheduling_block_id(num_blocks=num_blocks,
... |
def affiliations(self):
"""A list of namedtuples storing affiliation information,
where each namedtuple corresponds to one affiliation.
The information in each namedtuple is (eid name variant documents city
country parent).
All entries are strings or None. variant combines vari... | A list of namedtuples storing affiliation information,
where each namedtuple corresponds to one affiliation.
The information in each namedtuple is (eid name variant documents city
country parent).
All entries are strings or None. variant combines variants of names
with a semico... | Below is the the instruction that describes the task:
### Input:
A list of namedtuples storing affiliation information,
where each namedtuple corresponds to one affiliation.
The information in each namedtuple is (eid name variant documents city
country parent).
All entries are strin... |
def coerce(self, value):
"""Coerce a single value according to this parameter's settings.
@param value: A L{str}, or L{None}. If L{None} is passed - meaning no
value is avalable at all, not even the empty string - and this
parameter is optional, L{self.default} will be returned.... | Coerce a single value according to this parameter's settings.
@param value: A L{str}, or L{None}. If L{None} is passed - meaning no
value is avalable at all, not even the empty string - and this
parameter is optional, L{self.default} will be returned. | Below is the the instruction that describes the task:
### Input:
Coerce a single value according to this parameter's settings.
@param value: A L{str}, or L{None}. If L{None} is passed - meaning no
value is avalable at all, not even the empty string - and this
parameter is optional, ... |
def list(self, argv):
"""List available indexes if no names provided, otherwise list the
properties of the named indexes."""
def read(index):
print(index.name)
for key in sorted(index.content.keys()):
value = index.content[key]
print("... | List available indexes if no names provided, otherwise list the
properties of the named indexes. | Below is the the instruction that describes the task:
### Input:
List available indexes if no names provided, otherwise list the
properties of the named indexes.
### Response:
def list(self, argv):
"""List available indexes if no names provided, otherwise list the
properties of the na... |
def _clear(self):
"""
Clear the current image.
"""
self._plain_image = [" " * self._width for _ in range(self._height)]
self._colour_map = [[(None, 0, 0) for _ in range(self._width)]
for _ in range(self._height)] | Clear the current image. | Below is the the instruction that describes the task:
### Input:
Clear the current image.
### Response:
def _clear(self):
"""
Clear the current image.
"""
self._plain_image = [" " * self._width for _ in range(self._height)]
self._colour_map = [[(None, 0, 0) for _ in range(se... |
def on_master_missing(self):
'''
Tries to spawn a master agency if the slave agency failed to connect
for several times. To avoid several slave agencies spawning the master
agency a file lock is used
'''
self.info("We could not contact the master agency, starting a new on... | Tries to spawn a master agency if the slave agency failed to connect
for several times. To avoid several slave agencies spawning the master
agency a file lock is used | Below is the the instruction that describes the task:
### Input:
Tries to spawn a master agency if the slave agency failed to connect
for several times. To avoid several slave agencies spawning the master
agency a file lock is used
### Response:
def on_master_missing(self):
'''
Trie... |
def _wrap_client_error(e):
"""
Wrap botocore ClientError exception into ServerlessRepoClientError.
:param e: botocore exception
:type e: ClientError
:return: S3PermissionsRequired or InvalidS3UriError or general ServerlessRepoClientError
"""
error_code = e.response['Error']['Code']
mess... | Wrap botocore ClientError exception into ServerlessRepoClientError.
:param e: botocore exception
:type e: ClientError
:return: S3PermissionsRequired or InvalidS3UriError or general ServerlessRepoClientError | Below is the the instruction that describes the task:
### Input:
Wrap botocore ClientError exception into ServerlessRepoClientError.
:param e: botocore exception
:type e: ClientError
:return: S3PermissionsRequired or InvalidS3UriError or general ServerlessRepoClientError
### Response:
def _wrap_client... |
def dump_js(js, abspath, precision=None,
fastmode=False, replace=False, compress=False, enable_verbose=True):
"""Dump Json serializable object to file.
Provides multiple choice to customize the behavior.
:param js: Serializable python object.
:type js: dict or list
:param abspath: ``sa... | Dump Json serializable object to file.
Provides multiple choice to customize the behavior.
:param js: Serializable python object.
:type js: dict or list
:param abspath: ``save as`` path, file extension has to be ``.json`` or ``.gz``
(for compressed json).
:type abspath: string
:param ... | Below is the the instruction that describes the task:
### Input:
Dump Json serializable object to file.
Provides multiple choice to customize the behavior.
:param js: Serializable python object.
:type js: dict or list
:param abspath: ``save as`` path, file extension has to be ``.json`` or ``.gz``
... |
def server_info(self):
"""
Query information about the server.
"""
response = self._post(self.apiurl + "/v2/server/info", data={'apikey': self.apikey})
return self._raise_or_extract(response) | Query information about the server. | Below is the the instruction that describes the task:
### Input:
Query information about the server.
### Response:
def server_info(self):
"""
Query information about the server.
"""
response = self._post(self.apiurl + "/v2/server/info", data={'apikey': self.apikey})
return ... |
def print_result(self, directory_result):
"""
Print out the contents of the directory result, using ANSI color codes if
supported
"""
for file_name, line_results_dict in directory_result.iter_line_results_items():
full_path = path.join(directory_result.directory_path,... | Print out the contents of the directory result, using ANSI color codes if
supported | Below is the the instruction that describes the task:
### Input:
Print out the contents of the directory result, using ANSI color codes if
supported
### Response:
def print_result(self, directory_result):
"""
Print out the contents of the directory result, using ANSI color codes if
... |
def integrate(self,t,pot=None,method='test-particle',
**kwargs):
"""
NAME:
integrate
PURPOSE:
integrate the snapshot in time
INPUT:
t - numpy.array of times to save the snapshots at (must start at 0)
pot= potential object or l... | NAME:
integrate
PURPOSE:
integrate the snapshot in time
INPUT:
t - numpy.array of times to save the snapshots at (must start at 0)
pot= potential object or list of such objects (default=None)
method= method to use ('test-particle' or 'direct-python'... | Below is the the instruction that describes the task:
### Input:
NAME:
integrate
PURPOSE:
integrate the snapshot in time
INPUT:
t - numpy.array of times to save the snapshots at (must start at 0)
pot= potential object or list of such objects (default=None)... |
def _parse_host(cls, host='localhost', port=0):
""" Parse provided hostname and extract port number
:param host: Server hostname
:type host: string
:param port: Server port
:return: Tuple of (host, port)
:rtype: tuple
"""
if not port and (host.find(':') =... | Parse provided hostname and extract port number
:param host: Server hostname
:type host: string
:param port: Server port
:return: Tuple of (host, port)
:rtype: tuple | Below is the the instruction that describes the task:
### Input:
Parse provided hostname and extract port number
:param host: Server hostname
:type host: string
:param port: Server port
:return: Tuple of (host, port)
:rtype: tuple
### Response:
def _parse_host(cls, host='lo... |
def rosenbrock(theta):
"""Objective and gradient for the rosenbrock function"""
x, y = theta
obj = (1 - x)**2 + 100 * (y - x**2)**2
grad = np.zeros(2)
grad[0] = 2 * x - 400 * (x * y - x**3) - 2
grad[1] = 200 * (y - x**2)
return obj, grad | Objective and gradient for the rosenbrock function | Below is the the instruction that describes the task:
### Input:
Objective and gradient for the rosenbrock function
### Response:
def rosenbrock(theta):
"""Objective and gradient for the rosenbrock function"""
x, y = theta
obj = (1 - x)**2 + 100 * (y - x**2)**2
grad = np.zeros(2)
grad[0] = 2 *... |
def repolist(status='', media=None):
"""
Get the list of ``yum`` repositories.
Returns enabled repositories by default. Extra *status* may be passed
to list disabled repositories if necessary.
Media and debug repositories are kept disabled, except if you pass *media*.
::
import burla... | Get the list of ``yum`` repositories.
Returns enabled repositories by default. Extra *status* may be passed
to list disabled repositories if necessary.
Media and debug repositories are kept disabled, except if you pass *media*.
::
import burlap
# Install a package that may be includ... | Below is the the instruction that describes the task:
### Input:
Get the list of ``yum`` repositories.
Returns enabled repositories by default. Extra *status* may be passed
to list disabled repositories if necessary.
Media and debug repositories are kept disabled, except if you pass *media*.
::
... |
def get_job_results(self, job_resource_name: str) -> List[TrialResult]:
"""Returns the actual results (not metadata) of a completed job.
Params:
job_resource_name: A string of the form
`projects/project_id/programs/program_id/jobs/job_id`.
Returns:
An it... | Returns the actual results (not metadata) of a completed job.
Params:
job_resource_name: A string of the form
`projects/project_id/programs/program_id/jobs/job_id`.
Returns:
An iterable over the TrialResult, one per parameter in the
parameter sweep. | Below is the the instruction that describes the task:
### Input:
Returns the actual results (not metadata) of a completed job.
Params:
job_resource_name: A string of the form
`projects/project_id/programs/program_id/jobs/job_id`.
Returns:
An iterable over th... |
def run(filename: 'python file generated by `rbnf` command, or rbnf sour file',
opt: 'optimize switch' = False):
"""
You can apply immediate tests on your parser.
P.S: use `--opt` option takes longer starting time.
"""
from rbnf.easy import build_parser
import importlib.util
import t... | You can apply immediate tests on your parser.
P.S: use `--opt` option takes longer starting time. | Below is the the instruction that describes the task:
### Input:
You can apply immediate tests on your parser.
P.S: use `--opt` option takes longer starting time.
### Response:
def run(filename: 'python file generated by `rbnf` command, or rbnf sour file',
opt: 'optimize switch' = False):
"""
Y... |
def unbounded(self):
"""
Returns a list of key dimensions that are unbounded, excluding
stream parameters. If any of theses key dimensions are
unbounded, the DynamicMap as a whole is also unbounded.
"""
unbounded_dims = []
# Dimensioned streams do not need to be b... | Returns a list of key dimensions that are unbounded, excluding
stream parameters. If any of theses key dimensions are
unbounded, the DynamicMap as a whole is also unbounded. | Below is the the instruction that describes the task:
### Input:
Returns a list of key dimensions that are unbounded, excluding
stream parameters. If any of theses key dimensions are
unbounded, the DynamicMap as a whole is also unbounded.
### Response:
def unbounded(self):
"""
Retur... |
def parse_directive(lexer: Lexer, is_const: bool) -> DirectiveNode:
"""Directive[Const]: @ Name Arguments[?Const]?"""
start = lexer.token
expect_token(lexer, TokenKind.AT)
return DirectiveNode(
name=parse_name(lexer),
arguments=parse_arguments(lexer, is_const),
loc=loc(lexer, sta... | Directive[Const]: @ Name Arguments[?Const]? | Below is the the instruction that describes the task:
### Input:
Directive[Const]: @ Name Arguments[?Const]?
### Response:
def parse_directive(lexer: Lexer, is_const: bool) -> DirectiveNode:
"""Directive[Const]: @ Name Arguments[?Const]?"""
start = lexer.token
expect_token(lexer, TokenKind.AT)
retu... |
def archive(self, odir=None, aname=None, fmt=None, projectname=None,
experiments=None, current_project=False, no_append=False,
no_project_paths=False, exclude=None, keep_exp=False,
rm_project=False, dry_run=False, dereference=False, **kwargs):
"""
Archive ... | Archive one or more experiments or a project instance
This method may be used to archive experiments in order to minimize the
amount of necessary configuration files
Parameters
----------
odir: str
The path where to store the archive
aname: str
T... | Below is the the instruction that describes the task:
### Input:
Archive one or more experiments or a project instance
This method may be used to archive experiments in order to minimize the
amount of necessary configuration files
Parameters
----------
odir: str
... |
def array_join(col, delimiter, null_replacement=None):
"""
Concatenates the elements of `column` using the `delimiter`. Null values are replaced with
`null_replacement` if set, otherwise they are ignored.
>>> df = spark.createDataFrame([(["a", "b", "c"],), (["a", None],)], ['data'])
>>> df.select(a... | Concatenates the elements of `column` using the `delimiter`. Null values are replaced with
`null_replacement` if set, otherwise they are ignored.
>>> df = spark.createDataFrame([(["a", "b", "c"],), (["a", None],)], ['data'])
>>> df.select(array_join(df.data, ",").alias("joined")).collect()
[Row(joined=... | Below is the the instruction that describes the task:
### Input:
Concatenates the elements of `column` using the `delimiter`. Null values are replaced with
`null_replacement` if set, otherwise they are ignored.
>>> df = spark.createDataFrame([(["a", "b", "c"],), (["a", None],)], ['data'])
>>> df.select... |
def write_extent(self):
"""After the extent selection, save the extent and disconnect signals.
"""
self.extent_dialog.accept()
self.extent_dialog.clear_extent.disconnect(
self.parent.dock.extent.clear_user_analysis_extent)
self.extent_dialog.extent_defined.disconnect(... | After the extent selection, save the extent and disconnect signals. | Below is the the instruction that describes the task:
### Input:
After the extent selection, save the extent and disconnect signals.
### Response:
def write_extent(self):
"""After the extent selection, save the extent and disconnect signals.
"""
self.extent_dialog.accept()
self.exte... |
def get_listener(name):
'''
Return the listener class.
'''
try:
log.debug('Using %s as listener', name)
return LISTENER_LOOKUP[name]
except KeyError:
msg = 'Listener {} is not available. Are the dependencies installed?'.format(name)
log.error(msg, exc_info=True)
... | Return the listener class. | Below is the the instruction that describes the task:
### Input:
Return the listener class.
### Response:
def get_listener(name):
'''
Return the listener class.
'''
try:
log.debug('Using %s as listener', name)
return LISTENER_LOOKUP[name]
except KeyError:
msg = 'Listener... |
def get_item(dictionary, tuple_key, default_value):
"""Grab values from a dictionary using an unordered tuple as a key.
Dictionary should not contain None, 0, or False as dictionary values.
Args:
dictionary: Dictionary that uses two-element tuple as keys
tuple_key: Unordered tuple of two e... | Grab values from a dictionary using an unordered tuple as a key.
Dictionary should not contain None, 0, or False as dictionary values.
Args:
dictionary: Dictionary that uses two-element tuple as keys
tuple_key: Unordered tuple of two elements
default_value: Value that is returned when ... | Below is the the instruction that describes the task:
### Input:
Grab values from a dictionary using an unordered tuple as a key.
Dictionary should not contain None, 0, or False as dictionary values.
Args:
dictionary: Dictionary that uses two-element tuple as keys
tuple_key: Unordered tupl... |
def register(self, name, f, returnType=None):
"""Register a Python function (including lambda function) or a user-defined function
as a SQL function.
:param name: name of the user-defined function in SQL statements.
:param f: a Python function, or a user-defined function. The user-defin... | Register a Python function (including lambda function) or a user-defined function
as a SQL function.
:param name: name of the user-defined function in SQL statements.
:param f: a Python function, or a user-defined function. The user-defined function can
be either row-at-a-time or ve... | Below is the the instruction that describes the task:
### Input:
Register a Python function (including lambda function) or a user-defined function
as a SQL function.
:param name: name of the user-defined function in SQL statements.
:param f: a Python function, or a user-defined function. Th... |
def write_shiftfile(image_list, filename, outwcs='tweak_wcs.fits'):
""" Write out a shiftfile for a given list of input Image class objects
"""
rows = ''
nrows = 0
for img in image_list:
row = img.get_shiftfile_row()
if row is not None:
rows += row
nrows += 1
... | Write out a shiftfile for a given list of input Image class objects | Below is the the instruction that describes the task:
### Input:
Write out a shiftfile for a given list of input Image class objects
### Response:
def write_shiftfile(image_list, filename, outwcs='tweak_wcs.fits'):
""" Write out a shiftfile for a given list of input Image class objects
"""
rows = ''
... |
def _parse(self):
"""
Generates a dictionary of responses from a <random> element
"""
responses = []
for child in self._element:
weight = int_attribute(child, 'weight', 1)
self._log.debug('Parsing random entry with weight {weight}: {entry}'
... | Generates a dictionary of responses from a <random> element | Below is the the instruction that describes the task:
### Input:
Generates a dictionary of responses from a <random> element
### Response:
def _parse(self):
"""
Generates a dictionary of responses from a <random> element
"""
responses = []
for child in self._element:
... |
def order_by(self, attribute=None, *, ascending=True):
""" Applies a order_by clause
:param str attribute: attribute to apply on
:param bool ascending: should it apply ascending order or descending
:rtype: Query
"""
attribute = self._get_mapping(attribute) or self._attri... | Applies a order_by clause
:param str attribute: attribute to apply on
:param bool ascending: should it apply ascending order or descending
:rtype: Query | Below is the the instruction that describes the task:
### Input:
Applies a order_by clause
:param str attribute: attribute to apply on
:param bool ascending: should it apply ascending order or descending
:rtype: Query
### Response:
def order_by(self, attribute=None, *, ascending=True):
... |
def exp_comp_(t, alpha=1, beta=1):
"""beta*(1 - np.exp(-alpha*(t-beta)))"""
return beta * (1 - np.exp(-alpha * np.maximum(0, t - 10 * beta))) | beta*(1 - np.exp(-alpha*(t-beta))) | Below is the the instruction that describes the task:
### Input:
beta*(1 - np.exp(-alpha*(t-beta)))
### Response:
def exp_comp_(t, alpha=1, beta=1):
"""beta*(1 - np.exp(-alpha*(t-beta)))"""
return beta * (1 - np.exp(-alpha * np.maximum(0, t - 10 * beta))) |
def _bytes_generator(descriptor, max_length=0, limit=0):
'Helper to create bytes values. (Derived from string generator)'
strs = values.get_strings(max_length, limit)
vals = [bytes(_, 'utf-8') for _ in strs]
return gen.IterValueGenerator(descriptor.name, vals) | Helper to create bytes values. (Derived from string generator) | Below is the the instruction that describes the task:
### Input:
Helper to create bytes values. (Derived from string generator)
### Response:
def _bytes_generator(descriptor, max_length=0, limit=0):
'Helper to create bytes values. (Derived from string generator)'
strs = values.get_strings(max_length, limit... |
def pckcov(pck, idcode, cover):
"""
Find the coverage window for a specified reference frame in a
specified binary PCK file.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pckcov_c.html
:param pck: Name of PCK file.
:type pck: str
:param idcode: Class ID code of PCK reference fram... | Find the coverage window for a specified reference frame in a
specified binary PCK file.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pckcov_c.html
:param pck: Name of PCK file.
:type pck: str
:param idcode: Class ID code of PCK reference frame.
:type idcode: int
:param cover: W... | Below is the the instruction that describes the task:
### Input:
Find the coverage window for a specified reference frame in a
specified binary PCK file.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pckcov_c.html
:param pck: Name of PCK file.
:type pck: str
:param idcode: Class ID c... |
def predict_proba(self, X):
"""Predict probabilities on test vectors X.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Input vectors, where n_samples is the number of samples
and n_features is the number of features.
Returns
... | Predict probabilities on test vectors X.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Input vectors, where n_samples is the number of samples
and n_features is the number of features.
Returns
-------
proba : array, shape ... | Below is the the instruction that describes the task:
### Input:
Predict probabilities on test vectors X.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Input vectors, where n_samples is the number of samples
and n_features is the number of fea... |
def p_expression_Or(self, p):
'expression : expression OR expression'
p[0] = Or(p[1], p[3], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | expression : expression OR expression | Below is the the instruction that describes the task:
### Input:
expression : expression OR expression
### Response:
def p_expression_Or(self, p):
'expression : expression OR expression'
p[0] = Or(p[1], p[3], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) |
def _get_child_class(self, path):
""" Return the appropriate child class given a subdirectory path.
Args:
path (str): The path to the subdirectory.
Returns: An uninstantiated BIDSNode or one of its subclasses.
"""
if self._child_entity is None:
... | Return the appropriate child class given a subdirectory path.
Args:
path (str): The path to the subdirectory.
Returns: An uninstantiated BIDSNode or one of its subclasses. | Below is the the instruction that describes the task:
### Input:
Return the appropriate child class given a subdirectory path.
Args:
path (str): The path to the subdirectory.
Returns: An uninstantiated BIDSNode or one of its subclasses.
### Response:
def _get_child_cla... |
def get_temp_file(keep=False, autoext="", fd=False):
"""Creates a temporary file.
:param keep: If False, automatically delete the file when Scapy exits.
:param autoext: Suffix to add to the generated file name.
:param fd: If True, this returns a file-like object with the temporary
file o... | Creates a temporary file.
:param keep: If False, automatically delete the file when Scapy exits.
:param autoext: Suffix to add to the generated file name.
:param fd: If True, this returns a file-like object with the temporary
file opened. If False (default), this returns a file path. | Below is the the instruction that describes the task:
### Input:
Creates a temporary file.
:param keep: If False, automatically delete the file when Scapy exits.
:param autoext: Suffix to add to the generated file name.
:param fd: If True, this returns a file-like object with the temporary
... |
async def _fair_get_in_peer(self):
"""
Get the first available available inbound peer in a fair manner.
:returns: A `Peer` inbox, whose inbox is guaranteed not to be
empty (and thus can be read from without blocking).
"""
peer = None
while not peer:
... | Get the first available available inbound peer in a fair manner.
:returns: A `Peer` inbox, whose inbox is guaranteed not to be
empty (and thus can be read from without blocking). | Below is the the instruction that describes the task:
### Input:
Get the first available available inbound peer in a fair manner.
:returns: A `Peer` inbox, whose inbox is guaranteed not to be
empty (and thus can be read from without blocking).
### Response:
async def _fair_get_in_peer(self):
... |
def __init_yaml():
"""Lazy init yaml because canmatrix might not be fully loaded when loading this format."""
global _yaml_initialized
if not _yaml_initialized:
_yaml_initialized = True
yaml.add_constructor(u'tag:yaml.org,2002:Frame', _frame_constructor)
yaml.add_constructor(u'tag:ya... | Lazy init yaml because canmatrix might not be fully loaded when loading this format. | Below is the the instruction that describes the task:
### Input:
Lazy init yaml because canmatrix might not be fully loaded when loading this format.
### Response:
def __init_yaml():
"""Lazy init yaml because canmatrix might not be fully loaded when loading this format."""
global _yaml_initialized
if n... |
def _list_merge(src, dest):
"""
Merge the contents coming from src into dest
:param src: source dictionary
:param dest: destination dictionary
"""
for k in src:
if type(src[k]) != dict:
dest[k] = src[k]
else:
# ---
# src could have a key whose... | Merge the contents coming from src into dest
:param src: source dictionary
:param dest: destination dictionary | Below is the the instruction that describes the task:
### Input:
Merge the contents coming from src into dest
:param src: source dictionary
:param dest: destination dictionary
### Response:
def _list_merge(src, dest):
"""
Merge the contents coming from src into dest
:param src: source diction... |
def write(self, str):
'''Write string str to the underlying file.
Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.'''
if self.closed: raise ValueError('File closed')
if self._mode in _allowed_read:
raise... | Write string str to the underlying file.
Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written. | Below is the the instruction that describes the task:
### Input:
Write string str to the underlying file.
Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.
### Response:
def write(self, str):
'''Write string str to the underlyin... |
def comparable(self):
"""str: comparable representation of the path specification."""
string_parts = []
if self.location is not None:
string_parts.append('location: {0:s}'.format(self.location))
if self.store_index is not None:
string_parts.append('store index: {0:d}'.format(self.store_inde... | str: comparable representation of the path specification. | Below is the the instruction that describes the task:
### Input:
str: comparable representation of the path specification.
### Response:
def comparable(self):
"""str: comparable representation of the path specification."""
string_parts = []
if self.location is not None:
string_parts.append('loca... |
def get(self, list_id, webhook_id):
"""
Get information about a specific webhook.
:param list_id: The unique id for the list.
:type list_id: :py:class:`str`
:param webhook_id: The unique id for the webhook.
:type webhook_id: :py:class:`str`
"""
self.list_... | Get information about a specific webhook.
:param list_id: The unique id for the list.
:type list_id: :py:class:`str`
:param webhook_id: The unique id for the webhook.
:type webhook_id: :py:class:`str` | Below is the the instruction that describes the task:
### Input:
Get information about a specific webhook.
:param list_id: The unique id for the list.
:type list_id: :py:class:`str`
:param webhook_id: The unique id for the webhook.
:type webhook_id: :py:class:`str`
### Response:
de... |
def _update_table_cache(self):
"""Clears and updates the table cache to be in sync with self"""
self._table_cache.clear()
for sel, tab, val in self:
try:
self._table_cache[tab].append((sel, val))
except KeyError:
self._table_cache[tab] = [... | Clears and updates the table cache to be in sync with self | Below is the the instruction that describes the task:
### Input:
Clears and updates the table cache to be in sync with self
### Response:
def _update_table_cache(self):
"""Clears and updates the table cache to be in sync with self"""
self._table_cache.clear()
for sel, tab, val in self:
... |
def get_files_to_check(self):
"""Generate files and error codes to check on each one.
Walk dir trees under `self._arguments` and yield file names
that `match` under each directory that `match_dir`.
The method locates the configuration for each file name and yields a
tuple of (fi... | Generate files and error codes to check on each one.
Walk dir trees under `self._arguments` and yield file names
that `match` under each directory that `match_dir`.
The method locates the configuration for each file name and yields a
tuple of (filename, [error_codes]).
With eve... | Below is the the instruction that describes the task:
### Input:
Generate files and error codes to check on each one.
Walk dir trees under `self._arguments` and yield file names
that `match` under each directory that `match_dir`.
The method locates the configuration for each file name and y... |
def _matmul(a, b,
transpose_a=False, transpose_b=False,
adjoint_a=False, adjoint_b=False,
a_is_sparse=False, b_is_sparse=False,
name=None): # pylint: disable=unused-argument
"""Numpy matmul wrapper."""
if a_is_sparse or b_is_sparse:
raise NotImplementedError('Num... | Numpy matmul wrapper. | Below is the the instruction that describes the task:
### Input:
Numpy matmul wrapper.
### Response:
def _matmul(a, b,
transpose_a=False, transpose_b=False,
adjoint_a=False, adjoint_b=False,
a_is_sparse=False, b_is_sparse=False,
name=None): # pylint: disable=unused-... |
def random_weights(n, bounds=(0., 1.), total=1.0):
"""
Generate pseudo-random weights.
Returns a list of random weights that is of length
n, where each weight is in the range bounds, and
where the weights sum up to total.
Useful for creating random portfolios when benchmarking.
Args:
... | Generate pseudo-random weights.
Returns a list of random weights that is of length
n, where each weight is in the range bounds, and
where the weights sum up to total.
Useful for creating random portfolios when benchmarking.
Args:
* n (int): number of random weights
* bounds ((low,... | Below is the the instruction that describes the task:
### Input:
Generate pseudo-random weights.
Returns a list of random weights that is of length
n, where each weight is in the range bounds, and
where the weights sum up to total.
Useful for creating random portfolios when benchmarking.
Args... |
def _fill_albedos(self, mesh=None, irrad_frac_refl=0.0):
"""
TODO: add documentation
"""
logger.debug("{}._fill_albedos".format(self.component))
if mesh is None:
mesh = self.mesh
mesh.update_columns(irrad_frac_refl=irrad_frac_refl)
if not self.needs... | TODO: add documentation | Below is the the instruction that describes the task:
### Input:
TODO: add documentation
### Response:
def _fill_albedos(self, mesh=None, irrad_frac_refl=0.0):
"""
TODO: add documentation
"""
logger.debug("{}._fill_albedos".format(self.component))
if mesh is None:
... |
def regular_to_sparse_from_sparse_mappings(regular_to_unmasked_sparse, unmasked_sparse_to_sparse):
"""Using the mapping between the regular-grid and unmasked pixelization grid, compute the mapping between each regular
pixel and the masked pixelization grid.
Parameters
-----------
regular_to_unmaske... | Using the mapping between the regular-grid and unmasked pixelization grid, compute the mapping between each regular
pixel and the masked pixelization grid.
Parameters
-----------
regular_to_unmasked_sparse : ndarray
The index mapping between every regular-pixel and masked pixelization pixel.
... | Below is the the instruction that describes the task:
### Input:
Using the mapping between the regular-grid and unmasked pixelization grid, compute the mapping between each regular
pixel and the masked pixelization grid.
Parameters
-----------
regular_to_unmasked_sparse : ndarray
The index ... |
def crop(gens, seconds=5, cropper=None):
'''
Crop the generator to a finite number of frames
Return a generator which outputs the provided generator limited
to enough samples to produce seconds seconds of audio (default 5s)
at the provided frame rate.
'''
if hasattr(gens, "next"):
# single generator
gens = ... | Crop the generator to a finite number of frames
Return a generator which outputs the provided generator limited
to enough samples to produce seconds seconds of audio (default 5s)
at the provided frame rate. | Below is the the instruction that describes the task:
### Input:
Crop the generator to a finite number of frames
Return a generator which outputs the provided generator limited
to enough samples to produce seconds seconds of audio (default 5s)
at the provided frame rate.
### Response:
def crop(gens, seconds=5,... |
def get_version(program, *, version_arg='--version', regex=r'(\d+(\.\d+)*)'):
"Get the version of the specified program"
args_prog = [program, version_arg]
try:
proc = run(
args_prog,
close_fds=True,
universal_newlines=True,
stdout=PIPE,
st... | Get the version of the specified program | Below is the the instruction that describes the task:
### Input:
Get the version of the specified program
### Response:
def get_version(program, *, version_arg='--version', regex=r'(\d+(\.\d+)*)'):
"Get the version of the specified program"
args_prog = [program, version_arg]
try:
proc = run(
... |
def _set_rbridge_id(self, v, load=False):
"""
Setter method for rbridge_id, mapped from YANG variable /preprovision/rbridge_id (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_rbridge_id is considered as a private
method. Backends looking to populate this varia... | Setter method for rbridge_id, mapped from YANG variable /preprovision/rbridge_id (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_rbridge_id is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_rbridge_... | Below is the the instruction that describes the task:
### Input:
Setter method for rbridge_id, mapped from YANG variable /preprovision/rbridge_id (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_rbridge_id is considered as a private
method. Backends looking to popu... |
def parse(self, data, charset=None):
""" Parse the data.
It is usually a better idea to override ``_parse_data()`` than
this method in derived classes.
:param charset: the charset of the data. Uses datamapper's
default (``self.charset``) if not given.
:returns:
... | Parse the data.
It is usually a better idea to override ``_parse_data()`` than
this method in derived classes.
:param charset: the charset of the data. Uses datamapper's
default (``self.charset``) if not given.
:returns: | Below is the the instruction that describes the task:
### Input:
Parse the data.
It is usually a better idea to override ``_parse_data()`` than
this method in derived classes.
:param charset: the charset of the data. Uses datamapper's
default (``self.charset``) if not given.
... |
def macro_body(self, node, frame):
"""Dump the function def of a macro or call block."""
frame = frame.inner()
frame.symbols.analyze_node(node)
macro_ref = MacroRef(node)
explicit_caller = None
skip_special_params = set()
args = []
for idx, arg in enumera... | Dump the function def of a macro or call block. | Below is the the instruction that describes the task:
### Input:
Dump the function def of a macro or call block.
### Response:
def macro_body(self, node, frame):
"""Dump the function def of a macro or call block."""
frame = frame.inner()
frame.symbols.analyze_node(node)
macro_ref = ... |
def get(self, key, value):
"""Retrieve single group record by id or name
Supports resource cache
Keyword Args:
id (str): Full Group ID
name (str): Group name
Raises:
TypeError: Unexpected or more than one keyword argument provided
ValueE... | Retrieve single group record by id or name
Supports resource cache
Keyword Args:
id (str): Full Group ID
name (str): Group name
Raises:
TypeError: Unexpected or more than one keyword argument provided
ValueError: No matching group found based on... | Below is the the instruction that describes the task:
### Input:
Retrieve single group record by id or name
Supports resource cache
Keyword Args:
id (str): Full Group ID
name (str): Group name
Raises:
TypeError: Unexpected or more than one keyword argum... |
def use_code_colorscheme(self, name):
"""
Apply new colorscheme. (By name.)
"""
assert name in self.code_styles
self._current_code_style_name = name
self._current_style = self._generate_style() | Apply new colorscheme. (By name.) | Below is the the instruction that describes the task:
### Input:
Apply new colorscheme. (By name.)
### Response:
def use_code_colorscheme(self, name):
"""
Apply new colorscheme. (By name.)
"""
assert name in self.code_styles
self._current_code_style_name = name
self... |
def get_eager_datasource(cls, session, datasource_type, datasource_id):
"""Returns datasource with columns and metrics."""
datasource_class = ConnectorRegistry.sources[datasource_type]
return (
session.query(datasource_class)
.options(
subqueryload(datasou... | Returns datasource with columns and metrics. | Below is the the instruction that describes the task:
### Input:
Returns datasource with columns and metrics.
### Response:
def get_eager_datasource(cls, session, datasource_type, datasource_id):
"""Returns datasource with columns and metrics."""
datasource_class = ConnectorRegistry.sources[datasou... |
def get_stored_cert_serials(store):
'''
Get all of the certificate serials in the specified store
store
The store to get all the certificate serials from
CLI Example:
.. code-block:: bash
salt '*' certutil.get_stored_cert_serials <store>
'''
cmd = "certutil.exe -store {0}... | Get all of the certificate serials in the specified store
store
The store to get all the certificate serials from
CLI Example:
.. code-block:: bash
salt '*' certutil.get_stored_cert_serials <store> | Below is the the instruction that describes the task:
### Input:
Get all of the certificate serials in the specified store
store
The store to get all the certificate serials from
CLI Example:
.. code-block:: bash
salt '*' certutil.get_stored_cert_serials <store>
### Response:
def ge... |
def p_static_member(p):
'''static_member : class_name DOUBLE_COLON variable_without_objects
| variable_class_name DOUBLE_COLON variable_without_objects'''
p[0] = ast.StaticProperty(p[1], p[3], lineno=p.lineno(2)) | static_member : class_name DOUBLE_COLON variable_without_objects
| variable_class_name DOUBLE_COLON variable_without_objects | Below is the the instruction that describes the task:
### Input:
static_member : class_name DOUBLE_COLON variable_without_objects
| variable_class_name DOUBLE_COLON variable_without_objects
### Response:
def p_static_member(p):
'''static_member : class_name DOUBLE_COLON variable_without_ob... |
def entropy_bits_nrange(
minimum: Union[int, float], maximum: Union[int, float]
) -> float:
"""Calculate the number of entropy bits in a range of numbers."""
# Shannon:
# d = fabs(maximum - minimum)
# ent = -(1/d) * log(1/d, 2) * d
# Aprox form: log10(digits) * log2(10)
if not isinstance... | Calculate the number of entropy bits in a range of numbers. | Below is the the instruction that describes the task:
### Input:
Calculate the number of entropy bits in a range of numbers.
### Response:
def entropy_bits_nrange(
minimum: Union[int, float], maximum: Union[int, float]
) -> float:
"""Calculate the number of entropy bits in a range of numbers."""
# ... |
def add(self, sid, token):
"""
Add new sensor to the database
Parameters
----------
sid : str
SensorId
token : str
"""
try:
self.dbcur.execute(SQL_SENSOR_INS, (sid, token))
except sqlite3.IntegrityError: # sensor entry exi... | Add new sensor to the database
Parameters
----------
sid : str
SensorId
token : str | Below is the the instruction that describes the task:
### Input:
Add new sensor to the database
Parameters
----------
sid : str
SensorId
token : str
### Response:
def add(self, sid, token):
"""
Add new sensor to the database
Parameters
-... |
def check_dependency(self, dependency_path):
"""Check if mtime of dependency_path is greater than stored mtime."""
stored_hash = self._stamp_file_hashes.get(dependency_path)
# This file was newly added, or we don't have a file
# with stored hashes yet. Assume out of date.
if not... | Check if mtime of dependency_path is greater than stored mtime. | Below is the the instruction that describes the task:
### Input:
Check if mtime of dependency_path is greater than stored mtime.
### Response:
def check_dependency(self, dependency_path):
"""Check if mtime of dependency_path is greater than stored mtime."""
stored_hash = self._stamp_file_hashes.get... |
def reorient_wf(name='ReorientWorkflow'):
"""A workflow to reorient images to 'RPI' orientation"""
workflow = pe.Workflow(name=name)
inputnode = pe.Node(niu.IdentityInterface(fields=['in_file']),
name='inputnode')
outputnode = pe.Node(niu.IdentityInterface(
fields=['out_... | A workflow to reorient images to 'RPI' orientation | Below is the the instruction that describes the task:
### Input:
A workflow to reorient images to 'RPI' orientation
### Response:
def reorient_wf(name='ReorientWorkflow'):
"""A workflow to reorient images to 'RPI' orientation"""
workflow = pe.Workflow(name=name)
inputnode = pe.Node(niu.IdentityInterfa... |
def acquire(self, key):
"""Return the known information about the device and mark the record
as being used by a segmenation state machine."""
if _debug: DeviceInfoCache._debug("acquire %r", key)
if isinstance(key, int):
device_info = self.cache.get(key, None)
elif n... | Return the known information about the device and mark the record
as being used by a segmenation state machine. | Below is the the instruction that describes the task:
### Input:
Return the known information about the device and mark the record
as being used by a segmenation state machine.
### Response:
def acquire(self, key):
"""Return the known information about the device and mark the record
as bein... |
def init_handler(self):
""" Check self options. """
assert self.options.get('host') and self.options.get('port'), "Invalid options"
assert self.options.get('to'), 'Recipients list is empty. SMTP disabled.'
if not isinstance(self.options['to'], (list, tuple)):
self.options['to... | Check self options. | Below is the the instruction that describes the task:
### Input:
Check self options.
### Response:
def init_handler(self):
""" Check self options. """
assert self.options.get('host') and self.options.get('port'), "Invalid options"
assert self.options.get('to'), 'Recipients list is empty. SM... |
def get_proof(self):
"""
Get a proof produced while deciding the formula.
"""
if self.maplesat and self.prfile:
self.prfile.seek(0)
return [line.rstrip() for line in self.prfile.readlines()] | Get a proof produced while deciding the formula. | Below is the the instruction that describes the task:
### Input:
Get a proof produced while deciding the formula.
### Response:
def get_proof(self):
"""
Get a proof produced while deciding the formula.
"""
if self.maplesat and self.prfile:
self.prfile.seek(0)
... |
def WriteVtable(self):
"""
WriteVtable serializes the vtable for the current object, if needed.
Before writing out the vtable, this checks pre-existing vtables for
equality to this one. If an equal vtable is found, point the object to
the existing vtable and return.
Bec... | WriteVtable serializes the vtable for the current object, if needed.
Before writing out the vtable, this checks pre-existing vtables for
equality to this one. If an equal vtable is found, point the object to
the existing vtable and return.
Because vtable values are sensitive to alignme... | Below is the the instruction that describes the task:
### Input:
WriteVtable serializes the vtable for the current object, if needed.
Before writing out the vtable, this checks pre-existing vtables for
equality to this one. If an equal vtable is found, point the object to
the existing vtabl... |
def checkin_boardingpass(self, code, passenger_name, seat_class,
etkt_bnr, seat='', gate='', boarding_time=None,
is_cancel=False, qrcode_data=None, card_id=None):
"""
飞机票接口
"""
data = {
'code': code,
'passe... | 飞机票接口 | Below is the the instruction that describes the task:
### Input:
飞机票接口
### Response:
def checkin_boardingpass(self, code, passenger_name, seat_class,
etkt_bnr, seat='', gate='', boarding_time=None,
is_cancel=False, qrcode_data=None, card_id=None):
"... |
def _redis_connection_settings(self):
"""Return a dictionary of redis connection settings.
"""
return {config.HOST: self.settings.get(config.HOST, self._REDIS_HOST),
config.PORT: self.settings.get(config.PORT, self._REDIS_PORT),
'selected_db': self.settings.get(c... | Return a dictionary of redis connection settings. | Below is the the instruction that describes the task:
### Input:
Return a dictionary of redis connection settings.
### Response:
def _redis_connection_settings(self):
"""Return a dictionary of redis connection settings.
"""
return {config.HOST: self.settings.get(config.HOST, self._REDIS_HO... |
def netHours(self):
'''
For regular event staff, this is the net hours worked for financial purposes.
For Instructors, netHours is caclulated net of any substitutes.
'''
if self.specifiedHours is not None:
return self.specifiedHours
elif self.category in [getC... | For regular event staff, this is the net hours worked for financial purposes.
For Instructors, netHours is caclulated net of any substitutes. | Below is the the instruction that describes the task:
### Input:
For regular event staff, this is the net hours worked for financial purposes.
For Instructors, netHours is caclulated net of any substitutes.
### Response:
def netHours(self):
'''
For regular event staff, this is the net hours... |
def set_widgets(self):
"""Set widgets on the Field Mapping step."""
on_the_fly_metadata = {}
layer_purpose = self.parent.step_kw_purpose.selected_purpose()
on_the_fly_metadata['layer_purpose'] = layer_purpose['key']
if layer_purpose != layer_purpose_aggregation:
subca... | Set widgets on the Field Mapping step. | Below is the the instruction that describes the task:
### Input:
Set widgets on the Field Mapping step.
### Response:
def set_widgets(self):
"""Set widgets on the Field Mapping step."""
on_the_fly_metadata = {}
layer_purpose = self.parent.step_kw_purpose.selected_purpose()
on_the_fl... |
def _embedding_kernel_pca(matrix, dimensions=3, affinity_matrix=None,
sigma=1):
"""
Private method to calculate KPCA embedding
:param dimensions: (int)
:return: coordinate matrix (np.array)
"""
if affinity_matrix is None:
aff = rbf(matrix, sigma)
else:
... | Private method to calculate KPCA embedding
:param dimensions: (int)
:return: coordinate matrix (np.array) | Below is the the instruction that describes the task:
### Input:
Private method to calculate KPCA embedding
:param dimensions: (int)
:return: coordinate matrix (np.array)
### Response:
def _embedding_kernel_pca(matrix, dimensions=3, affinity_matrix=None,
sigma=1):
"""
Priv... |
def _get_fields_for_class(schema_graph, graphql_types, field_type_overrides, hidden_classes,
cls_name):
"""Return a dict from field name to GraphQL field type, for the specified graph class."""
properties = schema_graph.get_element_by_class_name(cls_name).properties
# Add leaf Gra... | Return a dict from field name to GraphQL field type, for the specified graph class. | Below is the the instruction that describes the task:
### Input:
Return a dict from field name to GraphQL field type, for the specified graph class.
### Response:
def _get_fields_for_class(schema_graph, graphql_types, field_type_overrides, hidden_classes,
cls_name):
"""Return a dict f... |
def get_transaction_status(self, transactionId):
"""
Returns the status of a given transaction.
"""
params = {}
params['TransactionId'] = transactionId
response = self.make_request("GetTransactionStatus", params)
body = response.read()
if(response.sta... | Returns the status of a given transaction. | Below is the the instruction that describes the task:
### Input:
Returns the status of a given transaction.
### Response:
def get_transaction_status(self, transactionId):
"""
Returns the status of a given transaction.
"""
params = {}
params['TransactionId'] = transactionId
... |
def export_service(self, svc_ref, export_props):
# type: (ServiceReference, Dict[str, Any]) -> EndpointDescription
"""
Exports the given service
:param svc_ref: Reference to the service to export
:param export_props: Export properties
:return: The endpoint description
... | Exports the given service
:param svc_ref: Reference to the service to export
:param export_props: Export properties
:return: The endpoint description | Below is the the instruction that describes the task:
### Input:
Exports the given service
:param svc_ref: Reference to the service to export
:param export_props: Export properties
:return: The endpoint description
### Response:
def export_service(self, svc_ref, export_props):
# ty... |
def bitpos(self, key, bit, start=None, end=None):
"""Find first bit set or clear in a string.
:raises ValueError: if bit is not 0 or 1
"""
if bit not in (1, 0):
raise ValueError("bit argument must be either 1 or 0")
bytes_range = []
if start is not None:
... | Find first bit set or clear in a string.
:raises ValueError: if bit is not 0 or 1 | Below is the the instruction that describes the task:
### Input:
Find first bit set or clear in a string.
:raises ValueError: if bit is not 0 or 1
### Response:
def bitpos(self, key, bit, start=None, end=None):
"""Find first bit set or clear in a string.
:raises ValueError: if bit is not ... |
def tabular(client, records):
"""Format dataset files with a tabular output.
:param client: LocalClient instance.
:param records: Filtered collection.
"""
from renku.models._tabulate import tabulate
echo_via_pager(
tabulate(
records,
headers=OrderedDict((
... | Format dataset files with a tabular output.
:param client: LocalClient instance.
:param records: Filtered collection. | Below is the the instruction that describes the task:
### Input:
Format dataset files with a tabular output.
:param client: LocalClient instance.
:param records: Filtered collection.
### Response:
def tabular(client, records):
"""Format dataset files with a tabular output.
:param client: LocalCli... |
def _verify_ssl_from_first(hosts):
"""Check if SSL validation parameter is passed in URI
>>> _verify_ssl_from_first(['https://myhost:4200/?verify_ssl=false'])
False
>>> _verify_ssl_from_first(['https://myhost:4200/'])
True
>>> _verify_ssl_from_first([
... 'https://h1:4200/?verify_ssl... | Check if SSL validation parameter is passed in URI
>>> _verify_ssl_from_first(['https://myhost:4200/?verify_ssl=false'])
False
>>> _verify_ssl_from_first(['https://myhost:4200/'])
True
>>> _verify_ssl_from_first([
... 'https://h1:4200/?verify_ssl=False',
... 'https://h2:4200/?ve... | Below is the the instruction that describes the task:
### Input:
Check if SSL validation parameter is passed in URI
>>> _verify_ssl_from_first(['https://myhost:4200/?verify_ssl=false'])
False
>>> _verify_ssl_from_first(['https://myhost:4200/'])
True
>>> _verify_ssl_from_first([
... '... |
def draw_round_rect(setter, x, y, w, h, r, color=None, aa=False):
"""Draw rectangle with top-left corner at x,y, width w, height h,
and corner radius r.
"""
_draw_fast_hline(setter, x + r, y, w - 2 * r, color, aa) # Top
_draw_fast_hline(setter, x + r, y + h - 1, w - 2 * r, color, aa) # Bottom
... | Draw rectangle with top-left corner at x,y, width w, height h,
and corner radius r. | Below is the the instruction that describes the task:
### Input:
Draw rectangle with top-left corner at x,y, width w, height h,
and corner radius r.
### Response:
def draw_round_rect(setter, x, y, w, h, r, color=None, aa=False):
"""Draw rectangle with top-left corner at x,y, width w, height h,
and corn... |
def get_backreferences(context, relationship=None, as_brains=None):
"""Return all objects which use a UIDReferenceField to reference context.
:param context: The object which is the target of references.
:param relationship: The relationship name of the UIDReferenceField.
:param as_brains: Requests tha... | Return all objects which use a UIDReferenceField to reference context.
:param context: The object which is the target of references.
:param relationship: The relationship name of the UIDReferenceField.
:param as_brains: Requests that this function returns only catalog brains.
as_brains can only be ... | Below is the the instruction that describes the task:
### Input:
Return all objects which use a UIDReferenceField to reference context.
:param context: The object which is the target of references.
:param relationship: The relationship name of the UIDReferenceField.
:param as_brains: Requests that this... |
def dumps(self, o):
"""
Returns a serialized string representing the object, post-deduplication.
:param o: the object
"""
f = io.BytesIO()
VaultPickler(self, f).dump(o)
f.seek(0)
return f.read() | Returns a serialized string representing the object, post-deduplication.
:param o: the object | Below is the the instruction that describes the task:
### Input:
Returns a serialized string representing the object, post-deduplication.
:param o: the object
### Response:
def dumps(self, o):
"""
Returns a serialized string representing the object, post-deduplication.
:param o: t... |
def regions_to_network(im, dt=None, voxel_size=1):
r"""
Analyzes an image that has been partitioned into pore regions and extracts
the pore and throat geometry as well as network connectivity.
Parameters
----------
im : ND-array
An image of the pore space partitioned into individual por... | r"""
Analyzes an image that has been partitioned into pore regions and extracts
the pore and throat geometry as well as network connectivity.
Parameters
----------
im : ND-array
An image of the pore space partitioned into individual pore regions.
Note that this image must have zeros... | Below is the the instruction that describes the task:
### Input:
r"""
Analyzes an image that has been partitioned into pore regions and extracts
the pore and throat geometry as well as network connectivity.
Parameters
----------
im : ND-array
An image of the pore space partitioned into ... |
def plot_compare_four(data_a, data_b, data_c, data_d, disply_kwargs=None,
plotter_kwargs=None, show_kwargs=None, screenshot=None,
camera_position=None, outline=None, outline_color='k',
labels=('A', 'B', 'C', 'D')):
"""Plot a 2 by 2 comparison of data... | Plot a 2 by 2 comparison of data objects. Plotting parameters and camera
positions will all be the same. | Below is the the instruction that describes the task:
### Input:
Plot a 2 by 2 comparison of data objects. Plotting parameters and camera
positions will all be the same.
### Response:
def plot_compare_four(data_a, data_b, data_c, data_d, disply_kwargs=None,
plotter_kwargs=None, show_kwarg... |
def _set_community_map(self, v, load=False):
"""
Setter method for community_map, mapped from YANG variable /snmp_server/mib/community_map (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_community_map is considered as a private
method. Backends looking to popu... | Setter method for community_map, mapped from YANG variable /snmp_server/mib/community_map (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_community_map is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._... | Below is the the instruction that describes the task:
### Input:
Setter method for community_map, mapped from YANG variable /snmp_server/mib/community_map (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_community_map is considered as a private
method. Backends loo... |
def has_next_question(self, assessment_section_id, item_id):
"""Tests if there is a next question following the given question ``Id``.
arg: assessment_section_id (osid.id.Id): ``Id`` of the
``AssessmentSection``
arg: item_id (osid.id.Id): ``Id`` of the ``Item``
ret... | Tests if there is a next question following the given question ``Id``.
arg: assessment_section_id (osid.id.Id): ``Id`` of the
``AssessmentSection``
arg: item_id (osid.id.Id): ``Id`` of the ``Item``
return: (boolean) - ``true`` if there is a next question,
`... | Below is the the instruction that describes the task:
### Input:
Tests if there is a next question following the given question ``Id``.
arg: assessment_section_id (osid.id.Id): ``Id`` of the
``AssessmentSection``
arg: item_id (osid.id.Id): ``Id`` of the ``Item``
return... |
def paragraphs(quantity=2, separator='\n\n', wrap_start='', wrap_end='',
html=False, sentences_quantity=3, as_list=False):
"""Random paragraphs."""
if html:
wrap_start = '<p>'
wrap_end = '</p>'
separator = '\n\n'
result = []
for i in xrange(0, quantity):
r... | Random paragraphs. | Below is the the instruction that describes the task:
### Input:
Random paragraphs.
### Response:
def paragraphs(quantity=2, separator='\n\n', wrap_start='', wrap_end='',
html=False, sentences_quantity=3, as_list=False):
"""Random paragraphs."""
if html:
wrap_start = '<p>'
wr... |
def layers(self) -> Circuit:
"""Split DAGCircuit into layers, where the operations within each
layer operate on different qubits (and therefore commute).
Returns: A Circuit of Circuits, one Circuit per layer
"""
node_depth: Dict[Qubit, int] = {}
G = self.graph
f... | Split DAGCircuit into layers, where the operations within each
layer operate on different qubits (and therefore commute).
Returns: A Circuit of Circuits, one Circuit per layer | Below is the the instruction that describes the task:
### Input:
Split DAGCircuit into layers, where the operations within each
layer operate on different qubits (and therefore commute).
Returns: A Circuit of Circuits, one Circuit per layer
### Response:
def layers(self) -> Circuit:
"""Spl... |
def calc_list_average(l):
"""
Calculates the average value of a list of numbers
Returns a float
"""
total = 0.0
for value in l:
total += value
return total / len(l) | Calculates the average value of a list of numbers
Returns a float | Below is the the instruction that describes the task:
### Input:
Calculates the average value of a list of numbers
Returns a float
### Response:
def calc_list_average(l):
"""
Calculates the average value of a list of numbers
Returns a float
"""
total = 0.0
for value in l:
total ... |
def format_pattrs(pattrs: List['api.PrettyAttribute']) -> str:
"""Generates repr string given a list of pattrs."""
output = []
pattrs.sort(
key=lambda x: (
_FORMATTER[x.display_group].display_index,
x.display_group,
x.name,
)
)
for display_group, g... | Generates repr string given a list of pattrs. | Below is the the instruction that describes the task:
### Input:
Generates repr string given a list of pattrs.
### Response:
def format_pattrs(pattrs: List['api.PrettyAttribute']) -> str:
"""Generates repr string given a list of pattrs."""
output = []
pattrs.sort(
key=lambda x: (
_F... |
def process_rewards(self, rewards):
"""Clips, rounds, and changes to integer type.
Args:
rewards: numpy array of raw (float) rewards.
Returns:
processed_rewards: numpy array of np.int64
"""
min_reward, max_reward = self.reward_range
# Clips at min and max reward.
rewards = np... | Clips, rounds, and changes to integer type.
Args:
rewards: numpy array of raw (float) rewards.
Returns:
processed_rewards: numpy array of np.int64 | Below is the the instruction that describes the task:
### Input:
Clips, rounds, and changes to integer type.
Args:
rewards: numpy array of raw (float) rewards.
Returns:
processed_rewards: numpy array of np.int64
### Response:
def process_rewards(self, rewards):
"""Clips, rounds, and chang... |
def import_rsakey_from_public_pem(pem, scheme='rsassa-pss-sha256'):
"""
<Purpose>
Generate an RSA key object from 'pem'. In addition, a keyid identifier for
the RSA key is generated. The object returned conforms to
'securesystemslib.formats.RSAKEY_SCHEMA' and has the form:
{'keytype': 'rsa',
... | <Purpose>
Generate an RSA key object from 'pem'. In addition, a keyid identifier for
the RSA key is generated. The object returned conforms to
'securesystemslib.formats.RSAKEY_SCHEMA' and has the form:
{'keytype': 'rsa',
'keyid': keyid,
'keyval': {'public': '-----BEGIN PUBLIC KEY----- ...',... | Below is the the instruction that describes the task:
### Input:
<Purpose>
Generate an RSA key object from 'pem'. In addition, a keyid identifier for
the RSA key is generated. The object returned conforms to
'securesystemslib.formats.RSAKEY_SCHEMA' and has the form:
{'keytype': 'rsa',
'keyid... |
def get_asset_lookup_session_for_repository(self, repository_id=None, proxy=None):
"""Gets the ``OsidSession`` associated with the asset lookup service for the
given repository.
arg: repository_id (osid.id.Id): the ``Id`` of the repository
arg: proxy (osid.proxy.Proxy): a proxy
... | Gets the ``OsidSession`` associated with the asset lookup service for the
given repository.
arg: repository_id (osid.id.Id): the ``Id`` of the repository
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.AssetLookupSession) - an
``AssetLookupSession``... | Below is the the instruction that describes the task:
### Input:
Gets the ``OsidSession`` associated with the asset lookup service for the
given repository.
arg: repository_id (osid.id.Id): the ``Id`` of the repository
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.repos... |
def to_python(self, value):
"""
Convert a string from the database to a Python value.
"""
if value == "":
return None
try:
if isinstance(value, six.string_types):
return self.deserializer(value)
elif isinstance(value, bytes):
... | Convert a string from the database to a Python value. | Below is the the instruction that describes the task:
### Input:
Convert a string from the database to a Python value.
### Response:
def to_python(self, value):
"""
Convert a string from the database to a Python value.
"""
if value == "":
return None
try:
... |
def check(self, var):
"""Return True if the variable matches the specified type."""
return (isinstance(var, _num_type) and
(self._lower_bound is None or var >= self._lower_bound) and
(self._upper_bound is None or var <= self._upper_bound)) | Return True if the variable matches the specified type. | Below is the the instruction that describes the task:
### Input:
Return True if the variable matches the specified type.
### Response:
def check(self, var):
"""Return True if the variable matches the specified type."""
return (isinstance(var, _num_type) and
(self._lower_bound is Non... |
def walk_oid(self, oid):
"""Get a list of SNMP varbinds in response to a walk for oid.
Each varbind in response list has a tag, iid, val and type attribute."""
var = netsnmp.Varbind(oid)
varlist = netsnmp.VarList(var)
data = self.walk(varlist)
if len(data) == 0:
... | Get a list of SNMP varbinds in response to a walk for oid.
Each varbind in response list has a tag, iid, val and type attribute. | Below is the the instruction that describes the task:
### Input:
Get a list of SNMP varbinds in response to a walk for oid.
Each varbind in response list has a tag, iid, val and type attribute.
### Response:
def walk_oid(self, oid):
"""Get a list of SNMP varbinds in response to a walk for ... |
def convert(area_um, deform, emodulus,
channel_width_in, channel_width_out,
flow_rate_in, flow_rate_out,
viscosity_in, viscosity_out,
inplace=False):
"""convert area-deformation-emodulus triplet
The conversion formula is described in :cite:`Mietke2015`.
Para... | convert area-deformation-emodulus triplet
The conversion formula is described in :cite:`Mietke2015`.
Parameters
----------
area_um: ndarray
Convex cell area [µm²]
deform: ndarray
Deformation
emodulus: ndarray
Young's Modulus [kPa]
channel_width_in: float
Ori... | Below is the the instruction that describes the task:
### Input:
convert area-deformation-emodulus triplet
The conversion formula is described in :cite:`Mietke2015`.
Parameters
----------
area_um: ndarray
Convex cell area [µm²]
deform: ndarray
Deformation
emodulus: ndarray
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.