code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def clear_text(self, label):
"""stub"""
if label not in self.my_osid_object_form._my_map['texts']:
raise NotFound()
del self.my_osid_object_form._my_map['texts'][label] | stub | Below is the the instruction that describes the task:
### Input:
stub
### Response:
def clear_text(self, label):
"""stub"""
if label not in self.my_osid_object_form._my_map['texts']:
raise NotFound()
del self.my_osid_object_form._my_map['texts'][label] |
def __process_by_python(self):
"""!
@brief Performs cluster analysis using python code.
"""
if self.__data_type == 'points':
self.__kdtree = kdtree(self.__sample_pointer, range(len(self.__sample_pointer)))
self.__allocate_clusters()
if (self.__a... | !
@brief Performs cluster analysis using python code. | Below is the the instruction that describes the task:
### Input:
!
@brief Performs cluster analysis using python code.
### Response:
def __process_by_python(self):
"""!
@brief Performs cluster analysis using python code.
"""
if self.__data_type == 'points':
... |
def get_config_item(self, key):
"""
Returns the value for a given config key.
A list is returned when multiple values are set.
"""
value = _lxc.Container.get_config_item(self, key)
if value is False:
return False
elif value.endswith("\n"):
... | Returns the value for a given config key.
A list is returned when multiple values are set. | Below is the the instruction that describes the task:
### Input:
Returns the value for a given config key.
A list is returned when multiple values are set.
### Response:
def get_config_item(self, key):
"""
Returns the value for a given config key.
A list is returned when... |
def _create_skeleton_3(pc, l, num_section):
"""
Bottom level: {"measurement": [], "model": [{summary, distributions, ensemble}]}
Fill in measurement and model tables with N number of EMPTY meas, summary, ensemble, and distributions.
:param str pc: Paleo or Chron "mode"
:param list l:
:param dict... | Bottom level: {"measurement": [], "model": [{summary, distributions, ensemble}]}
Fill in measurement and model tables with N number of EMPTY meas, summary, ensemble, and distributions.
:param str pc: Paleo or Chron "mode"
:param list l:
:param dict num_section:
:return dict: | Below is the the instruction that describes the task:
### Input:
Bottom level: {"measurement": [], "model": [{summary, distributions, ensemble}]}
Fill in measurement and model tables with N number of EMPTY meas, summary, ensemble, and distributions.
:param str pc: Paleo or Chron "mode"
:param list l:
... |
def score_wu(CIJ, s):
'''
The s-core is the largest subnetwork comprising nodes of strength at
least s. This function computes the s-core for a given weighted
undirected connection matrix. Computation is analogous to the more
widely used k-core, but is based on node strengths instead of node
deg... | The s-core is the largest subnetwork comprising nodes of strength at
least s. This function computes the s-core for a given weighted
undirected connection matrix. Computation is analogous to the more
widely used k-core, but is based on node strengths instead of node
degrees.
Parameters
--------... | Below is the the instruction that describes the task:
### Input:
The s-core is the largest subnetwork comprising nodes of strength at
least s. This function computes the s-core for a given weighted
undirected connection matrix. Computation is analogous to the more
widely used k-core, but is based on nod... |
def _set_config_src(self, v, load=False):
"""
Setter method for config_src, mapped from YANG variable /brocade_tunnels_ext_rpc/get_tunnel_info/output/tunnel/config_src (config-src-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_config_src is considered as a private... | Setter method for config_src, mapped from YANG variable /brocade_tunnels_ext_rpc/get_tunnel_info/output/tunnel/config_src (config-src-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_config_src is considered as a private
method. Backends looking to populate this variabl... | Below is the the instruction that describes the task:
### Input:
Setter method for config_src, mapped from YANG variable /brocade_tunnels_ext_rpc/get_tunnel_info/output/tunnel/config_src (config-src-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_config_src is consider... |
def get_tokens(tu, extent):
"""Helper method to return all tokens in an extent.
This functionality is needed multiple places in this module. We define
it here because it seems like a logical place.
"""
tokens_memory = POINTER(Token)()
tokens_count = c_uint()
con... | Helper method to return all tokens in an extent.
This functionality is needed multiple places in this module. We define
it here because it seems like a logical place. | Below is the the instruction that describes the task:
### Input:
Helper method to return all tokens in an extent.
This functionality is needed multiple places in this module. We define
it here because it seems like a logical place.
### Response:
def get_tokens(tu, extent):
"""Helper method... |
def value_output(value, quote_method='all', none_handle='strict'):
'''
Format types:
'all'.
(default) everything is embraced with quotes
'needed'.
Quote only if needed. Values are on placed in quotes if:
a. the value contains a quote
b. there is whitespace at the beginning or... | Format types:
'all'.
(default) everything is embraced with quotes
'needed'.
Quote only if needed. Values are on placed in quotes if:
a. the value contains a quote
b. there is whitespace at the beginning or end of string
'none'.
Quote nothing. | Below is the the instruction that describes the task:
### Input:
Format types:
'all'.
(default) everything is embraced with quotes
'needed'.
Quote only if needed. Values are on placed in quotes if:
a. the value contains a quote
b. there is whitespace at the beginning or end of st... |
def vlog(self, msg, *args):
"""Logs a message to stderr only if verbose is enabled."""
if self.verbose:
self.log(msg, *args) | Logs a message to stderr only if verbose is enabled. | Below is the the instruction that describes the task:
### Input:
Logs a message to stderr only if verbose is enabled.
### Response:
def vlog(self, msg, *args):
"""Logs a message to stderr only if verbose is enabled."""
if self.verbose:
self.log(msg, *args) |
def factory(db, collection, action):
"""
Instantiate trigger
:param db: db descriptor
:param collection: collection to be updated
:param action: ACTION_BEFORE_DELETE, ACTION_AFTER_DELETE, ACTION_BEFORE_UPSERT, ACTION_AFTER_DELETE
:return: trigger instance if trigger confi... | Instantiate trigger
:param db: db descriptor
:param collection: collection to be updated
:param action: ACTION_BEFORE_DELETE, ACTION_AFTER_DELETE, ACTION_BEFORE_UPSERT, ACTION_AFTER_DELETE
:return: trigger instance if trigger configured in triggers.json or None | Below is the the instruction that describes the task:
### Input:
Instantiate trigger
:param db: db descriptor
:param collection: collection to be updated
:param action: ACTION_BEFORE_DELETE, ACTION_AFTER_DELETE, ACTION_BEFORE_UPSERT, ACTION_AFTER_DELETE
:return: trigger instance if t... |
def get_gdns_publisher(config, metrics, **kwargs):
"""Get a GDNSPublisher client.
A factory function that validates configuration and returns a
publisher client (:interface:`gordon.interfaces.IMessageHandler`)
provider.
Args:
config (dict): Google Cloud DNS API related configuration.
... | Get a GDNSPublisher client.
A factory function that validates configuration and returns a
publisher client (:interface:`gordon.interfaces.IMessageHandler`)
provider.
Args:
config (dict): Google Cloud DNS API related configuration.
metrics (obj): :interface:`IMetricRelay` implementation... | Below is the the instruction that describes the task:
### Input:
Get a GDNSPublisher client.
A factory function that validates configuration and returns a
publisher client (:interface:`gordon.interfaces.IMessageHandler`)
provider.
Args:
config (dict): Google Cloud DNS API related configura... |
def folders(self):
'''gets the property value for folders'''
if self._folders is None :
self.__init()
if self._folders is not None and isinstance(self._folders, list):
if len(self._folders) == 0:
self._loadFolders()
return self._folders | gets the property value for folders | Below is the the instruction that describes the task:
### Input:
gets the property value for folders
### Response:
def folders(self):
'''gets the property value for folders'''
if self._folders is None :
self.__init()
if self._folders is not None and isinstance(self._folders, lis... |
def wait(
self, timeout: Union[int, float] = None, safe: bool = False
) -> List[Union[Any, Exception]]:
"""
Call :py:meth:`~Process.wait()` on all the Processes in this list.
:param timeout:
Same as :py:meth:`~Process.wait()`.
This parameter controls the tim... | Call :py:meth:`~Process.wait()` on all the Processes in this list.
:param timeout:
Same as :py:meth:`~Process.wait()`.
This parameter controls the timeout for all the Processes combined,
not a single :py:meth:`~Process.wait()` call.
:param safe:
Suppress... | Below is the the instruction that describes the task:
### Input:
Call :py:meth:`~Process.wait()` on all the Processes in this list.
:param timeout:
Same as :py:meth:`~Process.wait()`.
This parameter controls the timeout for all the Processes combined,
not a single :py:m... |
def get_safe_redirect_target(arg='next'):
"""Get URL to redirect to and ensure that it is local.
:param arg: URL argument.
:returns: The redirect target or ``None``.
"""
for target in request.args.get(arg), request.referrer:
if target:
redirect_uri = urisplit(target)
... | Get URL to redirect to and ensure that it is local.
:param arg: URL argument.
:returns: The redirect target or ``None``. | Below is the the instruction that describes the task:
### Input:
Get URL to redirect to and ensure that it is local.
:param arg: URL argument.
:returns: The redirect target or ``None``.
### Response:
def get_safe_redirect_target(arg='next'):
"""Get URL to redirect to and ensure that it is local.
... |
def _setup_logger(self, level, log_file):
"""Setup log level and log file if set"""
if logger.handlers:
return
level = getattr(logging, level.upper())
logger.setLevel(level)
formatter = logging.Formatter(
'[%(levelname)s] %(asctime)s - %(module)s.%(funcNam... | Setup log level and log file if set | Below is the the instruction that describes the task:
### Input:
Setup log level and log file if set
### Response:
def _setup_logger(self, level, log_file):
"""Setup log level and log file if set"""
if logger.handlers:
return
level = getattr(logging, level.upper())
logge... |
def _cache_dataset(dataset, prefix):
"""Cache the processed npy dataset the dataset into a npz
Parameters
----------
dataset : SimpleDataset
file_path : str
"""
if not os.path.exists(_constants.CACHE_PATH):
os.makedirs(_constants.CACHE_PATH)
src_data = np.concatenate([e[0] for e... | Cache the processed npy dataset the dataset into a npz
Parameters
----------
dataset : SimpleDataset
file_path : str | Below is the the instruction that describes the task:
### Input:
Cache the processed npy dataset the dataset into a npz
Parameters
----------
dataset : SimpleDataset
file_path : str
### Response:
def _cache_dataset(dataset, prefix):
"""Cache the processed npy dataset the dataset into a npz
... |
def instantiate_tasks(self):
""" All loaded tasks are initialized. Depending on configuration fails in such instantiations may be silent """
self.tasks_instances = {}
for task_name, task_class in self.tasks_classes.items():
try:
self.tasks_instances[task_name] = task_... | All loaded tasks are initialized. Depending on configuration fails in such instantiations may be silent | Below is the the instruction that describes the task:
### Input:
All loaded tasks are initialized. Depending on configuration fails in such instantiations may be silent
### Response:
def instantiate_tasks(self):
""" All loaded tasks are initialized. Depending on configuration fails in such instantiations m... |
def get_references(chebi_ids):
'''Returns references'''
references = []
chebi_ids = [str(chebi_id) for chebi_id in chebi_ids]
filename = get_file('reference.tsv.gz')
with io.open(filename, 'r', encoding='cp1252') as textfile:
next(textfile)
for line in textfile:
tokens... | Returns references | Below is the the instruction that describes the task:
### Input:
Returns references
### Response:
def get_references(chebi_ids):
'''Returns references'''
references = []
chebi_ids = [str(chebi_id) for chebi_id in chebi_ids]
filename = get_file('reference.tsv.gz')
with io.open(filename, 'r', e... |
def _update_versions():
"""Update :attr:`_versions` with the registered plotter methods"""
for pm_name in plot._plot_methods:
pm = getattr(plot, pm_name)
plugin = pm._plugin
if (plugin is not None and plugin not in _versions and
pm.module in sys.modules):
_ver... | Update :attr:`_versions` with the registered plotter methods | Below is the the instruction that describes the task:
### Input:
Update :attr:`_versions` with the registered plotter methods
### Response:
def _update_versions():
"""Update :attr:`_versions` with the registered plotter methods"""
for pm_name in plot._plot_methods:
pm = getattr(plot, pm_name)
... |
def filter_records(root, head, update, filters=()):
"""Apply the filters to the records."""
root, head, update = freeze(root), freeze(head), freeze(update)
for filter_ in filters:
root, head, update = filter_(root, head, update)
return thaw(root), thaw(head), thaw(update) | Apply the filters to the records. | Below is the the instruction that describes the task:
### Input:
Apply the filters to the records.
### Response:
def filter_records(root, head, update, filters=()):
"""Apply the filters to the records."""
root, head, update = freeze(root), freeze(head), freeze(update)
for filter_ in filters:
ro... |
def create_from_request_pdu(pdu):
""" Create instance from request PDU.
:param pdu: A response PDU.
"""
_, address, value = \
struct.unpack('>BH' + conf.MULTI_BIT_VALUE_FORMAT_CHARACTER, pdu)
instance = WriteSingleRegister()
instance.address = address
... | Create instance from request PDU.
:param pdu: A response PDU. | Below is the the instruction that describes the task:
### Input:
Create instance from request PDU.
:param pdu: A response PDU.
### Response:
def create_from_request_pdu(pdu):
""" Create instance from request PDU.
:param pdu: A response PDU.
"""
_, address, value = \
... |
def localization_diff(localizable_file, translated_file, excluded_strings_file, output_translation_file):
""" Generates a strings file representing the strings that were yet to be translated.
Args:
localizable_file (str): The path to the localization strings file, meaning the file that represents the s... | Generates a strings file representing the strings that were yet to be translated.
Args:
localizable_file (str): The path to the localization strings file, meaning the file that represents the strings
that require translation.
translated_file (str): The path to the translated strings fil... | Below is the the instruction that describes the task:
### Input:
Generates a strings file representing the strings that were yet to be translated.
Args:
localizable_file (str): The path to the localization strings file, meaning the file that represents the strings
that require translation.
... |
def _InitApiApprovalFromAff4Object(api_approval, approval_obj):
"""Initializes Api(Client|Hunt|CronJob)Approval from an AFF4 object."""
api_approval.id = approval_obj.urn.Basename()
api_approval.reason = approval_obj.Get(approval_obj.Schema.REASON)
api_approval.requestor = approval_obj.Get(approval_obj.Schema.... | Initializes Api(Client|Hunt|CronJob)Approval from an AFF4 object. | Below is the the instruction that describes the task:
### Input:
Initializes Api(Client|Hunt|CronJob)Approval from an AFF4 object.
### Response:
def _InitApiApprovalFromAff4Object(api_approval, approval_obj):
"""Initializes Api(Client|Hunt|CronJob)Approval from an AFF4 object."""
api_approval.id = approval_ob... |
def fix_orientation(image):
""" adapted from https://stackoverflow.com/a/30462851/318857
Apply Image.transpose to ensure 0th row of pixels is at the visual
top of the image, and 0th column is the visual left-hand side.
Return the original image if unable to determine the orientation.
... | adapted from https://stackoverflow.com/a/30462851/318857
Apply Image.transpose to ensure 0th row of pixels is at the visual
top of the image, and 0th column is the visual left-hand side.
Return the original image if unable to determine the orientation.
As per CIPA DC-008-2012, the orie... | Below is the the instruction that describes the task:
### Input:
adapted from https://stackoverflow.com/a/30462851/318857
Apply Image.transpose to ensure 0th row of pixels is at the visual
top of the image, and 0th column is the visual left-hand side.
Return the original image if unable to ... |
def create_tar_file(self, full_archive=False):
"""
Create tar file to be compressed
"""
tar_file_name = os.path.join(self.archive_tmp_dir, self.archive_name)
ext = "" if self.compressor == "none" else ".%s" % self.compressor
tar_file_name = tar_file_name + ".tar" + ext
... | Create tar file to be compressed | Below is the the instruction that describes the task:
### Input:
Create tar file to be compressed
### Response:
def create_tar_file(self, full_archive=False):
"""
Create tar file to be compressed
"""
tar_file_name = os.path.join(self.archive_tmp_dir, self.archive_name)
ext =... |
def __get_lookup(in_fn, selected_type=None):
"""Determine which lookup func to use based on inpt files and type option."""
lookup_func = None
if selected_type is not None:
lookup_func = get_lookup_by_filetype(selected_type)
else:
extension = os.path.splitext(in_fn)[1]
lookup_func = get_lookup_by_fil... | Determine which lookup func to use based on inpt files and type option. | Below is the the instruction that describes the task:
### Input:
Determine which lookup func to use based on inpt files and type option.
### Response:
def __get_lookup(in_fn, selected_type=None):
"""Determine which lookup func to use based on inpt files and type option."""
lookup_func = None
if selected_type... |
def is_different(old_value, new_value):
"""Numpy aware comparison between two values."""
if opt.has_numpy:
return not opt.np.array_equal(old_value, new_value)
else:
return old_value != new_value | Numpy aware comparison between two values. | Below is the the instruction that describes the task:
### Input:
Numpy aware comparison between two values.
### Response:
def is_different(old_value, new_value):
"""Numpy aware comparison between two values."""
if opt.has_numpy:
return not opt.np.array_equal(old_value, new_value)
else:
... |
def push(self, item):
'''Push the value item onto the heap, maintaining the heap invariant.
If the item is not hashable, a TypeError is raised.
'''
hash(item)
heapq.heappush(self._items, item) | Push the value item onto the heap, maintaining the heap invariant.
If the item is not hashable, a TypeError is raised. | Below is the the instruction that describes the task:
### Input:
Push the value item onto the heap, maintaining the heap invariant.
If the item is not hashable, a TypeError is raised.
### Response:
def push(self, item):
'''Push the value item onto the heap, maintaining the heap invariant.
I... |
def pickTextBackgroundColor(self):
"""
Prompts the user to select a text color.
"""
clr = QColorDialog.getColor(self.textBackgroundColor(),
self.window(),
'Pick Background Color')
if clr.isVa... | Prompts the user to select a text color. | Below is the the instruction that describes the task:
### Input:
Prompts the user to select a text color.
### Response:
def pickTextBackgroundColor(self):
"""
Prompts the user to select a text color.
"""
clr = QColorDialog.getColor(self.textBackgroundColor(),
... |
def sent2vec(self, words, transformer):
"""
Used with sqrt kernel
:param words:
:param transformer:
:return:
"""
sent_vec = np.zeros(transformer.vector_size)
numw = 0
for w in words:
try:
sent_vec = np.add(sent_vec, tran... | Used with sqrt kernel
:param words:
:param transformer:
:return: | Below is the the instruction that describes the task:
### Input:
Used with sqrt kernel
:param words:
:param transformer:
:return:
### Response:
def sent2vec(self, words, transformer):
"""
Used with sqrt kernel
:param words:
:param transformer:
:return... |
def get_deleted_objects(objs, opts, user, admin_site, using):
"""
Find all objects related to ``objs`` that should also be deleted. ``objs``
must be a homogeneous iterable of objects (e.g. a QuerySet).
Returns a nested list of strings suitable for display in the
template with the ``unordered_list`` ... | Find all objects related to ``objs`` that should also be deleted. ``objs``
must be a homogeneous iterable of objects (e.g. a QuerySet).
Returns a nested list of strings suitable for display in the
template with the ``unordered_list`` filter. | Below is the the instruction that describes the task:
### Input:
Find all objects related to ``objs`` that should also be deleted. ``objs``
must be a homogeneous iterable of objects (e.g. a QuerySet).
Returns a nested list of strings suitable for display in the
template with the ``unordered_list`` filte... |
def _ip_string_from_prefix(self, prefixlen=None):
"""Turn a prefix length into a dotted decimal string.
Args:
prefixlen: An integer, the netmask prefix length.
Returns:
A string, the dotted decimal netmask string.
"""
if not prefixlen:
prefi... | Turn a prefix length into a dotted decimal string.
Args:
prefixlen: An integer, the netmask prefix length.
Returns:
A string, the dotted decimal netmask string. | Below is the the instruction that describes the task:
### Input:
Turn a prefix length into a dotted decimal string.
Args:
prefixlen: An integer, the netmask prefix length.
Returns:
A string, the dotted decimal netmask string.
### Response:
def _ip_string_from_prefix(self, ... |
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
... | .. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
###... |
def map(self, key_pattern, func, all_args, timeout=None):
'''Cache return value of multiple calls.
Args:
key_pattern (str): the key pattern to use for generating
keys for caches of the decorated function.
func (function): the function to call.
... | Cache return value of multiple calls.
Args:
key_pattern (str): the key pattern to use for generating
keys for caches of the decorated function.
func (function): the function to call.
all_args (list): a list of args to be used to make calls to
... | Below is the the instruction that describes the task:
### Input:
Cache return value of multiple calls.
Args:
key_pattern (str): the key pattern to use for generating
keys for caches of the decorated function.
func (function): the function to call.
... |
def NormalizeRelativePath(path):
"""Normalize camelCase entries in path."""
path_components = path.split('/')
normalized_components = []
for component in path_components:
if re.match(r'{[A-Za-z0-9_]+}$', component):
normalized_components.append(
... | Normalize camelCase entries in path. | Below is the the instruction that describes the task:
### Input:
Normalize camelCase entries in path.
### Response:
def NormalizeRelativePath(path):
"""Normalize camelCase entries in path."""
path_components = path.split('/')
normalized_components = []
for component in path_componen... |
def fast_distance(r1: 'Region', r2: 'Region'):
""" A quicker way of calculating approximate distance. Lower accuracy but faster results."""
return abs(r1.x - r2.x) + abs(r1.y - r2.y) | A quicker way of calculating approximate distance. Lower accuracy but faster results. | Below is the the instruction that describes the task:
### Input:
A quicker way of calculating approximate distance. Lower accuracy but faster results.
### Response:
def fast_distance(r1: 'Region', r2: 'Region'):
""" A quicker way of calculating approximate distance. Lower accuracy but faster results."""
... |
def load_extension(self, module_str):
"""Load an IPython extension by its module name.
If :func:`load_ipython_extension` returns anything, this function
will return that object.
"""
from IPython.utils.syspathcontext import prepended_to_syspath
if module_str not in sys.m... | Load an IPython extension by its module name.
If :func:`load_ipython_extension` returns anything, this function
will return that object. | Below is the the instruction that describes the task:
### Input:
Load an IPython extension by its module name.
If :func:`load_ipython_extension` returns anything, this function
will return that object.
### Response:
def load_extension(self, module_str):
"""Load an IPython extension by its ... |
def _redis_process_checkpoint(host, port):
'''this helper method checks if
redis server is available in the sys
if not fires up one
'''
try:
subprocess.check_output("pgrep redis", shell=True)
except Exception:
logger.warning(
'Your redis server is offline, fake2db wil... | this helper method checks if
redis server is available in the sys
if not fires up one | Below is the the instruction that describes the task:
### Input:
this helper method checks if
redis server is available in the sys
if not fires up one
### Response:
def _redis_process_checkpoint(host, port):
'''this helper method checks if
redis server is available in the sys
if not fires up on... |
def select(*cases):
"""
Select the first case that becomes ready.
If a default case (:class:`goless.dcase`) is present,
return that if no other cases are ready.
If there is no default case and no case is ready,
block until one becomes ready.
See Go's ``reflect.Select`` method for an analog
... | Select the first case that becomes ready.
If a default case (:class:`goless.dcase`) is present,
return that if no other cases are ready.
If there is no default case and no case is ready,
block until one becomes ready.
See Go's ``reflect.Select`` method for an analog
(http://golang.org/pkg/refle... | Below is the the instruction that describes the task:
### Input:
Select the first case that becomes ready.
If a default case (:class:`goless.dcase`) is present,
return that if no other cases are ready.
If there is no default case and no case is ready,
block until one becomes ready.
See Go's ``r... |
def default_instruction_to_svg(self, instruction):
"""As :meth:`instruction_to_svg` but it only takes the ``default.svg``
file into account.
In case no file is found for an instruction in
:meth:`instruction_to_svg`,
this method is used to determine the default svg for it.
... | As :meth:`instruction_to_svg` but it only takes the ``default.svg``
file into account.
In case no file is found for an instruction in
:meth:`instruction_to_svg`,
this method is used to determine the default svg for it.
The content is created by replacing the text ``{instruction... | Below is the the instruction that describes the task:
### Input:
As :meth:`instruction_to_svg` but it only takes the ``default.svg``
file into account.
In case no file is found for an instruction in
:meth:`instruction_to_svg`,
this method is used to determine the default svg for it.... |
def list_roots():
'''
Return all of the files names in all available environments
'''
ret = {}
for saltenv in __opts__['pillar_roots']:
ret[saltenv] = []
ret[saltenv].append(list_env(saltenv))
return ret | Return all of the files names in all available environments | Below is the the instruction that describes the task:
### Input:
Return all of the files names in all available environments
### Response:
def list_roots():
'''
Return all of the files names in all available environments
'''
ret = {}
for saltenv in __opts__['pillar_roots']:
ret[saltenv]... |
def get_event_questions(self, id, **data):
"""
GET /events/:id/questions/
Eventbrite allows event organizers to add custom questions that attendees fill
out upon registration. This endpoint can be helpful for determining what
custom information is collected and available per even... | GET /events/:id/questions/
Eventbrite allows event organizers to add custom questions that attendees fill
out upon registration. This endpoint can be helpful for determining what
custom information is collected and available per event.
This endpoint will return :format:`question`. | Below is the the instruction that describes the task:
### Input:
GET /events/:id/questions/
Eventbrite allows event organizers to add custom questions that attendees fill
out upon registration. This endpoint can be helpful for determining what
custom information is collected and available pe... |
def parse_chinese_morphemes(seq, context=False):
"""
Parse a Chinese syllable and return its basic structure.
"""
# get the tokens
if isinstance(seq, list):
tokens = [s for s in seq]
else:
tokens = lingpy.ipa2tokens(seq, merge_vowels=False)
# get the sound classes ... | Parse a Chinese syllable and return its basic structure. | Below is the the instruction that describes the task:
### Input:
Parse a Chinese syllable and return its basic structure.
### Response:
def parse_chinese_morphemes(seq, context=False):
"""
Parse a Chinese syllable and return its basic structure.
"""
# get the tokens
if isinstance(seq, lis... |
def transformer_ada_lmpackedbase_dialog():
"""Set of hyperparameters."""
hparams = transformer_base_vq_ada_32ex_packed()
hparams.max_length = 1024
hparams.ffn_layer = "dense_relu_dense"
hparams.batch_size = 4096
return hparams | Set of hyperparameters. | Below is the the instruction that describes the task:
### Input:
Set of hyperparameters.
### Response:
def transformer_ada_lmpackedbase_dialog():
"""Set of hyperparameters."""
hparams = transformer_base_vq_ada_32ex_packed()
hparams.max_length = 1024
hparams.ffn_layer = "dense_relu_dense"
hparams.batch_si... |
def docx_preprocess(docx, batch=False):
"""
Load docx files from local filepath if not already b64 encoded
"""
if batch:
return [docx_preprocess(doc, batch=False) for doc in docx]
if os.path.isfile(docx):
# a filepath is provided, read and encode
return b64encode(open(docx, ... | Load docx files from local filepath if not already b64 encoded | Below is the the instruction that describes the task:
### Input:
Load docx files from local filepath if not already b64 encoded
### Response:
def docx_preprocess(docx, batch=False):
"""
Load docx files from local filepath if not already b64 encoded
"""
if batch:
return [docx_preprocess(doc,... |
def readbhfv1(filename, load_data=False, bdfext='.bdf', bhfext='.bhf'):
"""Read header data from bdf/bhf file (Bessy Data Format v1)
Input:
filename: the name of the file
load_data: if the matrices are to be loaded
Output:
bdf: the BDF header structure
Adapted the bdf_read.m m... | Read header data from bdf/bhf file (Bessy Data Format v1)
Input:
filename: the name of the file
load_data: if the matrices are to be loaded
Output:
bdf: the BDF header structure
Adapted the bdf_read.m macro from Sylvio Haas. | Below is the the instruction that describes the task:
### Input:
Read header data from bdf/bhf file (Bessy Data Format v1)
Input:
filename: the name of the file
load_data: if the matrices are to be loaded
Output:
bdf: the BDF header structure
Adapted the bdf_read.m macro from ... |
def chapters(self, title):
"""
Get a list of chapters for a visual novel. Keep in mind, this can be slow. I've certainly tried to make it as fast as possible, but it's still pulling text out of a webpage.
:param str title: The title of the novel you want chapters from
:return OrderedDic... | Get a list of chapters for a visual novel. Keep in mind, this can be slow. I've certainly tried to make it as fast as possible, but it's still pulling text out of a webpage.
:param str title: The title of the novel you want chapters from
:return OrderedDict: An OrderedDict which contains the chapters f... | Below is the the instruction that describes the task:
### Input:
Get a list of chapters for a visual novel. Keep in mind, this can be slow. I've certainly tried to make it as fast as possible, but it's still pulling text out of a webpage.
:param str title: The title of the novel you want chapters from
... |
def query(self, time_indices):
"""Query the values at given time indices.
Args:
time_indices: 0-based time indices to query, as a `list` of `int`.
Returns:
Values as a list of `numpy.ndarray` (for time indices in memory) or
`None` (for time indices discarded).
"""
if self._dispos... | Query the values at given time indices.
Args:
time_indices: 0-based time indices to query, as a `list` of `int`.
Returns:
Values as a list of `numpy.ndarray` (for time indices in memory) or
`None` (for time indices discarded). | Below is the the instruction that describes the task:
### Input:
Query the values at given time indices.
Args:
time_indices: 0-based time indices to query, as a `list` of `int`.
Returns:
Values as a list of `numpy.ndarray` (for time indices in memory) or
`None` (for time indices discarde... |
def convert_regex_to_flask_path(url_path):
"""
Converts a regex matching url to one that can be used with flask
"""
for token in ["$"]:
url_path = url_path.replace(token, "")
def caller(reg):
match_name, match_pattern = reg.groups()
return '<regex("{0}"):{1}>'.format(match_p... | Converts a regex matching url to one that can be used with flask | Below is the the instruction that describes the task:
### Input:
Converts a regex matching url to one that can be used with flask
### Response:
def convert_regex_to_flask_path(url_path):
"""
Converts a regex matching url to one that can be used with flask
"""
for token in ["$"]:
url_path = ... |
def connect(self):
"""Connect to LASAF through a CAM-socket."""
self.socket = socket.socket()
self.socket.connect((self.host, self.port))
self.socket.settimeout(False) # non-blocking
sleep(self.delay) # wait for response
self.welcome_msg = self.socket.recv(
... | Connect to LASAF through a CAM-socket. | Below is the the instruction that describes the task:
### Input:
Connect to LASAF through a CAM-socket.
### Response:
def connect(self):
"""Connect to LASAF through a CAM-socket."""
self.socket = socket.socket()
self.socket.connect((self.host, self.port))
self.socket.settimeout(Fals... |
def _shannon_radii_from_cn(species_list, cn_roman, radius_to_compare=0):
"""
Utility func to get Shannon radii for a particular coordination number.
As the Shannon radii depends on charge state and coordination number,
species without an entry for a particular coordination number will
be skipped.
... | Utility func to get Shannon radii for a particular coordination number.
As the Shannon radii depends on charge state and coordination number,
species without an entry for a particular coordination number will
be skipped.
Args:
species_list (list): A list of Species to get the Shannon radii for... | Below is the the instruction that describes the task:
### Input:
Utility func to get Shannon radii for a particular coordination number.
As the Shannon radii depends on charge state and coordination number,
species without an entry for a particular coordination number will
be skipped.
Args:
... |
def _addSpecfile(self, specfile, path):
"""Adds a new specfile entry to MsrunContainer.info. See also
:class:`MsrunContainer.addSpecfile()`.
:param specfile: the name of an ms-run file
:param path: filedirectory used for loading and saving ``mrc`` files
"""
datatypeStatu... | Adds a new specfile entry to MsrunContainer.info. See also
:class:`MsrunContainer.addSpecfile()`.
:param specfile: the name of an ms-run file
:param path: filedirectory used for loading and saving ``mrc`` files | Below is the the instruction that describes the task:
### Input:
Adds a new specfile entry to MsrunContainer.info. See also
:class:`MsrunContainer.addSpecfile()`.
:param specfile: the name of an ms-run file
:param path: filedirectory used for loading and saving ``mrc`` files
### Response:
... |
def _set_widget_background_color(widget, color):
"""
Changes the base color of a widget (background).
:param widget: widget to modify
:param color: the color to apply
"""
pal = widget.palette()
pal.setColor(pal.Base, color)
widget.setPalette(pal) | Changes the base color of a widget (background).
:param widget: widget to modify
:param color: the color to apply | Below is the the instruction that describes the task:
### Input:
Changes the base color of a widget (background).
:param widget: widget to modify
:param color: the color to apply
### Response:
def _set_widget_background_color(widget, color):
"""
Changes the base color of a widget (b... |
def bgp_normalize_table_data(bgp_table):
"""The 'show bgp all summary vrf all' table can have entries that wrap multiple lines.
2001:db8:4:701::2
4 65535 163664 163693 145 0 0 3w2d 3
2001:db8:e0:dd::1
4 10 327491 327278 145 0 0 3w1d 4
... | The 'show bgp all summary vrf all' table can have entries that wrap multiple lines.
2001:db8:4:701::2
4 65535 163664 163693 145 0 0 3w2d 3
2001:db8:e0:dd::1
4 10 327491 327278 145 0 0 3w1d 4
Normalize this so the line wrap doesn't exit. | Below is the the instruction that describes the task:
### Input:
The 'show bgp all summary vrf all' table can have entries that wrap multiple lines.
2001:db8:4:701::2
4 65535 163664 163693 145 0 0 3w2d 3
2001:db8:e0:dd::1
4 10 327491 327278 145 ... |
def check(self, window_name, object_name):
"""
Check item.
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to look for, either full name,
LDTP's name ... | Check item.
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type object_name: string
... | Below is the the instruction that describes the task:
### Input:
Check item.
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to look for, either full name,
LDTP's... |
def walk_propagation_tree(logger):
"""
Walk through the propagation hierarchy of the given logger.
:param logger: The logger whose hierarchy to walk (a
:class:`~logging.Logger` object).
:returns: A generator of :class:`~logging.Logger` objects.
.. note:: This uses the undocument... | Walk through the propagation hierarchy of the given logger.
:param logger: The logger whose hierarchy to walk (a
:class:`~logging.Logger` object).
:returns: A generator of :class:`~logging.Logger` objects.
.. note:: This uses the undocumented :class:`logging.Logger.parent`
... | Below is the the instruction that describes the task:
### Input:
Walk through the propagation hierarchy of the given logger.
:param logger: The logger whose hierarchy to walk (a
:class:`~logging.Logger` object).
:returns: A generator of :class:`~logging.Logger` objects.
.. note:: Th... |
def update_ar_listing_catalog(portal):
"""Add Indexes/Metadata to bika_catalog_analysisrequest_listing
"""
cat_id = CATALOG_ANALYSIS_REQUEST_LISTING
catalog = api.get_tool(cat_id)
logger.info("Updating Indexes/Metadata of Catalog '{}'".format(cat_id))
indexes_to_add = [
# name, attrib... | Add Indexes/Metadata to bika_catalog_analysisrequest_listing | Below is the the instruction that describes the task:
### Input:
Add Indexes/Metadata to bika_catalog_analysisrequest_listing
### Response:
def update_ar_listing_catalog(portal):
"""Add Indexes/Metadata to bika_catalog_analysisrequest_listing
"""
cat_id = CATALOG_ANALYSIS_REQUEST_LISTING
catalog =... |
def iter_random_chars(bits,
keyspace=string.ascii_letters + string.digits + '#/.',
rng=None):
""" Yields a cryptographically secure random key of desired @bits of
entropy within @keyspace using :class:random.SystemRandom
@bits: (#int) minimum bits of entr... | Yields a cryptographically secure random key of desired @bits of
entropy within @keyspace using :class:random.SystemRandom
@bits: (#int) minimum bits of entropy
@keyspace: (#str) or iterable allowed output chars
..
from vital.security import iter_rand
for char ... | Below is the the instruction that describes the task:
### Input:
Yields a cryptographically secure random key of desired @bits of
entropy within @keyspace using :class:random.SystemRandom
@bits: (#int) minimum bits of entropy
@keyspace: (#str) or iterable allowed output chars
..
... |
def remove_bond(self, particle_pair):
"""Deletes a bond between a pair of Particles
Parameters
----------
particle_pair : indexable object, length=2, dtype=mb.Compound
The pair of Particles to remove the bond between
"""
from mbuild.port import Port
... | Deletes a bond between a pair of Particles
Parameters
----------
particle_pair : indexable object, length=2, dtype=mb.Compound
The pair of Particles to remove the bond between | Below is the the instruction that describes the task:
### Input:
Deletes a bond between a pair of Particles
Parameters
----------
particle_pair : indexable object, length=2, dtype=mb.Compound
The pair of Particles to remove the bond between
### Response:
def remove_bond(self, p... |
def _needs_new_cc_config_for_update(old_template, old_version, new_template, new_version):
"""
Given two templates and their respective versions, return True if a new cookiecutter
config needs to be obtained from the user
"""
if old_template != new_template:
return True
else:
ret... | Given two templates and their respective versions, return True if a new cookiecutter
config needs to be obtained from the user | Below is the the instruction that describes the task:
### Input:
Given two templates and their respective versions, return True if a new cookiecutter
config needs to be obtained from the user
### Response:
def _needs_new_cc_config_for_update(old_template, old_version, new_template, new_version):
"""
Gi... |
def _initialize_client_from_environment():
''' Initialize a KeenClient instance using environment variables. '''
global _client, project_id, write_key, read_key, master_key, base_url
if _client is None:
# check environment for project ID and keys
project_id = project_id or os.environ.get("K... | Initialize a KeenClient instance using environment variables. | Below is the the instruction that describes the task:
### Input:
Initialize a KeenClient instance using environment variables.
### Response:
def _initialize_client_from_environment():
''' Initialize a KeenClient instance using environment variables. '''
global _client, project_id, write_key, read_key, mast... |
def _convert_to_config(self):
"""self.parsed_data->self.config"""
for k, v in vars(self.parsed_data).iteritems():
exec "self.config.%s = v"%k in locals(), globals() | self.parsed_data->self.config | Below is the the instruction that describes the task:
### Input:
self.parsed_data->self.config
### Response:
def _convert_to_config(self):
"""self.parsed_data->self.config"""
for k, v in vars(self.parsed_data).iteritems():
exec "self.config.%s = v"%k in locals(), globals() |
def validatePrepare(self, prepare: Prepare, sender: str) -> bool:
"""
Return whether the PREPARE specified is valid.
:param prepare: the PREPARE to validate
:param sender: the name of the node that sent the PREPARE
:return: True if PREPARE is valid, False otherwise
"""
... | Return whether the PREPARE specified is valid.
:param prepare: the PREPARE to validate
:param sender: the name of the node that sent the PREPARE
:return: True if PREPARE is valid, False otherwise | Below is the the instruction that describes the task:
### Input:
Return whether the PREPARE specified is valid.
:param prepare: the PREPARE to validate
:param sender: the name of the node that sent the PREPARE
:return: True if PREPARE is valid, False otherwise
### Response:
def validatePre... |
def send_file(self, url, name, **fileinfo):
"""Send a pre-uploaded file to the room.
See http://matrix.org/docs/spec/r0.2.0/client_server.html#m-file for
fileinfo.
Args:
url (str): The mxc url of the file.
name (str): The filename of the image.
filei... | Send a pre-uploaded file to the room.
See http://matrix.org/docs/spec/r0.2.0/client_server.html#m-file for
fileinfo.
Args:
url (str): The mxc url of the file.
name (str): The filename of the image.
fileinfo (): Extra information about the file | Below is the the instruction that describes the task:
### Input:
Send a pre-uploaded file to the room.
See http://matrix.org/docs/spec/r0.2.0/client_server.html#m-file for
fileinfo.
Args:
url (str): The mxc url of the file.
name (str): The filename of the image.
... |
def transaction(self, tx_hash):
"""The transaction details endpoint provides information on a single
transaction.
`GET /transactions/{hash}
<https://www.stellar.org/developers/horizon/reference/endpoints/transactions-single.html>`_
:param str tx_hash: The hex-encoded transactio... | The transaction details endpoint provides information on a single
transaction.
`GET /transactions/{hash}
<https://www.stellar.org/developers/horizon/reference/endpoints/transactions-single.html>`_
:param str tx_hash: The hex-encoded transaction hash.
:return: A single transacti... | Below is the the instruction that describes the task:
### Input:
The transaction details endpoint provides information on a single
transaction.
`GET /transactions/{hash}
<https://www.stellar.org/developers/horizon/reference/endpoints/transactions-single.html>`_
:param str tx_hash: ... |
def make_configure_tab(self):
""" initial set up of configure tab"""
# Setup the choice between single and multicolor
modeframe = tk.Frame(self.tab_configure)
self.mode = tk.IntVar()
singlecolor = tk.Radiobutton(modeframe, text="Single color", variable=self.mode,
... | initial set up of configure tab | Below is the the instruction that describes the task:
### Input:
initial set up of configure tab
### Response:
def make_configure_tab(self):
""" initial set up of configure tab"""
# Setup the choice between single and multicolor
modeframe = tk.Frame(self.tab_configure)
self.mode = t... |
def _create_xml_node(cls):
"""Create XML node from "_xml_map".
"""
try:
xml_map = cls._xml_map
except AttributeError:
raise ValueError("This model has no XML definition")
return _create_xml_node(
xml_map.get('name', cls.__name__),
... | Create XML node from "_xml_map". | Below is the the instruction that describes the task:
### Input:
Create XML node from "_xml_map".
### Response:
def _create_xml_node(cls):
"""Create XML node from "_xml_map".
"""
try:
xml_map = cls._xml_map
except AttributeError:
raise ValueError("This model ... |
def remove(self, cb):
"""Removes a callback."""
if cb in self.callbacks:
self.callbacks.remove(cb)
new_monitor = 0
for c in self.callbacks:
new_monitor |= c.bit
if new_monitor != self.monitor:
self.monitor = new_monitor
... | Removes a callback. | Below is the the instruction that describes the task:
### Input:
Removes a callback.
### Response:
def remove(self, cb):
"""Removes a callback."""
if cb in self.callbacks:
self.callbacks.remove(cb)
new_monitor = 0
for c in self.callbacks:
new_moni... |
def create_gzip_cache(pelican):
'''Create a gzip cache file for every file that a webserver would
reasonably want to cache (e.g., text type files).
:param pelican: The Pelican instance
'''
for dirpath, _, filenames in os.walk(pelican.settings['OUTPUT_PATH']):
for name in filenames:
... | Create a gzip cache file for every file that a webserver would
reasonably want to cache (e.g., text type files).
:param pelican: The Pelican instance | Below is the the instruction that describes the task:
### Input:
Create a gzip cache file for every file that a webserver would
reasonably want to cache (e.g., text type files).
:param pelican: The Pelican instance
### Response:
def create_gzip_cache(pelican):
'''Create a gzip cache file for every fil... |
def setVerbosity(self, verbose):
"""
Set verbosity of the SenseApi object.
@param verbose (boolean) - True of False
@return (boolean) - Boolean indicating whether setVerbosity succeeded
"""
if not (verbose == True or verbose =... | Set verbosity of the SenseApi object.
@param verbose (boolean) - True of False
@return (boolean) - Boolean indicating whether setVerbosity succeeded | Below is the the instruction that describes the task:
### Input:
Set verbosity of the SenseApi object.
@param verbose (boolean) - True of False
@return (boolean) - Boolean indicating whether setVerbosity succeeded
### Response:
def setVerbosity(self, verbose):
... |
def remove_pattern(self, pattern):
"""
Removes given pattern from the Model.
:param pattern: Pattern.
:type pattern: unicode
:return: Method success.
:rtype: bool
"""
for index, node in enumerate(self.root_node.children):
if node.name != patt... | Removes given pattern from the Model.
:param pattern: Pattern.
:type pattern: unicode
:return: Method success.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Removes given pattern from the Model.
:param pattern: Pattern.
:type pattern: unicode
:return: Method success.
:rtype: bool
### Response:
def remove_pattern(self, pattern):
"""
Removes given pattern fr... |
def get_gsod_filenames(self, year=None, with_host=False):
""" Get filenames of raw GSOD station data. """
return get_gsod_filenames(self.usaf_id, year, with_host=with_host) | Get filenames of raw GSOD station data. | Below is the the instruction that describes the task:
### Input:
Get filenames of raw GSOD station data.
### Response:
def get_gsod_filenames(self, year=None, with_host=False):
""" Get filenames of raw GSOD station data. """
return get_gsod_filenames(self.usaf_id, year, with_host=with_host) |
def logCdfNormal(z):
"""
Robust implementations of log cdf of a standard normal.
@see [[https://github.com/mseeger/apbsint/blob/master/src/eptools/potentials/SpecfunServices.h original implementation]]
in C from Matthias Seeger.
"""
if (abs(z) < ERF_CODY_LIMIT1):
# Phi(z) approx (1+y... | Robust implementations of log cdf of a standard normal.
@see [[https://github.com/mseeger/apbsint/blob/master/src/eptools/potentials/SpecfunServices.h original implementation]]
in C from Matthias Seeger. | Below is the the instruction that describes the task:
### Input:
Robust implementations of log cdf of a standard normal.
@see [[https://github.com/mseeger/apbsint/blob/master/src/eptools/potentials/SpecfunServices.h original implementation]]
in C from Matthias Seeger.
### Response:
def logCdfNormal(z):
... |
def hybridize(self, active=True, **kwargs):
"""Activates or deactivates `HybridBlock` s recursively. Has no effect on
non-hybrid children.
Parameters
----------
active : bool, default True
Whether to turn hybrid on or off.
**kwargs : string
Additi... | Activates or deactivates `HybridBlock` s recursively. Has no effect on
non-hybrid children.
Parameters
----------
active : bool, default True
Whether to turn hybrid on or off.
**kwargs : string
Additional flags for hybridized operator. | Below is the the instruction that describes the task:
### Input:
Activates or deactivates `HybridBlock` s recursively. Has no effect on
non-hybrid children.
Parameters
----------
active : bool, default True
Whether to turn hybrid on or off.
**kwargs : string
... |
def geom_reflect(g, nv):
""" Reflection symmetry operation.
nv is normal vector to reflection plane
g is assumed already translated to center of mass @ origin
.. todo:: Complete geom_reflect docstring
"""
# Imports
import numpy as np
# Force g to n-vector
g = make_nd_vec(g, nd=N... | Reflection symmetry operation.
nv is normal vector to reflection plane
g is assumed already translated to center of mass @ origin
.. todo:: Complete geom_reflect docstring | Below is the the instruction that describes the task:
### Input:
Reflection symmetry operation.
nv is normal vector to reflection plane
g is assumed already translated to center of mass @ origin
.. todo:: Complete geom_reflect docstring
### Response:
def geom_reflect(g, nv):
""" Reflection symmet... |
def QA_fetch_get_hkstock_list(ip=None, port=None):
"""[summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
# 港股 HKMARKET
27 5 香港指数 FH
31 2 香港主板 KH
48 2... | [summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
# 港股 HKMARKET
27 5 香港指数 FH
31 2 香港主板 KH
48 2 香港创业板 KG
49 2 香港基金 ... | Below is the the instruction that describes the task:
### Input:
[summary]
Keyword Arguments:
ip {[type]} -- [description] (default: {None})
port {[type]} -- [description] (default: {None})
# 港股 HKMARKET
27 5 香港指数 FH
31 2 香港主板 KH
4... |
def pop_events(self, regex_pattern, timeout):
"""Pop events whose names match a regex pattern.
If such event(s) exist, pop one event from each event queue that
satisfies the condition. Otherwise, wait for an event that satisfies
the condition to occur, with timeout.
Results are... | Pop events whose names match a regex pattern.
If such event(s) exist, pop one event from each event queue that
satisfies the condition. Otherwise, wait for an event that satisfies
the condition to occur, with timeout.
Results are sorted by timestamp in ascending order.
Args:
... | Below is the the instruction that describes the task:
### Input:
Pop events whose names match a regex pattern.
If such event(s) exist, pop one event from each event queue that
satisfies the condition. Otherwise, wait for an event that satisfies
the condition to occur, with timeout.
... |
def _handleModemNotification(self, lines):
""" Handler for unsolicited notifications from the modem
This method simply spawns a separate thread to handle the actual notification
(in order to release the read thread so that the handlers are able to write back to the modem, etc)
... | Handler for unsolicited notifications from the modem
This method simply spawns a separate thread to handle the actual notification
(in order to release the read thread so that the handlers are able to write back to the modem, etc)
:param lines The lines that were read | Below is the the instruction that describes the task:
### Input:
Handler for unsolicited notifications from the modem
This method simply spawns a separate thread to handle the actual notification
(in order to release the read thread so that the handlers are able to write back to the modem, ... |
def copy_with_new_atts(self, **attributes):
"""Returns a new FmtStr with the same content but new formatting"""
return FmtStr(*[Chunk(bfs.s, bfs.atts.extend(attributes))
for bfs in self.chunks]) | Returns a new FmtStr with the same content but new formatting | Below is the the instruction that describes the task:
### Input:
Returns a new FmtStr with the same content but new formatting
### Response:
def copy_with_new_atts(self, **attributes):
"""Returns a new FmtStr with the same content but new formatting"""
return FmtStr(*[Chunk(bfs.s, bfs.atts.extend(a... |
def generate_folds(node_label_matrix, labelled_node_indices, number_of_categories, percentage, number_of_folds=10):
"""
Form the seed nodes for training and testing.
Inputs: - node_label_matrix: The node-label ground truth in a SciPy sparse matrix format.
- labelled_node_indices: A NumPy arra... | Form the seed nodes for training and testing.
Inputs: - node_label_matrix: The node-label ground truth in a SciPy sparse matrix format.
- labelled_node_indices: A NumPy array containing the labelled node indices.
- number_of_categories: The number of categories/classes in the learning.
... | Below is the the instruction that describes the task:
### Input:
Form the seed nodes for training and testing.
Inputs: - node_label_matrix: The node-label ground truth in a SciPy sparse matrix format.
- labelled_node_indices: A NumPy array containing the labelled node indices.
- numb... |
def register_success(self, nick, message, channel, cmd_channel):
"""\
Received registration acknowledgement from the BotnetBot, as well as the
name of the command channel, so join up and indicate that registration
succeeded
"""
# the boss will tell what channel to join
... | \
Received registration acknowledgement from the BotnetBot, as well as the
name of the command channel, so join up and indicate that registration
succeeded | Below is the the instruction that describes the task:
### Input:
\
Received registration acknowledgement from the BotnetBot, as well as the
name of the command channel, so join up and indicate that registration
succeeded
### Response:
def register_success(self, nick, message, channel, cmd_c... |
def delete_policy(name, policy_name, region=None, key=None, keyid=None,
profile=None):
'''
Delete an ELB policy.
.. versionadded:: 2016.3.0
CLI example:
.. code-block:: bash
salt myminion boto_elb.delete_policy myelb mypolicy
'''
conn = _get_conn(region=region, ... | Delete an ELB policy.
.. versionadded:: 2016.3.0
CLI example:
.. code-block:: bash
salt myminion boto_elb.delete_policy myelb mypolicy | Below is the the instruction that describes the task:
### Input:
Delete an ELB policy.
.. versionadded:: 2016.3.0
CLI example:
.. code-block:: bash
salt myminion boto_elb.delete_policy myelb mypolicy
### Response:
def delete_policy(name, policy_name, region=None, key=None, keyid=None,
... |
def init_environment(self):
"""Configure the user's environment.
"""
env = os.environ
# These two ensure 'ls' produces nice coloring on BSD-derived systems
env['TERM'] = 'xterm-color'
env['CLICOLOR'] = '1'
# Since normal pagers don't work at all (over pexpect we ... | Configure the user's environment. | Below is the the instruction that describes the task:
### Input:
Configure the user's environment.
### Response:
def init_environment(self):
"""Configure the user's environment.
"""
env = os.environ
# These two ensure 'ls' produces nice coloring on BSD-derived systems
env['... |
def add_noise(weights, other_weights):
'''add noise to the layer.
'''
w_range = np.ptp(other_weights.flatten())
noise_range = NOISE_RATIO * w_range
noise = np.random.uniform(-noise_range / 2.0, noise_range / 2.0, weights.shape)
return np.add(noise, weights) | add noise to the layer. | Below is the the instruction that describes the task:
### Input:
add noise to the layer.
### Response:
def add_noise(weights, other_weights):
'''add noise to the layer.
'''
w_range = np.ptp(other_weights.flatten())
noise_range = NOISE_RATIO * w_range
noise = np.random.uniform(-noise_range / 2.0... |
def _is_extra_source(asset, field, map):
"""
Internal method that determines if this asset/field combination
represents a fetcher value or a regular OHLCVP lookup.
"""
# If we have an extra source with a column called "price", only look
# at it if it's on something like p... | Internal method that determines if this asset/field combination
represents a fetcher value or a regular OHLCVP lookup. | Below is the the instruction that describes the task:
### Input:
Internal method that determines if this asset/field combination
represents a fetcher value or a regular OHLCVP lookup.
### Response:
def _is_extra_source(asset, field, map):
"""
Internal method that determines if this asset/fi... |
def generate_keypair(keypair_file):
'''generate_keypair is used by some of the helpers that need a keypair.
The function should be used if the client doesn't have the attribute
self.key. We generate the key and return it.
We use pycryptodome (3.7.2)
Parameters
=========
... | generate_keypair is used by some of the helpers that need a keypair.
The function should be used if the client doesn't have the attribute
self.key. We generate the key and return it.
We use pycryptodome (3.7.2)
Parameters
=========
keypair_file: fullpath to where to s... | Below is the the instruction that describes the task:
### Input:
generate_keypair is used by some of the helpers that need a keypair.
The function should be used if the client doesn't have the attribute
self.key. We generate the key and return it.
We use pycryptodome (3.7.2)
Pa... |
def _convert_to_storage_entity_with_encryption_metadata(
self, options, store_raw_metadata, sa, entity, vio, is_file,
container, dir, file_snapshot):
# type: (SourcePath, StorageCredentials, any, bool, StorageAccount,
# any, blobxfer.models.metadata.VectoredStripe, bool, s... | Convert entity into StorageEntity with encryption metadata if avail
:param SourcePath self: this
:param StorageCredentials creds: storage creds
:param object options: download or synccopy options
:param bool store_raw_metadata: store raw metadata
:param StorageAccount sa: storage... | Below is the the instruction that describes the task:
### Input:
Convert entity into StorageEntity with encryption metadata if avail
:param SourcePath self: this
:param StorageCredentials creds: storage creds
:param object options: download or synccopy options
:param bool store_raw_m... |
def map_alleles(self, mapping, copy=True):
"""Transform alleles via a mapping.
Parameters
----------
mapping : ndarray, int8, shape (n_variants, max_allele)
An array defining the allele mapping for each variant.
copy : bool, optional
If True, return a new... | Transform alleles via a mapping.
Parameters
----------
mapping : ndarray, int8, shape (n_variants, max_allele)
An array defining the allele mapping for each variant.
copy : bool, optional
If True, return a new array; if False, apply mapping in place
(... | Below is the the instruction that describes the task:
### Input:
Transform alleles via a mapping.
Parameters
----------
mapping : ndarray, int8, shape (n_variants, max_allele)
An array defining the allele mapping for each variant.
copy : bool, optional
If Tru... |
def send(self, ws, seq):
"""
Sends heartbeat message to Discord
Attributes:
ws: Websocket connection to discord
seq: Sequence number of heartbeat
"""
payload = {'op': 1, 'd': seq}
payload = json.dumps(payload)
logger.debug("Sending heartb... | Sends heartbeat message to Discord
Attributes:
ws: Websocket connection to discord
seq: Sequence number of heartbeat | Below is the the instruction that describes the task:
### Input:
Sends heartbeat message to Discord
Attributes:
ws: Websocket connection to discord
seq: Sequence number of heartbeat
### Response:
def send(self, ws, seq):
"""
Sends heartbeat message to Discord
... |
def _main():
""" Command line interface for testing.
"""
import pprint
import tempfile
try:
image = sys.argv[1]
except IndexError:
print("Usage: python -m pyrobase.webservice.imgur <url>")
else:
try:
pprint.pprint(copy_image_from_url(image, cache_dir=temp... | Command line interface for testing. | Below is the the instruction that describes the task:
### Input:
Command line interface for testing.
### Response:
def _main():
""" Command line interface for testing.
"""
import pprint
import tempfile
try:
image = sys.argv[1]
except IndexError:
print("Usage: python -m pyro... |
def _add_trace_frame(self, graph: TraceGraph, trace_frame: TraceFrame) -> None:
""" Copies the trace frame from 'graph' to this (self) graph.
Also copies all the trace_frame-leaf assocs since we don't
know which ones are needed until we know the issue that reaches it
"""
trace_fr... | Copies the trace frame from 'graph' to this (self) graph.
Also copies all the trace_frame-leaf assocs since we don't
know which ones are needed until we know the issue that reaches it | Below is the the instruction that describes the task:
### Input:
Copies the trace frame from 'graph' to this (self) graph.
Also copies all the trace_frame-leaf assocs since we don't
know which ones are needed until we know the issue that reaches it
### Response:
def _add_trace_frame(self, graph: Tr... |
def set_brightness(self, brightness):
"""Set brightness of entire display to specified value (16 levels, from
0 to 15).
"""
if brightness < 0 or brightness > 15:
raise ValueError('Brightness must be a value of 0 to 15.')
self._device.writeList(HT16K33_CMD_BRIGHTNESS |... | Set brightness of entire display to specified value (16 levels, from
0 to 15). | Below is the the instruction that describes the task:
### Input:
Set brightness of entire display to specified value (16 levels, from
0 to 15).
### Response:
def set_brightness(self, brightness):
"""Set brightness of entire display to specified value (16 levels, from
0 to 15).
"""
... |
def assertTimeZoneNotEqual(self, dt, tz, msg=None):
'''Fail if ``dt``'s ``tzinfo`` attribute equals ``tz`` as
determined by the '!=' operator.
Parameters
----------
dt : datetime
tz : timezone
msg : str
If not provided, the :mod:`marbles.mixins` or
... | Fail if ``dt``'s ``tzinfo`` attribute equals ``tz`` as
determined by the '!=' operator.
Parameters
----------
dt : datetime
tz : timezone
msg : str
If not provided, the :mod:`marbles.mixins` or
:mod:`unittest` standard message will be used.
... | Below is the the instruction that describes the task:
### Input:
Fail if ``dt``'s ``tzinfo`` attribute equals ``tz`` as
determined by the '!=' operator.
Parameters
----------
dt : datetime
tz : timezone
msg : str
If not provided, the :mod:`marbles.mixins`... |
def filter(self, **kwargs):
'''
Only columns/attributes that have been specified as having an index with
the ``index=True`` option on the column definition can be filtered with
this method. Prefix, suffix, and pattern match filters must be provided
using the ``.startswith()``, ``... | Only columns/attributes that have been specified as having an index with
the ``index=True`` option on the column definition can be filtered with
this method. Prefix, suffix, and pattern match filters must be provided
using the ``.startswith()``, ``.endswith()``, and the ``.like()``
metho... | Below is the the instruction that describes the task:
### Input:
Only columns/attributes that have been specified as having an index with
the ``index=True`` option on the column definition can be filtered with
this method. Prefix, suffix, and pattern match filters must be provided
using the ... |
def get_substructure_mapping(self, other, limit=1):
"""
get self to other substructure mapping
:param limit: number of matches. if 0 return iterator for all possible; if 1 return dict or None;
if > 1 return list of dicts
"""
i = self._matcher(other).subgraph_isomorph... | get self to other substructure mapping
:param limit: number of matches. if 0 return iterator for all possible; if 1 return dict or None;
if > 1 return list of dicts | Below is the the instruction that describes the task:
### Input:
get self to other substructure mapping
:param limit: number of matches. if 0 return iterator for all possible; if 1 return dict or None;
if > 1 return list of dicts
### Response:
def get_substructure_mapping(self, other, limit=1)... |
def start_thread(self, lpStartAddress, lpParameter=0, bSuspended = False):
"""
Remotely creates a new thread in the process.
@type lpStartAddress: int
@param lpStartAddress: Start address for the new thread.
@type lpParameter: int
@param lpParameter: Optional argumen... | Remotely creates a new thread in the process.
@type lpStartAddress: int
@param lpStartAddress: Start address for the new thread.
@type lpParameter: int
@param lpParameter: Optional argument for the new thread.
@type bSuspended: bool
@param bSuspended: C{True} if the... | Below is the the instruction that describes the task:
### Input:
Remotely creates a new thread in the process.
@type lpStartAddress: int
@param lpStartAddress: Start address for the new thread.
@type lpParameter: int
@param lpParameter: Optional argument for the new thread.
... |
def retain_all(self, items):
"""
Removes the items which are not contained in the specified collection. In other words, only the items that
are contained in the specified collection will be retained.
:param items: (Collection), collection which includes the elements to be retained in th... | Removes the items which are not contained in the specified collection. In other words, only the items that
are contained in the specified collection will be retained.
:param items: (Collection), collection which includes the elements to be retained in this set.
:return: (bool), ``true`` if this... | Below is the the instruction that describes the task:
### Input:
Removes the items which are not contained in the specified collection. In other words, only the items that
are contained in the specified collection will be retained.
:param items: (Collection), collection which includes the elements ... |
def _run_purecn(paired, work_dir):
"""Run PureCN.R wrapper with pre-segmented CNVkit or GATK4 inputs.
"""
segfns = {"cnvkit": _segment_normalized_cnvkit, "gatk-cnv": _segment_normalized_gatk}
out_base, out, all_files = _get_purecn_files(paired, work_dir)
failed_file = out_base + "-failed.log"
cn... | Run PureCN.R wrapper with pre-segmented CNVkit or GATK4 inputs. | Below is the the instruction that describes the task:
### Input:
Run PureCN.R wrapper with pre-segmented CNVkit or GATK4 inputs.
### Response:
def _run_purecn(paired, work_dir):
"""Run PureCN.R wrapper with pre-segmented CNVkit or GATK4 inputs.
"""
segfns = {"cnvkit": _segment_normalized_cnvkit, "gatk-... |
def start(self):
'''
Starts a server on the port provided in the :class:`Server` constructor
in a separate thread
:rtype: Server
:returns: server instance for chaining
'''
self._handler = _create_handler_class(self._rules, self._always_rules)
self._server... | Starts a server on the port provided in the :class:`Server` constructor
in a separate thread
:rtype: Server
:returns: server instance for chaining | Below is the the instruction that describes the task:
### Input:
Starts a server on the port provided in the :class:`Server` constructor
in a separate thread
:rtype: Server
:returns: server instance for chaining
### Response:
def start(self):
'''
Starts a server on the port... |
def nga_west2_epistemic_adjustment(magnitude, distance):
"""
Applies the "average" adjustment factor for epistemic uncertainty
as defined in Table 17 of Petersen et al., (2014)::
| R < 10. | 10.0 <= R < 30.0 | R >= 30.0
-----------------------------------------------------------... | Applies the "average" adjustment factor for epistemic uncertainty
as defined in Table 17 of Petersen et al., (2014)::
| R < 10. | 10.0 <= R < 30.0 | R >= 30.0
-----------------------------------------------------------
M < 6.0 | 0.37 | 0.22 | 0.22
6... | Below is the the instruction that describes the task:
### Input:
Applies the "average" adjustment factor for epistemic uncertainty
as defined in Table 17 of Petersen et al., (2014)::
| R < 10. | 10.0 <= R < 30.0 | R >= 30.0
-----------------------------------------------------------... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.