code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _print_foreign_playlist_copy_error(self):
""" reset previous message """
self.operation_mode = self.window_mode = NORMAL_MODE
self.refreshBody()
txt ='''Foreign playlist copying |failed|!
Make sure the file is not open with another
application and try to load... | reset previous message | Below is the the instruction that describes the task:
### Input:
reset previous message
### Response:
def _print_foreign_playlist_copy_error(self):
""" reset previous message """
self.operation_mode = self.window_mode = NORMAL_MODE
self.refreshBody()
txt ='''Foreign playlist copying... |
def extract_from_urllib3():
"""
Undo monkey-patching by :func:`inject_into_urllib3`.
"""
util.ssl_.SSLContext = orig_util_SSLContext
util.HAS_SNI = orig_util_HAS_SNI
util.ssl_.HAS_SNI = orig_util_HAS_SNI
util.IS_SECURETRANSPORT = False
util.ssl_.IS_SECURETRANSPORT = False | Undo monkey-patching by :func:`inject_into_urllib3`. | Below is the the instruction that describes the task:
### Input:
Undo monkey-patching by :func:`inject_into_urllib3`.
### Response:
def extract_from_urllib3():
"""
Undo monkey-patching by :func:`inject_into_urllib3`.
"""
util.ssl_.SSLContext = orig_util_SSLContext
util.HAS_SNI = orig_util_HAS_S... |
def cycle(self):
"""
Cycles through notifications with latest results from data feeds.
"""
messages = self.poll_datafeeds()
notifications = self.process_notifications(messages)
self.draw_notifications(notifications) | Cycles through notifications with latest results from data feeds. | Below is the the instruction that describes the task:
### Input:
Cycles through notifications with latest results from data feeds.
### Response:
def cycle(self):
"""
Cycles through notifications with latest results from data feeds.
"""
messages = self.poll_datafeeds()
notifi... |
def right(self):
"""Right coordinate."""
if self._has_real():
return self._data.real_right
return self._data.right | Right coordinate. | Below is the the instruction that describes the task:
### Input:
Right coordinate.
### Response:
def right(self):
"""Right coordinate."""
if self._has_real():
return self._data.real_right
return self._data.right |
def build_server_from_argparser(description=None, server_klass=None, handler_klass=None):
"""
Build a server from command line arguments. If a ServerClass or
HandlerClass is specified, then the object must inherit from the
corresponding AdvancedHTTPServer base class.
:param str description: Description string to ... | Build a server from command line arguments. If a ServerClass or
HandlerClass is specified, then the object must inherit from the
corresponding AdvancedHTTPServer base class.
:param str description: Description string to be passed to the argument parser.
:param server_klass: Alternative server class to use.
:type ... | Below is the the instruction that describes the task:
### Input:
Build a server from command line arguments. If a ServerClass or
HandlerClass is specified, then the object must inherit from the
corresponding AdvancedHTTPServer base class.
:param str description: Description string to be passed to the argument p... |
def hexstr(text):
'''
Ensure a string is valid hex.
Args:
text (str): String to normalize.
Examples:
Norm a few strings:
hexstr('0xff00')
hexstr('ff00')
Notes:
Will accept strings prefixed by '0x' or '0X' and remove them.
Returns:
str:... | Ensure a string is valid hex.
Args:
text (str): String to normalize.
Examples:
Norm a few strings:
hexstr('0xff00')
hexstr('ff00')
Notes:
Will accept strings prefixed by '0x' or '0X' and remove them.
Returns:
str: Normalized hex string. | Below is the the instruction that describes the task:
### Input:
Ensure a string is valid hex.
Args:
text (str): String to normalize.
Examples:
Norm a few strings:
hexstr('0xff00')
hexstr('ff00')
Notes:
Will accept strings prefixed by '0x' or '0X' and ... |
def _create_network_doscript(self, network_file_path):
"""doscript: contains a invokeScript.sh which will do the special work
The network.doscript contains network configuration files and it will
be used by zvmguestconfigure to configure zLinux os network when it
starts up
"""
... | doscript: contains a invokeScript.sh which will do the special work
The network.doscript contains network configuration files and it will
be used by zvmguestconfigure to configure zLinux os network when it
starts up | Below is the the instruction that describes the task:
### Input:
doscript: contains a invokeScript.sh which will do the special work
The network.doscript contains network configuration files and it will
be used by zvmguestconfigure to configure zLinux os network when it
starts up
### Respon... |
def gif_summary(name, tensor, max_outputs=3, fps=10, collections=None,
family=None):
"""Outputs a `Summary` protocol buffer with gif animations.
Args:
name: Name of the summary.
tensor: A 5-D `uint8` `Tensor` of shape `[batch_size, time, height, width,
channels]` where `channels` is 1... | Outputs a `Summary` protocol buffer with gif animations.
Args:
name: Name of the summary.
tensor: A 5-D `uint8` `Tensor` of shape `[batch_size, time, height, width,
channels]` where `channels` is 1 or 3.
max_outputs: Max number of batch elements to generate gifs for.
fps: frames per second of t... | Below is the the instruction that describes the task:
### Input:
Outputs a `Summary` protocol buffer with gif animations.
Args:
name: Name of the summary.
tensor: A 5-D `uint8` `Tensor` of shape `[batch_size, time, height, width,
channels]` where `channels` is 1 or 3.
max_outputs: Max number of... |
def universal_anisotropy(self):
"""
returns the universal anisotropy value
"""
return 5. * self.g_voigt / self.g_reuss + \
self.k_voigt / self.k_reuss - 6. | returns the universal anisotropy value | Below is the the instruction that describes the task:
### Input:
returns the universal anisotropy value
### Response:
def universal_anisotropy(self):
"""
returns the universal anisotropy value
"""
return 5. * self.g_voigt / self.g_reuss + \
self.k_voigt / self.k_reuss - ... |
def _playsoundWin(sound, block = True):
'''
Utilizes windll.winmm. Tested and known to work with MP3 and WAVE on
Windows 7 with Python 2.7. Probably works with more file formats.
Probably works on Windows XP thru Windows 10. Probably works with all
versions of Python.
Inspired by (but not copie... | Utilizes windll.winmm. Tested and known to work with MP3 and WAVE on
Windows 7 with Python 2.7. Probably works with more file formats.
Probably works on Windows XP thru Windows 10. Probably works with all
versions of Python.
Inspired by (but not copied from) Michael Gundlach <gundlach@gmail.com>'s mp3p... | Below is the the instruction that describes the task:
### Input:
Utilizes windll.winmm. Tested and known to work with MP3 and WAVE on
Windows 7 with Python 2.7. Probably works with more file formats.
Probably works on Windows XP thru Windows 10. Probably works with all
versions of Python.
Inspired ... |
def p_unit_list(self, p):
""" unit_list : unit_list unit
| unit
"""
if isinstance(p[1], list):
if len(p) >= 3:
if isinstance(p[2], list):
p[1].extend(p[2])
else:
... | unit_list : unit_list unit
| unit | Below is the the instruction that describes the task:
### Input:
unit_list : unit_list unit
| unit
### Response:
def p_unit_list(self, p):
""" unit_list : unit_list unit
| unit
"""
if isi... |
def _process_datum(self, data, input_reader, ctx, transient_shard_state):
"""Process a single data piece.
Call mapper handler on the data.
Args:
data: a datum to process.
input_reader: input reader.
ctx: mapreduce context
transient_shard_state: transient shard state.
Returns:
... | Process a single data piece.
Call mapper handler on the data.
Args:
data: a datum to process.
input_reader: input reader.
ctx: mapreduce context
transient_shard_state: transient shard state.
Returns:
True if scan should be continued, False if scan should be stopped. | Below is the the instruction that describes the task:
### Input:
Process a single data piece.
Call mapper handler on the data.
Args:
data: a datum to process.
input_reader: input reader.
ctx: mapreduce context
transient_shard_state: transient shard state.
Returns:
True i... |
def new_transaction(self, timeout, durability, transaction_type):
"""
Creates a Transaction object with given timeout, durability and transaction type.
:param timeout: (long), the timeout in seconds determines the maximum lifespan of a transaction.
:param durability: (int), the durabili... | Creates a Transaction object with given timeout, durability and transaction type.
:param timeout: (long), the timeout in seconds determines the maximum lifespan of a transaction.
:param durability: (int), the durability is the number of machines that can take over if a member fails during a
... | Below is the the instruction that describes the task:
### Input:
Creates a Transaction object with given timeout, durability and transaction type.
:param timeout: (long), the timeout in seconds determines the maximum lifespan of a transaction.
:param durability: (int), the durability is the number ... |
def fit(sim_mat, D_len, cidx):
"""
Algorithm maximizes energy between clusters, which is distinction in this algorithm. Distance matrix contains mostly 0, which are overlooked due to search of maximal distances. Algorithm does not try to retain k clusters.
D: numpy array - Symmetric distance matrix
k: ... | Algorithm maximizes energy between clusters, which is distinction in this algorithm. Distance matrix contains mostly 0, which are overlooked due to search of maximal distances. Algorithm does not try to retain k clusters.
D: numpy array - Symmetric distance matrix
k: int - number of clusters | Below is the the instruction that describes the task:
### Input:
Algorithm maximizes energy between clusters, which is distinction in this algorithm. Distance matrix contains mostly 0, which are overlooked due to search of maximal distances. Algorithm does not try to retain k clusters.
D: numpy array - Symmetr... |
def jupyter_notebook_skeleton():
"""Returns a dictionary with the elements of a Jupyter notebook"""
py_version = sys.version_info
notebook_skeleton = {
"cells": [],
"metadata": {
"kernelspec": {
"display_name": "Python " + str(py_version[0]),
"lang... | Returns a dictionary with the elements of a Jupyter notebook | Below is the the instruction that describes the task:
### Input:
Returns a dictionary with the elements of a Jupyter notebook
### Response:
def jupyter_notebook_skeleton():
"""Returns a dictionary with the elements of a Jupyter notebook"""
py_version = sys.version_info
notebook_skeleton = {
"ce... |
def register_plugin(self):
"""Register plugin in Spyder's main window"""
self.profiler.datatree.sig_edit_goto.connect(self.main.editor.load)
self.profiler.redirect_stdio.connect(
self.main.redirect_internalshell_stdio)
self.main.add_dockwidget(self)
profiler_act = cr... | Register plugin in Spyder's main window | Below is the the instruction that describes the task:
### Input:
Register plugin in Spyder's main window
### Response:
def register_plugin(self):
"""Register plugin in Spyder's main window"""
self.profiler.datatree.sig_edit_goto.connect(self.main.editor.load)
self.profiler.redirect_stdio.co... |
def build(self):
"""
Generates the policy document based on the internal lists of
allowed and denied conditions. This will generate a policy with
two main statements for the effect: one statement for Allow and
one statement for Deny. Methods that includes conditions will
... | Generates the policy document based on the internal lists of
allowed and denied conditions. This will generate a policy with
two main statements for the effect: one statement for Allow and
one statement for Deny. Methods that includes conditions will
have their own statement in the polic... | Below is the the instruction that describes the task:
### Input:
Generates the policy document based on the internal lists of
allowed and denied conditions. This will generate a policy with
two main statements for the effect: one statement for Allow and
one statement for Deny. Methods that i... |
def update_id(self, sequence_id=None):
"""Alter the sequence id, and all of the names and ids derived from it. This
often needs to be done after an IntegrityError in a multiprocessing run"""
if sequence_id:
self.sequence_id = sequence_id
self._set_ids(force=True)
i... | Alter the sequence id, and all of the names and ids derived from it. This
often needs to be done after an IntegrityError in a multiprocessing run | Below is the the instruction that describes the task:
### Input:
Alter the sequence id, and all of the names and ids derived from it. This
often needs to be done after an IntegrityError in a multiprocessing run
### Response:
def update_id(self, sequence_id=None):
"""Alter the sequence id, and all o... |
def List(self, *branches, **kwargs):
"""
While `Seq` is sequential, `phi.dsl.Expression.List` allows you to split the computation and get back a list with the result of each path. While the list literal should be the most incarnation of this expresion, it can actually be any iterable (implements `__iter__`) tha... | While `Seq` is sequential, `phi.dsl.Expression.List` allows you to split the computation and get back a list with the result of each path. While the list literal should be the most incarnation of this expresion, it can actually be any iterable (implements `__iter__`) that is not a tuple and yields a valid expresion.
T... | Below is the the instruction that describes the task:
### Input:
While `Seq` is sequential, `phi.dsl.Expression.List` allows you to split the computation and get back a list with the result of each path. While the list literal should be the most incarnation of this expresion, it can actually be any iterable (implem... |
async def _clean_shutdown(self):
"""Cleanly shutdown the emulation loop."""
# Cleanly stop any other outstanding tasks not associated with tiles
remaining_tasks = []
for task in self._tasks.get(None, []):
self._logger.debug("Cancelling task at shutdown %s", task)
... | Cleanly shutdown the emulation loop. | Below is the the instruction that describes the task:
### Input:
Cleanly shutdown the emulation loop.
### Response:
async def _clean_shutdown(self):
"""Cleanly shutdown the emulation loop."""
# Cleanly stop any other outstanding tasks not associated with tiles
remaining_tasks = []
... |
async def open(self):
"""Register with the publisher."""
self.store.register(self)
while not self.finished:
message = await self.messages.get()
await self.publish(message) | Register with the publisher. | Below is the the instruction that describes the task:
### Input:
Register with the publisher.
### Response:
async def open(self):
"""Register with the publisher."""
self.store.register(self)
while not self.finished:
message = await self.messages.get()
await self... |
def included_profiles(self):
"""Load all profiles."""
profiles = []
for directory in self.tcex_json.get('profile_include_dirs') or []:
profiles.extend(self._load_config_include(directory))
return profiles | Load all profiles. | Below is the the instruction that describes the task:
### Input:
Load all profiles.
### Response:
def included_profiles(self):
"""Load all profiles."""
profiles = []
for directory in self.tcex_json.get('profile_include_dirs') or []:
profiles.extend(self._load_config_include(dire... |
def is_valid_geometry(self):
"""
It is possible to infer the geometry only if exactly
one of sites, sites_csv, hazard_curves_csv, gmfs_csv,
region is set. You did set more than one, or nothing.
"""
has_sites = (self.sites is not None or 'sites' in self.inputs
... | It is possible to infer the geometry only if exactly
one of sites, sites_csv, hazard_curves_csv, gmfs_csv,
region is set. You did set more than one, or nothing. | Below is the the instruction that describes the task:
### Input:
It is possible to infer the geometry only if exactly
one of sites, sites_csv, hazard_curves_csv, gmfs_csv,
region is set. You did set more than one, or nothing.
### Response:
def is_valid_geometry(self):
"""
It is poss... |
def log_decl_method(func):
"""Decorate do_declartion methods for debug logging."""
from functools import wraps
@wraps(func)
def with_logging(*args, **kwargs):
self = args[0]
decl = args[2]
log(DEBUG, u" {}: {} {}".format(
self.state['current_step'], decl.name,
... | Decorate do_declartion methods for debug logging. | Below is the the instruction that describes the task:
### Input:
Decorate do_declartion methods for debug logging.
### Response:
def log_decl_method(func):
"""Decorate do_declartion methods for debug logging."""
from functools import wraps
@wraps(func)
def with_logging(*args, **kwargs):
se... |
def Validate(self):
"""Ensure the pathspec is valid."""
self.pathspec.Validate()
if (self.HasField("start_time") and self.HasField("end_time") and
self.start_time > self.end_time):
raise ValueError("Start time must be before end time.")
if not self.path_regex and not self.data_regex and ... | Ensure the pathspec is valid. | Below is the the instruction that describes the task:
### Input:
Ensure the pathspec is valid.
### Response:
def Validate(self):
"""Ensure the pathspec is valid."""
self.pathspec.Validate()
if (self.HasField("start_time") and self.HasField("end_time") and
self.start_time > self.end_time):
... |
def titles(self, unique=False):
"""Return a list of contained worksheet titles.
Args:
unique (bool): drop duplicates
Returns:
list: list of titles/name strings
"""
if unique:
return tools.uniqued(s.title for s in self._items)
return [s... | Return a list of contained worksheet titles.
Args:
unique (bool): drop duplicates
Returns:
list: list of titles/name strings | Below is the the instruction that describes the task:
### Input:
Return a list of contained worksheet titles.
Args:
unique (bool): drop duplicates
Returns:
list: list of titles/name strings
### Response:
def titles(self, unique=False):
"""Return a list of contained ... |
def append(self, child, *args, **kwargs):
"""See :meth:`AbstractElement.append`"""
#if no set is associated with the layer yet, we learn it from span annotation elements that are added
if self.set is False or self.set is None:
if inspect.isclass(child):
if issubclass(... | See :meth:`AbstractElement.append` | Below is the the instruction that describes the task:
### Input:
See :meth:`AbstractElement.append`
### Response:
def append(self, child, *args, **kwargs):
"""See :meth:`AbstractElement.append`"""
#if no set is associated with the layer yet, we learn it from span annotation elements that are added
... |
def _expandDH(self, sampling, lmax, lmax_calc):
"""Evaluate the coefficients on a Driscoll and Healy (1994) grid."""
if self.normalization == '4pi':
norm = 1
elif self.normalization == 'schmidt':
norm = 2
elif self.normalization == 'unnorm':
norm = 3
... | Evaluate the coefficients on a Driscoll and Healy (1994) grid. | Below is the the instruction that describes the task:
### Input:
Evaluate the coefficients on a Driscoll and Healy (1994) grid.
### Response:
def _expandDH(self, sampling, lmax, lmax_calc):
"""Evaluate the coefficients on a Driscoll and Healy (1994) grid."""
if self.normalization == '4pi':
... |
def define_example_values(self, http_method, route, values, update=False):
"""Define example values for a given request.
By default, example values are determined from the example properties
in the schema. But if you want to change the example used in the
documentation for a specific ro... | Define example values for a given request.
By default, example values are determined from the example properties
in the schema. But if you want to change the example used in the
documentation for a specific route, and this method lets you do that.
:param str http_method: An HTTP method... | Below is the the instruction that describes the task:
### Input:
Define example values for a given request.
By default, example values are determined from the example properties
in the schema. But if you want to change the example used in the
documentation for a specific route, and this met... |
def unpersist(self, blocking=False):
"""
Mark the RDD as non-persistent, and remove all blocks for it from
memory and disk.
.. versionchanged:: 3.0.0
Added optional argument `blocking` to specify whether to block until all
blocks are deleted.
"""
se... | Mark the RDD as non-persistent, and remove all blocks for it from
memory and disk.
.. versionchanged:: 3.0.0
Added optional argument `blocking` to specify whether to block until all
blocks are deleted. | Below is the the instruction that describes the task:
### Input:
Mark the RDD as non-persistent, and remove all blocks for it from
memory and disk.
.. versionchanged:: 3.0.0
Added optional argument `blocking` to specify whether to block until all
blocks are deleted.
### Respon... |
def get_process_cmdline(self):
"""Return process cmdline as a list of arguments."""
if not pid_exists(self.pid):
raise NoSuchProcess(self.pid, self._process_name)
return _psutil_osx.get_process_cmdline(self.pid) | Return process cmdline as a list of arguments. | Below is the the instruction that describes the task:
### Input:
Return process cmdline as a list of arguments.
### Response:
def get_process_cmdline(self):
"""Return process cmdline as a list of arguments."""
if not pid_exists(self.pid):
raise NoSuchProcess(self.pid, self._process_name... |
def extend_variables(raw_variables, override_variables):
""" extend raw_variables with override_variables.
override_variables will merge and override raw_variables.
Args:
raw_variables (list):
override_variables (list):
Returns:
dict: extended variables mapping
Example... | extend raw_variables with override_variables.
override_variables will merge and override raw_variables.
Args:
raw_variables (list):
override_variables (list):
Returns:
dict: extended variables mapping
Examples:
>>> raw_variables = [{"var1": "val1"}, {"var2": "val2"... | Below is the the instruction that describes the task:
### Input:
extend raw_variables with override_variables.
override_variables will merge and override raw_variables.
Args:
raw_variables (list):
override_variables (list):
Returns:
dict: extended variables mapping
Exa... |
def recognise(self):
"""
Recognise which is Cube's OLL case.
"""
if not isinstance(self.cube, Cube):
raise ValueError("Use Solver.feed(cube) to feed the cube to solver.")
result = ""
for face in "LFRB":
for square in self.cube.get_face(face)[0]:
... | Recognise which is Cube's OLL case. | Below is the the instruction that describes the task:
### Input:
Recognise which is Cube's OLL case.
### Response:
def recognise(self):
"""
Recognise which is Cube's OLL case.
"""
if not isinstance(self.cube, Cube):
raise ValueError("Use Solver.feed(cube) to feed the cub... |
def simplify_U(theta, phi, lam):
"""Return the gate u1, u2, or u3 implementing U with the fewest pulses.
The returned gate implements U exactly, not up to a global phase.
Args:
theta, phi, lam: input Euler rotation angles for a general U gate
Returns:
Gate: one of IdGate, U1Gate, U2Ga... | Return the gate u1, u2, or u3 implementing U with the fewest pulses.
The returned gate implements U exactly, not up to a global phase.
Args:
theta, phi, lam: input Euler rotation angles for a general U gate
Returns:
Gate: one of IdGate, U1Gate, U2Gate, U3Gate. | Below is the the instruction that describes the task:
### Input:
Return the gate u1, u2, or u3 implementing U with the fewest pulses.
The returned gate implements U exactly, not up to a global phase.
Args:
theta, phi, lam: input Euler rotation angles for a general U gate
Returns:
Gate... |
def do_AUTOCOMPLETE(cmd, s):
"""Shows autocomplete results for a given token."""
s = list(preprocess_query(s))[0]
keys = [k.decode() for k in DB.smembers(edge_ngram_key(s))]
print(white(keys))
print(magenta('({} elements)'.format(len(keys)))) | Shows autocomplete results for a given token. | Below is the the instruction that describes the task:
### Input:
Shows autocomplete results for a given token.
### Response:
def do_AUTOCOMPLETE(cmd, s):
"""Shows autocomplete results for a given token."""
s = list(preprocess_query(s))[0]
keys = [k.decode() for k in DB.smembers(edge_ngram_key(s))]
... |
def get_rectangle(self, src):
"""
:param src: a source object
:returns: ((min_lon, min_lat), width, height), useful for plotting
"""
min_lon, min_lat, max_lon, max_lat = (
self.integration_distance.get_affected_box(src))
return (min_lon, min_lat), (max_lon - m... | :param src: a source object
:returns: ((min_lon, min_lat), width, height), useful for plotting | Below is the the instruction that describes the task:
### Input:
:param src: a source object
:returns: ((min_lon, min_lat), width, height), useful for plotting
### Response:
def get_rectangle(self, src):
"""
:param src: a source object
:returns: ((min_lon, min_lat), width, height), ... |
def _get_filehandler_with_formatter(logname, formatter=None):
""" Return a logging FileHandler for given logname using a given
logging formatter
:param logname: Name of the file where logs will be stored, ".log"
extension will be added
:param formatter: An instance of logging.Formatter or None if th... | Return a logging FileHandler for given logname using a given
logging formatter
:param logname: Name of the file where logs will be stored, ".log"
extension will be added
:param formatter: An instance of logging.Formatter or None if the default
should be used
:return: | Below is the the instruction that describes the task:
### Input:
Return a logging FileHandler for given logname using a given
logging formatter
:param logname: Name of the file where logs will be stored, ".log"
extension will be added
:param formatter: An instance of logging.Formatter or None if the... |
def processFlat(self):
"""Main process.
Returns
-------
est_idxs : np.array(N)
Estimated indeces for the segment boundaries in frames.
est_labels : np.array(N-1)
Estimated labels for the segments.
"""
# C-NMF params
niter = self.con... | Main process.
Returns
-------
est_idxs : np.array(N)
Estimated indeces for the segment boundaries in frames.
est_labels : np.array(N-1)
Estimated labels for the segments. | Below is the the instruction that describes the task:
### Input:
Main process.
Returns
-------
est_idxs : np.array(N)
Estimated indeces for the segment boundaries in frames.
est_labels : np.array(N-1)
Estimated labels for the segments.
### Response:
def proce... |
def load(self, draw_bbox = False, **kwargs):
''' Makes the canvas.
This could be far speedier if it copied raw pixels, but that would
take far too much time to write vs using Image inbuilts '''
im = Image.new('RGBA', self.img_size)
draw = None
if draw_bbox:
... | Makes the canvas.
This could be far speedier if it copied raw pixels, but that would
take far too much time to write vs using Image inbuilts | Below is the the instruction that describes the task:
### Input:
Makes the canvas.
This could be far speedier if it copied raw pixels, but that would
take far too much time to write vs using Image inbuilts
### Response:
def load(self, draw_bbox = False, **kwargs):
''' Makes the canv... |
def _check_for_crypto_done(self):
# type: (Downloader) -> None
"""Check queue for crypto done
:param Downloader self: this
"""
cv = self._crypto_offload.done_cv
while not self.termination_check:
result = None
cv.acquire()
while True:
... | Check queue for crypto done
:param Downloader self: this | Below is the the instruction that describes the task:
### Input:
Check queue for crypto done
:param Downloader self: this
### Response:
def _check_for_crypto_done(self):
# type: (Downloader) -> None
"""Check queue for crypto done
:param Downloader self: this
"""
cv =... |
def delete_service_version(self, service_id , service_version='default', mode='production'):
'''
delete_service(self, service_id, service_version='default', mode='production')
Deletes a Service version from Opereto
:Parameters:
* *service_id* (`string`) -- Service identifier
... | delete_service(self, service_id, service_version='default', mode='production')
Deletes a Service version from Opereto
:Parameters:
* *service_id* (`string`) -- Service identifier
* *service_version* (`string`) -- Service version. Default is 'default'
* *mode* (`string`) -- deve... | Below is the the instruction that describes the task:
### Input:
delete_service(self, service_id, service_version='default', mode='production')
Deletes a Service version from Opereto
:Parameters:
* *service_id* (`string`) -- Service identifier
* *service_version* (`string`) -- Serv... |
def find_all_primitives(pad):
"""
Recursively find all primities on a pad, even those hiding behind a
GetListOfFunctions() of a primitive
"""
result = []
for primitive in pad.GetListOfPrimitives():
result.append(primitive)
if hasattr(primitive, "GetListOfFunctions"):
... | Recursively find all primities on a pad, even those hiding behind a
GetListOfFunctions() of a primitive | Below is the the instruction that describes the task:
### Input:
Recursively find all primities on a pad, even those hiding behind a
GetListOfFunctions() of a primitive
### Response:
def find_all_primitives(pad):
"""
Recursively find all primities on a pad, even those hiding behind a
GetListOfFunct... |
def get_full_path(self, fn_attr):
'''Returns the full path of a FILENAME.
The NTFS filesystem allows for things called hardlinks. Hard links are
saved, internally, as different filename attributes. Because of this,
an entry can, when dealing with full paths, have multiple full paths.
... | Returns the full path of a FILENAME.
The NTFS filesystem allows for things called hardlinks. Hard links are
saved, internally, as different filename attributes. Because of this,
an entry can, when dealing with full paths, have multiple full paths.
As such, this function receives a fn_a... | Below is the the instruction that describes the task:
### Input:
Returns the full path of a FILENAME.
The NTFS filesystem allows for things called hardlinks. Hard links are
saved, internally, as different filename attributes. Because of this,
an entry can, when dealing with full paths, have... |
def parse(type: Type):
"""
Register a parser for a attribute type.
Parsers will be used to parse `str` type objects from either
the commandline arguments or environment variables.
Args:
type: the type the decorated function will be responsible
for pa... | Register a parser for a attribute type.
Parsers will be used to parse `str` type objects from either
the commandline arguments or environment variables.
Args:
type: the type the decorated function will be responsible
for parsing a environment variable to. | Below is the the instruction that describes the task:
### Input:
Register a parser for a attribute type.
Parsers will be used to parse `str` type objects from either
the commandline arguments or environment variables.
Args:
type: the type the decorated function will be responsi... |
def do_first(self):
"""Create PNM file from input image file."""
pid = os.getpid()
self.basename = os.path.join(self.tmpdir, 'iiif_netpbm_' + str(pid))
outfile = self.basename + '.pnm'
# Convert source file to pnm
filetype = self.file_type(self.srcfile)
if (filety... | Create PNM file from input image file. | Below is the the instruction that describes the task:
### Input:
Create PNM file from input image file.
### Response:
def do_first(self):
"""Create PNM file from input image file."""
pid = os.getpid()
self.basename = os.path.join(self.tmpdir, 'iiif_netpbm_' + str(pid))
outfile = sel... |
def enable(name, **kwargs):
'''
Enable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.enable <service name>
'''
if _service_is_upstart(name):
return _upstart_enable(name)
executable = _get_service_exec()
cmd = '{0} -f {1} defaults... | Enable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.enable <service name> | Below is the the instruction that describes the task:
### Input:
Enable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.enable <service name>
### Response:
def enable(name, **kwargs):
'''
Enable the named service to start at boot
CLI Example:
... |
def get_index_quote(self, code, as_json=False):
"""
params:
code : string index code
as_json: True|False
returns:
a dict | json quote for the given index
"""
url = self.index_url
if self.is_valid_index(code):
req = Request(u... | params:
code : string index code
as_json: True|False
returns:
a dict | json quote for the given index | Below is the the instruction that describes the task:
### Input:
params:
code : string index code
as_json: True|False
returns:
a dict | json quote for the given index
### Response:
def get_index_quote(self, code, as_json=False):
"""
params:
co... |
def data(self, root):
'''Convert etree.Element into a dictionary'''
value = self.dict()
children = [node for node in root if isinstance(node.tag, basestring)]
for attr, attrval in root.attrib.items():
attr = attr if self.attr_prefix is None else self.attr_prefix + attr
... | Convert etree.Element into a dictionary | Below is the the instruction that describes the task:
### Input:
Convert etree.Element into a dictionary
### Response:
def data(self, root):
'''Convert etree.Element into a dictionary'''
value = self.dict()
children = [node for node in root if isinstance(node.tag, basestring)]
for a... |
def step(self, observations, raw_rewards, processed_rewards, dones, actions):
"""Record the information obtained from taking a step in all envs.
Records (observation, rewards, done) in a new time-step and actions in the
current time-step.
If any trajectory gets done, we move that trajectory to
com... | Record the information obtained from taking a step in all envs.
Records (observation, rewards, done) in a new time-step and actions in the
current time-step.
If any trajectory gets done, we move that trajectory to
completed_trajectories.
Args:
observations: ndarray of first dimension self.b... | Below is the the instruction that describes the task:
### Input:
Record the information obtained from taking a step in all envs.
Records (observation, rewards, done) in a new time-step and actions in the
current time-step.
If any trajectory gets done, we move that trajectory to
completed_trajector... |
def log_player_roll(self, player, roll):
"""
:param player: catan.game.Player
:param roll: integer or string, the sum of the dice
"""
self._logln('{0} rolls {1}{2}'.format(player.color, roll, ' ...DEUCES!' if int(roll) == 2 else '')) | :param player: catan.game.Player
:param roll: integer or string, the sum of the dice | Below is the the instruction that describes the task:
### Input:
:param player: catan.game.Player
:param roll: integer or string, the sum of the dice
### Response:
def log_player_roll(self, player, roll):
"""
:param player: catan.game.Player
:param roll: integer or string, the sum o... |
def run_from_argv(self, argv):
"""
Called when run from the command line.
"""
try:
return self.main(args=argv[2:], standalone_mode=False)
except click.ClickException as e:
if getattr(e.ctx, 'traceback', False):
raise
e.show()
... | Called when run from the command line. | Below is the the instruction that describes the task:
### Input:
Called when run from the command line.
### Response:
def run_from_argv(self, argv):
"""
Called when run from the command line.
"""
try:
return self.main(args=argv[2:], standalone_mode=False)
except ... |
def stft(func=None, **kwparams):
"""
Short Time Fourier Transform for complex data.
Same to the default STFT strategy, but with new defaults. This is the same
to:
.. code-block:: python
stft.base(transform=numpy.fft.fft, inverse_transform=numpy.fft.ifft)
See ``stft.base`` docs for more.
"""
from... | Short Time Fourier Transform for complex data.
Same to the default STFT strategy, but with new defaults. This is the same
to:
.. code-block:: python
stft.base(transform=numpy.fft.fft, inverse_transform=numpy.fft.ifft)
See ``stft.base`` docs for more. | Below is the the instruction that describes the task:
### Input:
Short Time Fourier Transform for complex data.
Same to the default STFT strategy, but with new defaults. This is the same
to:
.. code-block:: python
stft.base(transform=numpy.fft.fft, inverse_transform=numpy.fft.ifft)
See ``stft.base``... |
def to_struct(cls, name=None):
"""
Convert the TreeModel into a compiled C struct
"""
if name is None:
name = cls.__name__
basic_attrs = dict([(attr_name, value)
for attr_name, value in cls.get_attrs()
if isinsta... | Convert the TreeModel into a compiled C struct | Below is the the instruction that describes the task:
### Input:
Convert the TreeModel into a compiled C struct
### Response:
def to_struct(cls, name=None):
"""
Convert the TreeModel into a compiled C struct
"""
if name is None:
name = cls.__name__
basic_attrs = ... |
def latsph(radius, lon, lat):
"""
Convert from latitudinal coordinates to spherical coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/latsph_c.html
:param radius: Distance of a point from the origin.
:param lon: Angle of the point from the XZ plane in radians.
:param lat: An... | Convert from latitudinal coordinates to spherical coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/latsph_c.html
:param radius: Distance of a point from the origin.
:param lon: Angle of the point from the XZ plane in radians.
:param lat: Angle of the point from the XY plane in radi... | Below is the the instruction that describes the task:
### Input:
Convert from latitudinal coordinates to spherical coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/latsph_c.html
:param radius: Distance of a point from the origin.
:param lon: Angle of the point from the XZ plane in ... |
def is_logged_in(username=None):
"""Checks if user is logged in if `username`
is passed check if specified user is logged in
username can be a list"""
if username:
if not isinstance(username, (list, tuple)):
username = [username]
return 'simple_logged_in' in session and get_u... | Checks if user is logged in if `username`
is passed check if specified user is logged in
username can be a list | Below is the the instruction that describes the task:
### Input:
Checks if user is logged in if `username`
is passed check if specified user is logged in
username can be a list
### Response:
def is_logged_in(username=None):
"""Checks if user is logged in if `username`
is passed check if specified u... |
def check(self, line_info):
"Allow ! and !! in multi-line statements if multi_line_specials is on"
# Note that this one of the only places we check the first character of
# ifun and *not* the pre_char. Also note that the below test matches
# both ! and !!.
if line_info.continue_... | Allow ! and !! in multi-line statements if multi_line_specials is on | Below is the the instruction that describes the task:
### Input:
Allow ! and !! in multi-line statements if multi_line_specials is on
### Response:
def check(self, line_info):
"Allow ! and !! in multi-line statements if multi_line_specials is on"
# Note that this one of the only places we check the... |
def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
"""Get version from 'git describe' in the root of the source tree.
This only gets called if the git-archive 'subst' keywords were *not*
expanded, and _version.py hasn't already been rewritten with a short
version string, meani... | Get version from 'git describe' in the root of the source tree.
This only gets called if the git-archive 'subst' keywords were *not*
expanded, and _version.py hasn't already been rewritten with a short
version string, meaning we're inside a checked out source tree. | Below is the the instruction that describes the task:
### Input:
Get version from 'git describe' in the root of the source tree.
This only gets called if the git-archive 'subst' keywords were *not*
expanded, and _version.py hasn't already been rewritten with a short
version string, meaning we're inside... |
def find_all(string, sub, start=None, end=None, ignore_case=False, **kwargs):
"""
Return all indices in string s where substring sub is
found, such that sub is contained in the slice s[start:end].
>>> list(find_all('The quick brown fox jumps over the lazy dog', 'fox'))
[16]
>>> list(find_all('... | Return all indices in string s where substring sub is
found, such that sub is contained in the slice s[start:end].
>>> list(find_all('The quick brown fox jumps over the lazy dog', 'fox'))
[16]
>>> list(find_all('The quick brown fox jumps over the lazy dog', 'mountain'))
[]
>>> list(find_all('... | Below is the the instruction that describes the task:
### Input:
Return all indices in string s where substring sub is
found, such that sub is contained in the slice s[start:end].
>>> list(find_all('The quick brown fox jumps over the lazy dog', 'fox'))
[16]
>>> list(find_all('The quick brown fox j... |
def user_sessions(self, user_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/sessions#list-sessions"
api_path = "/api/v2/users/{user_id}/sessions.json"
api_path = api_path.format(user_id=user_id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/sessions#list-sessions | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/core/sessions#list-sessions
### Response:
def user_sessions(self, user_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/sessions#list-sessions"
api_path = "/api/v2/users/{use... |
def get_keyvault(access_token, subscription_id, rgname, vault_name):
'''Gets details about the named key vault.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
rgname (str): Azure resource group name.
vault_name (str): ... | Gets details about the named key vault.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
rgname (str): Azure resource group name.
vault_name (str): Name of the key vault.
Returns:
HTTP response. JSON body of key... | Below is the the instruction that describes the task:
### Input:
Gets details about the named key vault.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
rgname (str): Azure resource group name.
vault_name (str): Name of... |
def trigger_installed(connection: connection, table: str, schema: str='public'):
"""Test whether or not a psycopg2-pgevents trigger is installed for a table.
Parameters
----------
connection: psycopg2.extensions.connection
Active connection to a PostGreSQL database.
table: str
Table... | Test whether or not a psycopg2-pgevents trigger is installed for a table.
Parameters
----------
connection: psycopg2.extensions.connection
Active connection to a PostGreSQL database.
table: str
Table whose trigger-existence will be checked.
schema: str
Schema to which the ta... | Below is the the instruction that describes the task:
### Input:
Test whether or not a psycopg2-pgevents trigger is installed for a table.
Parameters
----------
connection: psycopg2.extensions.connection
Active connection to a PostGreSQL database.
table: str
Table whose trigger-exis... |
def _scrape_document(self):
'''Extract links from the DOM.'''
mock_response = self._new_mock_response(
self._response, self._get_temp_path('phantom', '.html')
)
self._item_session.request = self._request
self._item_session.response = mock_response
self._proc... | Extract links from the DOM. | Below is the the instruction that describes the task:
### Input:
Extract links from the DOM.
### Response:
def _scrape_document(self):
'''Extract links from the DOM.'''
mock_response = self._new_mock_response(
self._response, self._get_temp_path('phantom', '.html')
)
se... |
def slack_ver():
"""
Open file and read Slackware version
"""
if _meta_.slackware_version in ["off", "OFF"]:
sv = Utils().read_file("/etc/slackware-version")
version = re.findall(r"\d+", sv)
if len(sv) > 2:
return (".".join(version[:2]))
else:
ret... | Open file and read Slackware version | Below is the the instruction that describes the task:
### Input:
Open file and read Slackware version
### Response:
def slack_ver():
"""
Open file and read Slackware version
"""
if _meta_.slackware_version in ["off", "OFF"]:
sv = Utils().read_file("/etc/slackware-version")
version ... |
def get_matching_rules(tweet):
"""
Retrieves the matching rules for a tweet with a gnip field enrichment.
Args:
tweet (Tweet): the tweet
Returns:
list: potential ``[{"tag": "user_tag", "value": "rule_value"}]``
pairs from standard rulesets or None if no rules or no
mat... | Retrieves the matching rules for a tweet with a gnip field enrichment.
Args:
tweet (Tweet): the tweet
Returns:
list: potential ``[{"tag": "user_tag", "value": "rule_value"}]``
pairs from standard rulesets or None if no rules or no
matching_rules field is found. \n
More... | Below is the the instruction that describes the task:
### Input:
Retrieves the matching rules for a tweet with a gnip field enrichment.
Args:
tweet (Tweet): the tweet
Returns:
list: potential ``[{"tag": "user_tag", "value": "rule_value"}]``
pairs from standard rulesets or None if ... |
def _postprocess_variants(record_file, data, ref_file, out_file):
"""Post-process variants, converting into standard VCF file.
"""
if not utils.file_uptodate(out_file, record_file):
with file_transaction(data, out_file) as tx_out_file:
cmd = ["dv_postprocess_variants.py", "--ref", ref_fi... | Post-process variants, converting into standard VCF file. | Below is the the instruction that describes the task:
### Input:
Post-process variants, converting into standard VCF file.
### Response:
def _postprocess_variants(record_file, data, ref_file, out_file):
"""Post-process variants, converting into standard VCF file.
"""
if not utils.file_uptodate(out_file... |
def ns_prefix(self, prefix, ns_uri):
"""
Set the namespace prefix of the :class:`xml4h.nodes.Element` node
represented by this Builder.
:return: the current Builder.
Delegates to :meth:`xml4h.nodes.Element.set_ns_prefix`.
"""
self._element.set_ns_prefix(prefix, ... | Set the namespace prefix of the :class:`xml4h.nodes.Element` node
represented by this Builder.
:return: the current Builder.
Delegates to :meth:`xml4h.nodes.Element.set_ns_prefix`. | Below is the the instruction that describes the task:
### Input:
Set the namespace prefix of the :class:`xml4h.nodes.Element` node
represented by this Builder.
:return: the current Builder.
Delegates to :meth:`xml4h.nodes.Element.set_ns_prefix`.
### Response:
def ns_prefix(self, prefix, n... |
def element_type(self, type_):
"""returns reference to the class value\\mapped type declaration"""
return self.__find_xxx_type(
type_,
self.element_type_index,
self.element_type_typedef,
'container_element_type') | returns reference to the class value\\mapped type declaration | Below is the the instruction that describes the task:
### Input:
returns reference to the class value\\mapped type declaration
### Response:
def element_type(self, type_):
"""returns reference to the class value\\mapped type declaration"""
return self.__find_xxx_type(
type_,
... |
def scp_data_length(self):
"""The maximum SCP data field length supported by the machine
(bytes).
"""
# If not known, query the machine
if self._scp_data_length is None:
data = self.get_software_version(255, 255, 0)
self._scp_data_length = data.buffer_size... | The maximum SCP data field length supported by the machine
(bytes). | Below is the the instruction that describes the task:
### Input:
The maximum SCP data field length supported by the machine
(bytes).
### Response:
def scp_data_length(self):
"""The maximum SCP data field length supported by the machine
(bytes).
"""
# If not known, query the ... |
def walk(self, where="/"):
""" Walk the pytables group hierarchy for pandas objects
This generator will yield the group path, subgroups and pandas object
names for each group.
Any non-pandas PyTables objects that are not a group will be ignored.
The `where` group itself is list... | Walk the pytables group hierarchy for pandas objects
This generator will yield the group path, subgroups and pandas object
names for each group.
Any non-pandas PyTables objects that are not a group will be ignored.
The `where` group itself is listed first (preorder), then each of its
... | Below is the the instruction that describes the task:
### Input:
Walk the pytables group hierarchy for pandas objects
This generator will yield the group path, subgroups and pandas object
names for each group.
Any non-pandas PyTables objects that are not a group will be ignored.
Th... |
def get_image(conn, vm_):
'''
Return the image object to use
'''
images = conn.list_images()
vm_image = config.get_cloud_config_value('image', vm_, __opts__)
if not six.PY3:
vm_image = vm_image.encode('ascii', 'salt-cloud-force-ascii')
for img in images:
if isinstance(img.i... | Return the image object to use | Below is the the instruction that describes the task:
### Input:
Return the image object to use
### Response:
def get_image(conn, vm_):
'''
Return the image object to use
'''
images = conn.list_images()
vm_image = config.get_cloud_config_value('image', vm_, __opts__)
if not six.PY3:
... |
def nodeprep(string, allow_unassigned=False):
"""
Process the given `string` using the Nodeprep (`RFC 6122`_) profile. In the
error cases defined in `RFC 3454`_ (stringprep), a :class:`ValueError` is
raised.
"""
chars = list(string)
_nodeprep_do_mapping(chars)
do_normalization(chars)
... | Process the given `string` using the Nodeprep (`RFC 6122`_) profile. In the
error cases defined in `RFC 3454`_ (stringprep), a :class:`ValueError` is
raised. | Below is the the instruction that describes the task:
### Input:
Process the given `string` using the Nodeprep (`RFC 6122`_) profile. In the
error cases defined in `RFC 3454`_ (stringprep), a :class:`ValueError` is
raised.
### Response:
def nodeprep(string, allow_unassigned=False):
"""
Process the ... |
def _map_to_cfg(self):
"""
Map our current slice to CFG.
Based on self._statements_per_run and self._exit_statements_per_run, this method will traverse the CFG and
check if there is any missing block on the path. If there is, the default exit of that missing block will be
includ... | Map our current slice to CFG.
Based on self._statements_per_run and self._exit_statements_per_run, this method will traverse the CFG and
check if there is any missing block on the path. If there is, the default exit of that missing block will be
included in the slice. This is because Slicecutor... | Below is the the instruction that describes the task:
### Input:
Map our current slice to CFG.
Based on self._statements_per_run and self._exit_statements_per_run, this method will traverse the CFG and
check if there is any missing block on the path. If there is, the default exit of that missing bl... |
def get_tasker2_slabs(self, tol=0.01, same_species_only=True):
"""
Get a list of slabs that have been Tasker 2 corrected.
Args:
tol (float): Tolerance to determine if atoms are within same plane.
This is a fractional tolerance, not an absolute one.
same_s... | Get a list of slabs that have been Tasker 2 corrected.
Args:
tol (float): Tolerance to determine if atoms are within same plane.
This is a fractional tolerance, not an absolute one.
same_species_only (bool): If True, only that are of the exact same
specie... | Below is the the instruction that describes the task:
### Input:
Get a list of slabs that have been Tasker 2 corrected.
Args:
tol (float): Tolerance to determine if atoms are within same plane.
This is a fractional tolerance, not an absolute one.
same_species_only (b... |
def schedule(self, callback, *args, **kwargs):
"""Schedule the callback to be called asynchronously in a thread pool.
Args:
callback (Callable): The function to call.
args: Positional arguments passed to the function.
kwargs: Key-word arguments passed to the function... | Schedule the callback to be called asynchronously in a thread pool.
Args:
callback (Callable): The function to call.
args: Positional arguments passed to the function.
kwargs: Key-word arguments passed to the function.
Returns:
None | Below is the the instruction that describes the task:
### Input:
Schedule the callback to be called asynchronously in a thread pool.
Args:
callback (Callable): The function to call.
args: Positional arguments passed to the function.
kwargs: Key-word arguments passed to t... |
def fgm(self, x, labels, targeted=False):
"""
TensorFlow Eager implementation of the Fast Gradient Method.
:param x: the input variable
:param targeted: Is the attack targeted or untargeted? Untargeted, the
default, will try to make the label incorrect.
Targeted... | TensorFlow Eager implementation of the Fast Gradient Method.
:param x: the input variable
:param targeted: Is the attack targeted or untargeted? Untargeted, the
default, will try to make the label incorrect.
Targeted will instead try to move in the direction
... | Below is the the instruction that describes the task:
### Input:
TensorFlow Eager implementation of the Fast Gradient Method.
:param x: the input variable
:param targeted: Is the attack targeted or untargeted? Untargeted, the
default, will try to make the label incorrect.
... |
def _iac_sniffer(self, byte):
"""
Watches incomming data for Telnet IAC sequences.
Passes the data, if any, with the IAC commands stripped to
_recv_byte().
"""
## Are we not currently in an IAC sequence coming from the DE?
if self.telnet_got_iac is False:
... | Watches incomming data for Telnet IAC sequences.
Passes the data, if any, with the IAC commands stripped to
_recv_byte(). | Below is the the instruction that describes the task:
### Input:
Watches incomming data for Telnet IAC sequences.
Passes the data, if any, with the IAC commands stripped to
_recv_byte().
### Response:
def _iac_sniffer(self, byte):
"""
Watches incomming data for Telnet IAC sequences.... |
def tokenize_init(spec):
"""Initialize a tokenizer. Should only be called by the
:func:`~textparser.Parser.tokenize` method in the parser.
"""
tokens = [Token('__SOF__', '__SOF__', 0)]
re_token = '|'.join([
'(?P<{}>{})'.format(name, regex) for name, regex in spec
])
return tokens,... | Initialize a tokenizer. Should only be called by the
:func:`~textparser.Parser.tokenize` method in the parser. | Below is the the instruction that describes the task:
### Input:
Initialize a tokenizer. Should only be called by the
:func:`~textparser.Parser.tokenize` method in the parser.
### Response:
def tokenize_init(spec):
"""Initialize a tokenizer. Should only be called by the
:func:`~textparser.Parser.tokeni... |
def load_agent(self, overall_index: int=None):
"""
Loads all data for overall_index from the overall config and also loads both presets
:param overall_index: the index of the targeted agent
:return agent: an Agent (gui_agent) class with all loaded values
"""
if not self.i... | Loads all data for overall_index from the overall config and also loads both presets
:param overall_index: the index of the targeted agent
:return agent: an Agent (gui_agent) class with all loaded values | Below is the the instruction that describes the task:
### Input:
Loads all data for overall_index from the overall config and also loads both presets
:param overall_index: the index of the targeted agent
:return agent: an Agent (gui_agent) class with all loaded values
### Response:
def load_agent(s... |
def add_port(self, port):
"""
Add a port object to the definition
:param port: port definition
:type port: PortDef
"""
self.ports.append(port)
if port.io_type not in self.port_seqs:
self.port_seqs[port.io_type] = 0
self.port_seqs[port.io_type]... | Add a port object to the definition
:param port: port definition
:type port: PortDef | Below is the the instruction that describes the task:
### Input:
Add a port object to the definition
:param port: port definition
:type port: PortDef
### Response:
def add_port(self, port):
"""
Add a port object to the definition
:param port: port definition
:type ... |
def run_report_from_console(output_file_name, callback):
"""
Runs the report from the command line. Receives the book url from the console.
"""
print("The report uses a read-only access to the book.")
print("Now enter the data or ^Z to continue:")
#report_method = kwargs["report_method"]
re... | Runs the report from the command line. Receives the book url from the console. | Below is the the instruction that describes the task:
### Input:
Runs the report from the command line. Receives the book url from the console.
### Response:
def run_report_from_console(output_file_name, callback):
"""
Runs the report from the command line. Receives the book url from the console.
"""
... |
def relation_get(attribute=None, unit=None, rid=None):
"""Get relation information"""
_args = ['relation-get', '--format=json']
if rid:
_args.append('-r')
_args.append(rid)
_args.append(attribute or '-')
if unit:
_args.append(unit)
try:
return json.loads(subproces... | Get relation information | Below is the the instruction that describes the task:
### Input:
Get relation information
### Response:
def relation_get(attribute=None, unit=None, rid=None):
"""Get relation information"""
_args = ['relation-get', '--format=json']
if rid:
_args.append('-r')
_args.append(rid)
_args.... |
def associate_psds_to_multi_ifo_segments(opt, fd_segments, gwstrain, flen,
delta_f, flow, ifos,
dyn_range_factor=1., precision=None):
"""
Associate PSDs to segments for all ifos when using the multi-detector CLI
"""
for if... | Associate PSDs to segments for all ifos when using the multi-detector CLI | Below is the the instruction that describes the task:
### Input:
Associate PSDs to segments for all ifos when using the multi-detector CLI
### Response:
def associate_psds_to_multi_ifo_segments(opt, fd_segments, gwstrain, flen,
delta_f, flow, ifos,
... |
def build(python=PYTHON):
"""Build the bigfloat library for in-place testing."""
clean()
local(
"LIBRARY_PATH={library_path} CPATH={include_path} {python} "
"setup.py build_ext --inplace".format(
library_path=LIBRARY_PATH,
include_path=INCLUDE_PATH,
python... | Build the bigfloat library for in-place testing. | Below is the the instruction that describes the task:
### Input:
Build the bigfloat library for in-place testing.
### Response:
def build(python=PYTHON):
"""Build the bigfloat library for in-place testing."""
clean()
local(
"LIBRARY_PATH={library_path} CPATH={include_path} {python} "
"s... |
def _is_mosaic(dicom_input):
"""
Use this function to detect if a dicom series is a siemens 4d dataset
NOTE: Only the first slice will be checked so you can only provide an already sorted dicom directory
(containing one series)
"""
# for grouped dicoms
if type(dicom_input) is list and type(d... | Use this function to detect if a dicom series is a siemens 4d dataset
NOTE: Only the first slice will be checked so you can only provide an already sorted dicom directory
(containing one series) | Below is the the instruction that describes the task:
### Input:
Use this function to detect if a dicom series is a siemens 4d dataset
NOTE: Only the first slice will be checked so you can only provide an already sorted dicom directory
(containing one series)
### Response:
def _is_mosaic(dicom_input):
... |
def remove(self, rel_path, propagate=False):
'''Delete the file from the cache, and from the upstream'''
key = self._get_boto_key(rel_path)
if key:
key.delete() | Delete the file from the cache, and from the upstream | Below is the the instruction that describes the task:
### Input:
Delete the file from the cache, and from the upstream
### Response:
def remove(self, rel_path, propagate=False):
'''Delete the file from the cache, and from the upstream'''
key = self._get_boto_key(rel_path)
if key:
... |
def consume_arguments(self, argument_list):
"""
Takes arguments from a list while this parameter can accept them
"""
if len(argument_list) == 0:
return []
if argument_list[0] == self.arg_name:
argument_list = argument_list[1:]
if self.constrain... | Takes arguments from a list while this parameter can accept them | Below is the the instruction that describes the task:
### Input:
Takes arguments from a list while this parameter can accept them
### Response:
def consume_arguments(self, argument_list):
"""
Takes arguments from a list while this parameter can accept them
"""
if len(argument_list) ... |
def asset_create(self, name, items, tag='', description='', atype='static'):
'''asset_create_static name, ips, tags, description
Create a new asset list with the defined information.
UN-DOCUMENTED CALL: This function is not considered stable.
:param name: asset list name (must be uniqu... | asset_create_static name, ips, tags, description
Create a new asset list with the defined information.
UN-DOCUMENTED CALL: This function is not considered stable.
:param name: asset list name (must be unique)
:type name: string
:param items: list of IP Addresses, CIDR, and Netw... | Below is the the instruction that describes the task:
### Input:
asset_create_static name, ips, tags, description
Create a new asset list with the defined information.
UN-DOCUMENTED CALL: This function is not considered stable.
:param name: asset list name (must be unique)
:type na... |
def qteNextApplet(self, numSkip: int=1, ofsApp: (QtmacsApplet, str)=None,
skipInvisible: bool=True, skipVisible: bool=False,
skipMiniApplet: bool=True,
windowObj: QtmacsWindow=None):
"""
Return the next applet in cyclic order.
If... | Return the next applet in cyclic order.
If ``ofsApp=None`` then start cycling at the currently active
applet. If ``ofsApp`` does not fit the selection criteria,
then the cycling starts at the next applet in cyclic order
that does.
The returned applet is ``numSkip`` items in cyc... | Below is the the instruction that describes the task:
### Input:
Return the next applet in cyclic order.
If ``ofsApp=None`` then start cycling at the currently active
applet. If ``ofsApp`` does not fit the selection criteria,
then the cycling starts at the next applet in cyclic order
... |
def AddEventTags(self, event_tags):
"""Adds event tags.
Args:
event_tags (list[EventTag]): event tags.
Raises:
IOError: when the storage file is closed or read-only or
if the event tags cannot be serialized.
OSError: when the storage file is closed or read-only or
if ... | Adds event tags.
Args:
event_tags (list[EventTag]): event tags.
Raises:
IOError: when the storage file is closed or read-only or
if the event tags cannot be serialized.
OSError: when the storage file is closed or read-only or
if the event tags cannot be serialized. | Below is the the instruction that describes the task:
### Input:
Adds event tags.
Args:
event_tags (list[EventTag]): event tags.
Raises:
IOError: when the storage file is closed or read-only or
if the event tags cannot be serialized.
OSError: when the storage file is closed or ... |
def _SendStruct(self, fmt, *args):
"""Pack a struct (without length or checksum) and send it.
"""
data = struct.pack(fmt, *args)
data_len = len(data) + 1
checksum = (data_len + sum(bytearray(data))) % 256
out = struct.pack("B", data_len) + data + struct.pack("B", checksum... | Pack a struct (without length or checksum) and send it. | Below is the the instruction that describes the task:
### Input:
Pack a struct (without length or checksum) and send it.
### Response:
def _SendStruct(self, fmt, *args):
"""Pack a struct (without length or checksum) and send it.
"""
data = struct.pack(fmt, *args)
data_len = len(data... |
def _ensure_slack(self, connector: Any, retries: int,
backoff: Callable[[int], float]) -> None:
""" Ensure we have a SlackClient. """
connector = self._env_var if connector is None else connector
slack: SlackClient = _create_slack(connector)
self._slack = _SlackClie... | Ensure we have a SlackClient. | Below is the the instruction that describes the task:
### Input:
Ensure we have a SlackClient.
### Response:
def _ensure_slack(self, connector: Any, retries: int,
backoff: Callable[[int], float]) -> None:
""" Ensure we have a SlackClient. """
connector = self._env_var if conne... |
def _keyboard_access(self, element):
"""
Provide keyboard access for element, if it not has.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
"""
# pylint: disable=no-self-use
if not element.has_attribute('tabindex'):
... | Provide keyboard access for element, if it not has.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement | Below is the the instruction that describes the task:
### Input:
Provide keyboard access for element, if it not has.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
### Response:
def _keyboard_access(self, element):
"""
Provide keyboard ... |
def mutate(self, mutation, timeout=None, metadata=None, credentials=None):
"""Runs mutate operation."""
return self.stub.Mutate(mutation, timeout=timeout, metadata=metadata,
credentials=credentials) | Runs mutate operation. | Below is the the instruction that describes the task:
### Input:
Runs mutate operation.
### Response:
def mutate(self, mutation, timeout=None, metadata=None, credentials=None):
"""Runs mutate operation."""
return self.stub.Mutate(mutation, timeout=timeout, metadata=metadata,
... |
def remove_namespace(doc, namespace):
"""
Takes in a ElementTree object and namespace value. The length of that
namespace value is removed from all Element nodes within the document.
This effectively removes the namespace from that document.
:param doc: lxml.etree
:param namespace: Namespace t... | Takes in a ElementTree object and namespace value. The length of that
namespace value is removed from all Element nodes within the document.
This effectively removes the namespace from that document.
:param doc: lxml.etree
:param namespace: Namespace that needs to be removed.
:return: Returns the ... | Below is the the instruction that describes the task:
### Input:
Takes in a ElementTree object and namespace value. The length of that
namespace value is removed from all Element nodes within the document.
This effectively removes the namespace from that document.
:param doc: lxml.etree
:param nam... |
def nl_complete_msg(sk, msg):
"""Finalize Netlink message.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L450
This function finalizes a Netlink message by completing the message with desirable flags and values depending on the
socket configuration.
- If not yet filled out, the source... | Finalize Netlink message.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L450
This function finalizes a Netlink message by completing the message with desirable flags and values depending on the
socket configuration.
- If not yet filled out, the source address of the message (`nlmsg_pid`)... | Below is the the instruction that describes the task:
### Input:
Finalize Netlink message.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L450
This function finalizes a Netlink message by completing the message with desirable flags and values depending on the
socket configuration.
- I... |
def clearAndSetComboBoxes(self, axesNames):
""" Removes all comboboxes.
"""
logger.debug("Collector clearAndSetComboBoxes: {}".format(axesNames))
check_is_a_sequence(axesNames)
row = 0
self._deleteComboBoxes(row)
self.clear()
self._setAxesNames(axesNames)
... | Removes all comboboxes. | Below is the the instruction that describes the task:
### Input:
Removes all comboboxes.
### Response:
def clearAndSetComboBoxes(self, axesNames):
""" Removes all comboboxes.
"""
logger.debug("Collector clearAndSetComboBoxes: {}".format(axesNames))
check_is_a_sequence(axesNames)
... |
def define_standalone_options(parser, extra_options=None):
'''
Adds the options specific to the database connection.
Parses the agency configuration files and uses its configuration as the
default values.
'''
c = config.parse_service_config()
parser.add_option('--dbhost', '-H', action='stor... | Adds the options specific to the database connection.
Parses the agency configuration files and uses its configuration as the
default values. | Below is the the instruction that describes the task:
### Input:
Adds the options specific to the database connection.
Parses the agency configuration files and uses its configuration as the
default values.
### Response:
def define_standalone_options(parser, extra_options=None):
'''
Adds the option... |
def update_coordinates(self, filename, update_port_locations=True):
"""Update the coordinates of this Compound from a file.
Parameters
----------
filename : str
Name of file from which to load coordinates. Supported file types
are the same as those supported by l... | Update the coordinates of this Compound from a file.
Parameters
----------
filename : str
Name of file from which to load coordinates. Supported file types
are the same as those supported by load()
update_port_locations : bool, optional, default=True
... | Below is the the instruction that describes the task:
### Input:
Update the coordinates of this Compound from a file.
Parameters
----------
filename : str
Name of file from which to load coordinates. Supported file types
are the same as those supported by load()
... |
def feedforward(inputs,
num_units,
scope="multihead_attention"):
'''Point-wise feed forward net.
Args:
inputs: A 3d tensor with shape of [N, T, C].
num_units: A list of two integers.
scope: Optional scope for `variable_scope`.
reuse: Boolean, whether to r... | Point-wise feed forward net.
Args:
inputs: A 3d tensor with shape of [N, T, C].
num_units: A list of two integers.
scope: Optional scope for `variable_scope`.
reuse: Boolean, whether to reuse the weights of a previous layer
by the same name.
Returns:
A 3d tensor with the ... | Below is the the instruction that describes the task:
### Input:
Point-wise feed forward net.
Args:
inputs: A 3d tensor with shape of [N, T, C].
num_units: A list of two integers.
scope: Optional scope for `variable_scope`.
reuse: Boolean, whether to reuse the weights of a previous laye... |
def setup_callbacks(self):
'''
Assign attributes for pygit2 callbacks
'''
if PYGIT2_VERSION >= _LooseVersion('0.23.2'):
self.remotecallbacks = pygit2.RemoteCallbacks(
credentials=self.credentials)
if not self.ssl_verify:
# Override ... | Assign attributes for pygit2 callbacks | Below is the the instruction that describes the task:
### Input:
Assign attributes for pygit2 callbacks
### Response:
def setup_callbacks(self):
'''
Assign attributes for pygit2 callbacks
'''
if PYGIT2_VERSION >= _LooseVersion('0.23.2'):
self.remotecallbacks = pygit2.Rem... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.