code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def learn(self, x):
"""Encodes an input array, and performs weight updates and updates to the activity
statistics according to the respective methods implemented below."""
y = self.encode(x)
self.update_statistics([y])
self.update_weights([x],[y])
return y | Encodes an input array, and performs weight updates and updates to the activity
statistics according to the respective methods implemented below. | Below is the the instruction that describes the task:
### Input:
Encodes an input array, and performs weight updates and updates to the activity
statistics according to the respective methods implemented below.
### Response:
def learn(self, x):
"""Encodes an input array, and performs weight update... |
def _process_properties(self, properties):
"""
Transforms the command line properties into python dictionary
:return:
"""
if properties is not None:
self._properties = {}
for p in properties:
d = p.split('=')
self._propertie... | Transforms the command line properties into python dictionary
:return: | Below is the the instruction that describes the task:
### Input:
Transforms the command line properties into python dictionary
:return:
### Response:
def _process_properties(self, properties):
"""
Transforms the command line properties into python dictionary
:return:
"""
... |
def config_new(args):
'''Attempt to install a new method config into a workspace, by: generating
a template from a versioned method in the methods repo, then launching
a local editor (respecting the $EDITOR environment variable) to fill in
the incomplete input/output fields. Returns True if th... | Attempt to install a new method config into a workspace, by: generating
a template from a versioned method in the methods repo, then launching
a local editor (respecting the $EDITOR environment variable) to fill in
the incomplete input/output fields. Returns True if the config was
successfu... | Below is the the instruction that describes the task:
### Input:
Attempt to install a new method config into a workspace, by: generating
a template from a versioned method in the methods repo, then launching
a local editor (respecting the $EDITOR environment variable) to fill in
the incomplete ... |
def _update_param(self):
r"""Update parameters
This method updates the values of the algorthm parameters with the
methods provided
"""
# Update the gamma parameter.
if not isinstance(self._gamma_update, type(None)):
self._gamma = self._gamma_update(self._ga... | r"""Update parameters
This method updates the values of the algorthm parameters with the
methods provided | Below is the the instruction that describes the task:
### Input:
r"""Update parameters
This method updates the values of the algorthm parameters with the
methods provided
### Response:
def _update_param(self):
r"""Update parameters
This method updates the values of the algorthm pa... |
def get_course_data_sharing_consent(username, course_id, enterprise_customer_uuid):
"""
Get the data sharing consent object associated with a certain user of a customer for a course.
:param username: The user that grants consent.
:param course_id: The course for which consent is granted.
:param ent... | Get the data sharing consent object associated with a certain user of a customer for a course.
:param username: The user that grants consent.
:param course_id: The course for which consent is granted.
:param enterprise_customer_uuid: The consent requester.
:return: The data sharing consent object | Below is the the instruction that describes the task:
### Input:
Get the data sharing consent object associated with a certain user of a customer for a course.
:param username: The user that grants consent.
:param course_id: The course for which consent is granted.
:param enterprise_customer_uuid: The ... |
def set_read_only(self, value):
"""
Sets whether model could be modified or not
"""
if self.__read_only__ != value:
self.__read_only__ = value
self._update_read_only() | Sets whether model could be modified or not | Below is the the instruction that describes the task:
### Input:
Sets whether model could be modified or not
### Response:
def set_read_only(self, value):
"""
Sets whether model could be modified or not
"""
if self.__read_only__ != value:
self.__read_only__ = value
... |
def create_from_pybankid_exception(cls, exception):
"""Class method for initiating from a `PyBankID` exception.
:param bankid.exceptions.BankIDError exception:
:return: The wrapped exception.
:rtype: :py:class:`~FlaskPyBankIDError`
"""
return cls(
"{0}: {1}"... | Class method for initiating from a `PyBankID` exception.
:param bankid.exceptions.BankIDError exception:
:return: The wrapped exception.
:rtype: :py:class:`~FlaskPyBankIDError` | Below is the the instruction that describes the task:
### Input:
Class method for initiating from a `PyBankID` exception.
:param bankid.exceptions.BankIDError exception:
:return: The wrapped exception.
:rtype: :py:class:`~FlaskPyBankIDError`
### Response:
def create_from_pybankid_exception... |
def evaluate_binop_logical(self, operation, left, right, **kwargs):
"""
Evaluate given logical binary operation with given operands.
"""
if not operation in self.binops_logical:
raise ValueError("Invalid logical binary operation '{}'".format(operation))
result = self.... | Evaluate given logical binary operation with given operands. | Below is the the instruction that describes the task:
### Input:
Evaluate given logical binary operation with given operands.
### Response:
def evaluate_binop_logical(self, operation, left, right, **kwargs):
"""
Evaluate given logical binary operation with given operands.
"""
if not... |
def _resubscribe(self, soft=False):
"""Resubscribes to all channels found in self.channel_configs.
:param soft: if True, unsubscribes first.
:return: None
"""
# Restore non-default Bitfinex websocket configuration
if self.bitfinex_config:
self.send(**self.bit... | Resubscribes to all channels found in self.channel_configs.
:param soft: if True, unsubscribes first.
:return: None | Below is the the instruction that describes the task:
### Input:
Resubscribes to all channels found in self.channel_configs.
:param soft: if True, unsubscribes first.
:return: None
### Response:
def _resubscribe(self, soft=False):
"""Resubscribes to all channels found in self.channel_confi... |
def dump_file_by_path(self, path, **kwargs):
"""
Returns the concrete content for a file by path.
:param path: file path as string
:param kwargs: passed to state.solver.eval
:return: file contents as string
"""
file = self.state.fs.get(path)
if file is No... | Returns the concrete content for a file by path.
:param path: file path as string
:param kwargs: passed to state.solver.eval
:return: file contents as string | Below is the the instruction that describes the task:
### Input:
Returns the concrete content for a file by path.
:param path: file path as string
:param kwargs: passed to state.solver.eval
:return: file contents as string
### Response:
def dump_file_by_path(self, path, **kwargs):
... |
def _prepare_io_handler(self, handler):
"""Call the `interfaces.IOHandler.prepare` method and
remove the handler from unprepared handler list when done.
"""
logger.debug(" preparing handler: {0!r}".format(handler))
ret = handler.prepare()
logger.debug(" prepare result: ... | Call the `interfaces.IOHandler.prepare` method and
remove the handler from unprepared handler list when done. | Below is the the instruction that describes the task:
### Input:
Call the `interfaces.IOHandler.prepare` method and
remove the handler from unprepared handler list when done.
### Response:
def _prepare_io_handler(self, handler):
"""Call the `interfaces.IOHandler.prepare` method and
remove t... |
def fail_fast_imap(pool, call, items):
""" Run a function against each item in a given list, yielding each
function result in turn, where the function call is handled in a
:class:`~eventlet.greenthread.GreenThread` spawned by the provided pool.
If any function raises an exception, all other ongoing thr... | Run a function against each item in a given list, yielding each
function result in turn, where the function call is handled in a
:class:`~eventlet.greenthread.GreenThread` spawned by the provided pool.
If any function raises an exception, all other ongoing threads are killed,
and the exception is raise... | Below is the the instruction that describes the task:
### Input:
Run a function against each item in a given list, yielding each
function result in turn, where the function call is handled in a
:class:`~eventlet.greenthread.GreenThread` spawned by the provided pool.
If any function raises an exception,... |
def _prob_match(self, features):
"""Compute match probabilities.
Parameters
----------
features : numpy.ndarray
The data to train the model on.
Returns
-------
numpy.ndarray
The match probabilties.
"""
# compute the proba... | Compute match probabilities.
Parameters
----------
features : numpy.ndarray
The data to train the model on.
Returns
-------
numpy.ndarray
The match probabilties. | Below is the the instruction that describes the task:
### Input:
Compute match probabilities.
Parameters
----------
features : numpy.ndarray
The data to train the model on.
Returns
-------
numpy.ndarray
The match probabilties.
### Response:
... |
def find_genus(files, database, threads=12):
"""
Uses MASH to find the genus of fasta files.
:param files: File dictionary returned by filer method.
:param database: Path to reduced refseq database sketch.
:param threads: Number of threads to run mash with.
:return: genus_dict: Dictionary of gen... | Uses MASH to find the genus of fasta files.
:param files: File dictionary returned by filer method.
:param database: Path to reduced refseq database sketch.
:param threads: Number of threads to run mash with.
:return: genus_dict: Dictionary of genus for each sample. Will return NA if genus could not be ... | Below is the the instruction that describes the task:
### Input:
Uses MASH to find the genus of fasta files.
:param files: File dictionary returned by filer method.
:param database: Path to reduced refseq database sketch.
:param threads: Number of threads to run mash with.
:return: genus_dict: Dicti... |
def reject(self, f, *args):
"""Like 'match', but throw a parse error if 'f' matches.
This is useful when a parser wants to be strict about specific things
being prohibited. For example, DottySQL bans the use of SQL keywords as
variable names.
"""
match = self.match(f, *a... | Like 'match', but throw a parse error if 'f' matches.
This is useful when a parser wants to be strict about specific things
being prohibited. For example, DottySQL bans the use of SQL keywords as
variable names. | Below is the the instruction that describes the task:
### Input:
Like 'match', but throw a parse error if 'f' matches.
This is useful when a parser wants to be strict about specific things
being prohibited. For example, DottySQL bans the use of SQL keywords as
variable names.
### Response: ... |
def __look_up_geom(self, geomType):
""" compares the geometry object's type verse the JSOn
specs for geometry types
Inputs:
geomType - string - geometry object's type
Returns:
string JSON geometry type or None if not an allowed type
"""
... | compares the geometry object's type verse the JSOn
specs for geometry types
Inputs:
geomType - string - geometry object's type
Returns:
string JSON geometry type or None if not an allowed type | Below is the the instruction that describes the task:
### Input:
compares the geometry object's type verse the JSOn
specs for geometry types
Inputs:
geomType - string - geometry object's type
Returns:
string JSON geometry type or None if not an allowe... |
def guard_sample(analysis_request):
"""Returns whether 'sample' transition can be performed or not. Returns
True only if the analysis request has the DateSampled and Sampler set or if
the user belongs to the Samplers group
"""
if analysis_request.getDateSampled() and analysis_request.getSampler():
... | Returns whether 'sample' transition can be performed or not. Returns
True only if the analysis request has the DateSampled and Sampler set or if
the user belongs to the Samplers group | Below is the the instruction that describes the task:
### Input:
Returns whether 'sample' transition can be performed or not. Returns
True only if the analysis request has the DateSampled and Sampler set or if
the user belongs to the Samplers group
### Response:
def guard_sample(analysis_request):
"""R... |
def plot_ants_plane(off_screen=False, notebook=None):
"""
Demonstrate how to create a plot class to plot multiple meshes while
adding scalars and text.
Plot two ants and airplane
"""
# load and shrink airplane
airplane = vtki.PolyData(planefile)
airplane.points /= 10
# pts = airpla... | Demonstrate how to create a plot class to plot multiple meshes while
adding scalars and text.
Plot two ants and airplane | Below is the the instruction that describes the task:
### Input:
Demonstrate how to create a plot class to plot multiple meshes while
adding scalars and text.
Plot two ants and airplane
### Response:
def plot_ants_plane(off_screen=False, notebook=None):
"""
Demonstrate how to create a plot class t... |
def migrated(name,
remote_addr,
cert,
key,
verify_cert,
src_remote_addr,
stop_and_start=False,
src_cert=None,
src_key=None,
src_verify_cert=None):
''' Ensure a container is migrated to another host
... | Ensure a container is migrated to another host
If the container is running, it either must be shut down
first (use stop_and_start=True) or criu must be installed
on the source and destination machines.
For this operation both certs need to be authenticated,
use :mod:`lxd.authenticate <salt.states.... | Below is the the instruction that describes the task:
### Input:
Ensure a container is migrated to another host
If the container is running, it either must be shut down
first (use stop_and_start=True) or criu must be installed
on the source and destination machines.
For this operation both certs n... |
def hicpro_mapping_chart (self):
""" Generate the HiC-Pro Aligned reads plot """
# Specify the order of the different possible categories
keys = OrderedDict()
keys['Full_Alignments_Read'] = { 'color': '#005ce6', 'name': 'Full reads Alignments' }
keys['Trimmed_Alignments_Read']... | Generate the HiC-Pro Aligned reads plot | Below is the the instruction that describes the task:
### Input:
Generate the HiC-Pro Aligned reads plot
### Response:
def hicpro_mapping_chart (self):
""" Generate the HiC-Pro Aligned reads plot """
# Specify the order of the different possible categories
keys = OrderedDict()
keys... |
def find(soup, name=None, attrs=None, recursive=True, text=None, **kwargs):
"""Modified find method; see `find_all`, above.
"""
tags = find_all(
soup, name, attrs or {}, recursive, text, 1, **kwargs
)
if tags:
return tags[0] | Modified find method; see `find_all`, above. | Below is the the instruction that describes the task:
### Input:
Modified find method; see `find_all`, above.
### Response:
def find(soup, name=None, attrs=None, recursive=True, text=None, **kwargs):
"""Modified find method; see `find_all`, above.
"""
tags = find_all(
soup, name, attrs or {}, ... |
def timestamp_pb(self):
"""Return a timestamp message.
Returns:
(:class:`~google.protobuf.timestamp_pb2.Timestamp`): Timestamp message
"""
inst = self if self.tzinfo is not None else self.replace(tzinfo=pytz.UTC)
delta = inst - _UTC_EPOCH
seconds = int(delta.... | Return a timestamp message.
Returns:
(:class:`~google.protobuf.timestamp_pb2.Timestamp`): Timestamp message | Below is the the instruction that describes the task:
### Input:
Return a timestamp message.
Returns:
(:class:`~google.protobuf.timestamp_pb2.Timestamp`): Timestamp message
### Response:
def timestamp_pb(self):
"""Return a timestamp message.
Returns:
(:class:`~goog... |
def bind(cls):
"""
Bind the buttons to adapter's event handler.
"""
super(cls, cls).bind()
cls.search_btn_el.bind("click", cls.start)
cls.input_el.bind("keypress", func_on_enter(cls.start)) | Bind the buttons to adapter's event handler. | Below is the the instruction that describes the task:
### Input:
Bind the buttons to adapter's event handler.
### Response:
def bind(cls):
"""
Bind the buttons to adapter's event handler.
"""
super(cls, cls).bind()
cls.search_btn_el.bind("click", cls.start)
cls.inpu... |
def error_response(self, e):
"""Make response for an IIIFError e.
Also add compliance header.
"""
self.add_compliance_header()
return self.make_response(*e.image_server_response(self.api_version)) | Make response for an IIIFError e.
Also add compliance header. | Below is the the instruction that describes the task:
### Input:
Make response for an IIIFError e.
Also add compliance header.
### Response:
def error_response(self, e):
"""Make response for an IIIFError e.
Also add compliance header.
"""
self.add_compliance_header()
... |
def run(self):
"""A bit bulky atm..."""
self.close_connection = False
try:
while True:
self.started_response = False
self.status = ""
self.outheaders = []
self.sent_headers = False
self.chunked_write = False
self.write_buffer = StringIO.Strin... | A bit bulky atm... | Below is the the instruction that describes the task:
### Input:
A bit bulky atm...
### Response:
def run(self):
"""A bit bulky atm..."""
self.close_connection = False
try:
while True:
self.started_response = False
self.status = ""
self.outheaders = []
se... |
def _make_key(self):
"""Make a key for caching files in the LRU cache."""
value = (self._opener,
self._args,
'a' if self._mode == 'w' else self._mode,
tuple(sorted(self._kwargs.items())))
return _HashedSequence(value) | Make a key for caching files in the LRU cache. | Below is the the instruction that describes the task:
### Input:
Make a key for caching files in the LRU cache.
### Response:
def _make_key(self):
"""Make a key for caching files in the LRU cache."""
value = (self._opener,
self._args,
'a' if self._mode == 'w' else ... |
def word2vec(
train,
output,
size=100,
window=5,
sample="1e-3",
hs=0,
negative=5,
threads=12,
iter_=5,
min_count=5,
alpha=0.025,
debug=2,
binary=1,
cbow=1,
save_vocab=None,
read_vocab=None,
... | word2vec execution
Parameters for training:
train <file>
Use text data from <file> to train the model
output <file>
Use <file> to save the resulting word vectors / word clusters
size <int>
Set size of word vectors; default is 100
window <int>
... | Below is the the instruction that describes the task:
### Input:
word2vec execution
Parameters for training:
train <file>
Use text data from <file> to train the model
output <file>
Use <file> to save the resulting word vectors / word clusters
size <int>
... |
def get(self, name, default=None):
'''
Gets the object for "name", or None if there's no such object. If
"default" is provided, return it if no object is found.
'''
session = self.__get_session_from_db()
return session.get(name, default) | Gets the object for "name", or None if there's no such object. If
"default" is provided, return it if no object is found. | Below is the the instruction that describes the task:
### Input:
Gets the object for "name", or None if there's no such object. If
"default" is provided, return it if no object is found.
### Response:
def get(self, name, default=None):
'''
Gets the object for "name", or None if there's no s... |
def get_computation(self,
message: Message,
transaction_context: 'BaseTransactionContext') -> 'BaseComputation':
"""
Return a computation instance for the given `message` and `transaction_context`
"""
if self.computation_class is None:
... | Return a computation instance for the given `message` and `transaction_context` | Below is the the instruction that describes the task:
### Input:
Return a computation instance for the given `message` and `transaction_context`
### Response:
def get_computation(self,
message: Message,
transaction_context: 'BaseTransactionContext') -> 'BaseComputati... |
def _GetUsernameFromProfilePath(self, path):
"""Retrieves the username from a Windows profile path.
Trailing path path segment are ignored.
Args:
path (str): a Windows path with '\\' as path segment separator.
Returns:
str: basename which is the last path segment.
"""
# Strip trai... | Retrieves the username from a Windows profile path.
Trailing path path segment are ignored.
Args:
path (str): a Windows path with '\\' as path segment separator.
Returns:
str: basename which is the last path segment. | Below is the the instruction that describes the task:
### Input:
Retrieves the username from a Windows profile path.
Trailing path path segment are ignored.
Args:
path (str): a Windows path with '\\' as path segment separator.
Returns:
str: basename which is the last path segment.
### Res... |
def is_depsignal_handler(class_, signal_name, cb, *, defer=False):
"""
Return true if `cb` has been decorated with :func:`depsignal` for the given
signal, class and connection mode.
"""
try:
handlers = get_magic_attr(cb)
except AttributeError:
return False
return _depsignal_... | Return true if `cb` has been decorated with :func:`depsignal` for the given
signal, class and connection mode. | Below is the the instruction that describes the task:
### Input:
Return true if `cb` has been decorated with :func:`depsignal` for the given
signal, class and connection mode.
### Response:
def is_depsignal_handler(class_, signal_name, cb, *, defer=False):
"""
Return true if `cb` has been decorated wit... |
def _handle_next_task(self):
"""
We have to catch three ways a task can be "done":
1. normal execution: the task runs/fails and puts a result back on the queue,
2. new dependencies: the task yielded new deps that were not complete and
will be rescheduled and dependencies adde... | We have to catch three ways a task can be "done":
1. normal execution: the task runs/fails and puts a result back on the queue,
2. new dependencies: the task yielded new deps that were not complete and
will be rescheduled and dependencies added,
3. child process dies: we need to catc... | Below is the the instruction that describes the task:
### Input:
We have to catch three ways a task can be "done":
1. normal execution: the task runs/fails and puts a result back on the queue,
2. new dependencies: the task yielded new deps that were not complete and
will be rescheduled a... |
def local_open(url):
"""Read a local path, with special support for directories"""
scheme, server, path, param, query, frag = urlparse(url)
filename = url2pathname(path)
if os.path.isfile(filename):
return urllib2.urlopen(url)
elif path.endswith('/') and os.path.isdir(filename):
file... | Read a local path, with special support for directories | Below is the the instruction that describes the task:
### Input:
Read a local path, with special support for directories
### Response:
def local_open(url):
"""Read a local path, with special support for directories"""
scheme, server, path, param, query, frag = urlparse(url)
filename = url2pathname(path... |
def _encode_long(name, value, dummy0, dummy1):
"""Encode a python long (python 2.x)"""
try:
return b"\x12" + name + _PACK_LONG(value)
except struct.error:
raise OverflowError("BSON can only handle up to 8-byte ints") | Encode a python long (python 2.x) | Below is the the instruction that describes the task:
### Input:
Encode a python long (python 2.x)
### Response:
def _encode_long(name, value, dummy0, dummy1):
"""Encode a python long (python 2.x)"""
try:
return b"\x12" + name + _PACK_LONG(value)
except struct.error:
raise OverflowError... |
def _update_message(self, sending_cluster):
"""
This is the message-update method.
Parameters
----------
sending_cluster: The resulting messages are lambda_{c-->s} from the given
cluster 'c' to all of its intersection_sets 's'.
Here 's' are the elements ... | This is the message-update method.
Parameters
----------
sending_cluster: The resulting messages are lambda_{c-->s} from the given
cluster 'c' to all of its intersection_sets 's'.
Here 's' are the elements of intersection_sets_for_cluster_c.
Reference
--... | Below is the the instruction that describes the task:
### Input:
This is the message-update method.
Parameters
----------
sending_cluster: The resulting messages are lambda_{c-->s} from the given
cluster 'c' to all of its intersection_sets 's'.
Here 's' are the eleme... |
def distance_to_semi_arc(alon, alat, aazimuth, plons, plats):
"""
In this method we use a reference system centerd on (alon, alat) and with
the y-axis corresponding to aazimuth direction to calculate the minimum
distance from a semiarc with generates in (alon, alat).
Parameters are the same as for ... | In this method we use a reference system centerd on (alon, alat) and with
the y-axis corresponding to aazimuth direction to calculate the minimum
distance from a semiarc with generates in (alon, alat).
Parameters are the same as for :func:`distance_to_arc`. | Below is the the instruction that describes the task:
### Input:
In this method we use a reference system centerd on (alon, alat) and with
the y-axis corresponding to aazimuth direction to calculate the minimum
distance from a semiarc with generates in (alon, alat).
Parameters are the same as for :func... |
def set_timeout(name, value, power='ac', scheme=None):
'''
Set the sleep timeouts of specific items such as disk, monitor, etc.
Args:
name (str)
The setting to change, can be one of the following:
- ``monitor``
- ``disk``
- ``standby``
... | Set the sleep timeouts of specific items such as disk, monitor, etc.
Args:
name (str)
The setting to change, can be one of the following:
- ``monitor``
- ``disk``
- ``standby``
- ``hibernate``
value (int):
Th... | Below is the the instruction that describes the task:
### Input:
Set the sleep timeouts of specific items such as disk, monitor, etc.
Args:
name (str)
The setting to change, can be one of the following:
- ``monitor``
- ``disk``
- ``standby``... |
def fast_compare(tree1, tree2):
""" This is optimized to compare two AST trees for equality.
It makes several assumptions that are currently true for
AST trees used by rtrip, and it doesn't examine the _attributes.
"""
geta = ast.AST.__getattribute__
work = [(tree1, tree2)]
pop = w... | This is optimized to compare two AST trees for equality.
It makes several assumptions that are currently true for
AST trees used by rtrip, and it doesn't examine the _attributes. | Below is the the instruction that describes the task:
### Input:
This is optimized to compare two AST trees for equality.
It makes several assumptions that are currently true for
AST trees used by rtrip, and it doesn't examine the _attributes.
### Response:
def fast_compare(tree1, tree2):
""" T... |
def _call_cmd_line(self):
"""Run the command line tool."""
try:
logging.info("Calling Popen with: {}".format(self.args))
p = Popen(self.args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
except OSError:
raise(RuntimeError("No such command found in PATH"))
# ... | Run the command line tool. | Below is the the instruction that describes the task:
### Input:
Run the command line tool.
### Response:
def _call_cmd_line(self):
"""Run the command line tool."""
try:
logging.info("Calling Popen with: {}".format(self.args))
p = Popen(self.args, stdin=PIPE, stdout=PIPE, st... |
def wait_for_operation_to_complete(
has_operation_completed, retries=10, delay_bw_retries=5,
delay_before_attempts=10, failover_exc=exception.IloError,
failover_msg=("Operation did not complete even after multiple "
"attempts."), is_silent_loop_exit=False):
"""Attempts ... | Attempts the provided operation for a specified number of times.
If it runs out of attempts, then it raises an exception. On success,
it breaks out of the loop.
:param has_operation_completed: the method to retry and it needs to return
a boolean to indicate success or fa... | Below is the the instruction that describes the task:
### Input:
Attempts the provided operation for a specified number of times.
If it runs out of attempts, then it raises an exception. On success,
it breaks out of the loop.
:param has_operation_completed: the method to retry and it needs to return
... |
def metadata(dataset, node, entityids, extended=False, api_key=None):
"""
Request metadata for a given scene in a USGS dataset.
:param dataset:
:param node:
:param entityids:
:param extended:
Send a second request to the metadata url to get extended metadata on the scene.
:param api... | Request metadata for a given scene in a USGS dataset.
:param dataset:
:param node:
:param entityids:
:param extended:
Send a second request to the metadata url to get extended metadata on the scene.
:param api_key: | Below is the the instruction that describes the task:
### Input:
Request metadata for a given scene in a USGS dataset.
:param dataset:
:param node:
:param entityids:
:param extended:
Send a second request to the metadata url to get extended metadata on the scene.
:param api_key:
### Res... |
def WriteOutput(self, output_file, feed_merger,
old_feed_path, new_feed_path, merged_feed_path):
"""Write the HTML output to a file.
Args:
output_file: The file object that the HTML output will be written to.
feed_merger: The FeedMerger instance.
old_feed_path: The path to t... | Write the HTML output to a file.
Args:
output_file: The file object that the HTML output will be written to.
feed_merger: The FeedMerger instance.
old_feed_path: The path to the old feed file as a string.
new_feed_path: The path to the new feed file as a string
merged_feed_path: The p... | Below is the the instruction that describes the task:
### Input:
Write the HTML output to a file.
Args:
output_file: The file object that the HTML output will be written to.
feed_merger: The FeedMerger instance.
old_feed_path: The path to the old feed file as a string.
new_feed_path: Th... |
def is_valid_line(self, line):
"""
Validates a given line against the associated "section" (e.g. 'global'
or 'frontend', etc.) of a stanza.
If a line represents a directive that shouldn't be within the stanza
it is rejected. See the `directives.json` file for a condensed look
... | Validates a given line against the associated "section" (e.g. 'global'
or 'frontend', etc.) of a stanza.
If a line represents a directive that shouldn't be within the stanza
it is rejected. See the `directives.json` file for a condensed look
at valid directives based on section. | Below is the the instruction that describes the task:
### Input:
Validates a given line against the associated "section" (e.g. 'global'
or 'frontend', etc.) of a stanza.
If a line represents a directive that shouldn't be within the stanza
it is rejected. See the `directives.json` file for ... |
def addMethod(self, m):
"""
Adds a L{Method} to the interface
"""
if m.nargs == -1:
m.nargs = len([a for a in marshal.genCompleteTypes(m.sigIn)])
m.nret = len([a for a in marshal.genCompleteTypes(m.sigOut)])
self.methods[m.name] = m
self._xml = Non... | Adds a L{Method} to the interface | Below is the the instruction that describes the task:
### Input:
Adds a L{Method} to the interface
### Response:
def addMethod(self, m):
"""
Adds a L{Method} to the interface
"""
if m.nargs == -1:
m.nargs = len([a for a in marshal.genCompleteTypes(m.sigIn)])
... |
def _callRestartAgent(self, ev_data: RestartLogData, failTimeout) -> None:
"""
Callback which is called when restart time come.
Writes restart record to restart log and asks
node control service to perform restart
:param ev_data: restart event data
:param version: versio... | Callback which is called when restart time come.
Writes restart record to restart log and asks
node control service to perform restart
:param ev_data: restart event data
:param version: version to restart to | Below is the the instruction that describes the task:
### Input:
Callback which is called when restart time come.
Writes restart record to restart log and asks
node control service to perform restart
:param ev_data: restart event data
:param version: version to restart to
### Respon... |
def on_api_socket_reconnected(self):
"""for API socket reconnected"""
# auto subscriber
resub_count = 0
subtype_list = []
code_list = []
resub_dict = copy(self._ctx_subscribe)
subtype_all_cnt = len(resub_dict.keys())
subtype_cur_cnt = 0
ret_code ... | for API socket reconnected | Below is the the instruction that describes the task:
### Input:
for API socket reconnected
### Response:
def on_api_socket_reconnected(self):
"""for API socket reconnected"""
# auto subscriber
resub_count = 0
subtype_list = []
code_list = []
resub_dict = copy(self.... |
def _execute(self,
native,
command,
data=None,
returning=True,
mapper=dict):
"""
Executes the inputted command into the current \
connection cursor.
:param command | <str>
da... | Executes the inputted command into the current \
connection cursor.
:param command | <str>
data | <dict> || None
:return [{<str> key: <variant>, ..}, ..], <int> count | Below is the the instruction that describes the task:
### Input:
Executes the inputted command into the current \
connection cursor.
:param command | <str>
data | <dict> || None
:return [{<str> key: <variant>, ..}, ..], <int> count
### Response:
def _... |
def zeroing(dev):
""" zeroing last few blocks of device """
# this kills the crab
#
# sgdisk will wipe out the main copy of the GPT partition
# table (sorry), but it doesn't remove the backup copies, and
# subsequent commands will continue to complain and fail when
# they see those. zeroing... | zeroing last few blocks of device | Below is the the instruction that describes the task:
### Input:
zeroing last few blocks of device
### Response:
def zeroing(dev):
""" zeroing last few blocks of device """
# this kills the crab
#
# sgdisk will wipe out the main copy of the GPT partition
# table (sorry), but it doesn't remove t... |
def get(self, frame_to, frame_from=None):
"""
Get the transform from one frame to another, assuming they are connected
in the transform tree.
If the frames are not connected a NetworkXNoPath error will be raised.
Parameters
---------
frame_from: hashable object,... | Get the transform from one frame to another, assuming they are connected
in the transform tree.
If the frames are not connected a NetworkXNoPath error will be raised.
Parameters
---------
frame_from: hashable object, usually a string (eg 'world').
If left as... | Below is the the instruction that describes the task:
### Input:
Get the transform from one frame to another, assuming they are connected
in the transform tree.
If the frames are not connected a NetworkXNoPath error will be raised.
Parameters
---------
frame_from: hashable ... |
def docker_pull(image):
'''Pulls an image'''
args = ['docker', 'pull', image]
# If this fails, the default docker stdout/stderr looks good to the user.
ret = call(args)
if ret != 0:
raise DockerError('Failed to pull image "{}"'.format(image)) | Pulls an image | Below is the the instruction that describes the task:
### Input:
Pulls an image
### Response:
def docker_pull(image):
'''Pulls an image'''
args = ['docker', 'pull', image]
# If this fails, the default docker stdout/stderr looks good to the user.
ret = call(args)
if ret != 0:
raise Dock... |
def run_cli_options(args):
"""
Quick implementation of Python interpreter's -m, -c and file execution.
The resulting dictionary is imported into global namespace, just in case
someone is using interactive mode.
We try to keep argument order as to pass them correctly to the subcommands.
"""
... | Quick implementation of Python interpreter's -m, -c and file execution.
The resulting dictionary is imported into global namespace, just in case
someone is using interactive mode.
We try to keep argument order as to pass them correctly to the subcommands. | Below is the the instruction that describes the task:
### Input:
Quick implementation of Python interpreter's -m, -c and file execution.
The resulting dictionary is imported into global namespace, just in case
someone is using interactive mode.
We try to keep argument order as to pass them correctly to... |
def on_augassign(self, node): # ('target', 'op', 'value')
"""Augmented assign."""
return self.on_assign(ast.Assign(targets=[node.target],
value=ast.BinOp(left=node.target,
op=node.op,
... | Augmented assign. | Below is the the instruction that describes the task:
### Input:
Augmented assign.
### Response:
def on_augassign(self, node): # ('target', 'op', 'value')
"""Augmented assign."""
return self.on_assign(ast.Assign(targets=[node.target],
value=ast.BinOp(left... |
def cls_build(inst, state):
"""
Apply the setstate protocol to initialize `inst` from `state`.
INPUT:
- ``inst`` -- a raw instance of a class
- ``state`` -- the state to restore; typically a dictionary mapping attribute names to their values
EXAMPLES::
>>> from openmath.convert_pickl... | Apply the setstate protocol to initialize `inst` from `state`.
INPUT:
- ``inst`` -- a raw instance of a class
- ``state`` -- the state to restore; typically a dictionary mapping attribute names to their values
EXAMPLES::
>>> from openmath.convert_pickle import cls_build
>>> class A(o... | Below is the the instruction that describes the task:
### Input:
Apply the setstate protocol to initialize `inst` from `state`.
INPUT:
- ``inst`` -- a raw instance of a class
- ``state`` -- the state to restore; typically a dictionary mapping attribute names to their values
EXAMPLES::
>>... |
def rowsWithin(self, bbox):
'return list of deduped rows within bbox'
ret = {}
for y in range(bbox.ymin, bbox.ymax+1):
for x in range(bbox.xmin, bbox.xmax+1):
for attr, rows in self.pixels[y][x].items():
if attr not in self.hiddenAttrs:
... | return list of deduped rows within bbox | Below is the the instruction that describes the task:
### Input:
return list of deduped rows within bbox
### Response:
def rowsWithin(self, bbox):
'return list of deduped rows within bbox'
ret = {}
for y in range(bbox.ymin, bbox.ymax+1):
for x in range(bbox.xmin, bbox.xmax+1):
... |
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
... | Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential. | Below is the the instruction that describes the task:
### Input:
Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
### Respon... |
def _set_mark(self, v, load=False):
"""
Setter method for mark, mapped from YANG variable /qos/map/dscp_mutation/mark (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_mark is considered as a private
method. Backends looking to populate this variable should
... | Setter method for mark, mapped from YANG variable /qos/map/dscp_mutation/mark (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_mark is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_mark() directly. | Below is the the instruction that describes the task:
### Input:
Setter method for mark, mapped from YANG variable /qos/map/dscp_mutation/mark (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_mark is considered as a private
method. Backends looking to populate this... |
def hash_reference_links(text, hashes, markdown_obj):
"""Hashes an <a> link or an <img> link.
This function only converts reference link styles:
[text here][ref id]
![alt text here][ref id]
For inline style links, see hash_inline_links.
Reference ids can be defined anywhere in the Ma... | Hashes an <a> link or an <img> link.
This function only converts reference link styles:
[text here][ref id]
![alt text here][ref id]
For inline style links, see hash_inline_links.
Reference ids can be defined anywhere in the Markdown text.
Reference ids can also be omitted, in which ... | Below is the the instruction that describes the task:
### Input:
Hashes an <a> link or an <img> link.
This function only converts reference link styles:
[text here][ref id]
![alt text here][ref id]
For inline style links, see hash_inline_links.
Reference ids can be defined anywhere i... |
def nodes_to_check(self, docs):
"""\
returns a list of nodes we want to search
on like paragraphs and tables
"""
nodes_to_check = []
for doc in docs:
for tag in ['p', 'pre', 'td']:
items = self.parser.getElementsByTag(doc, tag=tag)
... | \
returns a list of nodes we want to search
on like paragraphs and tables | Below is the the instruction that describes the task:
### Input:
\
returns a list of nodes we want to search
on like paragraphs and tables
### Response:
def nodes_to_check(self, docs):
"""\
returns a list of nodes we want to search
on like paragraphs and tables
"""
... |
def prepare_method_call(self, method, args):
"""
Wraps a method so that method() will call ``method(*args)`` or ``method(**args)``,
depending of args type
:param method: a callable object (method)
:param args: dict or list with the parameters for the function
:return: a ... | Wraps a method so that method() will call ``method(*args)`` or ``method(**args)``,
depending of args type
:param method: a callable object (method)
:param args: dict or list with the parameters for the function
:return: a 'patched' callable | Below is the the instruction that describes the task:
### Input:
Wraps a method so that method() will call ``method(*args)`` or ``method(**args)``,
depending of args type
:param method: a callable object (method)
:param args: dict or list with the parameters for the function
:return... |
def jacobi( a, n ):
"""Jacobi symbol"""
# Based on the Handbook of Applied Cryptography (HAC), algorithm 2.149.
# This function has been tested by comparison with a small
# table printed in HAC, and by extensive use in calculating
# modular square roots.
assert n >= 3
assert n%2 == 1
a = a % n
if a... | Jacobi symbol | Below is the the instruction that describes the task:
### Input:
Jacobi symbol
### Response:
def jacobi( a, n ):
"""Jacobi symbol"""
# Based on the Handbook of Applied Cryptography (HAC), algorithm 2.149.
# This function has been tested by comparison with a small
# table printed in HAC, and by extensive ... |
def get_value_for_datastore(self, model_instance):
"""Gets value for datastore.
Args:
model_instance: instance of the model class.
Returns:
datastore-compatible value.
"""
value = super(JsonProperty, self).get_value_for_datastore(model_instance)
if not value:
return None
... | Gets value for datastore.
Args:
model_instance: instance of the model class.
Returns:
datastore-compatible value. | Below is the the instruction that describes the task:
### Input:
Gets value for datastore.
Args:
model_instance: instance of the model class.
Returns:
datastore-compatible value.
### Response:
def get_value_for_datastore(self, model_instance):
"""Gets value for datastore.
Args:
... |
def get_conn(self):
"""
Returns a cassandra Session object
"""
if self.session and not self.session.is_shutdown:
return self.session
self.session = self.cluster.connect(self.keyspace)
return self.session | Returns a cassandra Session object | Below is the the instruction that describes the task:
### Input:
Returns a cassandra Session object
### Response:
def get_conn(self):
"""
Returns a cassandra Session object
"""
if self.session and not self.session.is_shutdown:
return self.session
self.session = s... |
def get_form_field_dict(self, model_dict):
"""
Takes a model dictionary representation and creates a dictionary
keyed by form field. Each value is a keyed 4 tuple of:
(widget, mode_field_instance, model_field_type, field_key)
"""
return_dict = OrderedDict()
# Wo... | Takes a model dictionary representation and creates a dictionary
keyed by form field. Each value is a keyed 4 tuple of:
(widget, mode_field_instance, model_field_type, field_key) | Below is the the instruction that describes the task:
### Input:
Takes a model dictionary representation and creates a dictionary
keyed by form field. Each value is a keyed 4 tuple of:
(widget, mode_field_instance, model_field_type, field_key)
### Response:
def get_form_field_dict(self, model_dic... |
def add_my_api_key_to_groups(self, body, **kwargs): # noqa: E501
"""Add API key to a list of groups. # noqa: E501
An endpoint for adding API key to groups. **Example usage:** `curl -X POST https://api.us-east-1.mbedcloud.com/v3/api-keys/me/groups -d '[0162056a9a1586f30242590700000000,0117056a9a1586... | Add API key to a list of groups. # noqa: E501
An endpoint for adding API key to groups. **Example usage:** `curl -X POST https://api.us-east-1.mbedcloud.com/v3/api-keys/me/groups -d '[0162056a9a1586f30242590700000000,0117056a9a1586f30242590700000000]' -H 'content-type: application/json' -H 'Authorization: B... | Below is the the instruction that describes the task:
### Input:
Add API key to a list of groups. # noqa: E501
An endpoint for adding API key to groups. **Example usage:** `curl -X POST https://api.us-east-1.mbedcloud.com/v3/api-keys/me/groups -d '[0162056a9a1586f30242590700000000,0117056a9a1586f3024259... |
def read_from_file(path, file_type='text', exception=ScriptWorkerException):
"""Read from ``path``.
Small helper function to read from ``file``.
Args:
path (str): the path to read from.
file_type (str, optional): the type of file. Currently accepts
``text`` or ``binary``. Defau... | Read from ``path``.
Small helper function to read from ``file``.
Args:
path (str): the path to read from.
file_type (str, optional): the type of file. Currently accepts
``text`` or ``binary``. Defaults to ``text``.
exception (Exception, optional): the exception to raise
... | Below is the the instruction that describes the task:
### Input:
Read from ``path``.
Small helper function to read from ``file``.
Args:
path (str): the path to read from.
file_type (str, optional): the type of file. Currently accepts
``text`` or ``binary``. Defaults to ``text``... |
def method(self, value):
"""
Before assigning the value validate that is in one of the
HTTP methods we implement
"""
keys = self._methods.keys()
if value not in keys:
raise AttributeError("Method value not in " + str(keys))
else:
self._meth... | Before assigning the value validate that is in one of the
HTTP methods we implement | Below is the the instruction that describes the task:
### Input:
Before assigning the value validate that is in one of the
HTTP methods we implement
### Response:
def method(self, value):
"""
Before assigning the value validate that is in one of the
HTTP methods we implement
... |
def createNotification(self, ulOverlayHandle, ulUserValue, type_, pchText, style):
"""
Create a notification and enqueue it to be shown to the user.
An overlay handle is required to create a notification, as otherwise it would be impossible for a user to act on it.
To create a two-line n... | Create a notification and enqueue it to be shown to the user.
An overlay handle is required to create a notification, as otherwise it would be impossible for a user to act on it.
To create a two-line notification, use a line break ('\n') to split the text into two lines.
The pImage argument may ... | Below is the the instruction that describes the task:
### Input:
Create a notification and enqueue it to be shown to the user.
An overlay handle is required to create a notification, as otherwise it would be impossible for a user to act on it.
To create a two-line notification, use a line break ('\n... |
def _populate_lp(self, dataset, **kwargs):
"""
Populate columns necessary for an LP dataset
This should not be called directly, but rather via :meth:`Body.populate_observable`
or :meth:`System.populate_observables`
"""
logger.debug("{}._populate_lp(dataset={})".format(se... | Populate columns necessary for an LP dataset
This should not be called directly, but rather via :meth:`Body.populate_observable`
or :meth:`System.populate_observables` | Below is the the instruction that describes the task:
### Input:
Populate columns necessary for an LP dataset
This should not be called directly, but rather via :meth:`Body.populate_observable`
or :meth:`System.populate_observables`
### Response:
def _populate_lp(self, dataset, **kwargs):
... |
def pick_scalar_condition(pred, true_value, false_value, name=None):
"""Convenience function that chooses one of two values based on the predicate.
This utility is equivalent to a version of `tf.where` that accepts only a
scalar predicate and computes its result statically when possible. It may also
be used in... | Convenience function that chooses one of two values based on the predicate.
This utility is equivalent to a version of `tf.where` that accepts only a
scalar predicate and computes its result statically when possible. It may also
be used in place of `tf.cond` when both branches yield a `Tensor` of the same
shap... | Below is the the instruction that describes the task:
### Input:
Convenience function that chooses one of two values based on the predicate.
This utility is equivalent to a version of `tf.where` that accepts only a
scalar predicate and computes its result statically when possible. It may also
be used in plac... |
def get_day_and_year():
"""
Returns tuple (day, year).
Here be dragons!
The correct date is determined with introspection of the call stack, first
finding the filename of the module from which ``aocd`` was imported.
This means your filenames should be something sensible, which identify the
... | Returns tuple (day, year).
Here be dragons!
The correct date is determined with introspection of the call stack, first
finding the filename of the module from which ``aocd`` was imported.
This means your filenames should be something sensible, which identify the
day and year unambiguously. The ex... | Below is the the instruction that describes the task:
### Input:
Returns tuple (day, year).
Here be dragons!
The correct date is determined with introspection of the call stack, first
finding the filename of the module from which ``aocd`` was imported.
This means your filenames should be somethin... |
def search(cls,
query_string,
options=None,
enable_facet_discovery=False,
return_facets=None,
facet_options=None,
facet_refinements=None,
deadline=None,
**kwargs):
"""
Searches the ind... | Searches the index. Conveniently searches only for documents that belong to instances of this class.
:param query_string: The query to match against documents in the index. See search.Query() for details.
:param options: A QueryOptions describing post-processing of search results.
:param enable... | Below is the the instruction that describes the task:
### Input:
Searches the index. Conveniently searches only for documents that belong to instances of this class.
:param query_string: The query to match against documents in the index. See search.Query() for details.
:param options: A QueryOption... |
def _fetch_file(url, file_name, resume=True,
hash_=None, timeout=10., progressbar=True, verbose=True):
"""Load requested file, downloading it if needed or requested.
Parameters
----------
url: string
The url of file to be downloaded.
file_name: string
Name, along wit... | Load requested file, downloading it if needed or requested.
Parameters
----------
url: string
The url of file to be downloaded.
file_name: string
Name, along with the path, of where downloaded file will be saved.
resume: bool, optional
If true, try to resume partially downlo... | Below is the the instruction that describes the task:
### Input:
Load requested file, downloading it if needed or requested.
Parameters
----------
url: string
The url of file to be downloaded.
file_name: string
Name, along with the path, of where downloaded file will be saved.
r... |
def list_locked(**kwargs):
'''
Query the package database those packages which are
locked against reinstallation, modification or deletion.
Returns returns a list of package names with version strings
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locked
jail
List l... | Query the package database those packages which are
locked against reinstallation, modification or deletion.
Returns returns a list of package names with version strings
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locked
jail
List locked packages within the specified jai... | Below is the the instruction that describes the task:
### Input:
Query the package database those packages which are
locked against reinstallation, modification or deletion.
Returns returns a list of package names with version strings
CLI Example:
.. code-block:: bash
salt '*' pkg.list_l... |
def create(self, repo_name, scm='git', private=True, **kwargs):
""" Creates a new repository on own Bitbucket account and return it."""
url = self.bitbucket.url('CREATE_REPO')
return self.bitbucket.dispatch('POST', url, auth=self.bitbucket.auth, name=repo_name, scm=scm, is_private=private, **kwa... | Creates a new repository on own Bitbucket account and return it. | Below is the the instruction that describes the task:
### Input:
Creates a new repository on own Bitbucket account and return it.
### Response:
def create(self, repo_name, scm='git', private=True, **kwargs):
""" Creates a new repository on own Bitbucket account and return it."""
url = self.bitbucke... |
def _init_usrgos(self, goids):
"""Return user GO IDs which have GO Terms."""
usrgos = set()
goids_missing = set()
_go2obj = self.gosubdag.go2obj
for goid in goids:
if goid in _go2obj:
usrgos.add(goid)
else:
goids_missing.add... | Return user GO IDs which have GO Terms. | Below is the the instruction that describes the task:
### Input:
Return user GO IDs which have GO Terms.
### Response:
def _init_usrgos(self, goids):
"""Return user GO IDs which have GO Terms."""
usrgos = set()
goids_missing = set()
_go2obj = self.gosubdag.go2obj
for goid in... |
def finite_pixels(self):
""" Return an array of the finite pixels.
Returns
-------
:obj:`numpy.ndarray`
Nx2 array of the finite pixels
"""
finite_px = np.where(np.isfinite(self.data))
finite_px = np.c_[finite_px[0], finite_px[1]]
return finit... | Return an array of the finite pixels.
Returns
-------
:obj:`numpy.ndarray`
Nx2 array of the finite pixels | Below is the the instruction that describes the task:
### Input:
Return an array of the finite pixels.
Returns
-------
:obj:`numpy.ndarray`
Nx2 array of the finite pixels
### Response:
def finite_pixels(self):
""" Return an array of the finite pixels.
Returns
... |
def get_strip_metadata(self, catID):
'''Retrieves the strip catalog metadata given a cat ID.
Args:
catID (str): The source catalog ID from the platform catalog.
Returns:
metadata (dict): A metadata dictionary .
TODO: have this return a class object with int... | Retrieves the strip catalog metadata given a cat ID.
Args:
catID (str): The source catalog ID from the platform catalog.
Returns:
metadata (dict): A metadata dictionary .
TODO: have this return a class object with interesting information exposed. | Below is the the instruction that describes the task:
### Input:
Retrieves the strip catalog metadata given a cat ID.
Args:
catID (str): The source catalog ID from the platform catalog.
Returns:
metadata (dict): A metadata dictionary .
TODO: have this return a ... |
def max_pathlen(self):
"""The maximum pathlen for any intermediate CAs signed by this CA.
This value is either ``None``, if this and all parent CAs don't have a ``pathlen`` attribute, or an
``int`` if any parent CA has the attribute.
"""
pathlen = self.pathlen
if self.p... | The maximum pathlen for any intermediate CAs signed by this CA.
This value is either ``None``, if this and all parent CAs don't have a ``pathlen`` attribute, or an
``int`` if any parent CA has the attribute. | Below is the the instruction that describes the task:
### Input:
The maximum pathlen for any intermediate CAs signed by this CA.
This value is either ``None``, if this and all parent CAs don't have a ``pathlen`` attribute, or an
``int`` if any parent CA has the attribute.
### Response:
def max_pat... |
def add(self, rid, data, raise_on_error=True):
"""Write cache data to the data store.
Args:
rid (str): The record identifier.
data (dict): The record data.
raise_on_error (bool): If True and not r.ok this method will raise a RunTimeError.
Returns:
... | Write cache data to the data store.
Args:
rid (str): The record identifier.
data (dict): The record data.
raise_on_error (bool): If True and not r.ok this method will raise a RunTimeError.
Returns:
object : Python request response. | Below is the the instruction that describes the task:
### Input:
Write cache data to the data store.
Args:
rid (str): The record identifier.
data (dict): The record data.
raise_on_error (bool): If True and not r.ok this method will raise a RunTimeError.
Returns:... |
def GET_close_server(self) -> None:
"""Stop and close the *HydPy* server."""
def _close_server():
self.server.shutdown()
self.server.server_close()
shutter = threading.Thread(target=_close_server)
shutter.deamon = True
shutter.start() | Stop and close the *HydPy* server. | Below is the the instruction that describes the task:
### Input:
Stop and close the *HydPy* server.
### Response:
def GET_close_server(self) -> None:
"""Stop and close the *HydPy* server."""
def _close_server():
self.server.shutdown()
self.server.server_close()
shutt... |
def info(vm, info_type='all', key='uuid'):
'''
Lookup info on running kvm
vm : string
vm to be targeted
info_type : string [all|block|blockstats|chardev|cpus|kvm|pci|spice|version|vnc]
info type to return
key : string [uuid|alias|hostname]
value type of 'vm' parameter
C... | Lookup info on running kvm
vm : string
vm to be targeted
info_type : string [all|block|blockstats|chardev|cpus|kvm|pci|spice|version|vnc]
info type to return
key : string [uuid|alias|hostname]
value type of 'vm' parameter
CLI Example:
.. code-block:: bash
salt '*'... | Below is the the instruction that describes the task:
### Input:
Lookup info on running kvm
vm : string
vm to be targeted
info_type : string [all|block|blockstats|chardev|cpus|kvm|pci|spice|version|vnc]
info type to return
key : string [uuid|alias|hostname]
value type of 'vm' pa... |
def get_ts_stats_significance(self, x, ts, stat_ts_func, null_ts_func, B=1000, permute_fast=False, label_ts=''):
""" Returns the statistics, pvalues and the actual number of bootstrap
samples. """
stats_ts, pvals, nums = ts_stats_significance(
ts, stat_ts_func, null_ts_func, B=B,... | Returns the statistics, pvalues and the actual number of bootstrap
samples. | Below is the the instruction that describes the task:
### Input:
Returns the statistics, pvalues and the actual number of bootstrap
samples.
### Response:
def get_ts_stats_significance(self, x, ts, stat_ts_func, null_ts_func, B=1000, permute_fast=False, label_ts=''):
""" Returns the statistics,... |
def synchelp(f):
'''
The synchelp decorator allows the transparent execution of
a coroutine using the global loop from a thread other than
the event loop. In both use cases, teh actual work is done
by the global event loop.
Examples:
Use as a decorator::
@s_glob.synchelp
... | The synchelp decorator allows the transparent execution of
a coroutine using the global loop from a thread other than
the event loop. In both use cases, teh actual work is done
by the global event loop.
Examples:
Use as a decorator::
@s_glob.synchelp
async def stuff(x... | Below is the the instruction that describes the task:
### Input:
The synchelp decorator allows the transparent execution of
a coroutine using the global loop from a thread other than
the event loop. In both use cases, teh actual work is done
by the global event loop.
Examples:
Use as a de... |
def on_message(self, fragment):
''' Process an individual wire protocol fragment.
The websocket RFC specifies opcodes for distinguishing text frames
from binary frames. Tornado passes us either a text or binary string
depending on that opcode, we have to look at the type of the fragment... | Process an individual wire protocol fragment.
The websocket RFC specifies opcodes for distinguishing text frames
from binary frames. Tornado passes us either a text or binary string
depending on that opcode, we have to look at the type of the fragment
to see what we got.
Args:
... | Below is the the instruction that describes the task:
### Input:
Process an individual wire protocol fragment.
The websocket RFC specifies opcodes for distinguishing text frames
from binary frames. Tornado passes us either a text or binary string
depending on that opcode, we have to look at... |
def weld_combine_scalars(scalars, weld_type):
"""Combine column-wise aggregations (so resulting scalars) into a single array.
Parameters
----------
scalars : tuple of WeldObjects
WeldObjects to combine.
weld_type : WeldType
The Weld type of the result. Currently expecting scalars to... | Combine column-wise aggregations (so resulting scalars) into a single array.
Parameters
----------
scalars : tuple of WeldObjects
WeldObjects to combine.
weld_type : WeldType
The Weld type of the result. Currently expecting scalars to be of the same type.
Returns
-------
We... | Below is the the instruction that describes the task:
### Input:
Combine column-wise aggregations (so resulting scalars) into a single array.
Parameters
----------
scalars : tuple of WeldObjects
WeldObjects to combine.
weld_type : WeldType
The Weld type of the result. Currently expe... |
def send_response(self, transaction):
"""
updates the cache with the response if there was a cache miss
:param transaction:
:return:
"""
if transaction.cacheHit is False:
"""
handling response based on the code
"""
logger.d... | updates the cache with the response if there was a cache miss
:param transaction:
:return: | Below is the the instruction that describes the task:
### Input:
updates the cache with the response if there was a cache miss
:param transaction:
:return:
### Response:
def send_response(self, transaction):
"""
updates the cache with the response if there was a cache miss
... |
def arg(self, state, index, stack_base=None):
"""
Returns a bitvector expression representing the nth argument of a function.
`stack_base` is an optional pointer to the top of the stack at the function start. If it is not
specified, use the current stack pointer.
WARNING: this ... | Returns a bitvector expression representing the nth argument of a function.
`stack_base` is an optional pointer to the top of the stack at the function start. If it is not
specified, use the current stack pointer.
WARNING: this assumes that none of the arguments are floating-point and they're ... | Below is the the instruction that describes the task:
### Input:
Returns a bitvector expression representing the nth argument of a function.
`stack_base` is an optional pointer to the top of the stack at the function start. If it is not
specified, use the current stack pointer.
WARNING: th... |
def UpsertStoredProcedure(self, collection_link, sproc, options=None):
"""Upserts a stored procedure in a collection.
:param str collection_link:
The link to the document collection.
:param str sproc:
:param dict options:
The request options for the request.
... | Upserts a stored procedure in a collection.
:param str collection_link:
The link to the document collection.
:param str sproc:
:param dict options:
The request options for the request.
:return:
The upserted Stored Procedure.
:rtype:
... | Below is the the instruction that describes the task:
### Input:
Upserts a stored procedure in a collection.
:param str collection_link:
The link to the document collection.
:param str sproc:
:param dict options:
The request options for the request.
:return:... |
def GetOobResult(self, param, user_ip, gitkit_token=None):
"""Gets out-of-band code for ResetPassword/ChangeEmail request.
Args:
param: dict of HTTP POST params
user_ip: string, end user's IP address
gitkit_token: string, the gitkit token if user logged in
Returns:
A dict of {
... | Gets out-of-band code for ResetPassword/ChangeEmail request.
Args:
param: dict of HTTP POST params
user_ip: string, end user's IP address
gitkit_token: string, the gitkit token if user logged in
Returns:
A dict of {
email: user email who initializes the request
new_emai... | Below is the the instruction that describes the task:
### Input:
Gets out-of-band code for ResetPassword/ChangeEmail request.
Args:
param: dict of HTTP POST params
user_ip: string, end user's IP address
gitkit_token: string, the gitkit token if user logged in
Returns:
A dict of {
... |
def reset_rammbock(self):
"""Closes all connections, deletes all servers, clients, and protocols.
You should call this method before exiting your test run. This will
close all the connections and the ports will therefore be available for
reuse faster.
"""
for client in s... | Closes all connections, deletes all servers, clients, and protocols.
You should call this method before exiting your test run. This will
close all the connections and the ports will therefore be available for
reuse faster. | Below is the the instruction that describes the task:
### Input:
Closes all connections, deletes all servers, clients, and protocols.
You should call this method before exiting your test run. This will
close all the connections and the ports will therefore be available for
reuse faster.
###... |
def _run_vardict_paired(align_bams, items, ref_file, assoc_files,
region=None, out_file=None):
"""Detect variants with Vardict.
This is used for paired tumor / normal samples.
"""
config = items[0]["config"]
if out_file is None:
out_file = "%s-paired-variants.vcf.g... | Detect variants with Vardict.
This is used for paired tumor / normal samples. | Below is the the instruction that describes the task:
### Input:
Detect variants with Vardict.
This is used for paired tumor / normal samples.
### Response:
def _run_vardict_paired(align_bams, items, ref_file, assoc_files,
region=None, out_file=None):
"""Detect variants with Vard... |
def locked_execute(self, sql, parameters = None, cursorClass = DictCursor, quiet = False):
'''We are lock-happy here but SQL performance is not currently an issue daemon-side.'''
return self.execute(sql, parameters, cursorClass, quiet = quiet, locked = True) | We are lock-happy here but SQL performance is not currently an issue daemon-side. | Below is the the instruction that describes the task:
### Input:
We are lock-happy here but SQL performance is not currently an issue daemon-side.
### Response:
def locked_execute(self, sql, parameters = None, cursorClass = DictCursor, quiet = False):
'''We are lock-happy here but SQL performance is not currentl... |
def _handle_args(self, cmd, args):
"""
We need to support deprecated behaviour for now which makes this
quite complicated
Current behaviour:
- install: Installs a new server, existing server causes an error
- install --upgrade: Installs or upgrades a server
- ins... | We need to support deprecated behaviour for now which makes this
quite complicated
Current behaviour:
- install: Installs a new server, existing server causes an error
- install --upgrade: Installs or upgrades a server
- install --managedb: Automatically initialise or upgrade th... | Below is the the instruction that describes the task:
### Input:
We need to support deprecated behaviour for now which makes this
quite complicated
Current behaviour:
- install: Installs a new server, existing server causes an error
- install --upgrade: Installs or upgrades a server... |
def log_message(self, format, *args):
"""
overrides the ``log_message`` method from the wsgiref server so that
normal logging works with whatever configuration the application has
been set to.
Levels are inferred from the HTTP status code, 4XX codes are treated as
warnin... | overrides the ``log_message`` method from the wsgiref server so that
normal logging works with whatever configuration the application has
been set to.
Levels are inferred from the HTTP status code, 4XX codes are treated as
warnings, 5XX as errors and everything else as INFO level. | Below is the the instruction that describes the task:
### Input:
overrides the ``log_message`` method from the wsgiref server so that
normal logging works with whatever configuration the application has
been set to.
Levels are inferred from the HTTP status code, 4XX codes are treated as
... |
def get_transaction_result(
self,
transaction: BaseOrSpoofTransaction,
at_header: BlockHeader) -> bytes:
"""
Return the result of running the given transaction.
This is referred to as a `call()` in web3.
"""
with self.get_vm(at_header).state_in... | Return the result of running the given transaction.
This is referred to as a `call()` in web3. | Below is the the instruction that describes the task:
### Input:
Return the result of running the given transaction.
This is referred to as a `call()` in web3.
### Response:
def get_transaction_result(
self,
transaction: BaseOrSpoofTransaction,
at_header: BlockHeader) ->... |
def _ScanFileSystem(self, scan_node, base_path_specs):
"""Scans a file system scan node for file systems.
Args:
scan_node (SourceScanNode): file system scan node.
base_path_specs (list[PathSpec]): file system base path specifications.
Raises:
SourceScannerError: if the scan node is inval... | Scans a file system scan node for file systems.
Args:
scan_node (SourceScanNode): file system scan node.
base_path_specs (list[PathSpec]): file system base path specifications.
Raises:
SourceScannerError: if the scan node is invalid. | Below is the the instruction that describes the task:
### Input:
Scans a file system scan node for file systems.
Args:
scan_node (SourceScanNode): file system scan node.
base_path_specs (list[PathSpec]): file system base path specifications.
Raises:
SourceScannerError: if the scan node i... |
def decode(data):
"""
Handles decoding of the CSV `data`.
Args:
data (str): Data which will be decoded.
Returns:
dict: Dictionary with decoded data.
"""
# try to guess dialect of the csv file
dialect = None
try:
dialect = csv.Sniffer().sniff(data)
except Exc... | Handles decoding of the CSV `data`.
Args:
data (str): Data which will be decoded.
Returns:
dict: Dictionary with decoded data. | Below is the the instruction that describes the task:
### Input:
Handles decoding of the CSV `data`.
Args:
data (str): Data which will be decoded.
Returns:
dict: Dictionary with decoded data.
### Response:
def decode(data):
"""
Handles decoding of the CSV `data`.
Args:
... |
def dump(self):
"""
Dump the output to json.
"""
report_as_json_string = utils.dict_to_json(self.report)
if self.out_file:
utils.string_to_file(self.out_file, report_as_json_string)
else:
print report_as_json_string | Dump the output to json. | Below is the the instruction that describes the task:
### Input:
Dump the output to json.
### Response:
def dump(self):
"""
Dump the output to json.
"""
report_as_json_string = utils.dict_to_json(self.report)
if self.out_file:
utils.string_to_file(self.out_file, ... |
def get_siblings_score(self, top_node):
"""\
we could have long articles that have tons of paragraphs
so if we tried to calculate the base score against
the total text score of those paragraphs it would be unfair.
So we need to normalize the score based on the average scoring
... | \
we could have long articles that have tons of paragraphs
so if we tried to calculate the base score against
the total text score of those paragraphs it would be unfair.
So we need to normalize the score based on the average scoring
of the paragraphs within the top node.
... | Below is the the instruction that describes the task:
### Input:
\
we could have long articles that have tons of paragraphs
so if we tried to calculate the base score against
the total text score of those paragraphs it would be unfair.
So we need to normalize the score based on the a... |
def _next_slide_partname(self):
"""
Return |PackURI| instance containing the partname for a slide to be
appended to this slide collection, e.g. ``/ppt/slides/slide9.xml``
for a slide collection containing 8 slides.
"""
sldIdLst = self._element.get_or_add_sldIdLst()
... | Return |PackURI| instance containing the partname for a slide to be
appended to this slide collection, e.g. ``/ppt/slides/slide9.xml``
for a slide collection containing 8 slides. | Below is the the instruction that describes the task:
### Input:
Return |PackURI| instance containing the partname for a slide to be
appended to this slide collection, e.g. ``/ppt/slides/slide9.xml``
for a slide collection containing 8 slides.
### Response:
def _next_slide_partname(self):
"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.