code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def start_worker_thread(
self,
sleep_interval=1.0):
"""start_worker_thread
Start the helper worker thread to publish queued messages
to Splunk
:param sleep_interval: sleep in seconds before reading from
the queue again
"""
... | start_worker_thread
Start the helper worker thread to publish queued messages
to Splunk
:param sleep_interval: sleep in seconds before reading from
the queue again | Below is the the instruction that describes the task:
### Input:
start_worker_thread
Start the helper worker thread to publish queued messages
to Splunk
:param sleep_interval: sleep in seconds before reading from
the queue again
### Response:
def start_worke... |
def put(self, pid, record, **kwargs):
"""Replace a record.
Permissions: ``update_permission_factory``
The body should be a JSON object, which will fully replace the current
record metadata.
Procedure description:
#. The ETag is checked.
#. The record is updat... | Replace a record.
Permissions: ``update_permission_factory``
The body should be a JSON object, which will fully replace the current
record metadata.
Procedure description:
#. The ETag is checked.
#. The record is updated by calling the record API `clear()`,
... | Below is the the instruction that describes the task:
### Input:
Replace a record.
Permissions: ``update_permission_factory``
The body should be a JSON object, which will fully replace the current
record metadata.
Procedure description:
#. The ETag is checked.
#.... |
def error_check(options):
"""
Error check
:rtype : object
"""
compare = options.compare
ensemble_paths = options.ensemble_paths
if compare and len(ensemble_paths) > 2:
print("\n Only 2 ensembles can be compared, {d} were specified\n".format(d=len(ensemble_paths)))
sys.exit(... | Error check
:rtype : object | Below is the the instruction that describes the task:
### Input:
Error check
:rtype : object
### Response:
def error_check(options):
"""
Error check
:rtype : object
"""
compare = options.compare
ensemble_paths = options.ensemble_paths
if compare and len(ensemble_paths) > 2:
... |
def divide(cls, jobs, count):
'''Divide up the provided jobs into count evenly-sized groups'''
jobs = list(zip(*zip_longest(*[iter(jobs)] * count)))
# If we had no jobs to resume, then we get an empty list
jobs = jobs or [()] * count
for index in range(count):
# Filte... | Divide up the provided jobs into count evenly-sized groups | Below is the the instruction that describes the task:
### Input:
Divide up the provided jobs into count evenly-sized groups
### Response:
def divide(cls, jobs, count):
'''Divide up the provided jobs into count evenly-sized groups'''
jobs = list(zip(*zip_longest(*[iter(jobs)] * count)))
# If... |
def _set_global_isis_info(self, v, load=False):
"""
Setter method for global_isis_info, mapped from YANG variable /isis_state/global_isis_info (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_global_isis_info is considered as a private
method. Backends loo... | Setter method for global_isis_info, mapped from YANG variable /isis_state/global_isis_info (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_global_isis_info is considered as a private
method. Backends looking to populate this variable should
do so via calling ... | Below is the the instruction that describes the task:
### Input:
Setter method for global_isis_info, mapped from YANG variable /isis_state/global_isis_info (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_global_isis_info is considered as a private
method. Bac... |
def _ParseStringOption(cls, options, argument_name, default_value=None):
"""Parses a string command line argument.
Args:
options (argparse.Namespace): parser options.
argument_name (str): name of the command line argument.
default_value (Optional[str]): default value of the command line argum... | Parses a string command line argument.
Args:
options (argparse.Namespace): parser options.
argument_name (str): name of the command line argument.
default_value (Optional[str]): default value of the command line argument.
Returns:
str: command line argument value or the default value i... | Below is the the instruction that describes the task:
### Input:
Parses a string command line argument.
Args:
options (argparse.Namespace): parser options.
argument_name (str): name of the command line argument.
default_value (Optional[str]): default value of the command line argument.
R... |
def _get_webpages(self):
"""
:rtype: list(list(str))
"""
urls = []
for child in self.vcard.getChildren():
if child.name == "URL":
urls.append(child.value)
return sorted(urls) | :rtype: list(list(str)) | Below is the the instruction that describes the task:
### Input:
:rtype: list(list(str))
### Response:
def _get_webpages(self):
"""
:rtype: list(list(str))
"""
urls = []
for child in self.vcard.getChildren():
if child.name == "URL":
urls.append(ch... |
def assign_param_names(cls=None, param_class=None):
"""Class decorator to assign parameter name to instances of :class:`Param`.
.. sourcecode::
@assign_param_names
class ConfigSectionSchema(object):
alice = Param(type=str)
bob = Param(type=str)
assert ConfigS... | Class decorator to assign parameter name to instances of :class:`Param`.
.. sourcecode::
@assign_param_names
class ConfigSectionSchema(object):
alice = Param(type=str)
bob = Param(type=str)
assert ConfigSectionSchema.alice.name == "alice"
assert ConfigSec... | Below is the the instruction that describes the task:
### Input:
Class decorator to assign parameter name to instances of :class:`Param`.
.. sourcecode::
@assign_param_names
class ConfigSectionSchema(object):
alice = Param(type=str)
bob = Param(type=str)
asse... |
def hashantijoin(left, right, key=None, lkey=None, rkey=None):
"""Alternative implementation of :func:`petl.transform.joins.antijoin`,
where the join is executed by constructing an in-memory set for all keys
found in the right hand table, then iterating over rows from the left
hand table.
May b... | Alternative implementation of :func:`petl.transform.joins.antijoin`,
where the join is executed by constructing an in-memory set for all keys
found in the right hand table, then iterating over rows from the left
hand table.
May be faster and/or more resource efficient where the right table is small... | Below is the the instruction that describes the task:
### Input:
Alternative implementation of :func:`petl.transform.joins.antijoin`,
where the join is executed by constructing an in-memory set for all keys
found in the right hand table, then iterating over rows from the left
hand table.
May be... |
def buy_on_drop(symbol_set="sp5002012",
dataobj=dataobj,
start=datetime.datetime(2008, 1, 3),
end=datetime.datetime(2009, 12, 28),
market_sym='$SPX',
threshold=6,
sell_delay=5,
):
'''Compute and display an "event profile" for mul... | Compute and display an "event profile" for multiple sets of symbols | Below is the the instruction that describes the task:
### Input:
Compute and display an "event profile" for multiple sets of symbols
### Response:
def buy_on_drop(symbol_set="sp5002012",
dataobj=dataobj,
start=datetime.datetime(2008, 1, 3),
end=datetime.datetime(2009, 12, 28)... |
def validate_query_params(self, request):
"""
Validate that query params are in the list of valid query keywords in
:py:attr:`query_regex`
:raises ValidationError: if not.
"""
# TODO: For jsonapi error object conformance, must set jsonapi errors "parameter" for
#... | Validate that query params are in the list of valid query keywords in
:py:attr:`query_regex`
:raises ValidationError: if not. | Below is the the instruction that describes the task:
### Input:
Validate that query params are in the list of valid query keywords in
:py:attr:`query_regex`
:raises ValidationError: if not.
### Response:
def validate_query_params(self, request):
"""
Validate that query params are ... |
def rectwv_coeff_from_mos_library(reduced_image,
master_rectwv,
ignore_dtu_configuration=True,
debugplot=0):
"""Evaluate rect.+wavecal. coefficients from MOS library
Parameters
----------
reduced_image... | Evaluate rect.+wavecal. coefficients from MOS library
Parameters
----------
reduced_image : HDUList object
Image with preliminary basic reduction: bpm, bias, dark and
flatfield.
master_rectwv : MasterRectWave instance
Rectification and Wavelength Calibrartion Library product.
... | Below is the the instruction that describes the task:
### Input:
Evaluate rect.+wavecal. coefficients from MOS library
Parameters
----------
reduced_image : HDUList object
Image with preliminary basic reduction: bpm, bias, dark and
flatfield.
master_rectwv : MasterRectWave instance
... |
def _hadoop_cmd(module, command, *args):
'''
Hadoop/hdfs command wrapper
As Hadoop command has been deprecated this module will default
to use hdfs command and fall back to hadoop if it is not found
In order to prevent random execution the module name is checked
Follows hadoop ... | Hadoop/hdfs command wrapper
As Hadoop command has been deprecated this module will default
to use hdfs command and fall back to hadoop if it is not found
In order to prevent random execution the module name is checked
Follows hadoop command template:
hadoop module -command args
... | Below is the the instruction that describes the task:
### Input:
Hadoop/hdfs command wrapper
As Hadoop command has been deprecated this module will default
to use hdfs command and fall back to hadoop if it is not found
In order to prevent random execution the module name is checked
Fo... |
def _pip_search(stdout, stderr):
"""Callback for pip search."""
result = {}
lines = to_text_string(stdout).split('\n')
while '' in lines:
lines.remove('')
for line in lines:
if ' - ' in line:
parts = line.split(' - ')
name ... | Callback for pip search. | Below is the the instruction that describes the task:
### Input:
Callback for pip search.
### Response:
def _pip_search(stdout, stderr):
"""Callback for pip search."""
result = {}
lines = to_text_string(stdout).split('\n')
while '' in lines:
lines.remove('')
for... |
def get_recipe_instance(self, badge):
"""
Returns the recipe instance for the given badge slug.
If badge has not been registered, raises ``exceptions.BadgeNotFound``.
"""
from .exceptions import BadgeNotFound
if badge in self._registry:
return self.recipes[bad... | Returns the recipe instance for the given badge slug.
If badge has not been registered, raises ``exceptions.BadgeNotFound``. | Below is the the instruction that describes the task:
### Input:
Returns the recipe instance for the given badge slug.
If badge has not been registered, raises ``exceptions.BadgeNotFound``.
### Response:
def get_recipe_instance(self, badge):
"""
Returns the recipe instance for the given bad... |
def process_response(self, request, response):
"""
Set compact P3P policies and save auth token to cookie.
P3P is a WC3 standard (see http://www.w3.org/TR/P3P/), and although largely ignored by most
browsers it is considered by IE before accepting third-party cookies (ie. cookies set by... | Set compact P3P policies and save auth token to cookie.
P3P is a WC3 standard (see http://www.w3.org/TR/P3P/), and although largely ignored by most
browsers it is considered by IE before accepting third-party cookies (ie. cookies set by
documents in iframes). If they are not set correctly, IE w... | Below is the the instruction that describes the task:
### Input:
Set compact P3P policies and save auth token to cookie.
P3P is a WC3 standard (see http://www.w3.org/TR/P3P/), and although largely ignored by most
browsers it is considered by IE before accepting third-party cookies (ie. cookies set ... |
def find(self,cell_designation,cell_filter=lambda x,c: 'c' in x and x['c'] == c):
"""
finds spike containers in a multi spike containers collection
"""
res = [i for i,sc in enumerate(self.spike_containers) if cell_filter(sc.meta,cell_designation)]
if len(res) > 0:
... | finds spike containers in a multi spike containers collection | Below is the the instruction that describes the task:
### Input:
finds spike containers in a multi spike containers collection
### Response:
def find(self,cell_designation,cell_filter=lambda x,c: 'c' in x and x['c'] == c):
"""
finds spike containers in a multi spike containers collection
... |
def parse_orf(insertion, gff):
"""
parse ORF to gff format
"""
offset = insertion['offset']
if type(insertion['orf']) is not str:
return gff
for orf in parse_fasta(insertion['orf'].split('|')):
ID = orf[0].split('>')[1].split()[0]
Start, End, strand = [int(i) for i in orf... | parse ORF to gff format | Below is the the instruction that describes the task:
### Input:
parse ORF to gff format
### Response:
def parse_orf(insertion, gff):
"""
parse ORF to gff format
"""
offset = insertion['offset']
if type(insertion['orf']) is not str:
return gff
for orf in parse_fasta(insertion['orf']... |
def execute_async(self, command, callback=None):
"""
Executes command on remote hosts without blocking
:type command: str
:param command: command to be run on remote host
:type callback: function
:param callback: function to call when execution completes
"""
... | Executes command on remote hosts without blocking
:type command: str
:param command: command to be run on remote host
:type callback: function
:param callback: function to call when execution completes | Below is the the instruction that describes the task:
### Input:
Executes command on remote hosts without blocking
:type command: str
:param command: command to be run on remote host
:type callback: function
:param callback: function to call when execution completes
### Response:
d... |
def remove_info_file():
"""Remove the current process's TensorBoardInfo file, if it exists.
If the file does not exist, no action is taken and no error is raised.
"""
try:
os.unlink(_get_info_file_path())
except OSError as e:
if e.errno == errno.ENOENT:
# The user may have wiped their temporary... | Remove the current process's TensorBoardInfo file, if it exists.
If the file does not exist, no action is taken and no error is raised. | Below is the the instruction that describes the task:
### Input:
Remove the current process's TensorBoardInfo file, if it exists.
If the file does not exist, no action is taken and no error is raised.
### Response:
def remove_info_file():
"""Remove the current process's TensorBoardInfo file, if it exists.
... |
def urljoin(base_url, url, allow_fragments=True):
'''Join URLs like ``urllib.parse.urljoin`` but allow scheme-relative URL.'''
if url.startswith('//') and len(url) > 2:
scheme = base_url.partition(':')[0]
if scheme:
return urllib.parse.urljoin(
base_url,
... | Join URLs like ``urllib.parse.urljoin`` but allow scheme-relative URL. | Below is the the instruction that describes the task:
### Input:
Join URLs like ``urllib.parse.urljoin`` but allow scheme-relative URL.
### Response:
def urljoin(base_url, url, allow_fragments=True):
'''Join URLs like ``urllib.parse.urljoin`` but allow scheme-relative URL.'''
if url.startswith('//') and le... |
def WriteAPIAuditEntry(self, entry):
"""Writes an audit entry to the database."""
copy = entry.Copy()
copy.timestamp = rdfvalue.RDFDatetime.Now()
self.api_audit_entries.append(copy) | Writes an audit entry to the database. | Below is the the instruction that describes the task:
### Input:
Writes an audit entry to the database.
### Response:
def WriteAPIAuditEntry(self, entry):
"""Writes an audit entry to the database."""
copy = entry.Copy()
copy.timestamp = rdfvalue.RDFDatetime.Now()
self.api_audit_entries.append(copy) |
def ensure(user, action, subject):
""" Similar to ``can`` but will raise a AccessDenied Exception if does not have access"""
ability = Ability(user, get_authorization_method())
if ability.cannot(action, subject):
raise AccessDenied() | Similar to ``can`` but will raise a AccessDenied Exception if does not have access | Below is the the instruction that describes the task:
### Input:
Similar to ``can`` but will raise a AccessDenied Exception if does not have access
### Response:
def ensure(user, action, subject):
""" Similar to ``can`` but will raise a AccessDenied Exception if does not have access"""
ability = Ability(us... |
def validate_bool_kwarg(value, arg_name):
""" Ensures that argument passed in arg_name is of type bool. """
if not (is_bool(value) or value is None):
raise ValueError('For argument "{arg}" expected type bool, received '
'type {typ}.'.format(arg=arg_name,
... | Ensures that argument passed in arg_name is of type bool. | Below is the the instruction that describes the task:
### Input:
Ensures that argument passed in arg_name is of type bool.
### Response:
def validate_bool_kwarg(value, arg_name):
""" Ensures that argument passed in arg_name is of type bool. """
if not (is_bool(value) or value is None):
raise ValueE... |
def conc(self,H=70.,Om=0.3,overdens=200.,wrtcrit=False,
ro=None,vo=None):
"""
NAME:
conc
PURPOSE:
return the concentration
INPUT:
H= (default: 70) Hubble constant in km/s/Mpc
Om= (default: 0.3) Omega matter
... | NAME:
conc
PURPOSE:
return the concentration
INPUT:
H= (default: 70) Hubble constant in km/s/Mpc
Om= (default: 0.3) Omega matter
overdens= (200) overdensity which defines the virial radius
wrtcrit= (False) if Tru... | Below is the the instruction that describes the task:
### Input:
NAME:
conc
PURPOSE:
return the concentration
INPUT:
H= (default: 70) Hubble constant in km/s/Mpc
Om= (default: 0.3) Omega matter
overdens= (200) overdensit... |
def read(filelines, mapping=None, wok=False):
"""Parse a ris lines and return a list of entries.
Entries are codified as dictionaries whose keys are the
different tags. For single line and singly occurring tags,
the content is codified as a string. In the case of multiline
or multiple key occurrenc... | Parse a ris lines and return a list of entries.
Entries are codified as dictionaries whose keys are the
different tags. For single line and singly occurring tags,
the content is codified as a string. In the case of multiline
or multiple key occurrences, the content is returned as a list
of strings.... | Below is the the instruction that describes the task:
### Input:
Parse a ris lines and return a list of entries.
Entries are codified as dictionaries whose keys are the
different tags. For single line and singly occurring tags,
the content is codified as a string. In the case of multiline
or multip... |
def __convertRlocToRouterId(self, xRloc16):
"""mapping Rloc16 to router id
Args:
xRloc16: hex rloc16 short address
Returns:
actual router id allocated by leader
"""
routerList = []
routerList = self.__sendCommand('router list')[0].split()
... | mapping Rloc16 to router id
Args:
xRloc16: hex rloc16 short address
Returns:
actual router id allocated by leader | Below is the the instruction that describes the task:
### Input:
mapping Rloc16 to router id
Args:
xRloc16: hex rloc16 short address
Returns:
actual router id allocated by leader
### Response:
def __convertRlocToRouterId(self, xRloc16):
"""mapping Rloc16 to router ... |
def _token_of(self, input):
"""
Returns the token type of the input.
:param input: Input whose type is to be determined
:return TOKENS: Token type of the input
"""
if isinstance(input, dict):
# Intrinsic functions are always dicts
if is_intrinsi... | Returns the token type of the input.
:param input: Input whose type is to be determined
:return TOKENS: Token type of the input | Below is the the instruction that describes the task:
### Input:
Returns the token type of the input.
:param input: Input whose type is to be determined
:return TOKENS: Token type of the input
### Response:
def _token_of(self, input):
"""
Returns the token type of the input.
... |
def set_locked_variable(self, key, access_key, value):
"""Set an already locked global variable
:param key: the key of the global variable to be set
:param access_key: the access key to the already locked global variable
:param value: the new value of the global variable
"""
... | Set an already locked global variable
:param key: the key of the global variable to be set
:param access_key: the access key to the already locked global variable
:param value: the new value of the global variable | Below is the the instruction that describes the task:
### Input:
Set an already locked global variable
:param key: the key of the global variable to be set
:param access_key: the access key to the already locked global variable
:param value: the new value of the global variable
### Response... |
def _diagonalize(self):
"""Performs SVD on covariance matrices and save left, right singular vectors and values in the model.
Parameters
----------
scaling : None or string, default=None
Scaling to be applied to the VAMP modes upon transformation
* None: no scali... | Performs SVD on covariance matrices and save left, right singular vectors and values in the model.
Parameters
----------
scaling : None or string, default=None
Scaling to be applied to the VAMP modes upon transformation
* None: no scaling will be applied, variance of the... | Below is the the instruction that describes the task:
### Input:
Performs SVD on covariance matrices and save left, right singular vectors and values in the model.
Parameters
----------
scaling : None or string, default=None
Scaling to be applied to the VAMP modes upon transform... |
def get_valid_configured_integrations(alert):
"""Return a list of integrations for alert filtered by alert_type.
:returns: A list of relevant integrations
"""
if not configured_integrations:
return []
# Collect all integrations that are configured for specific alert_type
# or have no s... | Return a list of integrations for alert filtered by alert_type.
:returns: A list of relevant integrations | Below is the the instruction that describes the task:
### Input:
Return a list of integrations for alert filtered by alert_type.
:returns: A list of relevant integrations
### Response:
def get_valid_configured_integrations(alert):
"""Return a list of integrations for alert filtered by alert_type.
:re... |
def _delete(self, pos, idx):
"""
Delete the item at the given (pos, idx).
Combines lists that are less than half the load level.
Updates the index when the sublist length is more than half the load
level. This requires decrementing the nodes in a traversal from the leaf
... | Delete the item at the given (pos, idx).
Combines lists that are less than half the load level.
Updates the index when the sublist length is more than half the load
level. This requires decrementing the nodes in a traversal from the leaf
node to the root. For an example traversal see s... | Below is the the instruction that describes the task:
### Input:
Delete the item at the given (pos, idx).
Combines lists that are less than half the load level.
Updates the index when the sublist length is more than half the load
level. This requires decrementing the nodes in a traversal f... |
def _prm_store_parameter_or_result(self,
instance,
store_data=pypetconstants.STORE_DATA,
store_flags=None,
overwrite=None,
wi... | Stores a parameter or result to hdf5.
:param instance:
The instance to be stored
:param store_data:
How to store data
:param store_flags:
Dictionary containing how to store individual data, usually empty.
:param overwrite:
Instructi... | Below is the the instruction that describes the task:
### Input:
Stores a parameter or result to hdf5.
:param instance:
The instance to be stored
:param store_data:
How to store data
:param store_flags:
Dictionary containing how to store individual d... |
def NetMHCpan(
alleles,
program_name="netMHCpan",
process_limit=-1,
default_peptide_lengths=[9],
extra_flags=[]):
"""
This function wraps NetMHCpan28 and NetMHCpan3 to automatically detect which class
to use, with the help of the miraculous and strange '--version' net... | This function wraps NetMHCpan28 and NetMHCpan3 to automatically detect which class
to use, with the help of the miraculous and strange '--version' netmhcpan argument. | Below is the the instruction that describes the task:
### Input:
This function wraps NetMHCpan28 and NetMHCpan3 to automatically detect which class
to use, with the help of the miraculous and strange '--version' netmhcpan argument.
### Response:
def NetMHCpan(
alleles,
program_name="netMHCpan",... |
def get_parent_path(brain_or_object):
"""Calculate the physical parent path of this object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Physical path of the parent object
:rtype: string
"""
... | Calculate the physical parent path of this object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Physical path of the parent object
:rtype: string | Below is the the instruction that describes the task:
### Input:
Calculate the physical parent path of this object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Physical path of the parent object
:rt... |
def wait_for_unicode_char(self, ignored_chars=None, timeout=0):
"""Returns a str that contains the single character that was pressed.
This already respects modifier keys and keyboard layouts. If timeout is
not none and no key is pressed within the specified timeout, None is
returned. If ... | Returns a str that contains the single character that was pressed.
This already respects modifier keys and keyboard layouts. If timeout is
not none and no key is pressed within the specified timeout, None is
returned. If a key is ingnored_chars it will be ignored. As argument for
irgnore... | Below is the the instruction that describes the task:
### Input:
Returns a str that contains the single character that was pressed.
This already respects modifier keys and keyboard layouts. If timeout is
not none and no key is pressed within the specified timeout, None is
returned. If a key ... |
def _check_view_permission(self, view):
"""
:param view: a :class:`ObjectView` class or instance
"""
security = get_service("security")
return security.has_permission(current_user, view.permission, self.obj) | :param view: a :class:`ObjectView` class or instance | Below is the the instruction that describes the task:
### Input:
:param view: a :class:`ObjectView` class or instance
### Response:
def _check_view_permission(self, view):
"""
:param view: a :class:`ObjectView` class or instance
"""
security = get_service("security")
return ... |
def _adjust_inferential_results_for_parameter_constraints(self,
constraints):
"""
Ensure that parameters that were constrained during estimation do not
have any values showed for inferential results. After all, no inference
wa... | Ensure that parameters that were constrained during estimation do not
have any values showed for inferential results. After all, no inference
was performed.
Parameters
----------
constraints : list of ints, or None.
If list, should contain the positions in the array ... | Below is the the instruction that describes the task:
### Input:
Ensure that parameters that were constrained during estimation do not
have any values showed for inferential results. After all, no inference
was performed.
Parameters
----------
constraints : list of ints, or ... |
def on_edit_grid(self, event):
"""sets self.changes to true when user edits the grid.
provides down and up key functionality for exiting the editor"""
if not self.changes:
self.changes = {event.Row}
else:
self.changes.add(event.Row)
#self.changes = True
... | sets self.changes to true when user edits the grid.
provides down and up key functionality for exiting the editor | Below is the the instruction that describes the task:
### Input:
sets self.changes to true when user edits the grid.
provides down and up key functionality for exiting the editor
### Response:
def on_edit_grid(self, event):
"""sets self.changes to true when user edits the grid.
provides dow... |
def create_for_caught_error(parser: _BaseParserDeclarationForRegistries, desired_type: Type[T],
obj: PersistedObject, caught: Exception, options: Dict[str, Dict[str, Any]]):
"""
Helper method provided because we actually can't put that in the constructor, it creates a bug... | Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests
https://github.com/nose-devs/nose/issues/725
:param parser:
:param desired_type:
:param obj:
:param caught:
:param options:
:return: | Below is the the instruction that describes the task:
### Input:
Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests
https://github.com/nose-devs/nose/issues/725
:param parser:
:param desired_type:
:param obj:
:param c... |
def unregisterGeneralHandler(self, handler):
"""注销通用事件处理函数监听"""
if handler in self.__generalHandlers:
self.__generalHandlers.remove(handler) | 注销通用事件处理函数监听 | Below is the the instruction that describes the task:
### Input:
注销通用事件处理函数监听
### Response:
def unregisterGeneralHandler(self, handler):
"""注销通用事件处理函数监听"""
if handler in self.__generalHandlers:
self.__generalHandlers.remove(handler) |
def env(key, default):
"""
Helper to try to get a setting from the environment, or pyconfig, or
finally use a provided default.
"""
value = os.environ.get(key, None)
if value is not None:
log.info(' %s = %r', key.lower().replace('_', '.'), value)
return value
key = key.l... | Helper to try to get a setting from the environment, or pyconfig, or
finally use a provided default. | Below is the the instruction that describes the task:
### Input:
Helper to try to get a setting from the environment, or pyconfig, or
finally use a provided default.
### Response:
def env(key, default):
"""
Helper to try to get a setting from the environment, or pyconfig, or
finally use a provided ... |
def bovy_hist(x,xlabel=None,ylabel=None,overplot=False,**kwargs):
"""
NAME:
bovy_hist
PURPOSE:
wrapper around matplotlib's hist function
INPUT:
x - array to histogram
xlabel - (raw string!) x-axis label, LaTeX math mode, no $s needed
ylabel - (raw string!) y-axi... | NAME:
bovy_hist
PURPOSE:
wrapper around matplotlib's hist function
INPUT:
x - array to histogram
xlabel - (raw string!) x-axis label, LaTeX math mode, no $s needed
ylabel - (raw string!) y-axis label, LaTeX math mode, no $s needed
yrange - set the y-axis range
... | Below is the the instruction that describes the task:
### Input:
NAME:
bovy_hist
PURPOSE:
wrapper around matplotlib's hist function
INPUT:
x - array to histogram
xlabel - (raw string!) x-axis label, LaTeX math mode, no $s needed
ylabel - (raw string!) y-axis label, ... |
def _get_version(ctx, _, value):
"""Click callback for option to show current ZSL version."""
if not value or ctx.resilient_parsing:
return
message = 'Zsl %(version)s\nPython %(python_version)s'
click.echo(message % {
'version': version,
'python_version': sys.version,
}, col... | Click callback for option to show current ZSL version. | Below is the the instruction that describes the task:
### Input:
Click callback for option to show current ZSL version.
### Response:
def _get_version(ctx, _, value):
"""Click callback for option to show current ZSL version."""
if not value or ctx.resilient_parsing:
return
message = 'Zsl %(ver... |
def south_field_triple(self):
"Returns a suitable description of this field for South."
args, kwargs = introspector(self)
kwargs.update({
'populate_from': 'None' if callable(self.populate_from) else repr(self.populate_from),
'unique_with': repr(self.unique_with)
}... | Returns a suitable description of this field for South. | Below is the the instruction that describes the task:
### Input:
Returns a suitable description of this field for South.
### Response:
def south_field_triple(self):
"Returns a suitable description of this field for South."
args, kwargs = introspector(self)
kwargs.update({
'popul... |
def enrich(self, gmt):
"""use local mode
p = p-value computed using the Fisher exact test (Hypergeometric test)
Not implemented here:
combine score = log(p)·z
see here: http://amp.pharm.mssm.edu/Enrichr/help#background&q=4
columns contain:
... | use local mode
p = p-value computed using the Fisher exact test (Hypergeometric test)
Not implemented here:
combine score = log(p)·z
see here: http://amp.pharm.mssm.edu/Enrichr/help#background&q=4
columns contain:
Term Overlap ... | Below is the the instruction that describes the task:
### Input:
use local mode
p = p-value computed using the Fisher exact test (Hypergeometric test)
Not implemented here:
combine score = log(p)·z
see here: http://amp.pharm.mssm.edu/Enrichr/help#background&q=4
... |
def builder(name, **builder_init_kwargs):
"""Fetches a `tfds.core.DatasetBuilder` by string name.
Args:
name: `str`, the registered name of the `DatasetBuilder` (the snake case
version of the class name). This can be either `"dataset_name"` or
`"dataset_name/config_name"` for datasets with `Builder... | Fetches a `tfds.core.DatasetBuilder` by string name.
Args:
name: `str`, the registered name of the `DatasetBuilder` (the snake case
version of the class name). This can be either `"dataset_name"` or
`"dataset_name/config_name"` for datasets with `BuilderConfig`s.
As a convenience, this string m... | Below is the the instruction that describes the task:
### Input:
Fetches a `tfds.core.DatasetBuilder` by string name.
Args:
name: `str`, the registered name of the `DatasetBuilder` (the snake case
version of the class name). This can be either `"dataset_name"` or
`"dataset_name/config_name"` for ... |
def timezone_from_str(tz_str):
"""
Convert a timezone string to a timezone object.
:param tz_str: string with format 'Asia/Shanghai' or 'UTC±[hh]:[mm]'
:return: a timezone object (tzinfo)
"""
m = re.match(r'UTC([+|-]\d{1,2}):(\d{2})', tz_str)
if m:
# in format 'UTC±[hh]:[mm]'
... | Convert a timezone string to a timezone object.
:param tz_str: string with format 'Asia/Shanghai' or 'UTC±[hh]:[mm]'
:return: a timezone object (tzinfo) | Below is the the instruction that describes the task:
### Input:
Convert a timezone string to a timezone object.
:param tz_str: string with format 'Asia/Shanghai' or 'UTC±[hh]:[mm]'
:return: a timezone object (tzinfo)
### Response:
def timezone_from_str(tz_str):
"""
Convert a timezone string to a ... |
def get_user_by_email(server_context, email):
"""
Get the user with the provided email. Throws a ValueError if not found.
:param server_context: A LabKey server context. See utils.create_server_context.
:param email:
:return:
"""
url = server_context.build_url(user_controller, 'getUsers.api'... | Get the user with the provided email. Throws a ValueError if not found.
:param server_context: A LabKey server context. See utils.create_server_context.
:param email:
:return: | Below is the the instruction that describes the task:
### Input:
Get the user with the provided email. Throws a ValueError if not found.
:param server_context: A LabKey server context. See utils.create_server_context.
:param email:
:return:
### Response:
def get_user_by_email(server_context, email):
... |
def merge(cls, source_blocks):
"""Merge multiple SourceBlocks together"""
if len(source_blocks) == 1:
return source_blocks[0]
source_blocks.sort(key=operator.attrgetter('start_line_number'))
main_block = source_blocks[0]
boot_lines = main_block.boot_lines
so... | Merge multiple SourceBlocks together | Below is the the instruction that describes the task:
### Input:
Merge multiple SourceBlocks together
### Response:
def merge(cls, source_blocks):
"""Merge multiple SourceBlocks together"""
if len(source_blocks) == 1:
return source_blocks[0]
source_blocks.sort(key=operator.att... |
def auto_newline(buffer):
r"""
Insert \n at the cursor position. Also add necessary padding.
"""
insert_text = buffer.insert_text
if buffer.document.current_line_after_cursor:
# When we are in the middle of a line. Always insert a newline.
insert_text('\n')
else:
# Go to... | r"""
Insert \n at the cursor position. Also add necessary padding. | Below is the the instruction that describes the task:
### Input:
r"""
Insert \n at the cursor position. Also add necessary padding.
### Response:
def auto_newline(buffer):
r"""
Insert \n at the cursor position. Also add necessary padding.
"""
insert_text = buffer.insert_text
if buffer.docu... |
def add(
self,
method=None, # method or ``Response``
url=None,
body="",
adding_headers=None,
*args,
**kwargs
):
"""
A basic request:
>>> responses.add(responses.GET, 'http://example.com')
You can also directly pass an object ... | A basic request:
>>> responses.add(responses.GET, 'http://example.com')
You can also directly pass an object which implements the
``BaseResponse`` interface:
>>> responses.add(Response(...))
A JSON payload:
>>> responses.add(
>>> method='GET',
>>>... | Below is the the instruction that describes the task:
### Input:
A basic request:
>>> responses.add(responses.GET, 'http://example.com')
You can also directly pass an object which implements the
``BaseResponse`` interface:
>>> responses.add(Response(...))
A JSON payload:
... |
def _get_default_price_id(items, option, hourly, location):
"""Returns a 'free' price id given an option."""
for item in items:
if utils.lookup(item, 'itemCategory', 'categoryCode') != option:
continue
for price in item['prices']:
if all([float(price.get('hourlyRecurrin... | Returns a 'free' price id given an option. | Below is the the instruction that describes the task:
### Input:
Returns a 'free' price id given an option.
### Response:
def _get_default_price_id(items, option, hourly, location):
"""Returns a 'free' price id given an option."""
for item in items:
if utils.lookup(item, 'itemCategory', 'categoryC... |
def select_specimen(self, specimen):
"""
Goes through the calculations necessary to plot measurement data for
specimen and sets specimen as current GUI specimen, also attempts to
handle changing current fit.
"""
try:
fit_index = self.pmag_results_data['specime... | Goes through the calculations necessary to plot measurement data for
specimen and sets specimen as current GUI specimen, also attempts to
handle changing current fit. | Below is the the instruction that describes the task:
### Input:
Goes through the calculations necessary to plot measurement data for
specimen and sets specimen as current GUI specimen, also attempts to
handle changing current fit.
### Response:
def select_specimen(self, specimen):
"""
... |
def _namespace_default():
"""
Get current namespace if running in a k8s cluster
If not in a k8s cluster with service accounts enabled, default to
'default'
Taken from https://github.com/jupyterhub/kubespawner/blob/master/kubespawner/spawner.py#L125
"""
ns_path = '/var/run/secrets/kubernete... | Get current namespace if running in a k8s cluster
If not in a k8s cluster with service accounts enabled, default to
'default'
Taken from https://github.com/jupyterhub/kubespawner/blob/master/kubespawner/spawner.py#L125 | Below is the the instruction that describes the task:
### Input:
Get current namespace if running in a k8s cluster
If not in a k8s cluster with service accounts enabled, default to
'default'
Taken from https://github.com/jupyterhub/kubespawner/blob/master/kubespawner/spawner.py#L125
### Response:
def... |
def run_query(self, query):
""" method runs the query and returns a list of filtered UnitOfWork records """
cursor = self.ds.filter(COLLECTION_UNIT_OF_WORK, query)
return [UnitOfWork.from_json(document) for document in cursor] | method runs the query and returns a list of filtered UnitOfWork records | Below is the the instruction that describes the task:
### Input:
method runs the query and returns a list of filtered UnitOfWork records
### Response:
def run_query(self, query):
""" method runs the query and returns a list of filtered UnitOfWork records """
cursor = self.ds.filter(COLLECTION_UNIT_... |
def _cgc_package_list_identifier(self, data_addr, data_size):
"""
Identifies the CGC package list associated with the CGC binary.
:param int data_addr: Address of the data in memory.
:param int data_size: Maximum size possible.
:return: A 2-tuple of data type and size.
:... | Identifies the CGC package list associated with the CGC binary.
:param int data_addr: Address of the data in memory.
:param int data_size: Maximum size possible.
:return: A 2-tuple of data type and size.
:rtype: tuple | Below is the the instruction that describes the task:
### Input:
Identifies the CGC package list associated with the CGC binary.
:param int data_addr: Address of the data in memory.
:param int data_size: Maximum size possible.
:return: A 2-tuple of data type and size.
:rtype: tuple
... |
def to_disk(self, path, **kwargs):
"""Save the entity ruler patterns to a directory. The patterns will be
saved as newline-delimited JSON (JSONL).
path (unicode / Path): The JSONL file to load.
**kwargs: Other config paramters, mostly for consistency.
RETURNS (EntityRuler): The ... | Save the entity ruler patterns to a directory. The patterns will be
saved as newline-delimited JSON (JSONL).
path (unicode / Path): The JSONL file to load.
**kwargs: Other config paramters, mostly for consistency.
RETURNS (EntityRuler): The loaded entity ruler.
DOCS: https://sp... | Below is the the instruction that describes the task:
### Input:
Save the entity ruler patterns to a directory. The patterns will be
saved as newline-delimited JSON (JSONL).
path (unicode / Path): The JSONL file to load.
**kwargs: Other config paramters, mostly for consistency.
RETU... |
def update_variant_by_id(cls, variant_id, variant, **kwargs):
"""Update Variant
Update attributes of Variant
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_variant_by_id(variant_id, va... | Update Variant
Update attributes of Variant
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_variant_by_id(variant_id, variant, async=True)
>>> result = thread.get()
:param asyn... | Below is the the instruction that describes the task:
### Input:
Update Variant
Update attributes of Variant
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_variant_by_id(variant_id, varian... |
def get_requests_batch(input_list, results={}, delay_time=0.5, max_threads=100):
"""
This is a parallel version of the HTTP GET primitive.
:param input_list: the input is a list of either dictionaries containing
query information, or just domain names (and NOT URLs).
:param delay... | This is a parallel version of the HTTP GET primitive.
:param input_list: the input is a list of either dictionaries containing
query information, or just domain names (and NOT URLs).
:param delay_time: delay before starting each thread
:param max_threads: maximum number of concurrent... | Below is the the instruction that describes the task:
### Input:
This is a parallel version of the HTTP GET primitive.
:param input_list: the input is a list of either dictionaries containing
query information, or just domain names (and NOT URLs).
:param delay_time: delay before star... |
def extern_equals(self, context_handle, val1, val2):
"""Return true if the given Handles are __eq__."""
return self._ffi.from_handle(val1[0]) == self._ffi.from_handle(val2[0]) | Return true if the given Handles are __eq__. | Below is the the instruction that describes the task:
### Input:
Return true if the given Handles are __eq__.
### Response:
def extern_equals(self, context_handle, val1, val2):
"""Return true if the given Handles are __eq__."""
return self._ffi.from_handle(val1[0]) == self._ffi.from_handle(val2[0]) |
def hgsub_report(self):
"""
Yields:
str: .hgsubs line for this repository
"""
if self.relpath == '.':
return
yield "%s = [%s]%s" % (
self.fpath.lstrip('./'),
self.label,
self.remote_url) | Yields:
str: .hgsubs line for this repository | Below is the the instruction that describes the task:
### Input:
Yields:
str: .hgsubs line for this repository
### Response:
def hgsub_report(self):
"""
Yields:
str: .hgsubs line for this repository
"""
if self.relpath == '.':
return
yield... |
def set_itunes_author_name(self):
"""Parses author name from itunes tags and sets value"""
try:
self.itunes_author_name = self.soup.find('itunes:author').string
except AttributeError:
self.itunes_author_name = None | Parses author name from itunes tags and sets value | Below is the the instruction that describes the task:
### Input:
Parses author name from itunes tags and sets value
### Response:
def set_itunes_author_name(self):
"""Parses author name from itunes tags and sets value"""
try:
self.itunes_author_name = self.soup.find('itunes:author').str... |
def status(self, id):
"""
Fetch information about a single toot.
Does not require authentication for publicly visible statuses.
Returns a `toot dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}'.format(str(id))
return self.__api_request('... | Fetch information about a single toot.
Does not require authentication for publicly visible statuses.
Returns a `toot dict`_. | Below is the the instruction that describes the task:
### Input:
Fetch information about a single toot.
Does not require authentication for publicly visible statuses.
Returns a `toot dict`_.
### Response:
def status(self, id):
"""
Fetch information about a single toot.
Do... |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: FeedbackContext for this FeedbackInstance
:rtype: twilio.rest.api.v2010.account.call.feedback.Fee... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: FeedbackContext for this FeedbackInstance
:rtype: twilio.rest.api.v2010.account.call.feedback.FeedbackContext | Below is the the instruction that describes the task:
### Input:
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: FeedbackContext for this FeedbackInstance
:rtype: twilio.rest.api.... |
def gaussian_kernel(sigma, truncate=4.0):
"""Return Gaussian that truncates at the given number of std deviations.
Adapted from https://github.com/nicjhan/gaussian-filter
"""
sigma = float(sigma)
radius = int(truncate * sigma + 0.5)
x, y = np.mgrid[-radius:radius + 1, -radius:radius + 1]
... | Return Gaussian that truncates at the given number of std deviations.
Adapted from https://github.com/nicjhan/gaussian-filter | Below is the the instruction that describes the task:
### Input:
Return Gaussian that truncates at the given number of std deviations.
Adapted from https://github.com/nicjhan/gaussian-filter
### Response:
def gaussian_kernel(sigma, truncate=4.0):
"""Return Gaussian that truncates at the given number of st... |
def read_environment():
""" Read all environment variables to see if they contain PERI """
out = {}
for k,v in iteritems(os.environ):
if transform(k) in default_conf:
out[transform(k)] = v
return out | Read all environment variables to see if they contain PERI | Below is the the instruction that describes the task:
### Input:
Read all environment variables to see if they contain PERI
### Response:
def read_environment():
""" Read all environment variables to see if they contain PERI """
out = {}
for k,v in iteritems(os.environ):
if transform(k) in defa... |
def search_location(loc, locations=None,
critical=False, create_in=None, verbose=True):
'''
Locates files with a twist:
* Check the existence of a file using the full path in `loc`
* Search for the filename `loc` in `locations`
* Create it's enclosing folders if th... | Locates files with a twist:
* Check the existence of a file using the full path in `loc`
* Search for the filename `loc` in `locations`
* Create it's enclosing folders if the file does not exist. \
use `create_in`
:param loc:
Filename to search
:param locations:
... | Below is the the instruction that describes the task:
### Input:
Locates files with a twist:
* Check the existence of a file using the full path in `loc`
* Search for the filename `loc` in `locations`
* Create it's enclosing folders if the file does not exist. \
use `create_in`
... |
def make_event_filter(self, filter_key, filter_value):
"""Create a new event filter."""
event_filter = EventFilter(
self.event_name,
self.event,
{filter_key: filter_value},
from_block=self.from_block,
to_block=self.to_block
)
ev... | Create a new event filter. | Below is the the instruction that describes the task:
### Input:
Create a new event filter.
### Response:
def make_event_filter(self, filter_key, filter_value):
"""Create a new event filter."""
event_filter = EventFilter(
self.event_name,
self.event,
{filter_key:... |
def delete_entry(request, entry_id):
"""
Give the user the ability to delete a log entry, with a confirmation
beforehand. If this method is invoked via a GET request, a form asking
for a confirmation of intent will be presented to the user. If this method
is invoked via a POST request, the entry wi... | Give the user the ability to delete a log entry, with a confirmation
beforehand. If this method is invoked via a GET request, a form asking
for a confirmation of intent will be presented to the user. If this method
is invoked via a POST request, the entry will be deleted. | Below is the the instruction that describes the task:
### Input:
Give the user the ability to delete a log entry, with a confirmation
beforehand. If this method is invoked via a GET request, a form asking
for a confirmation of intent will be presented to the user. If this method
is invoked via a POST r... |
def prepare_amazon_algorithm_estimator(estimator, inputs, mini_batch_size=None):
""" Set up amazon algorithm estimator, adding the required `feature_dim` hyperparameter from training data.
Args:
estimator (sagemaker.amazon.amazon_estimator.AmazonAlgorithmEstimatorBase):
An estimator for a b... | Set up amazon algorithm estimator, adding the required `feature_dim` hyperparameter from training data.
Args:
estimator (sagemaker.amazon.amazon_estimator.AmazonAlgorithmEstimatorBase):
An estimator for a built-in Amazon algorithm to get information from and update.
inputs: The training... | Below is the the instruction that describes the task:
### Input:
Set up amazon algorithm estimator, adding the required `feature_dim` hyperparameter from training data.
Args:
estimator (sagemaker.amazon.amazon_estimator.AmazonAlgorithmEstimatorBase):
An estimator for a built-in Amazon algor... |
def _normalize_coerce_to_format_with_lookup(self, v):
""" Replace a format with a default """
try:
return self.format_lookup.get(v, v)
except TypeError:
# v is something we can't lookup (like a list)
return v | Replace a format with a default | Below is the the instruction that describes the task:
### Input:
Replace a format with a default
### Response:
def _normalize_coerce_to_format_with_lookup(self, v):
""" Replace a format with a default """
try:
return self.format_lookup.get(v, v)
except TypeError:
# v... |
def _analyze_func_string(func_string):
"""
Analyze given functiion string an extract:
* function name
* function arguments
* function keyword arguments
All given arguments must by of type string, int/float or list.
:param func_string: string of the function
:return: function name, arg... | Analyze given functiion string an extract:
* function name
* function arguments
* function keyword arguments
All given arguments must by of type string, int/float or list.
:param func_string: string of the function
:return: function name, arguments, keyword arguments | Below is the the instruction that describes the task:
### Input:
Analyze given functiion string an extract:
* function name
* function arguments
* function keyword arguments
All given arguments must by of type string, int/float or list.
:param func_string: string of the function
:return: ... |
def load(klass, filename, inject_env=True):
"""Load a Pipfile from a given filename."""
p = PipfileParser(filename=filename)
pipfile = klass(filename=filename)
pipfile.data = p.parse(inject_env=inject_env)
return pipfile | Load a Pipfile from a given filename. | Below is the the instruction that describes the task:
### Input:
Load a Pipfile from a given filename.
### Response:
def load(klass, filename, inject_env=True):
"""Load a Pipfile from a given filename."""
p = PipfileParser(filename=filename)
pipfile = klass(filename=filename)
pipfil... |
def createNetwork(networkConfig):
"""
Create and initialize the specified network instance.
@param networkConfig: (dict) the configuration of this network.
@return network: (Network) The actual network
"""
registerAllResearchRegions()
network = Network()
if networkConfig["networkType"] == "L4L2Colum... | Create and initialize the specified network instance.
@param networkConfig: (dict) the configuration of this network.
@return network: (Network) The actual network | Below is the the instruction that describes the task:
### Input:
Create and initialize the specified network instance.
@param networkConfig: (dict) the configuration of this network.
@return network: (Network) The actual network
### Response:
def createNetwork(networkConfig):
"""
Create and initialize the... |
def resolve_signing_intent(self):
"""Determine the correct signing intent
Regardless of what was requested, or provided as signing_intent plugin parameter,
consult sigkeys of the actual composes used to guarantee information accuracy.
"""
all_signing_intents = [
sel... | Determine the correct signing intent
Regardless of what was requested, or provided as signing_intent plugin parameter,
consult sigkeys of the actual composes used to guarantee information accuracy. | Below is the the instruction that describes the task:
### Input:
Determine the correct signing intent
Regardless of what was requested, or provided as signing_intent plugin parameter,
consult sigkeys of the actual composes used to guarantee information accuracy.
### Response:
def resolve_signing_i... |
def PopulateForm(self):
"""
+-----------------------------------------------------------------------+
| +--- splitter ------------------------------------------------------+ |
| | +-- list widget--------------+ +- IdaSettingsView -------------+ | |
| | | ... | +-----------------------------------------------------------------------+
| +--- splitter ------------------------------------------------------+ |
| | +-- list widget--------------+ +- IdaSettingsView -------------+ | |
| | | | | | |... | Below is the the instruction that describes the task:
### Input:
+-----------------------------------------------------------------------+
| +--- splitter ------------------------------------------------------+ |
| | +-- list widget--------------+ +- IdaSettingsView -------------+ | |
| ... |
def handle_friday(next_date: Datum, period: str, mult: int, start_date: Datum):
""" Extracted the calculation for when the next_day is Friday """
assert isinstance(next_date, Datum)
assert isinstance(start_date, Datum)
# Starting from line 220.
tmp_sat = next_date.clone()
tmp_sat.add_days(1)
... | Extracted the calculation for when the next_day is Friday | Below is the the instruction that describes the task:
### Input:
Extracted the calculation for when the next_day is Friday
### Response:
def handle_friday(next_date: Datum, period: str, mult: int, start_date: Datum):
""" Extracted the calculation for when the next_day is Friday """
assert isinstance(next_d... |
def temporal_latent_to_dist(name, x, hparams, output_channels=None):
"""Network that maps a time-indexed list of 3-D latents to a gaussian.
Args:
name: variable scope.
x: List of 4-D Tensors indexed by time, (NHWC)
hparams: tf.contrib.training.Hparams.
output_channels: int, Number of channels of th... | Network that maps a time-indexed list of 3-D latents to a gaussian.
Args:
name: variable scope.
x: List of 4-D Tensors indexed by time, (NHWC)
hparams: tf.contrib.training.Hparams.
output_channels: int, Number of channels of the output gaussian mean.
Returns:
dist: tfp.distributions.Normal | Below is the the instruction that describes the task:
### Input:
Network that maps a time-indexed list of 3-D latents to a gaussian.
Args:
name: variable scope.
x: List of 4-D Tensors indexed by time, (NHWC)
hparams: tf.contrib.training.Hparams.
output_channels: int, Number of channels of the out... |
def basic_generator(in_size:int, n_channels:int, noise_sz:int=100, n_features:int=64, n_extra_layers=0, **conv_kwargs):
"A basic generator from `noise_sz` to images `n_channels` x `in_size` x `in_size`."
cur_size, cur_ftrs = 4, n_features//2
while cur_size < in_size: cur_size *= 2; cur_ftrs *= 2
layers... | A basic generator from `noise_sz` to images `n_channels` x `in_size` x `in_size`. | Below is the the instruction that describes the task:
### Input:
A basic generator from `noise_sz` to images `n_channels` x `in_size` x `in_size`.
### Response:
def basic_generator(in_size:int, n_channels:int, noise_sz:int=100, n_features:int=64, n_extra_layers=0, **conv_kwargs):
"A basic generator from `noise... |
def on_disconnect(client):
"""
Sample on_disconnect function.
Handles lost connections.
"""
print "-- Lost connection to %s" % client.addrport()
CLIENT_LIST.remove(client)
broadcast('%s leaves the conversation.\n' % client.addrport() ) | Sample on_disconnect function.
Handles lost connections. | Below is the the instruction that describes the task:
### Input:
Sample on_disconnect function.
Handles lost connections.
### Response:
def on_disconnect(client):
"""
Sample on_disconnect function.
Handles lost connections.
"""
print "-- Lost connection to %s" % client.addrport()
CLIENT... |
def _split_comma_separated(string):
"""Return a set of strings."""
return set(text.strip() for text in string.split(',') if text.strip()) | Return a set of strings. | Below is the the instruction that describes the task:
### Input:
Return a set of strings.
### Response:
def _split_comma_separated(string):
"""Return a set of strings."""
return set(text.strip() for text in string.split(',') if text.strip()) |
def save(self, *args, **kwargs):
"""
Custom save method does the following:
* automatically inherit node coordinates and elevation
* save shortcuts if HSTORE is enabled
"""
custom_checks = kwargs.pop('custom_checks', True)
super(Device, self).save(*args, ... | Custom save method does the following:
* automatically inherit node coordinates and elevation
* save shortcuts if HSTORE is enabled | Below is the the instruction that describes the task:
### Input:
Custom save method does the following:
* automatically inherit node coordinates and elevation
* save shortcuts if HSTORE is enabled
### Response:
def save(self, *args, **kwargs):
"""
Custom save method does the... |
def get_metadata_from_xml_tree(tree, get_issns_from_nlm=False,
get_abstracts=False, prepend_title=False,
mesh_annotations=False):
"""Get metadata for an XML tree containing PubmedArticle elements.
Documentation on the XML structure can be found at:
... | Get metadata for an XML tree containing PubmedArticle elements.
Documentation on the XML structure can be found at:
- https://www.nlm.nih.gov/bsd/licensee/elements_descriptions.html
- https://www.nlm.nih.gov/bsd/licensee/elements_alphabetical.html
Parameters
----------
tree : xml.etree... | Below is the the instruction that describes the task:
### Input:
Get metadata for an XML tree containing PubmedArticle elements.
Documentation on the XML structure can be found at:
- https://www.nlm.nih.gov/bsd/licensee/elements_descriptions.html
- https://www.nlm.nih.gov/bsd/licensee/elements_... |
def inputText(message="", title="Lackey Input", lines=9, width=20, text=""):
""" Creates a textarea dialog with the specified message and default text.
Returns the entered value. """
root = tk.Tk()
input_text = tk.StringVar()
input_text.set(text)
PopupTextarea(root, message, title, lines, width... | Creates a textarea dialog with the specified message and default text.
Returns the entered value. | Below is the the instruction that describes the task:
### Input:
Creates a textarea dialog with the specified message and default text.
Returns the entered value.
### Response:
def inputText(message="", title="Lackey Input", lines=9, width=20, text=""):
""" Creates a textarea dialog with the specified mes... |
def noun_chunks(obj):
"""
Detect base noun phrases from a dependency parse. Works on both Doc and Span.
"""
# this iterator extracts spans headed by NOUNs starting from the left-most
# syntactic dependent until the NOUN itself for close apposition and
# measurement construction, the span is some... | Detect base noun phrases from a dependency parse. Works on both Doc and Span. | Below is the the instruction that describes the task:
### Input:
Detect base noun phrases from a dependency parse. Works on both Doc and Span.
### Response:
def noun_chunks(obj):
"""
Detect base noun phrases from a dependency parse. Works on both Doc and Span.
"""
# this iterator extracts spans hea... |
def write(self, items):
"""Write items into ElasticSearch.
:param items: Pandas DataFrame
"""
if self._read_only:
raise IOError("Cannot write, Connector created as Read Only")
if len(items) == 0:
logger.info(self.__log_prefix + " Nothing to write")
... | Write items into ElasticSearch.
:param items: Pandas DataFrame | Below is the the instruction that describes the task:
### Input:
Write items into ElasticSearch.
:param items: Pandas DataFrame
### Response:
def write(self, items):
"""Write items into ElasticSearch.
:param items: Pandas DataFrame
"""
if self._read_only:
raise... |
def get_upregulated_genes_network(self) -> Graph:
"""Get the graph of up-regulated genes.
:return Graph: Graph of up-regulated genes.
"""
logger.info("In get_upregulated_genes_network()")
deg_graph = self.graph.copy() # deep copy graph
not_diff_expr = self.graph.vs(up_... | Get the graph of up-regulated genes.
:return Graph: Graph of up-regulated genes. | Below is the the instruction that describes the task:
### Input:
Get the graph of up-regulated genes.
:return Graph: Graph of up-regulated genes.
### Response:
def get_upregulated_genes_network(self) -> Graph:
"""Get the graph of up-regulated genes.
:return Graph: Graph of up-regulated ge... |
def _validate_compute_resources(self, cr):
"""
Checks contents of sub dictionary for managed clusters
:param cr: computeResources
:type cr: dict
"""
for param in ('instanceRole', 'maxvCpus', 'minvCpus', 'instanceTypes', 'securityGroupIds', 'subnets', 'type'):
... | Checks contents of sub dictionary for managed clusters
:param cr: computeResources
:type cr: dict | Below is the the instruction that describes the task:
### Input:
Checks contents of sub dictionary for managed clusters
:param cr: computeResources
:type cr: dict
### Response:
def _validate_compute_resources(self, cr):
"""
Checks contents of sub dictionary for managed clusters
... |
def find_all(self, pattern):
"""
Searches for all occurrences of a pattern in the current memory segment, returns all occurrences as a list
"""
pos = []
last_found = -1
while True:
last_found = self.current_segment.data.find(pattern, last_found + 1)
if last_found == -1:
break
pos.append(last_fo... | Searches for all occurrences of a pattern in the current memory segment, returns all occurrences as a list | Below is the the instruction that describes the task:
### Input:
Searches for all occurrences of a pattern in the current memory segment, returns all occurrences as a list
### Response:
def find_all(self, pattern):
"""
Searches for all occurrences of a pattern in the current memory segment, returns all occurre... |
def list_tables(self, like=None, database=None):
"""
List tables in the current (or indicated) database. Like the SHOW
TABLES command in the clickhouse-shell.
Parameters
----------
like : string, default None
e.g. 'foo*' to match all tables starting with 'foo'
... | List tables in the current (or indicated) database. Like the SHOW
TABLES command in the clickhouse-shell.
Parameters
----------
like : string, default None
e.g. 'foo*' to match all tables starting with 'foo'
database : string, default None
If not passed, uses... | Below is the the instruction that describes the task:
### Input:
List tables in the current (or indicated) database. Like the SHOW
TABLES command in the clickhouse-shell.
Parameters
----------
like : string, default None
e.g. 'foo*' to match all tables starting with 'foo'
... |
def _ValueMessageToJsonObject(self, message):
"""Converts Value message according to Proto3 JSON Specification."""
which = message.WhichOneof('kind')
# If the Value message is not set treat as null_value when serialize
# to JSON. The parse back result will be different from original message.
if whic... | Converts Value message according to Proto3 JSON Specification. | Below is the the instruction that describes the task:
### Input:
Converts Value message according to Proto3 JSON Specification.
### Response:
def _ValueMessageToJsonObject(self, message):
"""Converts Value message according to Proto3 JSON Specification."""
which = message.WhichOneof('kind')
# If the Va... |
def _classname(self):
"""Return the fully qualified class name."""
if self.__class__.__module__ in (None,):
return self.__class__.__name__
else:
return "%s.%s" % (self.__class__.__module__, self.__class__.__name__) | Return the fully qualified class name. | Below is the the instruction that describes the task:
### Input:
Return the fully qualified class name.
### Response:
def _classname(self):
"""Return the fully qualified class name."""
if self.__class__.__module__ in (None,):
return self.__class__.__name__
else:
retu... |
def _render(self, request, formencode=False, realm=None):
"""Render a signed request according to signature type
Returns a 3-tuple containing the request URI, headers, and body.
If the formencode argument is True and the body contains parameters, it
is escaped and returned as a valid f... | Render a signed request according to signature type
Returns a 3-tuple containing the request URI, headers, and body.
If the formencode argument is True and the body contains parameters, it
is escaped and returned as a valid formencoded string. | Below is the the instruction that describes the task:
### Input:
Render a signed request according to signature type
Returns a 3-tuple containing the request URI, headers, and body.
If the formencode argument is True and the body contains parameters, it
is escaped and returned as a valid f... |
def get_fetcher(data_format, data_class):
"""Return the :meth:`~EventTable.fetch` function for the given format
Parameters
----------
data_format : `str`
name of the format
data_class : `type`
the class that the fetcher returns
Raises
------
astropy.io.registry.IORegis... | Return the :meth:`~EventTable.fetch` function for the given format
Parameters
----------
data_format : `str`
name of the format
data_class : `type`
the class that the fetcher returns
Raises
------
astropy.io.registry.IORegistryError
if not registration is found mat... | Below is the the instruction that describes the task:
### Input:
Return the :meth:`~EventTable.fetch` function for the given format
Parameters
----------
data_format : `str`
name of the format
data_class : `type`
the class that the fetcher returns
Raises
------
astropy... |
def get_guest_connection_status(self, userid):
'''Get guest vm connection status.'''
rd = ' '.join(('getvm', userid, 'isreachable'))
results = self._request(rd)
if results['rs'] == 1:
return True
else:
return False | Get guest vm connection status. | Below is the the instruction that describes the task:
### Input:
Get guest vm connection status.
### Response:
def get_guest_connection_status(self, userid):
'''Get guest vm connection status.'''
rd = ' '.join(('getvm', userid, 'isreachable'))
results = self._request(rd)
if results[... |
def create_subscriber(self):
'''Create a subscriber instance using specified addresses and
message types.
'''
if self.subscriber is None:
if self.topics:
self.subscriber = NSSubscriber(self.services, self.topics,
... | Create a subscriber instance using specified addresses and
message types. | Below is the the instruction that describes the task:
### Input:
Create a subscriber instance using specified addresses and
message types.
### Response:
def create_subscriber(self):
'''Create a subscriber instance using specified addresses and
message types.
'''
if self.subs... |
def count_alleles(self, max_allele=None, subpop=None):
"""Count the number of calls of each allele per variant.
Parameters
----------
max_allele : int, optional
The highest allele index to count. Alleles greater than this
index will be ignored.
subpop : a... | Count the number of calls of each allele per variant.
Parameters
----------
max_allele : int, optional
The highest allele index to count. Alleles greater than this
index will be ignored.
subpop : array_like, int, optional
Indices of haplotypes to incl... | Below is the the instruction that describes the task:
### Input:
Count the number of calls of each allele per variant.
Parameters
----------
max_allele : int, optional
The highest allele index to count. Alleles greater than this
index will be ignored.
subpop ... |
def read_hashes(self):
"""
Read Hash values from the stream.
Returns:
list: a list of hash values. Each value is of the bytearray type.
"""
var_len = self.read_var_int()
items = []
for _ in range(0, var_len):
ba = bytearray(self.read_bytes... | Read Hash values from the stream.
Returns:
list: a list of hash values. Each value is of the bytearray type. | Below is the the instruction that describes the task:
### Input:
Read Hash values from the stream.
Returns:
list: a list of hash values. Each value is of the bytearray type.
### Response:
def read_hashes(self):
"""
Read Hash values from the stream.
Returns:
... |
def _validate_granttype(self, path, obj, _):
""" make sure either implicit or authorization_code is defined """
errs = []
if not obj.implicit and not obj.authorization_code:
errs.append('Either implicit or authorization_code should be defined.')
return path, obj.__class__._... | make sure either implicit or authorization_code is defined | Below is the the instruction that describes the task:
### Input:
make sure either implicit or authorization_code is defined
### Response:
def _validate_granttype(self, path, obj, _):
""" make sure either implicit or authorization_code is defined """
errs = []
if not obj.implicit and not ob... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.