code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _zp_decode(self, msg):
"""ZP: Zone partitions."""
zone_partitions = [ord(x)-0x31 for x in msg[4:4+Max.ZONES.value]]
return {'zone_partitions': zone_partitions} | ZP: Zone partitions. | Below is the the instruction that describes the task:
### Input:
ZP: Zone partitions.
### Response:
def _zp_decode(self, msg):
"""ZP: Zone partitions."""
zone_partitions = [ord(x)-0x31 for x in msg[4:4+Max.ZONES.value]]
return {'zone_partitions': zone_partitions} |
def hide(self):
"""Hide the spinner to allow for custom writing to the terminal."""
thr_is_alive = self._spin_thread and self._spin_thread.is_alive()
if thr_is_alive and not self._hide_spin.is_set():
# set the hidden spinner flag
self._hide_spin.set()
# clea... | Hide the spinner to allow for custom writing to the terminal. | Below is the the instruction that describes the task:
### Input:
Hide the spinner to allow for custom writing to the terminal.
### Response:
def hide(self):
"""Hide the spinner to allow for custom writing to the terminal."""
thr_is_alive = self._spin_thread and self._spin_thread.is_alive()
... |
def example_alter_configs(a, args):
""" Alter configs atomically, replacing non-specified
configuration properties with their default values.
"""
resources = []
for restype, resname, configs in zip(args[0::3], args[1::3], args[2::3]):
resource = ConfigResource(restype, resname)
reso... | Alter configs atomically, replacing non-specified
configuration properties with their default values. | Below is the the instruction that describes the task:
### Input:
Alter configs atomically, replacing non-specified
configuration properties with their default values.
### Response:
def example_alter_configs(a, args):
""" Alter configs atomically, replacing non-specified
configuration properties with th... |
def renew_service(request, pk):
"""
renew an existing service
:param request object
:param pk: the primary key of the service to renew
:type pk: int
"""
default_provider.load_services()
service = get_object_or_404(ServicesActivated, pk=pk)
service_name = str(service.n... | renew an existing service
:param request object
:param pk: the primary key of the service to renew
:type pk: int | Below is the the instruction that describes the task:
### Input:
renew an existing service
:param request object
:param pk: the primary key of the service to renew
:type pk: int
### Response:
def renew_service(request, pk):
"""
renew an existing service
:param request ob... |
def export_flow_di_data(params, plane):
"""
Creates a new BPMNEdge XML element for given edge parameters and adds it to 'plane' element.
:param params: dictionary with edge parameters,
:param plane: object of Element class, representing BPMN XML 'BPMNPlane' element (root for edge DI dat... | Creates a new BPMNEdge XML element for given edge parameters and adds it to 'plane' element.
:param params: dictionary with edge parameters,
:param plane: object of Element class, representing BPMN XML 'BPMNPlane' element (root for edge DI data). | Below is the the instruction that describes the task:
### Input:
Creates a new BPMNEdge XML element for given edge parameters and adds it to 'plane' element.
:param params: dictionary with edge parameters,
:param plane: object of Element class, representing BPMN XML 'BPMNPlane' element (root for ed... |
def rank_for_in(self, leaderboard_name, member):
'''
Retrieve the rank for a member in the named leaderboard.
@param leaderboard_name [String] Name of the leaderboard.
@param member [String] Member name.
@return the rank for a member in the leaderboard.
'''
if se... | Retrieve the rank for a member in the named leaderboard.
@param leaderboard_name [String] Name of the leaderboard.
@param member [String] Member name.
@return the rank for a member in the leaderboard. | Below is the the instruction that describes the task:
### Input:
Retrieve the rank for a member in the named leaderboard.
@param leaderboard_name [String] Name of the leaderboard.
@param member [String] Member name.
@return the rank for a member in the leaderboard.
### Response:
def rank_f... |
def geom_symm_match(g, atwts, ax, theta, do_refl):
""" [Revised match factor calculation]
.. todo:: Complete geom_symm_match docstring
"""
# Imports
import numpy as np
from scipy import linalg as spla
# Convert g and atwts to n-D vectors
g = make_nd_vec(g, nd=None, t=np.float64, norm... | [Revised match factor calculation]
.. todo:: Complete geom_symm_match docstring | Below is the the instruction that describes the task:
### Input:
[Revised match factor calculation]
.. todo:: Complete geom_symm_match docstring
### Response:
def geom_symm_match(g, atwts, ax, theta, do_refl):
""" [Revised match factor calculation]
.. todo:: Complete geom_symm_match docstring
""... |
def items(self):
"""
On Python 2.7+:
D.items() -> a set-like object providing a view on D's items
On Python 2.6:
D.items() -> an iterator over D's items
"""
if ver == (2, 7):
return self.viewitems()
elif ver == (2, 6):
retur... | On Python 2.7+:
D.items() -> a set-like object providing a view on D's items
On Python 2.6:
D.items() -> an iterator over D's items | Below is the the instruction that describes the task:
### Input:
On Python 2.7+:
D.items() -> a set-like object providing a view on D's items
On Python 2.6:
D.items() -> an iterator over D's items
### Response:
def items(self):
"""
On Python 2.7+:
D.items... |
def create_screenshot(self, app_id, filename, position=1):
"""Add a screenshot to the web app identified by by ``app_id``.
Screenshots are ordered by ``position``.
:returns: HttpResponse:
* status_code (int) 201 is successful
* content (dict) containing screenshot data
... | Add a screenshot to the web app identified by by ``app_id``.
Screenshots are ordered by ``position``.
:returns: HttpResponse:
* status_code (int) 201 is successful
* content (dict) containing screenshot data | Below is the the instruction that describes the task:
### Input:
Add a screenshot to the web app identified by by ``app_id``.
Screenshots are ordered by ``position``.
:returns: HttpResponse:
* status_code (int) 201 is successful
* content (dict) containing screenshot data
##... |
def subtract_column_median(df, prefix='Intensity '):
"""
Apply column-wise normalisation to expression columns.
Default is median transform to expression columns beginning with Intensity
:param df:
:param prefix: The column prefix for expression columns
:return:
"""
df = df.copy()
... | Apply column-wise normalisation to expression columns.
Default is median transform to expression columns beginning with Intensity
:param df:
:param prefix: The column prefix for expression columns
:return: | Below is the the instruction that describes the task:
### Input:
Apply column-wise normalisation to expression columns.
Default is median transform to expression columns beginning with Intensity
:param df:
:param prefix: The column prefix for expression columns
:return:
### Response:
def subtrac... |
def read_request_from_str(data, **params):
"""
从字符串中读取请求头,并根据格式化字符串模板,进行字符串格式化
:param data:
:param params:
:return:
"""
method, uri = None, None
headers = {}
host = ''
try:
split_list = data.split('\n\n')
headers_text = split_list[0]
body = '\n\n'.join(sp... | 从字符串中读取请求头,并根据格式化字符串模板,进行字符串格式化
:param data:
:param params:
:return: | Below is the the instruction that describes the task:
### Input:
从字符串中读取请求头,并根据格式化字符串模板,进行字符串格式化
:param data:
:param params:
:return:
### Response:
def read_request_from_str(data, **params):
"""
从字符串中读取请求头,并根据格式化字符串模板,进行字符串格式化
:param data:
:param params:
:return:
"""
method,... |
def create_assembly_instance(self, assembly_uri, part_uri, configuration):
'''
Insert a configurable part into an assembly.
Args:
- assembly (dict): eid, wid, and did of the assembly into which will be inserted
- part (dict): eid and did of the configurable part
... | Insert a configurable part into an assembly.
Args:
- assembly (dict): eid, wid, and did of the assembly into which will be inserted
- part (dict): eid and did of the configurable part
- configuration (dict): the configuration
Returns:
- requests.Response... | Below is the the instruction that describes the task:
### Input:
Insert a configurable part into an assembly.
Args:
- assembly (dict): eid, wid, and did of the assembly into which will be inserted
- part (dict): eid and did of the configurable part
- configuration (dict)... |
def md5_string(s):
"""
Shortcut to create md5 hash
:param s:
:return:
"""
m = hashlib.md5()
m.update(s)
return str(m.hexdigest()) | Shortcut to create md5 hash
:param s:
:return: | Below is the the instruction that describes the task:
### Input:
Shortcut to create md5 hash
:param s:
:return:
### Response:
def md5_string(s):
"""
Shortcut to create md5 hash
:param s:
:return:
"""
m = hashlib.md5()
m.update(s)
return str(m.hexdigest()) |
def _process_response(self, resp, out_folder=None):
""" processes the response object"""
CHUNK = 4056
maintype = self._mainType(resp)
contentDisposition = resp.headers.get('content-disposition')
contentEncoding = resp.headers.get('content-encoding')
contentType = resp.hea... | processes the response object | Below is the the instruction that describes the task:
### Input:
processes the response object
### Response:
def _process_response(self, resp, out_folder=None):
""" processes the response object"""
CHUNK = 4056
maintype = self._mainType(resp)
contentDisposition = resp.headers.get('c... |
def sign(self, secret=None):
"""Sign the generated :class:`TransactionEnvelope
<stellar_base.transaction_envelope.TransactionEnvelope>` from the list
of this builder's operations.
:param str secret: The secret seed to use if a key pair or secret was
not provided when this cl... | Sign the generated :class:`TransactionEnvelope
<stellar_base.transaction_envelope.TransactionEnvelope>` from the list
of this builder's operations.
:param str secret: The secret seed to use if a key pair or secret was
not provided when this class was originaly instantiated, or if
... | Below is the the instruction that describes the task:
### Input:
Sign the generated :class:`TransactionEnvelope
<stellar_base.transaction_envelope.TransactionEnvelope>` from the list
of this builder's operations.
:param str secret: The secret seed to use if a key pair or secret was
... |
def api_representation(self):
""" Returns the JSON formatting required by Outlook's API for contacts """
return dict(EmailAddress=dict(Name=self.name, Address=self.email)) | Returns the JSON formatting required by Outlook's API for contacts | Below is the the instruction that describes the task:
### Input:
Returns the JSON formatting required by Outlook's API for contacts
### Response:
def api_representation(self):
""" Returns the JSON formatting required by Outlook's API for contacts """
return dict(EmailAddress=dict(Name=self.name, Ad... |
def draw_mini_map(self, surf):
"""Draw the minimap."""
if (self._render_rgb and self._obs.observation.HasField("render_data") and
self._obs.observation.render_data.HasField("minimap")):
# Draw the rendered version.
surf.blit_np_array(features.Feature.unpack_rgb_image(
self._obs.obs... | Draw the minimap. | Below is the the instruction that describes the task:
### Input:
Draw the minimap.
### Response:
def draw_mini_map(self, surf):
"""Draw the minimap."""
if (self._render_rgb and self._obs.observation.HasField("render_data") and
self._obs.observation.render_data.HasField("minimap")):
# Draw the... |
def warp(self, srid=None, format=None, geom=None):
"""Returns a new RasterQuerySet with possibly warped/converted rasters.
Keyword args:
format -- raster file extension format as str
geom -- geometry for masking or spatial subsetting
srid -- spatial reference identifier as int f... | Returns a new RasterQuerySet with possibly warped/converted rasters.
Keyword args:
format -- raster file extension format as str
geom -- geometry for masking or spatial subsetting
srid -- spatial reference identifier as int for warping to | Below is the the instruction that describes the task:
### Input:
Returns a new RasterQuerySet with possibly warped/converted rasters.
Keyword args:
format -- raster file extension format as str
geom -- geometry for masking or spatial subsetting
srid -- spatial reference identifier a... |
def get_user(user_name=None, region=None, key=None, keyid=None, profile=None):
'''
Get user information.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_iam.get_user myuser
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
... | Get user information.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_iam.get_user myuser | Below is the the instruction that describes the task:
### Input:
Get user information.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_iam.get_user myuser
### Response:
def get_user(user_name=None, region=None, key=None, keyid=None, profile=None):
'''
... |
def add_arguments(self, parser):
"""
Define optional arguments with default values
"""
parser.add_argument('--length', default=self.length,
type=int, help=_('SECRET_KEY length default=%d' % self.length))
parser.add_argument('--alphabet', default=self.... | Define optional arguments with default values | Below is the the instruction that describes the task:
### Input:
Define optional arguments with default values
### Response:
def add_arguments(self, parser):
"""
Define optional arguments with default values
"""
parser.add_argument('--length', default=self.length,
... |
def first_available(self, *quantities):
"""
Return the first available quantity in the input arguments.
Return `None` if none of them is available.
"""
for i, q in enumerate(quantities):
if self.has_quantity(q):
if i:
warnings.warn(... | Return the first available quantity in the input arguments.
Return `None` if none of them is available. | Below is the the instruction that describes the task:
### Input:
Return the first available quantity in the input arguments.
Return `None` if none of them is available.
### Response:
def first_available(self, *quantities):
"""
Return the first available quantity in the input arguments.
... |
def set_driver_simulated(self):
"""Sets the device driver type to simulated"""
self._device_dict["servermain.MULTIPLE_TYPES_DEVICE_DRIVER"] = "Simulator"
if self._is_sixteen_bit:
self._device_dict["servermain.DEVICE_MODEL"] = 0
else:
self._device_dict["servermain.... | Sets the device driver type to simulated | Below is the the instruction that describes the task:
### Input:
Sets the device driver type to simulated
### Response:
def set_driver_simulated(self):
"""Sets the device driver type to simulated"""
self._device_dict["servermain.MULTIPLE_TYPES_DEVICE_DRIVER"] = "Simulator"
if self._is_sixte... |
def select_groups(adata, groups='all', key='louvain'):
"""Get subset of groups in adata.obs[key].
"""
strings_to_categoricals(adata)
if isinstance(groups, list) and isinstance(groups[0], int): groups = [str(n) for n in groups]
categories = adata.obs[key].cat.categories
groups_masks = np.array([c... | Get subset of groups in adata.obs[key]. | Below is the the instruction that describes the task:
### Input:
Get subset of groups in adata.obs[key].
### Response:
def select_groups(adata, groups='all', key='louvain'):
"""Get subset of groups in adata.obs[key].
"""
strings_to_categoricals(adata)
if isinstance(groups, list) and isinstance(grou... |
def get_user_info(self, request):
"""Implement custom getter."""
if not current_user.is_authenticated:
return {}
user_info = {
'id': current_user.get_id(),
}
if 'SENTRY_USER_ATTRS' in current_app.config:
for attr in current_app.config['SENTRY... | Implement custom getter. | Below is the the instruction that describes the task:
### Input:
Implement custom getter.
### Response:
def get_user_info(self, request):
"""Implement custom getter."""
if not current_user.is_authenticated:
return {}
user_info = {
'id': current_user.get_id(),
... |
def read_length_block(fp, fmt='I', padding=1):
"""
Read a block of data with a length marker at the beginning.
:param fp: file-like
:param fmt: format of the length marker
:return: bytes object
"""
length = read_fmt(fmt, fp)[0]
data = fp.read(length)
assert len(data) == length, (len... | Read a block of data with a length marker at the beginning.
:param fp: file-like
:param fmt: format of the length marker
:return: bytes object | Below is the the instruction that describes the task:
### Input:
Read a block of data with a length marker at the beginning.
:param fp: file-like
:param fmt: format of the length marker
:return: bytes object
### Response:
def read_length_block(fp, fmt='I', padding=1):
"""
Read a block of data ... |
def scanStoVars(self, strline):
""" scan input string line, replace sto parameters with calculated results.
"""
for wd in strline.split():
if wd in self.stodict:
strline = strline.replace(wd, str(self.stodict[wd]))
return strline | scan input string line, replace sto parameters with calculated results. | Below is the the instruction that describes the task:
### Input:
scan input string line, replace sto parameters with calculated results.
### Response:
def scanStoVars(self, strline):
""" scan input string line, replace sto parameters with calculated results.
"""
for wd in strline.split():
... |
def Write(self, grr_message):
"""Write the message into the transaction log."""
grr_message = grr_message.SerializeToString()
try:
with io.open(self.logfile, "wb") as fd:
fd.write(grr_message)
except (IOError, OSError):
# Check if we're missing directories and try to create them.
... | Write the message into the transaction log. | Below is the the instruction that describes the task:
### Input:
Write the message into the transaction log.
### Response:
def Write(self, grr_message):
"""Write the message into the transaction log."""
grr_message = grr_message.SerializeToString()
try:
with io.open(self.logfile, "wb") as fd:
... |
def parse_reqtype(self):
"""Return the authentication body."""
if self.job_args['os_auth_version'] == 'v1.0':
return dict()
else:
setup = {
'username': self.job_args.get('os_user')
}
# Check if any prefix items are set. A prefix s... | Return the authentication body. | Below is the the instruction that describes the task:
### Input:
Return the authentication body.
### Response:
def parse_reqtype(self):
"""Return the authentication body."""
if self.job_args['os_auth_version'] == 'v1.0':
return dict()
else:
setup = {
... |
def set_value(self, index, col, value, takeable=False):
"""
Put single value at passed column and index.
.. deprecated:: 0.21.0
Use .at[] or .iat[] accessors instead.
Parameters
----------
index : row label
col : column label
value : scalar
... | Put single value at passed column and index.
.. deprecated:: 0.21.0
Use .at[] or .iat[] accessors instead.
Parameters
----------
index : row label
col : column label
value : scalar
takeable : interpret the index/col as indexers, default False
... | Below is the the instruction that describes the task:
### Input:
Put single value at passed column and index.
.. deprecated:: 0.21.0
Use .at[] or .iat[] accessors instead.
Parameters
----------
index : row label
col : column label
value : scalar
... |
def env(config, endpoint):
"""Print RENKU environment variables.
Run this command to configure your Renku client:
$ eval "$(renku env)"
"""
access_token = config['endpoints'][endpoint]['token']['access_token']
click.echo('export {0}={1}'.format('RENKU_ENDPOINT', endpoint))
click.echo(... | Print RENKU environment variables.
Run this command to configure your Renku client:
$ eval "$(renku env)" | Below is the the instruction that describes the task:
### Input:
Print RENKU environment variables.
Run this command to configure your Renku client:
$ eval "$(renku env)"
### Response:
def env(config, endpoint):
"""Print RENKU environment variables.
Run this command to configure your Renku c... |
def _init_hdrgos(self, hdrgos_dflt, hdrgos_usr=None, add_dflt=True):
"""Initialize GO high"""
# Use default GO group header values
if (hdrgos_usr is None or hdrgos_usr is False) and not self.sections:
return set(hdrgos_dflt)
# Get GO group headers provided by user
hdr... | Initialize GO high | Below is the the instruction that describes the task:
### Input:
Initialize GO high
### Response:
def _init_hdrgos(self, hdrgos_dflt, hdrgos_usr=None, add_dflt=True):
"""Initialize GO high"""
# Use default GO group header values
if (hdrgos_usr is None or hdrgos_usr is False) and not self.se... |
def write_xmlbif(self, filename):
"""
Write the xml data into the file.
Parameters
----------
filename: Name of the file.
Examples
-------
>>> writer = XMLBIFWriter(model)
>>> writer.write_xmlbif(test_file)
"""
with open(filename,... | Write the xml data into the file.
Parameters
----------
filename: Name of the file.
Examples
-------
>>> writer = XMLBIFWriter(model)
>>> writer.write_xmlbif(test_file) | Below is the the instruction that describes the task:
### Input:
Write the xml data into the file.
Parameters
----------
filename: Name of the file.
Examples
-------
>>> writer = XMLBIFWriter(model)
>>> writer.write_xmlbif(test_file)
### Response:
def write... |
def getSolution(self, domains, constraints, vconstraints):
"""
Return one solution for the given problem
@param domains: Dictionary mapping variables to their domains
@type domains: dict
@param constraints: List of pairs of (constraint, variables)
@type constraints: li... | Return one solution for the given problem
@param domains: Dictionary mapping variables to their domains
@type domains: dict
@param constraints: List of pairs of (constraint, variables)
@type constraints: list
@param vconstraints: Dictionary mapping variables to a list of
... | Below is the the instruction that describes the task:
### Input:
Return one solution for the given problem
@param domains: Dictionary mapping variables to their domains
@type domains: dict
@param constraints: List of pairs of (constraint, variables)
@type constraints: list
... |
def _extract_value_from_storage(self, string):
"""Taking a string that was a member of the zset, extract the value and pk
Parameters
----------
string: str
The member extracted from the sorted set
Returns
-------
tuple
Tuple with the valu... | Taking a string that was a member of the zset, extract the value and pk
Parameters
----------
string: str
The member extracted from the sorted set
Returns
-------
tuple
Tuple with the value and the pk, extracted from the string | Below is the the instruction that describes the task:
### Input:
Taking a string that was a member of the zset, extract the value and pk
Parameters
----------
string: str
The member extracted from the sorted set
Returns
-------
tuple
Tuple wi... |
def clean_key_name(key):
"""
Makes ``key`` a valid and appropriate SQL column name:
1. Replaces illegal characters in column names with ``_``
2. Prevents name from beginning with a digit (prepends ``_``)
3. Lowercases name. If you want case-sensitive table
or column names, you are a bad pers... | Makes ``key`` a valid and appropriate SQL column name:
1. Replaces illegal characters in column names with ``_``
2. Prevents name from beginning with a digit (prepends ``_``)
3. Lowercases name. If you want case-sensitive table
or column names, you are a bad person and you should feel bad. | Below is the the instruction that describes the task:
### Input:
Makes ``key`` a valid and appropriate SQL column name:
1. Replaces illegal characters in column names with ``_``
2. Prevents name from beginning with a digit (prepends ``_``)
3. Lowercases name. If you want case-sensitive table
or ... |
def c_struct(self):
"""Get the struct of the module."""
member = '\n'.join(self.c_member_funcs(True))
if self.opts.windll:
return 'struct {{\n{}{} }} {};\n'.format(
self._c_dll_base(), member, self.name
)
return 'typedef\nstruct {2} {{\n{0}\n{1}}}\... | Get the struct of the module. | Below is the the instruction that describes the task:
### Input:
Get the struct of the module.
### Response:
def c_struct(self):
"""Get the struct of the module."""
member = '\n'.join(self.c_member_funcs(True))
if self.opts.windll:
return 'struct {{\n{}{} }} {};\n'.format(
... |
def add_tip_labels_to_axes(self):
"""
Add text offset from tips of tree with correction for orientation,
and fixed_order which is usually used in multitree plotting.
"""
# get tip-coords and replace if using fixed_order
if self.style.orient in ("up", "down"):
... | Add text offset from tips of tree with correction for orientation,
and fixed_order which is usually used in multitree plotting. | Below is the the instruction that describes the task:
### Input:
Add text offset from tips of tree with correction for orientation,
and fixed_order which is usually used in multitree plotting.
### Response:
def add_tip_labels_to_axes(self):
"""
Add text offset from tips of tree with correc... |
def get_progress(self):
"""Get the progress of the queue in percentage (float).
Returns:
float: The 'finished' progress in percentage.
"""
count_remaining = len(self.items_queued) + len(self.items_in_progress)
percentage_remaining = 100 / self.count_total * count_r... | Get the progress of the queue in percentage (float).
Returns:
float: The 'finished' progress in percentage. | Below is the the instruction that describes the task:
### Input:
Get the progress of the queue in percentage (float).
Returns:
float: The 'finished' progress in percentage.
### Response:
def get_progress(self):
"""Get the progress of the queue in percentage (float).
Returns:
... |
def NormalizePath(path, sep="/"):
"""A sane implementation of os.path.normpath.
The standard implementation treats leading / and // as different leading to
incorrect normal forms.
NOTE: Its ok to use a relative path here (without leading /) but any /../ will
still be removed anchoring the path at the top le... | A sane implementation of os.path.normpath.
The standard implementation treats leading / and // as different leading to
incorrect normal forms.
NOTE: Its ok to use a relative path here (without leading /) but any /../ will
still be removed anchoring the path at the top level (e.g. foo/../../../../bar
=> bar)... | Below is the the instruction that describes the task:
### Input:
A sane implementation of os.path.normpath.
The standard implementation treats leading / and // as different leading to
incorrect normal forms.
NOTE: Its ok to use a relative path here (without leading /) but any /../ will
still be removed an... |
def cycles(self):
"""
Fairly expensive cycle detection algorithm. This method
will return the shortest unique cycles that were detected.
Debug usage may look something like:
print("The following cycles were found:")
for cycle in network.cycles():
print(" ... | Fairly expensive cycle detection algorithm. This method
will return the shortest unique cycles that were detected.
Debug usage may look something like:
print("The following cycles were found:")
for cycle in network.cycles():
print(" ", " -> ".join(cycle)) | Below is the the instruction that describes the task:
### Input:
Fairly expensive cycle detection algorithm. This method
will return the shortest unique cycles that were detected.
Debug usage may look something like:
print("The following cycles were found:")
for cycle in network.cy... |
def download_task(url, headers, destination, download_type='layer'):
'''download an image layer (.tar.gz) to a specified download folder.
This task is done by using local versions of the same download functions
that are used for the client.
core stream/download functions of the parent client.
... | download an image layer (.tar.gz) to a specified download folder.
This task is done by using local versions of the same download functions
that are used for the client.
core stream/download functions of the parent client.
Parameters
==========
image_id: the shasum id of the la... | Below is the the instruction that describes the task:
### Input:
download an image layer (.tar.gz) to a specified download folder.
This task is done by using local versions of the same download functions
that are used for the client.
core stream/download functions of the parent client.
... |
def mute_modmail_author(self, _unmute=False):
"""Mute the sender of this modmail message.
:param _unmute: Unmute the user instead. Please use
:meth:`unmute_modmail_author` instead of setting this directly.
"""
path = 'unmute_sender' if _unmute else 'mute_sender'
ret... | Mute the sender of this modmail message.
:param _unmute: Unmute the user instead. Please use
:meth:`unmute_modmail_author` instead of setting this directly. | Below is the the instruction that describes the task:
### Input:
Mute the sender of this modmail message.
:param _unmute: Unmute the user instead. Please use
:meth:`unmute_modmail_author` instead of setting this directly.
### Response:
def mute_modmail_author(self, _unmute=False):
"""M... |
def get_bug_stats(self, startday, endday):
"""Get all intermittent failures per specified date range and repository,
returning a dict of bug_id's with total, repository and platform totals
if totals are greater than or equal to the threshold.
eg:
{
"1206327": {
... | Get all intermittent failures per specified date range and repository,
returning a dict of bug_id's with total, repository and platform totals
if totals are greater than or equal to the threshold.
eg:
{
"1206327": {
"total": 5,
"per_repos... | Below is the the instruction that describes the task:
### Input:
Get all intermittent failures per specified date range and repository,
returning a dict of bug_id's with total, repository and platform totals
if totals are greater than or equal to the threshold.
eg:
{
... |
def exampleRand(S, A):
"""WARNING: This will delete a database with the same name as 'db'."""
db = "MDP-%sx%s.db" % (S, A)
if os.path.exists(db):
os.remove(db)
conn = sqlite3.connect(db)
with conn:
c = conn.cursor()
cmd = '''
CREATE TABLE info (name TEXT, value IN... | WARNING: This will delete a database with the same name as 'db'. | Below is the the instruction that describes the task:
### Input:
WARNING: This will delete a database with the same name as 'db'.
### Response:
def exampleRand(S, A):
"""WARNING: This will delete a database with the same name as 'db'."""
db = "MDP-%sx%s.db" % (S, A)
if os.path.exists(db):
os.re... |
def grow_mask(anat, aseg, ants_segs=None, ww=7, zval=2.0, bw=4):
"""
Grow mask including pixels that have a high likelihood.
GM tissue parameters are sampled in image patches of ``ww`` size.
This is inspired on mindboggle's solution to the problem:
https://github.com/nipy/mindboggle/blob/master/min... | Grow mask including pixels that have a high likelihood.
GM tissue parameters are sampled in image patches of ``ww`` size.
This is inspired on mindboggle's solution to the problem:
https://github.com/nipy/mindboggle/blob/master/mindboggle/guts/segment.py#L1660 | Below is the the instruction that describes the task:
### Input:
Grow mask including pixels that have a high likelihood.
GM tissue parameters are sampled in image patches of ``ww`` size.
This is inspired on mindboggle's solution to the problem:
https://github.com/nipy/mindboggle/blob/master/mindboggle/... |
def check_if_release_is_current(log):
"""Warns the user if their release is behind the latest PyPi __version__."""
if __version__ == '0.0.0':
return
client = xmlrpclib.ServerProxy('https://pypi.python.org/pypi')
latest_pypi_version = client.package_releases('hca')
latest_version_nums = [int... | Warns the user if their release is behind the latest PyPi __version__. | Below is the the instruction that describes the task:
### Input:
Warns the user if their release is behind the latest PyPi __version__.
### Response:
def check_if_release_is_current(log):
"""Warns the user if their release is behind the latest PyPi __version__."""
if __version__ == '0.0.0':
return
... |
def install(*pkgs, **kwargs):
'''
Installs a single or multiple packages via nix
:type pkgs: list(str)
:param pkgs:
packages to update
:param bool attributes:
Pass the list of packages or single package as attribues, not package names.
default: False
:return: Installed ... | Installs a single or multiple packages via nix
:type pkgs: list(str)
:param pkgs:
packages to update
:param bool attributes:
Pass the list of packages or single package as attribues, not package names.
default: False
:return: Installed packages. Example element: ``gcc-3.3.2``
... | Below is the the instruction that describes the task:
### Input:
Installs a single or multiple packages via nix
:type pkgs: list(str)
:param pkgs:
packages to update
:param bool attributes:
Pass the list of packages or single package as attribues, not package names.
default: Fal... |
def random_unitary_matrix(dim, seed=None):
"""Deprecated in 0.8+
"""
warnings.warn('The random_unitary_matrix() function in qiskit.tools.qi has been '
'deprecated and will be removed in the future. Instead use '
'the function in qiskit.quantum_info.random',
... | Deprecated in 0.8+ | Below is the the instruction that describes the task:
### Input:
Deprecated in 0.8+
### Response:
def random_unitary_matrix(dim, seed=None):
"""Deprecated in 0.8+
"""
warnings.warn('The random_unitary_matrix() function in qiskit.tools.qi has been '
'deprecated and will be removed in t... |
def load_csv_data(resource_name):
# type: (str) -> List[str]
""" Loads first column of specified CSV file from package data.
"""
data_bytes = pkgutil.get_data('clkhash', 'data/{}'.format(resource_name))
if data_bytes is None:
raise ValueError("No data resource found with name {}".format(reso... | Loads first column of specified CSV file from package data. | Below is the the instruction that describes the task:
### Input:
Loads first column of specified CSV file from package data.
### Response:
def load_csv_data(resource_name):
# type: (str) -> List[str]
""" Loads first column of specified CSV file from package data.
"""
data_bytes = pkgutil.get_data('... |
def _convert(self, value):
"""Returns a PasswordHash from the given string.
PasswordHash instances or None values will return unchanged.
Strings will be hashed and the resulting PasswordHash returned.
Any other input will result in a TypeError.
"""
if isinstance(value, P... | Returns a PasswordHash from the given string.
PasswordHash instances or None values will return unchanged.
Strings will be hashed and the resulting PasswordHash returned.
Any other input will result in a TypeError. | Below is the the instruction that describes the task:
### Input:
Returns a PasswordHash from the given string.
PasswordHash instances or None values will return unchanged.
Strings will be hashed and the resulting PasswordHash returned.
Any other input will result in a TypeError.
### Respons... |
def generate_sample_json():
"""Generate sample json data for testing"""
check = EpubCheck(samples.EPUB3_VALID)
with open(samples.RESULT_VALID, 'wb') as jsonfile:
jsonfile.write(check._stdout)
check = EpubCheck(samples.EPUB3_INVALID)
with open(samples.RESULT_INVALID, 'wb') as jsonfile:
... | Generate sample json data for testing | Below is the the instruction that describes the task:
### Input:
Generate sample json data for testing
### Response:
def generate_sample_json():
"""Generate sample json data for testing"""
check = EpubCheck(samples.EPUB3_VALID)
with open(samples.RESULT_VALID, 'wb') as jsonfile:
jsonfile.write(... |
def generate_patches(self):
"""
Generates a list of patches for each file underneath
self.root_directory
that satisfy the given conditions given
query conditions, where patches for
each file are suggested by self.suggestor.
"""
start_pos = self.start_posit... | Generates a list of patches for each file underneath
self.root_directory
that satisfy the given conditions given
query conditions, where patches for
each file are suggested by self.suggestor. | Below is the the instruction that describes the task:
### Input:
Generates a list of patches for each file underneath
self.root_directory
that satisfy the given conditions given
query conditions, where patches for
each file are suggested by self.suggestor.
### Response:
def generate... |
def exists(self, index, id, doc_type='_all', params=None):
"""
Returns a boolean indicating whether or not given document exists in
Elasticsearch. `<http://elasticsearch.org/guide/reference/api/get/>`_
:arg index: The name of the index
:arg id: The document ID
:arg doc_t... | Returns a boolean indicating whether or not given document exists in
Elasticsearch. `<http://elasticsearch.org/guide/reference/api/get/>`_
:arg index: The name of the index
:arg id: The document ID
:arg doc_type: The type of the document (uses `_all` by default to
fetch the ... | Below is the the instruction that describes the task:
### Input:
Returns a boolean indicating whether or not given document exists in
Elasticsearch. `<http://elasticsearch.org/guide/reference/api/get/>`_
:arg index: The name of the index
:arg id: The document ID
:arg doc_type: The t... |
def compute_header_hmac_hash(context):
"""Compute HMAC-SHA256 hash of header.
Used to prevent header tampering."""
return hmac.new(
hashlib.sha512(
b'\xff' * 8 +
hashlib.sha512(
context._.header.value.dynamic_header.master_seed.data +
context.... | Compute HMAC-SHA256 hash of header.
Used to prevent header tampering. | Below is the the instruction that describes the task:
### Input:
Compute HMAC-SHA256 hash of header.
Used to prevent header tampering.
### Response:
def compute_header_hmac_hash(context):
"""Compute HMAC-SHA256 hash of header.
Used to prevent header tampering."""
return hmac.new(
hashlib.s... |
def clear(self):
""" Discards all registered handlers and cached results """
with self._hlock:
self.handlers.clear()
with self._mlock:
self.memoize.clear() | Discards all registered handlers and cached results | Below is the the instruction that describes the task:
### Input:
Discards all registered handlers and cached results
### Response:
def clear(self):
""" Discards all registered handlers and cached results """
with self._hlock:
self.handlers.clear()
with self._mlock:
... |
def generateCertificate(self, alias,
commonName, organizationalUnit,
city, state, country,
keyalg="RSA", keysize=1024,
sigalg="SHA256withRSA",
validity=90
... | Use this operation to create a self-signed certificate or as a
starting point for getting a production-ready CA-signed
certificate. The portal will generate a certificate for you and
store it in its keystore. | Below is the the instruction that describes the task:
### Input:
Use this operation to create a self-signed certificate or as a
starting point for getting a production-ready CA-signed
certificate. The portal will generate a certificate for you and
store it in its keystore.
### Response:
def... |
def uniq(args):
"""
%prog uniq fasta uniq.fasta
remove fasta records that are the same
"""
p = OptionParser(uniq.__doc__)
p.add_option("--seq", default=False, action="store_true",
help="Uniqify the sequences [default: %default]")
p.add_option("-t", "--trimname", dest="trimname",... | %prog uniq fasta uniq.fasta
remove fasta records that are the same | Below is the the instruction that describes the task:
### Input:
%prog uniq fasta uniq.fasta
remove fasta records that are the same
### Response:
def uniq(args):
"""
%prog uniq fasta uniq.fasta
remove fasta records that are the same
"""
p = OptionParser(uniq.__doc__)
p.add_option("--s... |
def signature(self, name, file_name, file_type, file_content, owner=None, **kwargs):
"""
Create the Signature TI object.
Args:
owner:
file_content:
file_name:
file_type:
name:
**kwargs:
Return:
"""
... | Create the Signature TI object.
Args:
owner:
file_content:
file_name:
file_type:
name:
**kwargs:
Return: | Below is the the instruction that describes the task:
### Input:
Create the Signature TI object.
Args:
owner:
file_content:
file_name:
file_type:
name:
**kwargs:
Return:
### Response:
def signature(self, name, file_name, file... |
def fix_missing(df, col, name, na_dict):
""" Fill missing data in a column of df with the median, and add a {name}_na column
which specifies if the data was missing.
Parameters:
-----------
df: The data frame that will be changed.
col: The column of data to fix by filling in missing data.
na... | Fill missing data in a column of df with the median, and add a {name}_na column
which specifies if the data was missing.
Parameters:
-----------
df: The data frame that will be changed.
col: The column of data to fix by filling in missing data.
name: The name of the new filled column in df.
... | Below is the the instruction that describes the task:
### Input:
Fill missing data in a column of df with the median, and add a {name}_na column
which specifies if the data was missing.
Parameters:
-----------
df: The data frame that will be changed.
col: The column of data to fix by filling in ... |
def get_email_forwarding(netid):
"""
Return a restclients.models.uwnetid.UwEmailForwarding object
on the given uwnetid
"""
subscriptions = get_netid_subscriptions(netid, Subscription.SUBS_CODE_U_FORWARDING)
for subscription in subscriptions:
if subscription.subscription_code == Subscript... | Return a restclients.models.uwnetid.UwEmailForwarding object
on the given uwnetid | Below is the the instruction that describes the task:
### Input:
Return a restclients.models.uwnetid.UwEmailForwarding object
on the given uwnetid
### Response:
def get_email_forwarding(netid):
"""
Return a restclients.models.uwnetid.UwEmailForwarding object
on the given uwnetid
"""
subscri... |
def _copy_mbox(self, mbox):
"""Copy the contents of a mbox to a temporary file"""
tmp_path = tempfile.mktemp(prefix='perceval_')
with mbox.container as f_in:
with open(tmp_path, mode='wb') as f_out:
for l in f_in:
f_out.write(l)
return tm... | Copy the contents of a mbox to a temporary file | Below is the the instruction that describes the task:
### Input:
Copy the contents of a mbox to a temporary file
### Response:
def _copy_mbox(self, mbox):
"""Copy the contents of a mbox to a temporary file"""
tmp_path = tempfile.mktemp(prefix='perceval_')
with mbox.container as f_in:
... |
def invalid_example_number(region_code):
"""Gets an invalid number for the specified region.
This is useful for unit-testing purposes, where you want to test what
will happen with an invalid number. Note that the number that is
returned will always be able to be parsed and will have the correct
cou... | Gets an invalid number for the specified region.
This is useful for unit-testing purposes, where you want to test what
will happen with an invalid number. Note that the number that is
returned will always be able to be parsed and will have the correct
country code. It may also be a valid *short* number... | Below is the the instruction that describes the task:
### Input:
Gets an invalid number for the specified region.
This is useful for unit-testing purposes, where you want to test what
will happen with an invalid number. Note that the number that is
returned will always be able to be parsed and will hav... |
def get_device_by_name(self, device_name):
"""Search the list of connected devices by name.
device_name param is the string name of the device
"""
# Find the device for the vera device name we are interested in
found_device = None
for device in self.get_devices():
... | Search the list of connected devices by name.
device_name param is the string name of the device | Below is the the instruction that describes the task:
### Input:
Search the list of connected devices by name.
device_name param is the string name of the device
### Response:
def get_device_by_name(self, device_name):
"""Search the list of connected devices by name.
device_name param is ... |
def jsonarrtrim(self, name, path, start, stop):
"""
Trim the array JSON value under ``path`` at key ``name`` to the
inclusive range given by ``start`` and ``stop``
"""
return self.execute_command('JSON.ARRTRIM', name, str_path(path), start, stop) | Trim the array JSON value under ``path`` at key ``name`` to the
inclusive range given by ``start`` and ``stop`` | Below is the the instruction that describes the task:
### Input:
Trim the array JSON value under ``path`` at key ``name`` to the
inclusive range given by ``start`` and ``stop``
### Response:
def jsonarrtrim(self, name, path, start, stop):
"""
Trim the array JSON value under ``path`` at key... |
def kpl_set_on_mask(self, address, group, mask):
"""Get the status of a KPL button."""
addr = Address(address)
device = self.plm.devices[addr.id]
device.states[group].set_on_mask(mask) | Get the status of a KPL button. | Below is the the instruction that describes the task:
### Input:
Get the status of a KPL button.
### Response:
def kpl_set_on_mask(self, address, group, mask):
"""Get the status of a KPL button."""
addr = Address(address)
device = self.plm.devices[addr.id]
device.states[group].set_o... |
def _init_glyph(self, plot, mapping, properties):
"""
Returns a Bokeh glyph object.
"""
plot_method = properties.pop('plot_method', None)
properties = mpl_to_bokeh(properties)
data = dict(properties, **mapping)
if self._has_holes:
plot_method = 'multi_... | Returns a Bokeh glyph object. | Below is the the instruction that describes the task:
### Input:
Returns a Bokeh glyph object.
### Response:
def _init_glyph(self, plot, mapping, properties):
"""
Returns a Bokeh glyph object.
"""
plot_method = properties.pop('plot_method', None)
properties = mpl_to_bokeh(pr... |
def parse(cls, buff, offset):
"""
Given a buffer and offset, returns the parsed value and new offset.
Parses the ``size_primitive`` first to determine how many more bytes to
consume to extract the value.
"""
size, offset = cls.size_primitive.parse(buff, offset)
i... | Given a buffer and offset, returns the parsed value and new offset.
Parses the ``size_primitive`` first to determine how many more bytes to
consume to extract the value. | Below is the the instruction that describes the task:
### Input:
Given a buffer and offset, returns the parsed value and new offset.
Parses the ``size_primitive`` first to determine how many more bytes to
consume to extract the value.
### Response:
def parse(cls, buff, offset):
"""
... |
def isPe32(self):
"""
Determines if the current L{PE} instance is a PE32 file.
@rtype: bool
@return: C{True} if the current L{PE} instance is a PE32 file. Otherwise, returns C{False}.
"""
if self.ntHeaders.optionalHeader.magic.value == consts.PE32:
re... | Determines if the current L{PE} instance is a PE32 file.
@rtype: bool
@return: C{True} if the current L{PE} instance is a PE32 file. Otherwise, returns C{False}. | Below is the the instruction that describes the task:
### Input:
Determines if the current L{PE} instance is a PE32 file.
@rtype: bool
@return: C{True} if the current L{PE} instance is a PE32 file. Otherwise, returns C{False}.
### Response:
def isPe32(self):
"""
Determines ... |
def fts_match(self, fts_mask, segment):
"""Evaluates whether a set of features 'match' a segment (are a subset
of that segment's features)
Args:
fts_mask (list): list of (value, feature) tuples
segment (unicode): IPA string corresponding to segment (consonant or
... | Evaluates whether a set of features 'match' a segment (are a subset
of that segment's features)
Args:
fts_mask (list): list of (value, feature) tuples
segment (unicode): IPA string corresponding to segment (consonant or
vowel)
Returns:
... | Below is the the instruction that describes the task:
### Input:
Evaluates whether a set of features 'match' a segment (are a subset
of that segment's features)
Args:
fts_mask (list): list of (value, feature) tuples
segment (unicode): IPA string corresponding to segment (con... |
def sort_targets(targets):
"""
:API: public
:return: the targets that `targets` depend on sorted from most dependent to least.
"""
roots, inverted_deps = invert_dependencies(targets)
ordered = []
visited = set()
def topological_sort(target):
if target not in visited:
visited.add(target)
... | :API: public
:return: the targets that `targets` depend on sorted from most dependent to least. | Below is the the instruction that describes the task:
### Input:
:API: public
:return: the targets that `targets` depend on sorted from most dependent to least.
### Response:
def sort_targets(targets):
"""
:API: public
:return: the targets that `targets` depend on sorted from most dependent to least.
"... |
def run_primlist(self, primlist, skip_remaining=False):
'''Runs runs from a primlist.
Parameters
----------
primlist : string
Filename of primlist.
skip_remaining : bool
If True, skip remaining runs, if a run does not exit with status FINISHED.
N... | Runs runs from a primlist.
Parameters
----------
primlist : string
Filename of primlist.
skip_remaining : bool
If True, skip remaining runs, if a run does not exit with status FINISHED.
Note
----
Primlist is a text file of the following f... | Below is the the instruction that describes the task:
### Input:
Runs runs from a primlist.
Parameters
----------
primlist : string
Filename of primlist.
skip_remaining : bool
If True, skip remaining runs, if a run does not exit with status FINISHED.
... |
def check(self, pointer, expected, raise_onerror=False):
"""Check if value exists into object.
:param pointer: the path to search in
:param expected: the expected value
:param raise_onerror: should raise on error?
:return: boolean
"""
obj = self.document
... | Check if value exists into object.
:param pointer: the path to search in
:param expected: the expected value
:param raise_onerror: should raise on error?
:return: boolean | Below is the the instruction that describes the task:
### Input:
Check if value exists into object.
:param pointer: the path to search in
:param expected: the expected value
:param raise_onerror: should raise on error?
:return: boolean
### Response:
def check(self, pointer, expecte... |
def lastId(self):
""" Children passage
:rtype: str
:returns: First children of the graph. Shortcut to self.graph.children[0]
"""
if self._last is False:
# Request the next urn
self._last = self.childIds[-1]
return self._last | Children passage
:rtype: str
:returns: First children of the graph. Shortcut to self.graph.children[0] | Below is the the instruction that describes the task:
### Input:
Children passage
:rtype: str
:returns: First children of the graph. Shortcut to self.graph.children[0]
### Response:
def lastId(self):
""" Children passage
:rtype: str
:returns: First children of the graph. S... |
def call_on_commit(self, callback):
"""Call a callback upon successful commit of a transaction.
If not in a transaction, the callback is called immediately.
In a transaction, multiple callbacks may be registered and will be
called once the transaction commits, in the order in which they
were regis... | Call a callback upon successful commit of a transaction.
If not in a transaction, the callback is called immediately.
In a transaction, multiple callbacks may be registered and will be
called once the transaction commits, in the order in which they
were registered. If the transaction fails, the callb... | Below is the the instruction that describes the task:
### Input:
Call a callback upon successful commit of a transaction.
If not in a transaction, the callback is called immediately.
In a transaction, multiple callbacks may be registered and will be
called once the transaction commits, in the order in... |
def signal_to_exception(sig: signal.Signals) -> SignalException:
"""
Convert a ``signal.Signals`` to a ``SignalException``.
This allows for natural, pythonic signal handing with the use of try-except blocks.
.. code-block:: python
import signal
import zproc
zproc.signal_to_ex... | Convert a ``signal.Signals`` to a ``SignalException``.
This allows for natural, pythonic signal handing with the use of try-except blocks.
.. code-block:: python
import signal
import zproc
zproc.signal_to_exception(signals.SIGTERM)
try:
...
except zproc.Si... | Below is the the instruction that describes the task:
### Input:
Convert a ``signal.Signals`` to a ``SignalException``.
This allows for natural, pythonic signal handing with the use of try-except blocks.
.. code-block:: python
import signal
import zproc
zproc.signal_to_exception(... |
def _query(self, method, path, data=None, page=False, retry=0):
"""
Fetch an object from the Graph API and parse the output, returning a tuple where the first item
is the object yielded by the Graph API and the second is the URL for the next page of results, or
``None`` if results have b... | Fetch an object from the Graph API and parse the output, returning a tuple where the first item
is the object yielded by the Graph API and the second is the URL for the next page of results, or
``None`` if results have been exhausted.
:param method: A string describing the HTTP method.
... | Below is the the instruction that describes the task:
### Input:
Fetch an object from the Graph API and parse the output, returning a tuple where the first item
is the object yielded by the Graph API and the second is the URL for the next page of results, or
``None`` if results have been exhausted.
... |
def to_vars_dict(self):
"""
Return local state which is relevant for the cluster setup process.
"""
return {
'aws_access_key_id': self._access_key,
'aws_secret_access_key': self._secret_key,
'aws_region': self._region_name,
... | Return local state which is relevant for the cluster setup process. | Below is the the instruction that describes the task:
### Input:
Return local state which is relevant for the cluster setup process.
### Response:
def to_vars_dict(self):
"""
Return local state which is relevant for the cluster setup process.
"""
return {
'aws_access_key... |
def _sign(translator, expr):
"""Workaround for missing sign function"""
op = expr.op()
arg, = op.args
arg_ = translator.translate(arg)
return 'intDivOrZero({0}, abs({0}))'.format(arg_) | Workaround for missing sign function | Below is the the instruction that describes the task:
### Input:
Workaround for missing sign function
### Response:
def _sign(translator, expr):
"""Workaround for missing sign function"""
op = expr.op()
arg, = op.args
arg_ = translator.translate(arg)
return 'intDivOrZero({0}, abs({0}))'.format(... |
def get_user(
self, identified_with, identifier, req, resp, resource, uri_kwargs
):
"""Return default user object."""
return self.user | Return default user object. | Below is the the instruction that describes the task:
### Input:
Return default user object.
### Response:
def get_user(
self, identified_with, identifier, req, resp, resource, uri_kwargs
):
"""Return default user object."""
return self.user |
def process_response(self, response):
"""
Load a JSON response.
:param Response response: The HTTP response.
:return dict: The JSON-loaded content.
"""
if response.status_code != 200:
raise TwilioException('Unable to fetch page', response)
return jso... | Load a JSON response.
:param Response response: The HTTP response.
:return dict: The JSON-loaded content. | Below is the the instruction that describes the task:
### Input:
Load a JSON response.
:param Response response: The HTTP response.
:return dict: The JSON-loaded content.
### Response:
def process_response(self, response):
"""
Load a JSON response.
:param Response response... |
def get_dashboard_panels_visibility_by_section(section_name):
"""
Return a list of pairs as values that represents the role-permission
view relation for the panel section passed in.
:param section_name: the panels section id.
:return: a list of tuples.
"""
registry_info = get_dashboard_regis... | Return a list of pairs as values that represents the role-permission
view relation for the panel section passed in.
:param section_name: the panels section id.
:return: a list of tuples. | Below is the the instruction that describes the task:
### Input:
Return a list of pairs as values that represents the role-permission
view relation for the panel section passed in.
:param section_name: the panels section id.
:return: a list of tuples.
### Response:
def get_dashboard_panels_visibility_b... |
def _to_legacy_path(dict_path):
"""Convert a tuple of ints and strings in a legacy "Path".
.. note:
This assumes, but does not verify, that each entry in
``dict_path`` is valid (i.e. doesn't have more than one
key out of "name" / "id").
:type dict_path: lsit
:param dict_path: ... | Convert a tuple of ints and strings in a legacy "Path".
.. note:
This assumes, but does not verify, that each entry in
``dict_path`` is valid (i.e. doesn't have more than one
key out of "name" / "id").
:type dict_path: lsit
:param dict_path: The "structured" path for a key, i.e. i... | Below is the the instruction that describes the task:
### Input:
Convert a tuple of ints and strings in a legacy "Path".
.. note:
This assumes, but does not verify, that each entry in
``dict_path`` is valid (i.e. doesn't have more than one
key out of "name" / "id").
:type dict_pat... |
def trigger(self, source, actions, event_args):
"""
Perform actions as a result of an event listener (TRIGGER)
"""
type = BlockType.TRIGGER
return self.action_block(source, actions, type, event_args=event_args) | Perform actions as a result of an event listener (TRIGGER) | Below is the the instruction that describes the task:
### Input:
Perform actions as a result of an event listener (TRIGGER)
### Response:
def trigger(self, source, actions, event_args):
"""
Perform actions as a result of an event listener (TRIGGER)
"""
type = BlockType.TRIGGER
return self.action_block(so... |
async def create_scene(self, scene_name, room_id) -> Scene:
"""Create a scene and returns the scene object.
:raises PvApiError when something is wrong with the hub.
"""
_raw = await self._scenes_entry_point.create_scene(room_id, scene_name)
result = Scene(_raw, self.request)
... | Create a scene and returns the scene object.
:raises PvApiError when something is wrong with the hub. | Below is the the instruction that describes the task:
### Input:
Create a scene and returns the scene object.
:raises PvApiError when something is wrong with the hub.
### Response:
async def create_scene(self, scene_name, room_id) -> Scene:
"""Create a scene and returns the scene object.
... |
def _join_info_fields(self):
"""Updates info attribute from info dict."""
if self.info_dict:
info_fields = []
if len(self.info_dict) > 1:
self.info_dict.pop(".", None)
for field, value in self.info_dict.items():
if field == value:
... | Updates info attribute from info dict. | Below is the the instruction that describes the task:
### Input:
Updates info attribute from info dict.
### Response:
def _join_info_fields(self):
"""Updates info attribute from info dict."""
if self.info_dict:
info_fields = []
if len(self.info_dict) > 1:
sel... |
def create_token(self, request, refresh_token=False, **kwargs):
"""
Create a BearerToken, by default without refresh token.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:param refresh_token:
"""
if "save_token" in kwargs:
w... | Create a BearerToken, by default without refresh token.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:param refresh_token: | Below is the the instruction that describes the task:
### Input:
Create a BearerToken, by default without refresh token.
:param request: OAuthlib request.
:type request: oauthlib.common.Request
:param refresh_token:
### Response:
def create_token(self, request, refresh_token=False, **kwarg... |
def symlink_bundles(self, app, bundle_dir):
"""For each bundle in the given app, symlinks relevant matched paths.
Validates that at least one path was matched by a bundle.
"""
for bundle_counter, bundle in enumerate(app.bundles):
count = 0
for path, relpath in bundle.filemap.items():
... | For each bundle in the given app, symlinks relevant matched paths.
Validates that at least one path was matched by a bundle. | Below is the the instruction that describes the task:
### Input:
For each bundle in the given app, symlinks relevant matched paths.
Validates that at least one path was matched by a bundle.
### Response:
def symlink_bundles(self, app, bundle_dir):
"""For each bundle in the given app, symlinks relevant mat... |
def highlightBlock(self, text):
""" Actually highlight the block"""
# Note that an undefined blockstate is equal to -1, so the first block
# will have the correct behaviour of starting at 0.
if self._allow_highlight:
start = self.previousBlockState() + 1
end... | Actually highlight the block | Below is the the instruction that describes the task:
### Input:
Actually highlight the block
### Response:
def highlightBlock(self, text):
""" Actually highlight the block"""
# Note that an undefined blockstate is equal to -1, so the first block
# will have the correct behaviour of star... |
def point_distance(point1, point2):
"""
calculate the distance between two points on the sphere like google map
reference http://www.movable-type.co.uk/scripts/latlong.html
Keyword arguments:
point1 -- point one geojson object
point2 -- point two geojson object
return distance
"""
... | calculate the distance between two points on the sphere like google map
reference http://www.movable-type.co.uk/scripts/latlong.html
Keyword arguments:
point1 -- point one geojson object
point2 -- point two geojson object
return distance | Below is the the instruction that describes the task:
### Input:
calculate the distance between two points on the sphere like google map
reference http://www.movable-type.co.uk/scripts/latlong.html
Keyword arguments:
point1 -- point one geojson object
point2 -- point two geojson object
retur... |
def get_dependencies(self, id, **kwargs):
"""
Get the direct dependencies of the specified configuration
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the re... | Get the direct dependencies of the specified configuration
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>... | Below is the the instruction that describes the task:
### Input:
Get the direct dependencies of the specified configuration
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving... |
def searchForUsers(self, name, limit=10):
"""
Find and get user by his/her name
:param name: Name of the user
:param limit: The max. amount of users to fetch
:return: :class:`models.User` objects, ordered by relevance
:rtype: list
:raises: FBchatException if requ... | Find and get user by his/her name
:param name: Name of the user
:param limit: The max. amount of users to fetch
:return: :class:`models.User` objects, ordered by relevance
:rtype: list
:raises: FBchatException if request failed | Below is the the instruction that describes the task:
### Input:
Find and get user by his/her name
:param name: Name of the user
:param limit: The max. amount of users to fetch
:return: :class:`models.User` objects, ordered by relevance
:rtype: list
:raises: FBchatException ... |
def _load_activity(self, activity):
"""
Iterates trough the all enabled `~zengine.settings.ACTIVITY_MODULES_IMPORT_PATHS` to find the given path.
"""
fpths = []
full_path = ''
errors = []
paths = settings.ACTIVITY_MODULES_IMPORT_PATHS
number_of_paths = len... | Iterates trough the all enabled `~zengine.settings.ACTIVITY_MODULES_IMPORT_PATHS` to find the given path. | Below is the the instruction that describes the task:
### Input:
Iterates trough the all enabled `~zengine.settings.ACTIVITY_MODULES_IMPORT_PATHS` to find the given path.
### Response:
def _load_activity(self, activity):
"""
Iterates trough the all enabled `~zengine.settings.ACTIVITY_MODULES_IMPORT... |
def get_job(self, id_job, hub=None, group=None, project=None,
access_token=None, user_id=None):
"""
Get the information about a job, by its id
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.... | Get the information about a job, by its id | Below is the the instruction that describes the task:
### Input:
Get the information about a job, by its id
### Response:
def get_job(self, id_job, hub=None, group=None, project=None,
access_token=None, user_id=None):
"""
Get the information about a job, by its id
"""
... |
def close_db(self, exception):
"""Added as a `~flask.Flask.teardown_request` to applications to
commit the transaction and disconnect ZODB if it was used during
the request."""
if self.is_connected:
if exception is None and not transaction.isDoomed():
transact... | Added as a `~flask.Flask.teardown_request` to applications to
commit the transaction and disconnect ZODB if it was used during
the request. | Below is the the instruction that describes the task:
### Input:
Added as a `~flask.Flask.teardown_request` to applications to
commit the transaction and disconnect ZODB if it was used during
the request.
### Response:
def close_db(self, exception):
"""Added as a `~flask.Flask.teardown_requ... |
def load(self, infile):
'''
Deserialize a model from a stored file.
By default, unpickle an entire object. If `dump` is overridden to
use a different storage format, `load` should be as well.
:param file outfile: A file-like object from which to retrieve the
seriali... | Deserialize a model from a stored file.
By default, unpickle an entire object. If `dump` is overridden to
use a different storage format, `load` should be as well.
:param file outfile: A file-like object from which to retrieve the
serialized model. | Below is the the instruction that describes the task:
### Input:
Deserialize a model from a stored file.
By default, unpickle an entire object. If `dump` is overridden to
use a different storage format, `load` should be as well.
:param file outfile: A file-like object from which to retriev... |
def date_to_number(self, date):
"""
Converts a date or datetime instance to a corresponding float value.
"""
if isinstance(date, datetime.datetime):
delta = date - self._null_date
elif isinstance(date, datetime.date):
delta = date - self._null_date.date()
... | Converts a date or datetime instance to a corresponding float value. | Below is the the instruction that describes the task:
### Input:
Converts a date or datetime instance to a corresponding float value.
### Response:
def date_to_number(self, date):
"""
Converts a date or datetime instance to a corresponding float value.
"""
if isinstance(date, dateti... |
def get_text_position_and_inner_alignment(ax, pos, scale=default_text_relative_padding, with_transAxes_kwargs=True):
"""Return text position and its alignment in its bounding box.
The returned position is given in Axes coordinate,
as defined in matplotlib documentation on transformation.
The retur... | Return text position and its alignment in its bounding box.
The returned position is given in Axes coordinate,
as defined in matplotlib documentation on transformation.
The returned alignment is given in dictionary,
which can be put as a fontdict to text-relavent method. | Below is the the instruction that describes the task:
### Input:
Return text position and its alignment in its bounding box.
The returned position is given in Axes coordinate,
as defined in matplotlib documentation on transformation.
The returned alignment is given in dictionary,
which can be ... |
def update_properties(self, new_properties):
""" Update config properties values
Property name must be equal to 'Section_option' of config property
:param new_properties: dict with new properties values
"""
[self._update_property_from_dict(section, option, new_properties)
... | Update config properties values
Property name must be equal to 'Section_option' of config property
:param new_properties: dict with new properties values | Below is the the instruction that describes the task:
### Input:
Update config properties values
Property name must be equal to 'Section_option' of config property
:param new_properties: dict with new properties values
### Response:
def update_properties(self, new_properties):
""" Update c... |
def _process_transfer(self, ud, ase, offsets, data):
# type: (Uploader, blobxfer.models.upload.Descriptor,
# blobxfer.models.azure.StorageEntity,
# blobxfer.models.upload.Offsets, bytes) -> None
"""Process transfer instructions
:param Uploader self: this
:pa... | Process transfer instructions
:param Uploader self: this
:param blobxfer.models.upload.Descriptor ud: upload descriptor
:param blobxfer.models.azure.StorageEntity ase: Storage entity
:param blobxfer.models.upload.Offsets offsets: offsets
:param bytes data: data to upload | Below is the the instruction that describes the task:
### Input:
Process transfer instructions
:param Uploader self: this
:param blobxfer.models.upload.Descriptor ud: upload descriptor
:param blobxfer.models.azure.StorageEntity ase: Storage entity
:param blobxfer.models.upload.Offset... |
def attach_arguments(cls, parser, prefix='--', skip_formats=False,
format_excludes=None, format_title=None,
format_desc=None, skip_render=False,
render_excludes=None, render_title=None,
render_desc=None, skip_filters=Fal... | Attach argparse arguments to an argparse parser/group with table
options. These are renderer options and filtering options with the
ability to turn off headers and footers. The return value is function
that parses an argparse.Namespace object into keyword arguments for a
layout.Table c... | Below is the the instruction that describes the task:
### Input:
Attach argparse arguments to an argparse parser/group with table
options. These are renderer options and filtering options with the
ability to turn off headers and footers. The return value is function
that parses an argparse... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.