code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def run_analysis(self, argv):
"""Run this analysis"""
args = self._parser.parse_args(argv)
if not HAVE_ST:
raise RuntimeError(
"Trying to run fermipy analysis, but don't have ST")
gta = GTAnalysis(args.config, logging={'verbosity': 3},
... | Run this analysis | Below is the the instruction that describes the task:
### Input:
Run this analysis
### Response:
def run_analysis(self, argv):
"""Run this analysis"""
args = self._parser.parse_args(argv)
if not HAVE_ST:
raise RuntimeError(
"Trying to run fermipy analysis, but d... |
def create_dir(path):
"""Create dir with the path
:param path: The path to be created
:type path: str
"""
if os.path.exists(path):
if not os.path.isdir(path):
logger.error('%s is not a directory', path)
sys.exit(1)
else: # ignore
pass
else:
... | Create dir with the path
:param path: The path to be created
:type path: str | Below is the the instruction that describes the task:
### Input:
Create dir with the path
:param path: The path to be created
:type path: str
### Response:
def create_dir(path):
"""Create dir with the path
:param path: The path to be created
:type path: str
"""
if os.path.exists(path)... |
def square_batch_region(data, region, bam_files, vrn_files, out_file):
"""Perform squaring of a batch in a supplied region, with input BAMs
"""
from bcbio.variation import sentieon, strelka2
if not utils.file_exists(out_file):
jointcaller = tz.get_in(("config", "algorithm", "jointcaller"), data)... | Perform squaring of a batch in a supplied region, with input BAMs | Below is the the instruction that describes the task:
### Input:
Perform squaring of a batch in a supplied region, with input BAMs
### Response:
def square_batch_region(data, region, bam_files, vrn_files, out_file):
"""Perform squaring of a batch in a supplied region, with input BAMs
"""
from bcbio.var... |
def on_button_release(self, event):
"""Select or deselect rubber banded groups of items
The selection of elements is prior and never items are selected or deselected at the same time.
"""
self.queue_draw(self.view)
x0, y0, x1, y1 = self.x0, self.y0, self.x1, self.y1
re... | Select or deselect rubber banded groups of items
The selection of elements is prior and never items are selected or deselected at the same time. | Below is the the instruction that describes the task:
### Input:
Select or deselect rubber banded groups of items
The selection of elements is prior and never items are selected or deselected at the same time.
### Response:
def on_button_release(self, event):
"""Select or deselect rubber banded g... |
def insert(self, **kwargs):
"""
Saves the Document to the database if it is valid.
Returns errors otherwise.
"""
if self.is_valid:
before = self.before_insert()
if before:
return before
try:
self._document['_id'... | Saves the Document to the database if it is valid.
Returns errors otherwise. | Below is the the instruction that describes the task:
### Input:
Saves the Document to the database if it is valid.
Returns errors otherwise.
### Response:
def insert(self, **kwargs):
"""
Saves the Document to the database if it is valid.
Returns errors otherwise.
"""
... |
def push(self, index=None):
"""Push built documents to ElasticSearch.
If ``index`` is specified, only that index will be pushed.
"""
for ind in self.indexes:
if index and not isinstance(ind, index):
continue
ind.push() | Push built documents to ElasticSearch.
If ``index`` is specified, only that index will be pushed. | Below is the the instruction that describes the task:
### Input:
Push built documents to ElasticSearch.
If ``index`` is specified, only that index will be pushed.
### Response:
def push(self, index=None):
"""Push built documents to ElasticSearch.
If ``index`` is specified, only that index... |
def get_arguments(self):
"""
CLIs get called back so that they can process any command line arguments
that are given. This method handles the standard command line arguments for:
API Host, user, password, etc.
"""
# We call this first so that logging is enabled as soon a... | CLIs get called back so that they can process any command line arguments
that are given. This method handles the standard command line arguments for:
API Host, user, password, etc. | Below is the the instruction that describes the task:
### Input:
CLIs get called back so that they can process any command line arguments
that are given. This method handles the standard command line arguments for:
API Host, user, password, etc.
### Response:
def get_arguments(self):
"""
... |
def create_instance(self, image_id, pem_file, group_ids, instance_type, volume_type='gp2', ebs_optimized=False, instance_monitoring=False, iam_profile='', tag_list=None, auction_bid=0.0):
'''
a method for starting an instance on AWS EC2
:param image_id: string with aws id of im... | a method for starting an instance on AWS EC2
:param image_id: string with aws id of image for instance
:param pem_file: string with path to pem file to access image
:param group_ids: list with aws id of security group(s) to attach to instance
:param instance_type: string wi... | Below is the the instruction that describes the task:
### Input:
a method for starting an instance on AWS EC2
:param image_id: string with aws id of image for instance
:param pem_file: string with path to pem file to access image
:param group_ids: list with aws id of security g... |
def build_event_out(self, event_out):
"""
Build event out code.
@param event_out: event out object
@type event_out: lems.model.dynamics.EventOut
@return: Generated event out code
@rtype: string
"""
event_out_code = ['if "{0}" in self.event_out_callbacks... | Build event out code.
@param event_out: event out object
@type event_out: lems.model.dynamics.EventOut
@return: Generated event out code
@rtype: string | Below is the the instruction that describes the task:
### Input:
Build event out code.
@param event_out: event out object
@type event_out: lems.model.dynamics.EventOut
@return: Generated event out code
@rtype: string
### Response:
def build_event_out(self, event_out):
"""
... |
def filter(self, field_name, field_value):
"""Add permanent filter on the collection
:param field_name: name of the field to filter on
:type field_name: str
:param field_value: value to filter on
:rtype: Collection
"""
self.filters.append((field_name, field_valu... | Add permanent filter on the collection
:param field_name: name of the field to filter on
:type field_name: str
:param field_value: value to filter on
:rtype: Collection | Below is the the instruction that describes the task:
### Input:
Add permanent filter on the collection
:param field_name: name of the field to filter on
:type field_name: str
:param field_value: value to filter on
:rtype: Collection
### Response:
def filter(self, field_name, fiel... |
def version():
"""
Version
Imports and displays current boiler version.
:return:
"""
echo(green('\nshift-boiler:'))
echo(green('-' * 40))
echo(yellow('Version: ') + '{}'.format(boiler_version))
echo(yellow('GitHub: ') + 'https://github.com/projectshift/shift-boiler')
echo(yellow(... | Version
Imports and displays current boiler version.
:return: | Below is the the instruction that describes the task:
### Input:
Version
Imports and displays current boiler version.
:return:
### Response:
def version():
"""
Version
Imports and displays current boiler version.
:return:
"""
echo(green('\nshift-boiler:'))
echo(green('-' * 40))
... |
def matches(self, properties):
"""
Tests if the given properties matches this LDAP filter and its children
:param properties: A dictionary of properties
:return: True if the properties matches this filter, else False
"""
# Use a generator, and declare it outside of the m... | Tests if the given properties matches this LDAP filter and its children
:param properties: A dictionary of properties
:return: True if the properties matches this filter, else False | Below is the the instruction that describes the task:
### Input:
Tests if the given properties matches this LDAP filter and its children
:param properties: A dictionary of properties
:return: True if the properties matches this filter, else False
### Response:
def matches(self, properties):
... |
def net_recv(ws, conn):
''' Read pending data from network into websocket. '''
in_data = conn.recv(RECEIVE_BYTES)
if not in_data:
# A receive of zero bytes indicates the TCP socket has been closed. We
# need to pass None to wsproto to update its internal state.
print('Received 0 byte... | Read pending data from network into websocket. | Below is the the instruction that describes the task:
### Input:
Read pending data from network into websocket.
### Response:
def net_recv(ws, conn):
''' Read pending data from network into websocket. '''
in_data = conn.recv(RECEIVE_BYTES)
if not in_data:
# A receive of zero bytes indicates the... |
def qvalues(pv, m = None, verbose = False, lowmem = False, pi0 = None):
"""
Copyright (c) 2012, Nicolo Fusi, University of Sheffield
All rights reserved.
Estimates q-values from p-values
Args
=====
m: number of tests. If not specified m = pv.size
verbose: print verbose messages? (defa... | Copyright (c) 2012, Nicolo Fusi, University of Sheffield
All rights reserved.
Estimates q-values from p-values
Args
=====
m: number of tests. If not specified m = pv.size
verbose: print verbose messages? (default False)
lowmem: use memory-efficient in-place algorithm
pi0: if None, it'... | Below is the the instruction that describes the task:
### Input:
Copyright (c) 2012, Nicolo Fusi, University of Sheffield
All rights reserved.
Estimates q-values from p-values
Args
=====
m: number of tests. If not specified m = pv.size
verbose: print verbose messages? (default False)
... |
def from_response(cls, response_data):
"""
Factory method to create a Mail instance from a Guerrillamail response
dict.
"""
identity = lambda x: x
return Mail(**_transform_dict(response_data, {
'guid': ('mail_id', identity),
'subject': ('mail_subje... | Factory method to create a Mail instance from a Guerrillamail response
dict. | Below is the the instruction that describes the task:
### Input:
Factory method to create a Mail instance from a Guerrillamail response
dict.
### Response:
def from_response(cls, response_data):
"""
Factory method to create a Mail instance from a Guerrillamail response
dict.
... |
def adsSyncSetTimeoutEx(port, nMs):
# type: (int, int) -> None
"""Set Timeout.
:param int port: local AMS port as returned by adsPortOpenEx()
:param int nMs: timeout in ms
"""
adsSyncSetTimeoutFct = _adsDLL.AdsSyncSetTimeoutEx
cms = ctypes.c_long(nMs)
err_code = adsSyncSetTimeoutFct(po... | Set Timeout.
:param int port: local AMS port as returned by adsPortOpenEx()
:param int nMs: timeout in ms | Below is the the instruction that describes the task:
### Input:
Set Timeout.
:param int port: local AMS port as returned by adsPortOpenEx()
:param int nMs: timeout in ms
### Response:
def adsSyncSetTimeoutEx(port, nMs):
# type: (int, int) -> None
"""Set Timeout.
:param int port: local AMS po... |
def check_max_filesize(chosen_file, max_size):
"""
Checks file sizes for host
"""
if os.path.getsize(chosen_file) > max_size:
return False
else:
return True | Checks file sizes for host | Below is the the instruction that describes the task:
### Input:
Checks file sizes for host
### Response:
def check_max_filesize(chosen_file, max_size):
"""
Checks file sizes for host
"""
if os.path.getsize(chosen_file) > max_size:
return False
else:
return True |
def collapse_times():
"""Make copies of everything, assign to global shortcuts so functions work
on them, extract the times, then restore the running stacks.
"""
orig_ts = f.timer_stack
orig_ls = f.loop_stack
copy_ts = _copy_timer_stack()
copy_ls = copy.deepcopy(f.loop_stack)
f.timer_sta... | Make copies of everything, assign to global shortcuts so functions work
on them, extract the times, then restore the running stacks. | Below is the the instruction that describes the task:
### Input:
Make copies of everything, assign to global shortcuts so functions work
on them, extract the times, then restore the running stacks.
### Response:
def collapse_times():
"""Make copies of everything, assign to global shortcuts so functions wor... |
def read_image(img_spec, bkground_thresh, ensure_num_dim=3):
"""Image reader, with additional checks on size.
Can optionally remove stray values close to zero (smaller than 5 %ile)."""
img = load_image_from_disk(img_spec)
if not np.issubdtype(img.dtype, np.floating):
img = img.astype('float32... | Image reader, with additional checks on size.
Can optionally remove stray values close to zero (smaller than 5 %ile). | Below is the the instruction that describes the task:
### Input:
Image reader, with additional checks on size.
Can optionally remove stray values close to zero (smaller than 5 %ile).
### Response:
def read_image(img_spec, bkground_thresh, ensure_num_dim=3):
"""Image reader, with additional checks on size.... |
def complete(
self, config, prompt, session, context, current_arguments, current
):
# type: (CompletionInfo, str, ShellSession, BundleContext, List[str], str) -> List[str]
"""
Returns the list of services IDs matching the current state
:param config: Configuration of the cur... | Returns the list of services IDs matching the current state
:param config: Configuration of the current completion
:param prompt: Shell prompt (for re-display)
:param session: Shell session (to display in shell)
:param context: Bundle context of the Shell bundle
:param current_a... | Below is the the instruction that describes the task:
### Input:
Returns the list of services IDs matching the current state
:param config: Configuration of the current completion
:param prompt: Shell prompt (for re-display)
:param session: Shell session (to display in shell)
:param... |
def new_fact(self):
"""Create a new Fact from this template."""
fact = lib.EnvCreateFact(self._env, self._tpl)
if fact == ffi.NULL:
raise CLIPSError(self._env)
return new_fact(self._env, fact) | Create a new Fact from this template. | Below is the the instruction that describes the task:
### Input:
Create a new Fact from this template.
### Response:
def new_fact(self):
"""Create a new Fact from this template."""
fact = lib.EnvCreateFact(self._env, self._tpl)
if fact == ffi.NULL:
raise CLIPSError(self._env)
... |
def limitations():
"""Get InaSAFE limitations.
:return: All limitations on current InaSAFE.
:rtype: list
"""
limitation_list = list()
limitation_list.append(tr('InaSAFE is not a hazard modelling tool.'))
limitation_list.append(
tr('InaSAFE is a Free and Open Source Software (FOSS) p... | Get InaSAFE limitations.
:return: All limitations on current InaSAFE.
:rtype: list | Below is the the instruction that describes the task:
### Input:
Get InaSAFE limitations.
:return: All limitations on current InaSAFE.
:rtype: list
### Response:
def limitations():
"""Get InaSAFE limitations.
:return: All limitations on current InaSAFE.
:rtype: list
"""
limitation_lis... |
def _match_spec(self, nugget):
"""
match the string `nugget` to a format specifier.
"""
# TODO: handle positional modifiers and other similar format string tricks.
all_spec = self._all_spec
# iterate through nugget throwing away anything which is an int
# TODO st... | match the string `nugget` to a format specifier. | Below is the the instruction that describes the task:
### Input:
match the string `nugget` to a format specifier.
### Response:
def _match_spec(self, nugget):
"""
match the string `nugget` to a format specifier.
"""
# TODO: handle positional modifiers and other similar format string... |
def _hash(self):
"""Return a hash for the current query.
This hash is _not_ a unique representation of the dataset!
"""
dump = dumps(self.query, sort_keys=True)
if isinstance(dump, str):
dump = dump.encode('utf-8')
return md5(dump).hexdigest() | Return a hash for the current query.
This hash is _not_ a unique representation of the dataset! | Below is the the instruction that describes the task:
### Input:
Return a hash for the current query.
This hash is _not_ a unique representation of the dataset!
### Response:
def _hash(self):
"""Return a hash for the current query.
This hash is _not_ a unique representation of the dataset... |
def _poll_for_refresh(self, check_id):
"""
Given a Trusted Advisor check_id that has just been refreshed, poll
until the refresh is complete. Once complete, return the check result.
:param check_id: the Trusted Advisor check ID
:type check_id: str
:returns: dict check re... | Given a Trusted Advisor check_id that has just been refreshed, poll
until the refresh is complete. Once complete, return the check result.
:param check_id: the Trusted Advisor check ID
:type check_id: str
:returns: dict check result. The return value of
:py:meth:`Support.Clien... | Below is the the instruction that describes the task:
### Input:
Given a Trusted Advisor check_id that has just been refreshed, poll
until the refresh is complete. Once complete, return the check result.
:param check_id: the Trusted Advisor check ID
:type check_id: str
:returns: dic... |
def _per_era_supply(self, block_height):
"""
Calculate the coin supply based on 'eras' defined in crypto_data. Some
currencies don't have a simple algorithmically defined halfing schedule
so coins supply has to be defined explicitly per era.
"""
coins = 0
for era ... | Calculate the coin supply based on 'eras' defined in crypto_data. Some
currencies don't have a simple algorithmically defined halfing schedule
so coins supply has to be defined explicitly per era. | Below is the the instruction that describes the task:
### Input:
Calculate the coin supply based on 'eras' defined in crypto_data. Some
currencies don't have a simple algorithmically defined halfing schedule
so coins supply has to be defined explicitly per era.
### Response:
def _per_era_supply(sel... |
def from_command_line():
"""
Run CGI var to gVCF conversion from the command line.
"""
# Parse options
parser = argparse.ArgumentParser(
description='Convert Complete Genomics var files to gVCF format.')
parser.add_argument(
'-d', '--refseqdir', metavar='REFSEQDIR', required=True... | Run CGI var to gVCF conversion from the command line. | Below is the the instruction that describes the task:
### Input:
Run CGI var to gVCF conversion from the command line.
### Response:
def from_command_line():
"""
Run CGI var to gVCF conversion from the command line.
"""
# Parse options
parser = argparse.ArgumentParser(
description='Conv... |
def kind(path, user=None):
"""
Get the kind of item ("file" or "directory") that the path references.
Return :obj:`None` if ``path`` doesn't exist.
"""
hostname, port, path = split(path, user=user)
fs = hdfs_fs.hdfs(hostname, port)
try:
return fs.get_path_info(path)['kind']
exce... | Get the kind of item ("file" or "directory") that the path references.
Return :obj:`None` if ``path`` doesn't exist. | Below is the the instruction that describes the task:
### Input:
Get the kind of item ("file" or "directory") that the path references.
Return :obj:`None` if ``path`` doesn't exist.
### Response:
def kind(path, user=None):
"""
Get the kind of item ("file" or "directory") that the path references.
... |
def delete(self, msg, claim_id=None):
"""
Deletes the specified message from its queue. If the message has been
claimed, the ID of that claim must be passed as the 'claim_id'
parameter.
"""
msg_id = utils.get_id(msg)
if claim_id:
uri = "/%s/%s?claim_id... | Deletes the specified message from its queue. If the message has been
claimed, the ID of that claim must be passed as the 'claim_id'
parameter. | Below is the the instruction that describes the task:
### Input:
Deletes the specified message from its queue. If the message has been
claimed, the ID of that claim must be passed as the 'claim_id'
parameter.
### Response:
def delete(self, msg, claim_id=None):
"""
Deletes the specif... |
def plot_ellipsoid(hessian, center, lattice=None, rescale=1.0, ax=None,
coords_are_cartesian=False, arrows=False, **kwargs):
"""
Plots a 3D ellipsoid rappresenting the Hessian matrix in input.
Useful to get a graphical visualization of the effective mass
of a band in a single k-point.... | Plots a 3D ellipsoid rappresenting the Hessian matrix in input.
Useful to get a graphical visualization of the effective mass
of a band in a single k-point.
Args:
hessian: the Hessian matrix
center: the center of the ellipsoid in reciprocal coords (Default)
lattice: Lattice obje... | Below is the the instruction that describes the task:
### Input:
Plots a 3D ellipsoid rappresenting the Hessian matrix in input.
Useful to get a graphical visualization of the effective mass
of a band in a single k-point.
Args:
hessian: the Hessian matrix
center: the center of the e... |
def search_song(self, title, artist="", get_full_info=True):
""" Search Genius.com for lyrics to a specific song
:param title: Song title to search for
:param artist: Name of the artist
:param get_full_info: Get full info for each song (slower)
"""
# Search the Genius AP... | Search Genius.com for lyrics to a specific song
:param title: Song title to search for
:param artist: Name of the artist
:param get_full_info: Get full info for each song (slower) | Below is the the instruction that describes the task:
### Input:
Search Genius.com for lyrics to a specific song
:param title: Song title to search for
:param artist: Name of the artist
:param get_full_info: Get full info for each song (slower)
### Response:
def search_song(self, title, art... |
def total_regular_pixels_from_mask(mask):
"""Compute the total number of unmasked regular pixels in a masks."""
total_regular_pixels = 0
for y in range(mask.shape[0]):
for x in range(mask.shape[1]):
if not mask[y, x]:
total_regular_pixels += 1
return total_regular_... | Compute the total number of unmasked regular pixels in a masks. | Below is the the instruction that describes the task:
### Input:
Compute the total number of unmasked regular pixels in a masks.
### Response:
def total_regular_pixels_from_mask(mask):
"""Compute the total number of unmasked regular pixels in a masks."""
total_regular_pixels = 0
for y in range(mask.s... |
def filter_by_user(self, user):
"""All filters that should be displayed to a user (by users/group)"""
return self.filter(Q(users=user) | Q(groups__in=user.groups.all())) | All filters that should be displayed to a user (by users/group) | Below is the the instruction that describes the task:
### Input:
All filters that should be displayed to a user (by users/group)
### Response:
def filter_by_user(self, user):
"""All filters that should be displayed to a user (by users/group)"""
return self.filter(Q(users=user) | Q(groups__in=user.... |
def p_dynamic_class_name_reference(p):
'''dynamic_class_name_reference : base_variable OBJECT_OPERATOR object_property dynamic_class_name_variable_properties
| base_variable'''
if len(p) == 5:
name, dims = p[3]
p[0] = ast.ObjectProperty(p[1], name, lineno=p.li... | dynamic_class_name_reference : base_variable OBJECT_OPERATOR object_property dynamic_class_name_variable_properties
| base_variable | Below is the the instruction that describes the task:
### Input:
dynamic_class_name_reference : base_variable OBJECT_OPERATOR object_property dynamic_class_name_variable_properties
| base_variable
### Response:
def p_dynamic_class_name_reference(p):
'''dynamic_class_name_ref... |
def get(self, cluster, environ, topology):
'''
:param cluster:
:param environ:
:param topology:
:return:
'''
# pylint: disable=no-member
options = dict(
cluster=cluster,
environ=environ,
topology=topology,
active="topologies",
function=common.class... | :param cluster:
:param environ:
:param topology:
:return: | Below is the the instruction that describes the task:
### Input:
:param cluster:
:param environ:
:param topology:
:return:
### Response:
def get(self, cluster, environ, topology):
'''
:param cluster:
:param environ:
:param topology:
:return:
'''
# pylint: disable=no-member
... |
def build_event_graph(graph, tree, node):
"""Return a DiGraph of a specific event structure, built recursively"""
# If we have already added this node then let's return
if node_key(node) in graph:
return
type = get_type(node)
text = get_text(node)
label = '%s (%s)' % (type, text)
gra... | Return a DiGraph of a specific event structure, built recursively | Below is the the instruction that describes the task:
### Input:
Return a DiGraph of a specific event structure, built recursively
### Response:
def build_event_graph(graph, tree, node):
"""Return a DiGraph of a specific event structure, built recursively"""
# If we have already added this node then let's ... |
def minibatches(inputs=None, targets=None, batch_size=None, allow_dynamic_batch_size=False, shuffle=False):
"""Generate a generator that input a group of example in numpy.array and
their labels, return the examples and labels by the given batch size.
Parameters
----------
inputs : numpy.array
... | Generate a generator that input a group of example in numpy.array and
their labels, return the examples and labels by the given batch size.
Parameters
----------
inputs : numpy.array
The input features, every row is a example.
targets : numpy.array
The labels of inputs, every row is... | Below is the the instruction that describes the task:
### Input:
Generate a generator that input a group of example in numpy.array and
their labels, return the examples and labels by the given batch size.
Parameters
----------
inputs : numpy.array
The input features, every row is a example.... |
def backup_emulate(self, insn):
"""
If we could not handle emulating an instruction, use Unicorn to emulate
it.
:param capstone.CsInsn instruction: The instruction object to emulate
"""
if not hasattr(self, 'backup_emu'):
self.backup_emu = UnicornEmulator(se... | If we could not handle emulating an instruction, use Unicorn to emulate
it.
:param capstone.CsInsn instruction: The instruction object to emulate | Below is the the instruction that describes the task:
### Input:
If we could not handle emulating an instruction, use Unicorn to emulate
it.
:param capstone.CsInsn instruction: The instruction object to emulate
### Response:
def backup_emulate(self, insn):
"""
If we could not handl... |
def getDataRowCount(self):
"""
Iterates through stream to calculate total records after aggregation.
This will alter the bookmark state.
"""
inputRowCountAfterAggregation = 0
while True:
record = self.getNextRecord()
if record is None:
return inputRowCountAfterAggregation
... | Iterates through stream to calculate total records after aggregation.
This will alter the bookmark state. | Below is the the instruction that describes the task:
### Input:
Iterates through stream to calculate total records after aggregation.
This will alter the bookmark state.
### Response:
def getDataRowCount(self):
"""
Iterates through stream to calculate total records after aggregation.
This will alt... |
def claim_messages(self, queue, ttl, grace, count=None):
"""
Claims up to `count` unclaimed messages from the specified queue. If
count is not specified, the default is to claim 10 messages.
The `ttl` parameter specifies how long the server should wait before
releasing the claim... | Claims up to `count` unclaimed messages from the specified queue. If
count is not specified, the default is to claim 10 messages.
The `ttl` parameter specifies how long the server should wait before
releasing the claim. The ttl value MUST be between 60 and 43200 seconds.
The `grace` pa... | Below is the the instruction that describes the task:
### Input:
Claims up to `count` unclaimed messages from the specified queue. If
count is not specified, the default is to claim 10 messages.
The `ttl` parameter specifies how long the server should wait before
releasing the claim. The tt... |
def environ(request: httputil.HTTPServerRequest) -> Dict[Text, Any]:
"""Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment.
"""
hostport = request.host.split(":")
if len(hostport) == 2:
host = hostport[0]
port = int(hostport[1])
else:
... | Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment. | Below is the the instruction that describes the task:
### Input:
Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment.
### Response:
def environ(request: httputil.HTTPServerRequest) -> Dict[Text, Any]:
"""Converts a `tornado.httputil.HTTPServerRequest` to a WSGI environment.
"""
... |
def download_and_run(config):
'''
Main operation of the executor.
Returns True when a job was downloaded and executed.
Returns False when no job could be downloaded.
'''
job = fetch_job(config)
if job:
job._run_validate()
return True
else:
return False | Main operation of the executor.
Returns True when a job was downloaded and executed.
Returns False when no job could be downloaded. | Below is the the instruction that describes the task:
### Input:
Main operation of the executor.
Returns True when a job was downloaded and executed.
Returns False when no job could be downloaded.
### Response:
def download_and_run(config):
'''
Main operation of the executor.
Returns True whe... |
def posterior_to_xarray(self):
"""Extract posterior samples from fit."""
posterior = self.posterior
posterior_model = self.posterior_model
# filter posterior_predictive and log_likelihood
posterior_predictive = self.posterior_predictive
if posterior_predictive is No... | Extract posterior samples from fit. | Below is the the instruction that describes the task:
### Input:
Extract posterior samples from fit.
### Response:
def posterior_to_xarray(self):
"""Extract posterior samples from fit."""
posterior = self.posterior
posterior_model = self.posterior_model
# filter posterior_predic... |
def dockerCheckOutput(*args, **kwargs):
"""
Deprecated. Runs subprocessDockerCall() using 'subprocess.check_output()'.
Provided for backwards compatibility with a previous implementation that
used 'subprocess.check_output()'. This has since been supplanted and
apiDockerCall() is recommended.
... | Deprecated. Runs subprocessDockerCall() using 'subprocess.check_output()'.
Provided for backwards compatibility with a previous implementation that
used 'subprocess.check_output()'. This has since been supplanted and
apiDockerCall() is recommended. | Below is the the instruction that describes the task:
### Input:
Deprecated. Runs subprocessDockerCall() using 'subprocess.check_output()'.
Provided for backwards compatibility with a previous implementation that
used 'subprocess.check_output()'. This has since been supplanted and
apiDockerCall() is ... |
def init_cli_human(self):
"""
Send post_cli_cmds to dut
:return: Nothing
"""
if self.post_cli_cmds is None:
self.post_cli_cmds = self.set_default_init_cli_human_cmds()
for cli_cmd in self.post_cli_cmds:
try:
if isinstance(cli_cmd, ... | Send post_cli_cmds to dut
:return: Nothing | Below is the the instruction that describes the task:
### Input:
Send post_cli_cmds to dut
:return: Nothing
### Response:
def init_cli_human(self):
"""
Send post_cli_cmds to dut
:return: Nothing
"""
if self.post_cli_cmds is None:
self.post_cli_cmds = se... |
def max(self):
"""Return the maximum value in this histogram.
If there are no values in the histogram at all, return 600.
Returns:
int: The maximum value in the histogram.
"""
if len(self._data) == 0:
return 600
return next(iter(reversed(sorted(s... | Return the maximum value in this histogram.
If there are no values in the histogram at all, return 600.
Returns:
int: The maximum value in the histogram. | Below is the the instruction that describes the task:
### Input:
Return the maximum value in this histogram.
If there are no values in the histogram at all, return 600.
Returns:
int: The maximum value in the histogram.
### Response:
def max(self):
"""Return the maximum value i... |
def records(self, part=None, fallback=True):
"""Return an iterator over the records in the pack.
Each record is supplied as a namedtuple with the channel names
as field names. This is useful if each record make a meaningful
data set on its own.
part: int or None
Sam... | Return an iterator over the records in the pack.
Each record is supplied as a namedtuple with the channel names
as field names. This is useful if each record make a meaningful
data set on its own.
part: int or None
Same meaning as in
:meth:`~channelpack.ChannelP... | Below is the the instruction that describes the task:
### Input:
Return an iterator over the records in the pack.
Each record is supplied as a namedtuple with the channel names
as field names. This is useful if each record make a meaningful
data set on its own.
part: int or None
... |
def init_app(self, app):
"""Flask application initialization.
Initialize the UI endpoints. Connect all signals if
`DEPOSIT_REGISTER_SIGNALS` is ``True``.
:param app: An instance of :class:`flask.Flask`.
"""
self.init_config(app)
app.register_blueprint(ui.create... | Flask application initialization.
Initialize the UI endpoints. Connect all signals if
`DEPOSIT_REGISTER_SIGNALS` is ``True``.
:param app: An instance of :class:`flask.Flask`. | Below is the the instruction that describes the task:
### Input:
Flask application initialization.
Initialize the UI endpoints. Connect all signals if
`DEPOSIT_REGISTER_SIGNALS` is ``True``.
:param app: An instance of :class:`flask.Flask`.
### Response:
def init_app(self, app):
"... |
def handle_stderr(stderr_pipe):
"""
Takes stderr from the command's output and displays it AFTER the stdout
is printed by run_command().
"""
stderr_output = stderr_pipe.read()
if len(stderr_output) > 0:
click.secho("\n__ Error Output {0}".format('_'*62), fg='white',
... | Takes stderr from the command's output and displays it AFTER the stdout
is printed by run_command(). | Below is the the instruction that describes the task:
### Input:
Takes stderr from the command's output and displays it AFTER the stdout
is printed by run_command().
### Response:
def handle_stderr(stderr_pipe):
"""
Takes stderr from the command's output and displays it AFTER the stdout
is printed ... |
def message_iter(evt):
""" provide a message iterator which checks for a response error prior to returning """
for msg in evt:
if logger.isEnabledFor(log.logging.DEBUG):
logger.debug(msg.toString())
if msg.asElement().hasElement('responseError'):
r... | provide a message iterator which checks for a response error prior to returning | Below is the the instruction that describes the task:
### Input:
provide a message iterator which checks for a response error prior to returning
### Response:
def message_iter(evt):
""" provide a message iterator which checks for a response error prior to returning """
for msg in evt:
i... |
def parse_mapreduce_yaml(contents):
"""Parses mapreduce.yaml file contents.
Args:
contents: mapreduce.yaml file contents.
Returns:
MapReduceYaml object with all the data from original file.
Raises:
errors.BadYamlError: when contents is not a valid mapreduce.yaml file.
"""
try:
builder = y... | Parses mapreduce.yaml file contents.
Args:
contents: mapreduce.yaml file contents.
Returns:
MapReduceYaml object with all the data from original file.
Raises:
errors.BadYamlError: when contents is not a valid mapreduce.yaml file. | Below is the the instruction that describes the task:
### Input:
Parses mapreduce.yaml file contents.
Args:
contents: mapreduce.yaml file contents.
Returns:
MapReduceYaml object with all the data from original file.
Raises:
errors.BadYamlError: when contents is not a valid mapreduce.yaml file.
... |
def fail(self, msg, lineno=None, exc=TemplateSyntaxError):
"""Convenience method that raises `exc` with the message, passed
line number or last line number as well as the current name and
filename.
"""
if lineno is None:
lineno = self.stream.current.lineno
rai... | Convenience method that raises `exc` with the message, passed
line number or last line number as well as the current name and
filename. | Below is the the instruction that describes the task:
### Input:
Convenience method that raises `exc` with the message, passed
line number or last line number as well as the current name and
filename.
### Response:
def fail(self, msg, lineno=None, exc=TemplateSyntaxError):
"""Convenience me... |
def hold_exception(method):
"""Decorator for glib callback methods of GLibMainLoop used to store the
exception raised."""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
"""Wrapper for methods decorated with `hold_exception`."""
# pylint: disable=W0703,W0212
try:
... | Decorator for glib callback methods of GLibMainLoop used to store the
exception raised. | Below is the the instruction that describes the task:
### Input:
Decorator for glib callback methods of GLibMainLoop used to store the
exception raised.
### Response:
def hold_exception(method):
"""Decorator for glib callback methods of GLibMainLoop used to store the
exception raised."""
@functools... |
def chunk(self, size):
"""
Chunk the underlying collection.
:param size: The chunk size
:type size: int
:rtype: Collection
"""
chunks = self._chunk(size)
return self.__class__(list(map(self.__class__, chunks))) | Chunk the underlying collection.
:param size: The chunk size
:type size: int
:rtype: Collection | Below is the the instruction that describes the task:
### Input:
Chunk the underlying collection.
:param size: The chunk size
:type size: int
:rtype: Collection
### Response:
def chunk(self, size):
"""
Chunk the underlying collection.
:param size: The chunk size
... |
def verboselogs_class_transform(cls):
"""Make Pylint aware of our custom logger methods."""
if cls.name == 'RootLogger':
for meth in ['notice', 'spam', 'success', 'verbose']:
cls.locals[meth] = [scoped_nodes.Function(meth, None)] | Make Pylint aware of our custom logger methods. | Below is the the instruction that describes the task:
### Input:
Make Pylint aware of our custom logger methods.
### Response:
def verboselogs_class_transform(cls):
"""Make Pylint aware of our custom logger methods."""
if cls.name == 'RootLogger':
for meth in ['notice', 'spam', 'success', 'verbose'... |
def generate_shared_public_key(my_private_key, their_public_pair, generator):
"""
Two parties each generate a private key and share their public key with the
other party over an insecure channel. The shared public key can be generated by
either side, but not by eavesdroppers. You can then use the entrop... | Two parties each generate a private key and share their public key with the
other party over an insecure channel. The shared public key can be generated by
either side, but not by eavesdroppers. You can then use the entropy from the
shared public key to created a common symmetric key for encryption. (This
... | Below is the the instruction that describes the task:
### Input:
Two parties each generate a private key and share their public key with the
other party over an insecure channel. The shared public key can be generated by
either side, but not by eavesdroppers. You can then use the entropy from the
shared... |
def _get_obs_array(self, k, use_raw=False, layer='X'):
"""Get an array from the layer (default layer='X') along the observation dimension by first looking up
obs.keys and then var.index."""
in_raw_var_names = k in self.raw.var_names if self.raw is not None else False
if use_raw and self... | Get an array from the layer (default layer='X') along the observation dimension by first looking up
obs.keys and then var.index. | Below is the the instruction that describes the task:
### Input:
Get an array from the layer (default layer='X') along the observation dimension by first looking up
obs.keys and then var.index.
### Response:
def _get_obs_array(self, k, use_raw=False, layer='X'):
"""Get an array from the layer (defa... |
def _debug_on():
"""
Turns on debugging by creating hidden tmp file
This is only run by the __main__ engine.
"""
## make tmp file and set loglevel for top-level init
with open(__debugflag__, 'w') as dfile:
dfile.write("wat")
__loglevel__ = "DEBUG"
_LOGGER.info("debugging turned o... | Turns on debugging by creating hidden tmp file
This is only run by the __main__ engine. | Below is the the instruction that describes the task:
### Input:
Turns on debugging by creating hidden tmp file
This is only run by the __main__ engine.
### Response:
def _debug_on():
"""
Turns on debugging by creating hidden tmp file
This is only run by the __main__ engine.
"""
## make tmp... |
def poisson_source(rate, iterable, target):
"""Send events at random times with uniform probability.
Args:
rate: The average number of events to send per second.
iterable: A series of items which will be sent to the target one by one.
target: The target coroutine or sink.
Returns:
... | Send events at random times with uniform probability.
Args:
rate: The average number of events to send per second.
iterable: A series of items which will be sent to the target one by one.
target: The target coroutine or sink.
Returns:
An iterator over any remaining items. | Below is the the instruction that describes the task:
### Input:
Send events at random times with uniform probability.
Args:
rate: The average number of events to send per second.
iterable: A series of items which will be sent to the target one by one.
target: The target coroutine or si... |
def exception(self):
"""
The exception that occured while the job executed. The value is #None if
no exception occurred.
# Raises
InvalidState: If the job is #PENDING or #RUNNING.
"""
if self.__state in (Job.PENDING, Job.RUNNING):
raise self.InvalidState('job is {0}'.format(self.__st... | The exception that occured while the job executed. The value is #None if
no exception occurred.
# Raises
InvalidState: If the job is #PENDING or #RUNNING. | Below is the the instruction that describes the task:
### Input:
The exception that occured while the job executed. The value is #None if
no exception occurred.
# Raises
InvalidState: If the job is #PENDING or #RUNNING.
### Response:
def exception(self):
"""
The exception that occured while th... |
def _log(func):
"""
Function for logging method calls and parameters
"""
@wraps(func)
def wrapper(self, *args, **kwargs):
a = func(self, *args, **kwargs)
self.log.append(func.__name__ + ' :: args={} kwargs={}'.format(args, kwargs))
return a
return wrapper | Function for logging method calls and parameters | Below is the the instruction that describes the task:
### Input:
Function for logging method calls and parameters
### Response:
def _log(func):
"""
Function for logging method calls and parameters
"""
@wraps(func)
def wrapper(self, *args, **kwargs):
a = func(self, *args, **kwargs)
... |
def to_xml(self):
"""Creates an ``ET.Element`` representing self, then returns it.
:returns root, an ``ET.Element`` representing this scheme.
"""
root = ET.Element("scheme")
ET.SubElement(root, "title").text = self.title
# add a description subelement if it's defined
... | Creates an ``ET.Element`` representing self, then returns it.
:returns root, an ``ET.Element`` representing this scheme. | Below is the the instruction that describes the task:
### Input:
Creates an ``ET.Element`` representing self, then returns it.
:returns root, an ``ET.Element`` representing this scheme.
### Response:
def to_xml(self):
"""Creates an ``ET.Element`` representing self, then returns it.
:retur... |
def _check_xl_path(xl_path: str):
""" Return the expanded absolute path of `xl_path` if
if exists and 'xlrd' or 'openpyxl' depending on
which module should be used for the Excel file in `xl_path`.
Parameters
----------
xl_path: str
Path to an Excel file
Returns
-------
xl_p... | Return the expanded absolute path of `xl_path` if
if exists and 'xlrd' or 'openpyxl' depending on
which module should be used for the Excel file in `xl_path`.
Parameters
----------
xl_path: str
Path to an Excel file
Returns
-------
xl_path: str
User expanded and absolut... | Below is the the instruction that describes the task:
### Input:
Return the expanded absolute path of `xl_path` if
if exists and 'xlrd' or 'openpyxl' depending on
which module should be used for the Excel file in `xl_path`.
Parameters
----------
xl_path: str
Path to an Excel file
R... |
def print_table(self, items, fields):
""" print a table of items, for a set of fields defined
Parameters
==========
items: a list of items to print
fields: a list of fields to select from items
"""
formats = []
borders = []
for f i... | print a table of items, for a set of fields defined
Parameters
==========
items: a list of items to print
fields: a list of fields to select from items | Below is the the instruction that describes the task:
### Input:
print a table of items, for a set of fields defined
Parameters
==========
items: a list of items to print
fields: a list of fields to select from items
### Response:
def print_table(self, items, fields... |
def find_occurrences(project, resource, offset, unsure=False, resources=None,
in_hierarchy=False,
task_handle=taskhandle.NullTaskHandle()):
"""Return a list of `Location`\s
If `unsure` is `True`, possible matches are returned, too. You
can use `Location.unsure` to... | Return a list of `Location`\s
If `unsure` is `True`, possible matches are returned, too. You
can use `Location.unsure` to see which are unsure occurrences.
`resources` can be a list of `rope.base.resource.File`\s that
should be searched for occurrences; if `None` all python files
in the project ar... | Below is the the instruction that describes the task:
### Input:
Return a list of `Location`\s
If `unsure` is `True`, possible matches are returned, too. You
can use `Location.unsure` to see which are unsure occurrences.
`resources` can be a list of `rope.base.resource.File`\s that
should be searc... |
def get_function(self, fn_name):
"""Compile the code, and return the function `fn_name`."""
assert self.indent_amount == 0
g = {}
code_text = str(self)
exec(code_text, g)
return g[fn_name] | Compile the code, and return the function `fn_name`. | Below is the the instruction that describes the task:
### Input:
Compile the code, and return the function `fn_name`.
### Response:
def get_function(self, fn_name):
"""Compile the code, and return the function `fn_name`."""
assert self.indent_amount == 0
g = {}
code_text = str(self)... |
def main():
"""Upgrades the firmware of the J-Links connected to a Windows device.
Returns:
None.
Raises:
OSError: if there are no J-Link software packages.
"""
windows_libraries = list(pylink.Library.find_library_windows())
latest_library = None
for lib in windows_libraries:
... | Upgrades the firmware of the J-Links connected to a Windows device.
Returns:
None.
Raises:
OSError: if there are no J-Link software packages. | Below is the the instruction that describes the task:
### Input:
Upgrades the firmware of the J-Links connected to a Windows device.
Returns:
None.
Raises:
OSError: if there are no J-Link software packages.
### Response:
def main():
"""Upgrades the firmware of the J-Links connected to a W... |
def find_jobs(self, job_ids):
"""Finds the jobs in the completed job queue."""
matched_jobs = []
if self.skip:
return matched_jobs
json_data = self.download_queue(job_ids)
if not json_data:
return matched_jobs
jobs = json_data["jobs"]
for... | Finds the jobs in the completed job queue. | Below is the the instruction that describes the task:
### Input:
Finds the jobs in the completed job queue.
### Response:
def find_jobs(self, job_ids):
"""Finds the jobs in the completed job queue."""
matched_jobs = []
if self.skip:
return matched_jobs
json_data = self.... |
def gtype(n):
"""
Return the a string with the data type of a value, for Graph data
"""
t = type(n).__name__
return str(t) if t != 'Literal' else 'Literal, {}'.format(n.language) | Return the a string with the data type of a value, for Graph data | Below is the the instruction that describes the task:
### Input:
Return the a string with the data type of a value, for Graph data
### Response:
def gtype(n):
"""
Return the a string with the data type of a value, for Graph data
"""
t = type(n).__name__
return str(t) if t != 'Literal' else 'Lit... |
def set_room_alias(self, room_id, room_alias):
"""Set alias to room id
Args:
room_id (str): The room id.
room_alias (str): The room wanted alias name.
"""
data = {
"room_id": room_id
}
return self._send("PUT", "/directory/room/{}".for... | Set alias to room id
Args:
room_id (str): The room id.
room_alias (str): The room wanted alias name. | Below is the the instruction that describes the task:
### Input:
Set alias to room id
Args:
room_id (str): The room id.
room_alias (str): The room wanted alias name.
### Response:
def set_room_alias(self, room_id, room_alias):
"""Set alias to room id
Args:
... |
def __load_dump(self, message):
"""
Calls the hook method to modify the loaded peer description before
giving it to the directory
:param message: The received Herald message
:return: The updated peer description
"""
dump = message.content
if self._hook is... | Calls the hook method to modify the loaded peer description before
giving it to the directory
:param message: The received Herald message
:return: The updated peer description | Below is the the instruction that describes the task:
### Input:
Calls the hook method to modify the loaded peer description before
giving it to the directory
:param message: The received Herald message
:return: The updated peer description
### Response:
def __load_dump(self, message):
... |
def extend_children(self, parent, wanted_children, child_class, child_glossary=None):
"""
Extend the number of children so that the parent object contains wanted children.
No child will be removed if wanted_children is smaller than the current number of children.
"""
from cms.api... | Extend the number of children so that the parent object contains wanted children.
No child will be removed if wanted_children is smaller than the current number of children. | Below is the the instruction that describes the task:
### Input:
Extend the number of children so that the parent object contains wanted children.
No child will be removed if wanted_children is smaller than the current number of children.
### Response:
def extend_children(self, parent, wanted_children, chi... |
def to_python(self,value):
"""
Validates that the value is in self.choices and can be coerced to the right type.
"""
if value==self.emptyValue or value in EMPTY_VALUES:
return self.emptyValue
try:
value=self.coerce(value)
except(ValueErro... | Validates that the value is in self.choices and can be coerced to the right type. | Below is the the instruction that describes the task:
### Input:
Validates that the value is in self.choices and can be coerced to the right type.
### Response:
def to_python(self,value):
"""
Validates that the value is in self.choices and can be coerced to the right type.
"""
i... |
def end_log_output(self, **kwargs):
"""Print ending output to log."""
kwargs.update(dict(
downloaded_bytes=self.downloaded_bytes,
num_urls = len(self.result_cache),
))
self.logger.end_log_output(**kwargs) | Print ending output to log. | Below is the the instruction that describes the task:
### Input:
Print ending output to log.
### Response:
def end_log_output(self, **kwargs):
"""Print ending output to log."""
kwargs.update(dict(
downloaded_bytes=self.downloaded_bytes,
num_urls = len(self.result_cache),
... |
def find_xi_extrema_brute(xis, bestMasses, bestXis, direction_num, req_match, \
massRangeParams, metricParams, fUpper, \
find_minimum=False, scaleFactor=0.8, \
numIterations=3000):
"""
This function is used to find the largest or s... | This function is used to find the largest or smallest value of the xi
space in a specified
dimension at a specified point in the higher dimensions. It does this by
iteratively throwing points at the space to find extrema.
Parameters
-----------
xis : list or array
Position in the xi sp... | Below is the the instruction that describes the task:
### Input:
This function is used to find the largest or smallest value of the xi
space in a specified
dimension at a specified point in the higher dimensions. It does this by
iteratively throwing points at the space to find extrema.
Parameters
... |
def delete_multi(self, keys, time=0, key_prefix=''):
'''
Delete multiple keys in the memcache doing just one query.
>>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'})
>>> mc.get_multi(['key1', 'key2']) == {'key1' : 'val1', 'key2' : 'val2'}
1
>>> mc.delete... | Delete multiple keys in the memcache doing just one query.
>>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'})
>>> mc.get_multi(['key1', 'key2']) == {'key1' : 'val1', 'key2' : 'val2'}
1
>>> mc.delete_multi(['key1', 'key2'])
1
>>> mc.get_multi(['key1', 'key... | Below is the the instruction that describes the task:
### Input:
Delete multiple keys in the memcache doing just one query.
>>> notset_keys = mc.set_multi({'key1' : 'val1', 'key2' : 'val2'})
>>> mc.get_multi(['key1', 'key2']) == {'key1' : 'val1', 'key2' : 'val2'}
1
>>> mc.delete_mul... |
def senkou_b(data, period=52):
"""
Senkou B (Leading Span B)
Formula:
(H + L) / 2 :: default period=52 :: shifted forward 26 bars
"""
sb = conversion_base_line_helper(data, period)
shift_by = np.repeat(np.nan, 26)
sb = np.append(shift_by, sb)
return sb | Senkou B (Leading Span B)
Formula:
(H + L) / 2 :: default period=52 :: shifted forward 26 bars | Below is the the instruction that describes the task:
### Input:
Senkou B (Leading Span B)
Formula:
(H + L) / 2 :: default period=52 :: shifted forward 26 bars
### Response:
def senkou_b(data, period=52):
"""
Senkou B (Leading Span B)
Formula:
(H + L) / 2 :: default period=52 :: shifted... |
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
# this callback is used to prevent an auto-migration from being generated
# when there are no changes to the schema
# reference: h... | Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context. | Below is the the instruction that describes the task:
### Input:
Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
### Response:
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to cr... |
def _update_exit_code_from_error(self, error):
'''Set the exit code based on the error type.
Args:
error (:class:`Exception`): An exception instance.
'''
for error_type, exit_code in self.ERROR_CODE_MAP.items():
if isinstance(error, error_type):
s... | Set the exit code based on the error type.
Args:
error (:class:`Exception`): An exception instance. | Below is the the instruction that describes the task:
### Input:
Set the exit code based on the error type.
Args:
error (:class:`Exception`): An exception instance.
### Response:
def _update_exit_code_from_error(self, error):
'''Set the exit code based on the error type.
Args:... |
def process_exception(self, request, exception):
"""
Disconnects the signal receiver to prevent it from staying active in case of an exception.
"""
if hasattr(threadlocal, 'actionslog'):
pre_save.disconnect(sender=LogAction, dispatch_uid=threadlocal.actionslog['signal_duid'])... | Disconnects the signal receiver to prevent it from staying active in case of an exception. | Below is the the instruction that describes the task:
### Input:
Disconnects the signal receiver to prevent it from staying active in case of an exception.
### Response:
def process_exception(self, request, exception):
"""
Disconnects the signal receiver to prevent it from staying active in case of... |
def auto_type(s):
""" Get a XML response and tries to convert it to Python base object
"""
if isinstance(s, bool):
return s
elif s is None:
return ''
elif s == 'TRUE':
return True
elif s == 'FALSE':
return False
else:
try:
try:
... | Get a XML response and tries to convert it to Python base object | Below is the the instruction that describes the task:
### Input:
Get a XML response and tries to convert it to Python base object
### Response:
def auto_type(s):
""" Get a XML response and tries to convert it to Python base object
"""
if isinstance(s, bool):
return s
elif s is None:
... |
def _compute_B_statistics(self, K, W, log_concave, *args, **kwargs):
"""
Rasmussen suggests the use of a numerically stable positive definite matrix B
Which has a positive diagonal element and can be easyily inverted
:param K: Prior Covariance matrix evaluated at locations X
:ty... | Rasmussen suggests the use of a numerically stable positive definite matrix B
Which has a positive diagonal element and can be easyily inverted
:param K: Prior Covariance matrix evaluated at locations X
:type K: NxN matrix
:param W: Negative hessian at a point (diagonal matrix)
... | Below is the the instruction that describes the task:
### Input:
Rasmussen suggests the use of a numerically stable positive definite matrix B
Which has a positive diagonal element and can be easyily inverted
:param K: Prior Covariance matrix evaluated at locations X
:type K: NxN matrix
... |
def _generate_consumer_tag(self):
"""Generate a unique consumer tag.
:rtype string:
"""
return "%s.%s%s" % (
self.__class__.__module__,
self.__class__.__name__,
self._next_consumer_tag()) | Generate a unique consumer tag.
:rtype string: | Below is the the instruction that describes the task:
### Input:
Generate a unique consumer tag.
:rtype string:
### Response:
def _generate_consumer_tag(self):
"""Generate a unique consumer tag.
:rtype string:
"""
return "%s.%s%s" % (
self.__class__.__modu... |
def to_skycoord(self, unit=None):
"""Convert this distance to an AstroPy ``SkyCoord`` object."""
from astropy.coordinates import SkyCoord
from astropy.units import au
x, y, z = self.position.au
return SkyCoord(representation='cartesian', x=x, y=y, z=z, unit=au) | Convert this distance to an AstroPy ``SkyCoord`` object. | Below is the the instruction that describes the task:
### Input:
Convert this distance to an AstroPy ``SkyCoord`` object.
### Response:
def to_skycoord(self, unit=None):
"""Convert this distance to an AstroPy ``SkyCoord`` object."""
from astropy.coordinates import SkyCoord
from astropy.unit... |
def set_genus_type(self, genus_type):
"""Sets a genus.
A genus cannot be cleared because all objects have at minimum a
root genus.
arg: genus_type (osid.type.Type): the new genus
raise: InvalidArgument - ``genus_type`` is invalid
raise: NoAccess - ``Metadata.isRead... | Sets a genus.
A genus cannot be cleared because all objects have at minimum a
root genus.
arg: genus_type (osid.type.Type): the new genus
raise: InvalidArgument - ``genus_type`` is invalid
raise: NoAccess - ``Metadata.isReadonly()`` is ``true``
raise: NullArgument... | Below is the the instruction that describes the task:
### Input:
Sets a genus.
A genus cannot be cleared because all objects have at minimum a
root genus.
arg: genus_type (osid.type.Type): the new genus
raise: InvalidArgument - ``genus_type`` is invalid
raise: NoAccess... |
def post_send_process(context):
"""
Task to ensure subscription is bumped or converted
"""
if "error" in context:
return context
[deserialized_subscription] = serializers.deserialize(
"json", context["subscription"]
)
subscription = deserialized_subscription.object
[mess... | Task to ensure subscription is bumped or converted | Below is the the instruction that describes the task:
### Input:
Task to ensure subscription is bumped or converted
### Response:
def post_send_process(context):
"""
Task to ensure subscription is bumped or converted
"""
if "error" in context:
return context
[deserialized_subscription]... |
def retrieveVals(self):
"""Retrieve values for graphs."""
if self._diskList:
self._fetchDevAll('disk', self._diskList,
self._info.getDiskStats)
if self._mdList:
self._fetchDevAll('md', self._mdList,
self._info.... | Retrieve values for graphs. | Below is the the instruction that describes the task:
### Input:
Retrieve values for graphs.
### Response:
def retrieveVals(self):
"""Retrieve values for graphs."""
if self._diskList:
self._fetchDevAll('disk', self._diskList,
self._info.getDiskStats)
... |
def get_long_query(self, base_object_query, limit_to=100, max_calls=None,
start_record=0, verbose=False):
"""
Takes a base query for all objects and recursively requests them
:param str base_object_query: the base query to be executed
:param int limit_to: how many... | Takes a base query for all objects and recursively requests them
:param str base_object_query: the base query to be executed
:param int limit_to: how many rows to query for in each chunk
:param int max_calls: the max calls(chunks to request) None is infinite
:param int start_record: the... | Below is the the instruction that describes the task:
### Input:
Takes a base query for all objects and recursively requests them
:param str base_object_query: the base query to be executed
:param int limit_to: how many rows to query for in each chunk
:param int max_calls: the max calls(chu... |
def currency_iso_code(self, allow_random: bool = False) -> str:
"""Get code of the currency for current locale.
:param allow_random: Get a random ISO code.
:return: Currency code.
"""
if allow_random:
return self.random.choice(CURRENCY_ISO_CODES)
else:
... | Get code of the currency for current locale.
:param allow_random: Get a random ISO code.
:return: Currency code. | Below is the the instruction that describes the task:
### Input:
Get code of the currency for current locale.
:param allow_random: Get a random ISO code.
:return: Currency code.
### Response:
def currency_iso_code(self, allow_random: bool = False) -> str:
"""Get code of the currency for cu... |
def invalidate(self, *paths):
"""
Issues invalidation requests to a Cloudfront distribution
for the current static media bucket, triggering it to reload the specified
paths from the origin.
Note, only 1000 paths can be issued in a request at any one time.
"""
dj ... | Issues invalidation requests to a Cloudfront distribution
for the current static media bucket, triggering it to reload the specified
paths from the origin.
Note, only 1000 paths can be issued in a request at any one time. | Below is the the instruction that describes the task:
### Input:
Issues invalidation requests to a Cloudfront distribution
for the current static media bucket, triggering it to reload the specified
paths from the origin.
Note, only 1000 paths can be issued in a request at any one time.
### ... |
def add_to_team(self, **kw):
"""
We override this method to add our additional participation
policy groups, as detailed in available_groups above
"""
group = self.context.participant_policy.title()
data = kw.copy()
if "groups" in data:
data["groups"].a... | We override this method to add our additional participation
policy groups, as detailed in available_groups above | Below is the the instruction that describes the task:
### Input:
We override this method to add our additional participation
policy groups, as detailed in available_groups above
### Response:
def add_to_team(self, **kw):
"""
We override this method to add our additional participation
... |
def collect_overwrites_for_sid(self,
group,
dates,
requested_qtr_data,
last_per_qtr,
sid_idx,
columns,
... | Given a sid, collect all overwrites that should be applied for this
sid at each quarter boundary.
Parameters
----------
group : pd.DataFrame
The data for `sid`.
dates : pd.DatetimeIndex
The calendar dates for which estimates data is requested.
req... | Below is the the instruction that describes the task:
### Input:
Given a sid, collect all overwrites that should be applied for this
sid at each quarter boundary.
Parameters
----------
group : pd.DataFrame
The data for `sid`.
dates : pd.DatetimeIndex
... |
def draw_cloud(width=140, height=60, color=rgb(255, 255, 255)):
""" Draw a cloud with the given width, height, and color. """
cairo_color = color / rgb(255, 255, 255)
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
ctx = cairo.Context(surface)
# A cloud consists of 4 circles
... | Draw a cloud with the given width, height, and color. | Below is the the instruction that describes the task:
### Input:
Draw a cloud with the given width, height, and color.
### Response:
def draw_cloud(width=140, height=60, color=rgb(255, 255, 255)):
""" Draw a cloud with the given width, height, and color. """
cairo_color = color / rgb(255, 255, 255)
s... |
def genty(target_cls):
"""
This decorator takes the information provided by @genty_dataset,
@genty_dataprovider, and @genty_repeat and generates the corresponding
test methods.
:param target_cls:
Test class whose test methods have been decorated.
:type target_cls:
`class`
""... | This decorator takes the information provided by @genty_dataset,
@genty_dataprovider, and @genty_repeat and generates the corresponding
test methods.
:param target_cls:
Test class whose test methods have been decorated.
:type target_cls:
`class` | Below is the the instruction that describes the task:
### Input:
This decorator takes the information provided by @genty_dataset,
@genty_dataprovider, and @genty_repeat and generates the corresponding
test methods.
:param target_cls:
Test class whose test methods have been decorated.
:type ... |
def handle_exception(self, exc):
"""
Handle any exception that occurs, by returning an appropriate response,
or re-raising the error.
"""
if isinstance(exc, (exceptions.NotAuthenticated,
exceptions.AuthenticationFailed)):
# WWW-Authenticate... | Handle any exception that occurs, by returning an appropriate response,
or re-raising the error. | Below is the the instruction that describes the task:
### Input:
Handle any exception that occurs, by returning an appropriate response,
or re-raising the error.
### Response:
def handle_exception(self, exc):
"""
Handle any exception that occurs, by returning an appropriate response,
... |
def estimates(symbol, token='', version=''):
'''Provides the latest consensus estimate for the next fiscal period
https://iexcloud.io/docs/api/#estimates
Updates at 9am, 11am, 12pm UTC every day
Args:
symbol (string); Ticker to request
token (string); Access token
version (stri... | Provides the latest consensus estimate for the next fiscal period
https://iexcloud.io/docs/api/#estimates
Updates at 9am, 11am, 12pm UTC every day
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
dict: result | Below is the the instruction that describes the task:
### Input:
Provides the latest consensus estimate for the next fiscal period
https://iexcloud.io/docs/api/#estimates
Updates at 9am, 11am, 12pm UTC every day
Args:
symbol (string); Ticker to request
token (string); Access token
... |
def fromXml(xml):
"""
Creates a new walkthrough element from XML
:param xml | <xml.etree.ElementTree.Element>
:return <XWalkthrough> || None
"""
walkthrough = XWalkthrough(name=xml.get('name', ''),
ver... | Creates a new walkthrough element from XML
:param xml | <xml.etree.ElementTree.Element>
:return <XWalkthrough> || None | Below is the the instruction that describes the task:
### Input:
Creates a new walkthrough element from XML
:param xml | <xml.etree.ElementTree.Element>
:return <XWalkthrough> || None
### Response:
def fromXml(xml):
"""
Creates a new walkthrough elem... |
def draw(data, format='auto', size=(400, 300), drawing_type='ball and stick',
camera_type='perspective', shader='lambert', display_html=True,
element_properties=None, show_save=False):
"""Draws an interactive 3D visualization of the inputted chemical.
Args:
data: A string or file repr... | Draws an interactive 3D visualization of the inputted chemical.
Args:
data: A string or file representing a chemical.
format: The format of the `data` variable (default is 'auto').
size: Starting dimensions of visualization, in pixels.
drawing_type: Specifies the molecular represent... | Below is the the instruction that describes the task:
### Input:
Draws an interactive 3D visualization of the inputted chemical.
Args:
data: A string or file representing a chemical.
format: The format of the `data` variable (default is 'auto').
size: Starting dimensions of visualizatio... |
def add_accept_handler(
sock: socket.socket, callback: Callable[[socket.socket, Any], None]
) -> Callable[[], None]:
"""Adds an `.IOLoop` event handler to accept new connections on ``sock``.
When a connection is accepted, ``callback(connection, address)`` will
be run (``connection`` is a socket object,... | Adds an `.IOLoop` event handler to accept new connections on ``sock``.
When a connection is accepted, ``callback(connection, address)`` will
be run (``connection`` is a socket object, and ``address`` is the
address of the other end of the connection). Note that this signature
is different from the ``c... | Below is the the instruction that describes the task:
### Input:
Adds an `.IOLoop` event handler to accept new connections on ``sock``.
When a connection is accepted, ``callback(connection, address)`` will
be run (``connection`` is a socket object, and ``address`` is the
address of the other end of the... |
def main(args):
'''Function run when called from command line.'''
options = { '-rfft': ['resetFFTscale',False],
'-r1': ['readOneCoil',False],
'-rp': ['readPhaseCorInfo',False],
'-rn': ['readNavigator',False],
'-skipts': ['readTimeSta... | Function run when called from command line. | Below is the the instruction that describes the task:
### Input:
Function run when called from command line.
### Response:
def main(args):
'''Function run when called from command line.'''
options = { '-rfft': ['resetFFTscale',False],
'-r1': ['readOneCoil',False],
'-r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.