code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def run(self, file, updateconfig=True, clean=False, path=None):
"""
Run SExtractor.
If updateconfig is True (default), the configuration
files will be updated before running SExtractor.
If clean is True (default: False), configuration files
(if any) will be deleted afte... | Run SExtractor.
If updateconfig is True (default), the configuration
files will be updated before running SExtractor.
If clean is True (default: False), configuration files
(if any) will be deleted after SExtractor terminates. | Below is the the instruction that describes the task:
### Input:
Run SExtractor.
If updateconfig is True (default), the configuration
files will be updated before running SExtractor.
If clean is True (default: False), configuration files
(if any) will be deleted after SExtractor te... |
def params(self):
"""
Returns all params ordered by name. The default implementation
uses :py:func:`dir` to get all attributes of type
:py:class:`Param`.
"""
if self._params is None:
self._params = list(filter(lambda attr: isinstance(attr, Param),
... | Returns all params ordered by name. The default implementation
uses :py:func:`dir` to get all attributes of type
:py:class:`Param`. | Below is the the instruction that describes the task:
### Input:
Returns all params ordered by name. The default implementation
uses :py:func:`dir` to get all attributes of type
:py:class:`Param`.
### Response:
def params(self):
"""
Returns all params ordered by name. The default im... |
def get_node_ip_address(address="8.8.8.8:53"):
"""Determine the IP address of the local node.
Args:
address (str): The IP address and port of any known live service on the
network you care about.
Returns:
The IP address of the current node.
"""
ip_address, port = addres... | Determine the IP address of the local node.
Args:
address (str): The IP address and port of any known live service on the
network you care about.
Returns:
The IP address of the current node. | Below is the the instruction that describes the task:
### Input:
Determine the IP address of the local node.
Args:
address (str): The IP address and port of any known live service on the
network you care about.
Returns:
The IP address of the current node.
### Response:
def get... |
def __rmfile(path):
"""Delete a file.
Args:
path (str): Path to the file that needs to be deleted.
Returns:
bool: True if the operation is successful, False otherwise.
"""
logger.info("rmfile: %s" % path)
try:
os.remove(path)
return True
except Exception as ... | Delete a file.
Args:
path (str): Path to the file that needs to be deleted.
Returns:
bool: True if the operation is successful, False otherwise. | Below is the the instruction that describes the task:
### Input:
Delete a file.
Args:
path (str): Path to the file that needs to be deleted.
Returns:
bool: True if the operation is successful, False otherwise.
### Response:
def __rmfile(path):
"""Delete a file.
Args:
path... |
def remove_existing_fpaths(fpath_list, verbose=VERBOSE, quiet=QUIET,
strict=False, print_caller=PRINT_CALLER,
lbl='files'):
""" checks existance before removing. then tries to remove exisint paths """
import utool as ut
if print_caller:
print(uti... | checks existance before removing. then tries to remove exisint paths | Below is the the instruction that describes the task:
### Input:
checks existance before removing. then tries to remove exisint paths
### Response:
def remove_existing_fpaths(fpath_list, verbose=VERBOSE, quiet=QUIET,
strict=False, print_caller=PRINT_CALLER,
lbl... |
def read_rtt(jlink):
"""Reads the JLink RTT buffer #0 at 10Hz and prints to stdout.
This method is a polling loop against the connected JLink unit. If
the JLink is disconnected, it will exit. Additionally, if any exceptions
are raised, they will be caught and re-raised after interrupting the
main t... | Reads the JLink RTT buffer #0 at 10Hz and prints to stdout.
This method is a polling loop against the connected JLink unit. If
the JLink is disconnected, it will exit. Additionally, if any exceptions
are raised, they will be caught and re-raised after interrupting the
main thread.
sys.stdout.write... | Below is the the instruction that describes the task:
### Input:
Reads the JLink RTT buffer #0 at 10Hz and prints to stdout.
This method is a polling loop against the connected JLink unit. If
the JLink is disconnected, it will exit. Additionally, if any exceptions
are raised, they will be caught and re... |
def set_reps(self, reps):
"""set the number of repetitions for the stimuli (reference tone and cal stim)
:param reps: number of times to present the same stimulus
:type reps: int
"""
self.stimulus.setRepCount(reps)
self.refstim.setRepCount(reps) | set the number of repetitions for the stimuli (reference tone and cal stim)
:param reps: number of times to present the same stimulus
:type reps: int | Below is the the instruction that describes the task:
### Input:
set the number of repetitions for the stimuli (reference tone and cal stim)
:param reps: number of times to present the same stimulus
:type reps: int
### Response:
def set_reps(self, reps):
"""set the number of repetitions fo... |
def git_clone_job_list(job_list):
"""Deal with all git clone jobs in $job_list."""
queue = Queue()
for job in job_list:
queue.put(job)
if len(job_list) < 20:
thread_num = len(job_list)
else:
thread_num = 20
threads = []
for _ in range(thread_num):
thread = T... | Deal with all git clone jobs in $job_list. | Below is the the instruction that describes the task:
### Input:
Deal with all git clone jobs in $job_list.
### Response:
def git_clone_job_list(job_list):
"""Deal with all git clone jobs in $job_list."""
queue = Queue()
for job in job_list:
queue.put(job)
if len(job_list) < 20:
th... |
def xgroup_setid(self, stream, group_name, latest_id='$'):
"""Set the latest ID for a consumer group"""
fut = self.execute(b'XGROUP', b'SETID', stream, group_name, latest_id)
return wait_ok(fut) | Set the latest ID for a consumer group | Below is the the instruction that describes the task:
### Input:
Set the latest ID for a consumer group
### Response:
def xgroup_setid(self, stream, group_name, latest_id='$'):
"""Set the latest ID for a consumer group"""
fut = self.execute(b'XGROUP', b'SETID', stream, group_name, latest_id)
... |
def dmsToDeg(sign, deg, min, sec):
"""Convert dec sign, degrees, minutes, seconds into a signed angle in
degrees."""
return sign * (deg + min * degPerDmsMin + sec * degPerDmsSec) | Convert dec sign, degrees, minutes, seconds into a signed angle in
degrees. | Below is the the instruction that describes the task:
### Input:
Convert dec sign, degrees, minutes, seconds into a signed angle in
degrees.
### Response:
def dmsToDeg(sign, deg, min, sec):
"""Convert dec sign, degrees, minutes, seconds into a signed angle in
degrees."""
return sign * (deg + min * ... |
def mask_and_dates_for_term(self,
term,
root_mask_term,
workspace,
all_dates):
"""
Load mask and mask row labels for term.
Parameters
----------
term :... | Load mask and mask row labels for term.
Parameters
----------
term : Term
The term to load the mask and labels for.
root_mask_term : Term
The term that represents the root asset exists mask.
workspace : dict[Term, any]
The values that have bee... | Below is the the instruction that describes the task:
### Input:
Load mask and mask row labels for term.
Parameters
----------
term : Term
The term to load the mask and labels for.
root_mask_term : Term
The term that represents the root asset exists mask.
... |
def get_timestamp(self, cycle=None, dataset_number=None,
in_minutes=False, full=True):
"""Returns timestamps (in sec or minutes (if in_minutes==True)).
Args:
cycle: cycle number (all if None)
dataset_number: first dataset if None
in_minutes: ret... | Returns timestamps (in sec or minutes (if in_minutes==True)).
Args:
cycle: cycle number (all if None)
dataset_number: first dataset if None
in_minutes: return values in minutes instead of seconds if True
full: valid only for cycle=None (i.e. all cycles), returns ... | Below is the the instruction that describes the task:
### Input:
Returns timestamps (in sec or minutes (if in_minutes==True)).
Args:
cycle: cycle number (all if None)
dataset_number: first dataset if None
in_minutes: return values in minutes instead of seconds if True
... |
def draw_line(self, img, pixmapper, pt1, pt2, colour, linewidth):
'''draw a line on the image'''
pix1 = pixmapper(pt1)
pix2 = pixmapper(pt2)
(width, height) = image_shape(img)
(ret, pix1, pix2) = cv2.clipLine((0, 0, width, height), pix1, pix2)
if ret is False:
... | draw a line on the image | Below is the the instruction that describes the task:
### Input:
draw a line on the image
### Response:
def draw_line(self, img, pixmapper, pt1, pt2, colour, linewidth):
'''draw a line on the image'''
pix1 = pixmapper(pt1)
pix2 = pixmapper(pt2)
(width, height) = image_shape(img)
... |
def decode(self, value):
"""Decode value."""
if self.encoding:
value = value.decode(self.encoding)
return self.deserialize(value) | Decode value. | Below is the the instruction that describes the task:
### Input:
Decode value.
### Response:
def decode(self, value):
"""Decode value."""
if self.encoding:
value = value.decode(self.encoding)
return self.deserialize(value) |
def parse(readDataInstance):
"""
Returns a new L{ImageBoundImportDescriptorEntry} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: A L{ReadData} object containing data to create a new L{ImageBoundImportDescriptorEntry}.
@rtype: L{ImageBoundIm... | Returns a new L{ImageBoundImportDescriptorEntry} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: A L{ReadData} object containing data to create a new L{ImageBoundImportDescriptorEntry}.
@rtype: L{ImageBoundImportDescriptorEntry}
@return: A new {Imag... | Below is the the instruction that describes the task:
### Input:
Returns a new L{ImageBoundImportDescriptorEntry} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: A L{ReadData} object containing data to create a new L{ImageBoundImportDescriptorEntry}.
@r... |
def _federation_indicators(catalog, central_catalog,
identifier_search=False):
"""Cuenta la cantidad de datasets incluídos tanto en la lista
'catalogs' como en el catálogo central, y genera indicadores a partir
de esa información.
Args:
catalog (dict): catálogo ya par... | Cuenta la cantidad de datasets incluídos tanto en la lista
'catalogs' como en el catálogo central, y genera indicadores a partir
de esa información.
Args:
catalog (dict): catálogo ya parseado
central_catalog (str o dict): ruta a catálogo central, o un dict
con el catálogo ya par... | Below is the the instruction that describes the task:
### Input:
Cuenta la cantidad de datasets incluídos tanto en la lista
'catalogs' como en el catálogo central, y genera indicadores a partir
de esa información.
Args:
catalog (dict): catálogo ya parseado
central_catalog (str o dict): ... |
def parseExtensionArgs(self, args, strict=False):
"""Parse the provider authentication policy arguments into the
internal state of this object
@param args: unqualified provider authentication policy
arguments
@param strict: Whether to raise an exception when bad data is
... | Parse the provider authentication policy arguments into the
internal state of this object
@param args: unqualified provider authentication policy
arguments
@param strict: Whether to raise an exception when bad data is
encountered
@returns: None. The data is par... | Below is the the instruction that describes the task:
### Input:
Parse the provider authentication policy arguments into the
internal state of this object
@param args: unqualified provider authentication policy
arguments
@param strict: Whether to raise an exception when bad dat... |
def step(self, actions):
"""Makes a step in all environments.
Does any preprocessing and records frames.
Args:
actions: Batch of actions.
Returns:
(obs, rewards, dones) - batches of observations, rewards and done flags
respectively.
Raises:
ValueError: when the data for c... | Makes a step in all environments.
Does any preprocessing and records frames.
Args:
actions: Batch of actions.
Returns:
(obs, rewards, dones) - batches of observations, rewards and done flags
respectively.
Raises:
ValueError: when the data for current epoch has already been lo... | Below is the the instruction that describes the task:
### Input:
Makes a step in all environments.
Does any preprocessing and records frames.
Args:
actions: Batch of actions.
Returns:
(obs, rewards, dones) - batches of observations, rewards and done flags
respectively.
Raises:
... |
def make(ctx, check, version, initial_release, skip_sign, sign_only):
"""Perform a set of operations needed to release a single check:
\b
* update the version in __about__.py
* update the changelog
* update the requirements-agent-release.txt file
* update in-toto metadata
* commit... | Perform a set of operations needed to release a single check:
\b
* update the version in __about__.py
* update the changelog
* update the requirements-agent-release.txt file
* update in-toto metadata
* commit the above changes
You can release everything at once by setting the che... | Below is the the instruction that describes the task:
### Input:
Perform a set of operations needed to release a single check:
\b
* update the version in __about__.py
* update the changelog
* update the requirements-agent-release.txt file
* update in-toto metadata
* commit the abo... |
def cast(self, dtype):
"""Cast this Block to use another data type.
Parameters
----------
dtype : str or numpy.dtype
The new data type.
"""
for child in self._children.values():
child.cast(dtype)
for _, param in self.params.items():
... | Cast this Block to use another data type.
Parameters
----------
dtype : str or numpy.dtype
The new data type. | Below is the the instruction that describes the task:
### Input:
Cast this Block to use another data type.
Parameters
----------
dtype : str or numpy.dtype
The new data type.
### Response:
def cast(self, dtype):
"""Cast this Block to use another data type.
Para... |
def radianceSpectrum(Omegas,AbsorptionCoefficient,Environment={'l':100.,'T':296.},
File=None, Format='%e %e', Wavenumber=None):
"""
INPUT PARAMETERS:
Wavenumber/Omegas: wavenumber grid (required)
AbsorptionCoefficient: absorption coefficient on grid (re... | INPUT PARAMETERS:
Wavenumber/Omegas: wavenumber grid (required)
AbsorptionCoefficient: absorption coefficient on grid (required)
Environment: dictionary containing path length in cm.
and temperature in Kelvin.
Default={'l':100.,'... | Below is the the instruction that describes the task:
### Input:
INPUT PARAMETERS:
Wavenumber/Omegas: wavenumber grid (required)
AbsorptionCoefficient: absorption coefficient on grid (required)
Environment: dictionary containing path length in cm.
... |
def get_app_model_voice(self, app_model_item):
""" App Model voice
Returns the js menu compatible voice dict if the user
can see it, None otherwise
"""
if app_model_item.get('name', None) is None:
raise ImproperlyConfigured('Model menu voices must have a name ... | App Model voice
Returns the js menu compatible voice dict if the user
can see it, None otherwise | Below is the the instruction that describes the task:
### Input:
App Model voice
Returns the js menu compatible voice dict if the user
can see it, None otherwise
### Response:
def get_app_model_voice(self, app_model_item):
""" App Model voice
Returns the js menu compatib... |
def create(self, *args, **kwargs):
"""
Allow an 'author' kwarg to automatically fill in the created_by and last_modified_by fields.
"""
if kwargs.has_key('author'):
kwargs['created_by'] = kwargs['author']
kwargs['last_modified_by'] = kwargs['author']
d... | Allow an 'author' kwarg to automatically fill in the created_by and last_modified_by fields. | Below is the the instruction that describes the task:
### Input:
Allow an 'author' kwarg to automatically fill in the created_by and last_modified_by fields.
### Response:
def create(self, *args, **kwargs):
"""
Allow an 'author' kwarg to automatically fill in the created_by and last_modified_by fie... |
def parse(self, text):
"""Parse statement/expression to Ast representation."""
self.expr = text
try:
out = ast.parse(text)
except SyntaxError:
self.raise_exception(None, msg='Syntax Error', expr=text)
except:
self.raise_exception(None, msg='Run... | Parse statement/expression to Ast representation. | Below is the the instruction that describes the task:
### Input:
Parse statement/expression to Ast representation.
### Response:
def parse(self, text):
"""Parse statement/expression to Ast representation."""
self.expr = text
try:
out = ast.parse(text)
except SyntaxError:... |
def start(self):
"""Use this method to start the Client after creating it.
Requires no parameters.
Raises:
:class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error.
``ConnectionError`` in case you try to start an already started Client.
"""
i... | Use this method to start the Client after creating it.
Requires no parameters.
Raises:
:class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error.
``ConnectionError`` in case you try to start an already started Client. | Below is the the instruction that describes the task:
### Input:
Use this method to start the Client after creating it.
Requires no parameters.
Raises:
:class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error.
``ConnectionError`` in case you try to start an alre... |
def note_update(self, note_id, coor_x=None, coor_y=None, width=None,
height=None, body=None):
"""Function to update a note (Requires login) (UNTESTED).
Parameters:
note_id (int): Where note_id is the note id.
coor_x (int): The x coordinates of the note in pix... | Function to update a note (Requires login) (UNTESTED).
Parameters:
note_id (int): Where note_id is the note id.
coor_x (int): The x coordinates of the note in pixels,
with respect to the top-left corner of the image.
coor_y (int): The y coordinates ... | Below is the the instruction that describes the task:
### Input:
Function to update a note (Requires login) (UNTESTED).
Parameters:
note_id (int): Where note_id is the note id.
coor_x (int): The x coordinates of the note in pixels,
with respect to the top-l... |
def set_pid():
"""
Explicitly ask the ipython kernel for its pid
"""
global pid
lines = '\n'.join(['import os', '_pid = os.getpid()'])
try:
msg_id = send(lines, silent=True, user_variables=['_pid'])
except TypeError: # change in IPython 3.0+
msg_id = send(lines, silent=True,... | Explicitly ask the ipython kernel for its pid | Below is the the instruction that describes the task:
### Input:
Explicitly ask the ipython kernel for its pid
### Response:
def set_pid():
"""
Explicitly ask the ipython kernel for its pid
"""
global pid
lines = '\n'.join(['import os', '_pid = os.getpid()'])
try:
msg_id = send(lin... |
def delete(self, query_id=None, **kwargs): # pragma: no cover
"""Delete a query job.
Uses the DELETE HTTP method to delete a query job. After calling
this endpoint, it is an error to poll for query results using
the queryId specified here.
Args:
query_id (str): Spe... | Delete a query job.
Uses the DELETE HTTP method to delete a query job. After calling
this endpoint, it is an error to poll for query results using
the queryId specified here.
Args:
query_id (str): Specifies the ID of the query job.
**kwargs: Supported :meth:`~pa... | Below is the the instruction that describes the task:
### Input:
Delete a query job.
Uses the DELETE HTTP method to delete a query job. After calling
this endpoint, it is an error to poll for query results using
the queryId specified here.
Args:
query_id (str): Specifie... |
def check_categories(lines):
'''
find out how many row and col categories are available
'''
# count the number of row categories
rcat_line = lines[0].split('\t')
# calc the number of row names and categories
num_rc = 0
found_end = False
# skip first tab
for inst_string in rcat_line[1:]:
if ins... | find out how many row and col categories are available | Below is the the instruction that describes the task:
### Input:
find out how many row and col categories are available
### Response:
def check_categories(lines):
'''
find out how many row and col categories are available
'''
# count the number of row categories
rcat_line = lines[0].split('\t')
# calc... |
def get_expire_time(cache_duration=None, valid_until=None):
"""
Compares 2 dates and returns the earliest.
:param cache_duration: The duration, as a string.
:type: string
:param valid_until: The valid until date, as a string or as a timestamp
:type: string
:ret... | Compares 2 dates and returns the earliest.
:param cache_duration: The duration, as a string.
:type: string
:param valid_until: The valid until date, as a string or as a timestamp
:type: string
:return: The expiration time.
:rtype: int | Below is the the instruction that describes the task:
### Input:
Compares 2 dates and returns the earliest.
:param cache_duration: The duration, as a string.
:type: string
:param valid_until: The valid until date, as a string or as a timestamp
:type: string
:return: The ex... |
def named_eq_relations(self, name, neg=False):
'''Returns list of named eqLinks.
<name> may be string or list.
'''
if self.eqLinks and not neg:
if isinstance(name, six.string_types):
return filter(lambda x: x.relation.name == name,
... | Returns list of named eqLinks.
<name> may be string or list. | Below is the the instruction that describes the task:
### Input:
Returns list of named eqLinks.
<name> may be string or list.
### Response:
def named_eq_relations(self, name, neg=False):
'''Returns list of named eqLinks.
<name> may be string or list.
'''
if self.eqLinks an... |
def fetch_git_package(self, config):
"""Make a remote git repository available for local use.
Args:
config (dict): git config dictionary
"""
# only loading git here when needed to avoid load errors on systems
# without git installed
from git import Repo
... | Make a remote git repository available for local use.
Args:
config (dict): git config dictionary | Below is the the instruction that describes the task:
### Input:
Make a remote git repository available for local use.
Args:
config (dict): git config dictionary
### Response:
def fetch_git_package(self, config):
"""Make a remote git repository available for local use.
Args:
... |
def as_txt(self):
"""Text rendering of error response.
Designed for use with Image API version 1.1 and above where the
error response is suggested to be text or html but not otherwise
specified. Intended to provide useful information for debugging.
"""
s = "IIIF Image Se... | Text rendering of error response.
Designed for use with Image API version 1.1 and above where the
error response is suggested to be text or html but not otherwise
specified. Intended to provide useful information for debugging. | Below is the the instruction that describes the task:
### Input:
Text rendering of error response.
Designed for use with Image API version 1.1 and above where the
error response is suggested to be text or html but not otherwise
specified. Intended to provide useful information for debugging... |
def sessions_info(self, hosts):
"""Returns ClientInfo per session.
:param hosts: comma separated lists of members of the ZK ensemble.
:returns: A dictionary of (session_id, ClientInfo).
"""
info_by_id = {}
for server_endpoint, dump in self.dump_by_server(hosts).items()... | Returns ClientInfo per session.
:param hosts: comma separated lists of members of the ZK ensemble.
:returns: A dictionary of (session_id, ClientInfo). | Below is the the instruction that describes the task:
### Input:
Returns ClientInfo per session.
:param hosts: comma separated lists of members of the ZK ensemble.
:returns: A dictionary of (session_id, ClientInfo).
### Response:
def sessions_info(self, hosts):
"""Returns ClientInfo per se... |
def json_integrity(baseline, suspect):
"""
Summary:
Validates baseline dict against suspect dict to ensure contain USERNAME
k,v parameters.
Args:
baseline (dict): baseline json structure
suspect (dict): json object validated against baseline structure
Returns:
Suc... | Summary:
Validates baseline dict against suspect dict to ensure contain USERNAME
k,v parameters.
Args:
baseline (dict): baseline json structure
suspect (dict): json object validated against baseline structure
Returns:
Success (matches baseline) | Failure (no match), TYPE:... | Below is the the instruction that describes the task:
### Input:
Summary:
Validates baseline dict against suspect dict to ensure contain USERNAME
k,v parameters.
Args:
baseline (dict): baseline json structure
suspect (dict): json object validated against baseline structure
Re... |
def spawn_spark_cluster(job,
numWorkers,
cores=None,
memory=None,
disk=None,
overrideLeaderIP=None):
'''
:param numWorkers: The number of worker nodes to have in the cluster. \
Must be gre... | :param numWorkers: The number of worker nodes to have in the cluster. \
Must be greater than or equal to 1.
:param cores: Optional parameter to set the number of cores per node. \
If not provided, we use the number of cores on the node that launches \
the service.
:param memory: Optional parameter t... | Below is the the instruction that describes the task:
### Input:
:param numWorkers: The number of worker nodes to have in the cluster. \
Must be greater than or equal to 1.
:param cores: Optional parameter to set the number of cores per node. \
If not provided, we use the number of cores on the node tha... |
def keys(self, pattern=None):
"""Returns a list of keys matching ``pattern``.
By default return all keys.
>>> dc = Dictator()
>>> dc['l0'] = [1, 2, 3, 4]
>>> dc['s0'] = 'string value'
>>> dc.keys()
['l0', 's0']
>>> dc.keys('h*')
[]
>>> dc.... | Returns a list of keys matching ``pattern``.
By default return all keys.
>>> dc = Dictator()
>>> dc['l0'] = [1, 2, 3, 4]
>>> dc['s0'] = 'string value'
>>> dc.keys()
['l0', 's0']
>>> dc.keys('h*')
[]
>>> dc.clear()
:param pattern: key patt... | Below is the the instruction that describes the task:
### Input:
Returns a list of keys matching ``pattern``.
By default return all keys.
>>> dc = Dictator()
>>> dc['l0'] = [1, 2, 3, 4]
>>> dc['s0'] = 'string value'
>>> dc.keys()
['l0', 's0']
>>> dc.keys('h*'... |
def planfn(*args, **kwargs):
'''
planfn(val1=fn1, val2=fn2...) uses the pimms plan mechanism to yield a function f that produces
an immutable imap when called with the correct paramters. Unlike in plan(), planfn() does not
care about the names of the calculation units; instead the val1, val2, etc. a... | planfn(val1=fn1, val2=fn2...) uses the pimms plan mechanism to yield a function f that produces
an immutable imap when called with the correct paramters. Unlike in plan(), planfn() does not
care about the names of the calculation units; instead the val1, val2, etc. are names of the
efferent values whi... | Below is the the instruction that describes the task:
### Input:
planfn(val1=fn1, val2=fn2...) uses the pimms plan mechanism to yield a function f that produces
an immutable imap when called with the correct paramters. Unlike in plan(), planfn() does not
care about the names of the calculation units; in... |
def to_iso_time_string(self) -> str:
""" Return the iso time string only """
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{second:02}" | Return the iso time string only | Below is the the instruction that describes the task:
### Input:
Return the iso time string only
### Response:
def to_iso_time_string(self) -> str:
""" Return the iso time string only """
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{secon... |
def set_log_level(log_level):
"""
Set logging level of this module. Using
`logbook <https://logbook.readthedocs.io/en/stable/>`__ module for logging.
:param int log_level:
One of the log level of
`logbook <https://logbook.readthedocs.io/en/stable/api/base.html>`__.
Disabled logg... | Set logging level of this module. Using
`logbook <https://logbook.readthedocs.io/en/stable/>`__ module for logging.
:param int log_level:
One of the log level of
`logbook <https://logbook.readthedocs.io/en/stable/api/base.html>`__.
Disabled logging if ``log_level`` is ``logbook.NOTSET``... | Below is the the instruction that describes the task:
### Input:
Set logging level of this module. Using
`logbook <https://logbook.readthedocs.io/en/stable/>`__ module for logging.
:param int log_level:
One of the log level of
`logbook <https://logbook.readthedocs.io/en/stable/api/base.html... |
def pull_image(self, image_name, stream=None):
"""
Ask Docker to pull the container image with given name.
Parameters
----------
image_name str
Name of the image
stream samcli.lib.utils.stream_writer.StreamWriter
Optional stream writer to output t... | Ask Docker to pull the container image with given name.
Parameters
----------
image_name str
Name of the image
stream samcli.lib.utils.stream_writer.StreamWriter
Optional stream writer to output to. Defaults to stderr
Raises
------
Docker... | Below is the the instruction that describes the task:
### Input:
Ask Docker to pull the container image with given name.
Parameters
----------
image_name str
Name of the image
stream samcli.lib.utils.stream_writer.StreamWriter
Optional stream writer to output... |
def range_daily(start=None, stop=None, timezone='UTC', count=None):
"""
This an alternative way to generating sets of Delorean objects with
DAILY stops
"""
return stops(start=start, stop=stop, freq=DAILY, timezone=timezone, count=count) | This an alternative way to generating sets of Delorean objects with
DAILY stops | Below is the the instruction that describes the task:
### Input:
This an alternative way to generating sets of Delorean objects with
DAILY stops
### Response:
def range_daily(start=None, stop=None, timezone='UTC', count=None):
"""
This an alternative way to generating sets of Delorean objects with
... |
def cmd_list(unused_conf: Config):
"""Print out information on loaded builders and hooks."""
for name, builder in sorted(Plugin.builders.items()):
if builder.func:
print('+- {0:16s} implemented in {1.__module__}.{1.__name__}()'
.format(name, builder.func))
else:
... | Print out information on loaded builders and hooks. | Below is the the instruction that describes the task:
### Input:
Print out information on loaded builders and hooks.
### Response:
def cmd_list(unused_conf: Config):
"""Print out information on loaded builders and hooks."""
for name, builder in sorted(Plugin.builders.items()):
if builder.func:
... |
def output(self, name):
"""Returns the output buffer for the specified output name (e.g., 'stdout'), creating it if
necessary.
:API: public
"""
m = WorkUnit._valid_name_re.match(name)
if not m or m.group(0) != name:
raise Exception('Invalid output name: {}'.format(name))
if name not i... | Returns the output buffer for the specified output name (e.g., 'stdout'), creating it if
necessary.
:API: public | Below is the the instruction that describes the task:
### Input:
Returns the output buffer for the specified output name (e.g., 'stdout'), creating it if
necessary.
:API: public
### Response:
def output(self, name):
"""Returns the output buffer for the specified output name (e.g., 'stdout'), creating ... |
def boll(self, n, dev, array=False):
"""布林通道"""
mid = self.sma(n, array)
std = self.std(n, array)
up = mid + std * dev
down = mid - std * dev
return up, down | 布林通道 | Below is the the instruction that describes the task:
### Input:
布林通道
### Response:
def boll(self, n, dev, array=False):
"""布林通道"""
mid = self.sma(n, array)
std = self.std(n, array)
up = mid + std * dev
down = mid - std * dev
return up, down |
def get_actions(self, request):
"""Disable the "delete selected" admin action.
Otherwise the action is present even though has_delete_permission is False, it just doesn't
work.
"""
actions = super(CertificateMixin, self).get_actions(request)
actions.pop('delete_selected'... | Disable the "delete selected" admin action.
Otherwise the action is present even though has_delete_permission is False, it just doesn't
work. | Below is the the instruction that describes the task:
### Input:
Disable the "delete selected" admin action.
Otherwise the action is present even though has_delete_permission is False, it just doesn't
work.
### Response:
def get_actions(self, request):
"""Disable the "delete selected" admi... |
def cmd_full_return(
self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
verbose=False,
kwarg=None,
**kwargs):
'''
Execute a salt command and return
'''
was_... | Execute a salt command and return | Below is the the instruction that describes the task:
### Input:
Execute a salt command and return
### Response:
def cmd_full_return(
self,
tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
verbose=False,
... |
def detect_events(self, data, method, params, label):
"""Detect events and display on signal.
Parameters
----------
data : instance of ChanTime
one segment with all channels of interest
method : str
Method used for detection.
params : dict
... | Detect events and display on signal.
Parameters
----------
data : instance of ChanTime
one segment with all channels of interest
method : str
Method used for detection.
params : dict
Parameters used for detection.
label : str
... | Below is the the instruction that describes the task:
### Input:
Detect events and display on signal.
Parameters
----------
data : instance of ChanTime
one segment with all channels of interest
method : str
Method used for detection.
params : dict
... |
def text_filepaths_for_task(self, tmp_dir, task_id):
"""List of input filepaths for a particular training or dev shard.
Args:
tmp_dir: a string
task_id: an integer less than self.num_shards
Returns:
a list of tuples (filepath, start_pos, num_bytes)
"""
assert task_id >= 0
asse... | List of input filepaths for a particular training or dev shard.
Args:
tmp_dir: a string
task_id: an integer less than self.num_shards
Returns:
a list of tuples (filepath, start_pos, num_bytes) | Below is the the instruction that describes the task:
### Input:
List of input filepaths for a particular training or dev shard.
Args:
tmp_dir: a string
task_id: an integer less than self.num_shards
Returns:
a list of tuples (filepath, start_pos, num_bytes)
### Response:
def text_filepat... |
def l(*members, meta=None) -> List:
"""Creates a new list from members."""
return List( # pylint: disable=abstract-class-instantiated
plist(iterable=members), meta=meta
) | Creates a new list from members. | Below is the the instruction that describes the task:
### Input:
Creates a new list from members.
### Response:
def l(*members, meta=None) -> List:
"""Creates a new list from members."""
return List( # pylint: disable=abstract-class-instantiated
plist(iterable=members), meta=meta
) |
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
"""
Index Map Read from File Method
"""
# Set file extension property
self.fileExtension = extension
# Open file and read plain text into text field
... | Index Map Read from File Method | Below is the the instruction that describes the task:
### Input:
Index Map Read from File Method
### Response:
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
"""
Index Map Read from File Method
"""
# Set file exte... |
def generate(self):
'''
Generate noise samples.
Returns:
`np.ndarray` of samples.
'''
sampled_arr = np.zeros((self.__batch_size, self.__channel, self.__seq_len, self.__dim))
for batch in range(self.__batch_size):
for i in range(... | Generate noise samples.
Returns:
`np.ndarray` of samples. | Below is the the instruction that describes the task:
### Input:
Generate noise samples.
Returns:
`np.ndarray` of samples.
### Response:
def generate(self):
'''
Generate noise samples.
Returns:
`np.ndarray` of samples.
'''
... |
def delta_unaccelerated(self):
"""The relative delta of the unaccelerated motion vector of
the current event.
For gesture events that are not of type
:attr:`~libinput.constant.EventType.GESTURE_SWIPE_UPDATE` or
:attr:`~libinput.constant.EventType.GESTURE_PINCH_UPDATE`, this
property raises :exc:`AttributeE... | The relative delta of the unaccelerated motion vector of
the current event.
For gesture events that are not of type
:attr:`~libinput.constant.EventType.GESTURE_SWIPE_UPDATE` or
:attr:`~libinput.constant.EventType.GESTURE_PINCH_UPDATE`, this
property raises :exc:`AttributeError`.
Relative unaccelerated mot... | Below is the the instruction that describes the task:
### Input:
The relative delta of the unaccelerated motion vector of
the current event.
For gesture events that are not of type
:attr:`~libinput.constant.EventType.GESTURE_SWIPE_UPDATE` or
:attr:`~libinput.constant.EventType.GESTURE_PINCH_UPDATE`, this
... |
def cross(self, other):
'''
:other: Point or point equivalent
:return: float
Vector cross product of points U (self) and V (other), computed:
U x V = (u1*i + u2*j + u3*k) x (v1*i + v2*j + v3*k)
s1 = u2v3 - u3v2
s2 = u3v1 - u1v3
s3 = u1v2 - u2v1
... | :other: Point or point equivalent
:return: float
Vector cross product of points U (self) and V (other), computed:
U x V = (u1*i + u2*j + u3*k) x (v1*i + v2*j + v3*k)
s1 = u2v3 - u3v2
s2 = u3v1 - u1v3
s3 = u1v2 - u2v1
U x V = s1 + s2 + s3
Returns a floa... | Below is the the instruction that describes the task:
### Input:
:other: Point or point equivalent
:return: float
Vector cross product of points U (self) and V (other), computed:
U x V = (u1*i + u2*j + u3*k) x (v1*i + v2*j + v3*k)
s1 = u2v3 - u3v2
s2 = u3v1 - u1v3
s... |
def console_get_height_rect(
con: tcod.console.Console, x: int, y: int, w: int, h: int, fmt: str
) -> int:
"""Return the height of this text once word-wrapped into this rectangle.
Returns:
int: The number of lines of text once word-wrapped.
.. deprecated:: 8.5
Use :any:`Console.get_hei... | Return the height of this text once word-wrapped into this rectangle.
Returns:
int: The number of lines of text once word-wrapped.
.. deprecated:: 8.5
Use :any:`Console.get_height_rect` instead. | Below is the the instruction that describes the task:
### Input:
Return the height of this text once word-wrapped into this rectangle.
Returns:
int: The number of lines of text once word-wrapped.
.. deprecated:: 8.5
Use :any:`Console.get_height_rect` instead.
### Response:
def console_get... |
def pretty_to_link(inst, link):
'''
Create a human-readable representation of a link on the 'TO'-side
'''
values = ''
prefix = ''
metaclass = xtuml.get_metaclass(inst)
for name, ty in metaclass.attributes:
if name in link.key_map:
value = getattr(inst, name)
... | Create a human-readable representation of a link on the 'TO'-side | Below is the the instruction that describes the task:
### Input:
Create a human-readable representation of a link on the 'TO'-side
### Response:
def pretty_to_link(inst, link):
'''
Create a human-readable representation of a link on the 'TO'-side
'''
values = ''
prefix = ''
metaclass = xtum... |
def do_GET(self):
"""Serve a GET request."""
f = self.send_head()
if f:
self.copyfile(f, self.wfile)
f.close() | Serve a GET request. | Below is the the instruction that describes the task:
### Input:
Serve a GET request.
### Response:
def do_GET(self):
"""Serve a GET request."""
f = self.send_head()
if f:
self.copyfile(f, self.wfile)
f.close() |
def _set_pfc(self, v, load=False):
"""
Setter method for pfc, mapped from YANG variable /interface/port_channel/qos/flowcontrol/pfc (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_pfc is considered as a private
method. Backends looking to populate this variabl... | Setter method for pfc, mapped from YANG variable /interface/port_channel/qos/flowcontrol/pfc (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_pfc is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_pfc... | Below is the the instruction that describes the task:
### Input:
Setter method for pfc, mapped from YANG variable /interface/port_channel/qos/flowcontrol/pfc (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_pfc is considered as a private
method. Backends looking to... |
def get_agg_data(cls, obj, category=None):
"""
Reduces any Overlay or NdOverlay of Elements into a single
xarray Dataset that can be aggregated.
"""
paths = []
if isinstance(obj, Graph):
obj = obj.edgepaths
kdims = list(obj.kdims)
vdims = list(... | Reduces any Overlay or NdOverlay of Elements into a single
xarray Dataset that can be aggregated. | Below is the the instruction that describes the task:
### Input:
Reduces any Overlay or NdOverlay of Elements into a single
xarray Dataset that can be aggregated.
### Response:
def get_agg_data(cls, obj, category=None):
"""
Reduces any Overlay or NdOverlay of Elements into a single
... |
def getNamespace(self, prefix):
"""prefix -- deference namespace prefix in node's context.
Ascends parent nodes until found.
"""
namespace = None
if prefix == 'xmlns':
namespace = DOM.findDefaultNS(prefix, self.__node)
else:
try:
... | prefix -- deference namespace prefix in node's context.
Ascends parent nodes until found. | Below is the the instruction that describes the task:
### Input:
prefix -- deference namespace prefix in node's context.
Ascends parent nodes until found.
### Response:
def getNamespace(self, prefix):
"""prefix -- deference namespace prefix in node's context.
Ascends parent nodes unti... |
def enforce(self, rule, target, creds, exc=None, *args, **kwargs):
"""Checks authorization of a rule against the target and credentials."""
self.load_rules()
if isinstance(rule, checks.BaseCheck):
result = rule(target, creds, self, rule)
elif not self.rules:
# N... | Checks authorization of a rule against the target and credentials. | Below is the the instruction that describes the task:
### Input:
Checks authorization of a rule against the target and credentials.
### Response:
def enforce(self, rule, target, creds, exc=None, *args, **kwargs):
"""Checks authorization of a rule against the target and credentials."""
self.load_ru... |
def absence_info(self):
"""Return information about the user's absences."""
# FIXME: remove recursive dep
from ..eighth.models import EighthSignup
return EighthSignup.objects.filter(user=self, was_absent=True, scheduled_activity__attendance_taken=True) | Return information about the user's absences. | Below is the the instruction that describes the task:
### Input:
Return information about the user's absences.
### Response:
def absence_info(self):
"""Return information about the user's absences."""
# FIXME: remove recursive dep
from ..eighth.models import EighthSignup
return Eig... |
def users(self, username=None, pk=None, **kwargs):
"""
Users of KE-chain.
Provide a list of :class:`User`s of KE-chain. You can filter on username or id or any other advanced filter.
:param username: (optional) username to filter
:type username: basestring or None
:para... | Users of KE-chain.
Provide a list of :class:`User`s of KE-chain. You can filter on username or id or any other advanced filter.
:param username: (optional) username to filter
:type username: basestring or None
:param pk: (optional) id of the user to filter
:type pk: basestring ... | Below is the the instruction that describes the task:
### Input:
Users of KE-chain.
Provide a list of :class:`User`s of KE-chain. You can filter on username or id or any other advanced filter.
:param username: (optional) username to filter
:type username: basestring or None
:param ... |
def date_to_string(date):
"""Transform a date or datetime object into a string and return it.
Examples:
>>> date_to_string(datetime.datetime(2012, 1, 3, 12, 23, 34, tzinfo=UTC))
'2012-01-03T12:23:34+00:00'
>>> date_to_string(datetime.datetime(2012, 1, 3, 12, 23, 34))
'2012-01-03T12:23:34'
>... | Transform a date or datetime object into a string and return it.
Examples:
>>> date_to_string(datetime.datetime(2012, 1, 3, 12, 23, 34, tzinfo=UTC))
'2012-01-03T12:23:34+00:00'
>>> date_to_string(datetime.datetime(2012, 1, 3, 12, 23, 34))
'2012-01-03T12:23:34'
>>> date_to_string(datetime.date(2... | Below is the the instruction that describes the task:
### Input:
Transform a date or datetime object into a string and return it.
Examples:
>>> date_to_string(datetime.datetime(2012, 1, 3, 12, 23, 34, tzinfo=UTC))
'2012-01-03T12:23:34+00:00'
>>> date_to_string(datetime.datetime(2012, 1, 3, 12, 23, ... |
def ClientCertFromCSR(cls, csr):
"""Creates a new cert for the given common name.
Args:
csr: A CertificateSigningRequest.
Returns:
The signed cert.
"""
builder = x509.CertificateBuilder()
# Use the client CN for a cert serial_id. This will ensure we do
# not have clashing cert ... | Creates a new cert for the given common name.
Args:
csr: A CertificateSigningRequest.
Returns:
The signed cert. | Below is the the instruction that describes the task:
### Input:
Creates a new cert for the given common name.
Args:
csr: A CertificateSigningRequest.
Returns:
The signed cert.
### Response:
def ClientCertFromCSR(cls, csr):
"""Creates a new cert for the given common name.
Args:
... |
def attr_gen(self, attr):
"""Returns attribute generator that yields namedtuples containing
path value pairs
Parameters
----------
attr : str
Name of the search attribute
Returns
-------
attr_generator : generator
Returns ... | Returns attribute generator that yields namedtuples containing
path value pairs
Parameters
----------
attr : str
Name of the search attribute
Returns
-------
attr_generator : generator
Returns a generator that yields named tuples ... | Below is the the instruction that describes the task:
### Input:
Returns attribute generator that yields namedtuples containing
path value pairs
Parameters
----------
attr : str
Name of the search attribute
Returns
-------
attr_generator ... |
def ss_reg(self):
"""Sum of squares of the regression."""
return np.sum(np.square(self.predicted - self.ybar), axis=0) | Sum of squares of the regression. | Below is the the instruction that describes the task:
### Input:
Sum of squares of the regression.
### Response:
def ss_reg(self):
"""Sum of squares of the regression."""
return np.sum(np.square(self.predicted - self.ybar), axis=0) |
def uinit(self, ushape):
"""Return initialiser for working variable U."""
if self.opt['Y0'] is None:
return np.zeros(ushape, dtype=self.dtype)
else:
# If initial Y is non-zero, initial U is chosen so that
# the relevant dual optimality criterion (see (3.10) i... | Return initialiser for working variable U. | Below is the the instruction that describes the task:
### Input:
Return initialiser for working variable U.
### Response:
def uinit(self, ushape):
"""Return initialiser for working variable U."""
if self.opt['Y0'] is None:
return np.zeros(ushape, dtype=self.dtype)
else:
... |
def alphabetical_formula(self):
"""
Returns a reduced formula string with appended charge
"""
alph_formula = super().alphabetical_formula
chg_str = ""
if self.charge > 0:
chg_str = " +" + formula_double_format(self.charge, False)
elif self.charge < 0:
... | Returns a reduced formula string with appended charge | Below is the the instruction that describes the task:
### Input:
Returns a reduced formula string with appended charge
### Response:
def alphabetical_formula(self):
"""
Returns a reduced formula string with appended charge
"""
alph_formula = super().alphabetical_formula
chg_... |
def to_nifti(obj, like=None, header=None, affine=None, extensions=Ellipsis, version=1):
'''
to_nifti(obj) yields a Nifti2Image object that is as equivalent as possible to the given object
obj. If obj is a Nifti2Image already, then it is returned unmolested; other deduction rules
are described below.... | to_nifti(obj) yields a Nifti2Image object that is as equivalent as possible to the given object
obj. If obj is a Nifti2Image already, then it is returned unmolested; other deduction rules
are described below.
The following options are accepted:
* like (default: None) may be provided to give a gui... | Below is the the instruction that describes the task:
### Input:
to_nifti(obj) yields a Nifti2Image object that is as equivalent as possible to the given object
obj. If obj is a Nifti2Image already, then it is returned unmolested; other deduction rules
are described below.
The following options are... |
def _get_bandwidth_price_id(items,
hourly=True,
no_public=False,
location=None):
"""Choose a valid price id for bandwidth."""
# Prefer pay-for-use data transfer with hourly
for item in items:
capacity = float(item.... | Choose a valid price id for bandwidth. | Below is the the instruction that describes the task:
### Input:
Choose a valid price id for bandwidth.
### Response:
def _get_bandwidth_price_id(items,
hourly=True,
no_public=False,
location=None):
"""Choose a valid price id f... |
def to_gremlin(self):
"""Return a unicode object with the Gremlin representation of this block."""
self.validate()
template = (
u'transform{{'
u'it, m -> new com.orientechnologies.orient.core.record.impl.ODocument([ {} ])'
u'}}')
field_representation... | Return a unicode object with the Gremlin representation of this block. | Below is the the instruction that describes the task:
### Input:
Return a unicode object with the Gremlin representation of this block.
### Response:
def to_gremlin(self):
"""Return a unicode object with the Gremlin representation of this block."""
self.validate()
template = (
... |
def findall(self, string):
""" Parse string, returning all outputs as parsed by functions
"""
output = []
for match in self.pattern.findall(string):
if hasattr(match, 'strip'):
match = [match]
self._list_add(output, self.run(match))
return ... | Parse string, returning all outputs as parsed by functions | Below is the the instruction that describes the task:
### Input:
Parse string, returning all outputs as parsed by functions
### Response:
def findall(self, string):
""" Parse string, returning all outputs as parsed by functions
"""
output = []
for match in self.pattern.findall(strin... |
def connect_to_syslog(address=None, facility=None, level=None):
"""
Create a :class:`~logging.handlers.SysLogHandler`.
:param address: The device file or network address of the system logging
daemon (a string or tuple, defaults to the result of
:func:`find_syslog_add... | Create a :class:`~logging.handlers.SysLogHandler`.
:param address: The device file or network address of the system logging
daemon (a string or tuple, defaults to the result of
:func:`find_syslog_address()`).
:param facility: Refer to :class:`~logging.handlers.SysLogHand... | Below is the the instruction that describes the task:
### Input:
Create a :class:`~logging.handlers.SysLogHandler`.
:param address: The device file or network address of the system logging
daemon (a string or tuple, defaults to the result of
:func:`find_syslog_address()`... |
def _build_block_element_list(self):
"""Return a list of block elements, ordered from highest priority to lowest.
"""
return sorted(
[e for e in self.block_elements.values() if not e.virtual],
key=lambda e: e.priority,
reverse=True
) | Return a list of block elements, ordered from highest priority to lowest. | Below is the the instruction that describes the task:
### Input:
Return a list of block elements, ordered from highest priority to lowest.
### Response:
def _build_block_element_list(self):
"""Return a list of block elements, ordered from highest priority to lowest.
"""
return sorted(
... |
def example_exc_handler(tries_remaining, exception, delay):
"""Example exception handler; prints a warning to stderr.
tries_remaining: The number of tries remaining.
exception: The exception instance which was raised.
"""
print >> sys.stderr, "Caught '%s', %d tries remaining, sleeping for %s second... | Example exception handler; prints a warning to stderr.
tries_remaining: The number of tries remaining.
exception: The exception instance which was raised. | Below is the the instruction that describes the task:
### Input:
Example exception handler; prints a warning to stderr.
tries_remaining: The number of tries remaining.
exception: The exception instance which was raised.
### Response:
def example_exc_handler(tries_remaining, exception, delay):
"""Examp... |
def _validate_isvalid_uncertainty(self, isvalid_uncertainty, field, value):
"""Checks for valid given value and appropriate units with uncertainty.
Args:
isvalid_uncertainty (`bool`): flag from schema indicating uncertainty to be checked
field (`str`): property associated with t... | Checks for valid given value and appropriate units with uncertainty.
Args:
isvalid_uncertainty (`bool`): flag from schema indicating uncertainty to be checked
field (`str`): property associated with the quantity in question.
value (`list`): list with the string of the value ... | Below is the the instruction that describes the task:
### Input:
Checks for valid given value and appropriate units with uncertainty.
Args:
isvalid_uncertainty (`bool`): flag from schema indicating uncertainty to be checked
field (`str`): property associated with the quantity in que... |
def _check_self_cls_assign(self, node):
"""Check that self/cls don't get assigned"""
assign_names = {
target.name
for target in node.targets
if isinstance(target, astroid.AssignName)
}
scope = node.scope()
nonlocals_with_same_name = any(
... | Check that self/cls don't get assigned | Below is the the instruction that describes the task:
### Input:
Check that self/cls don't get assigned
### Response:
def _check_self_cls_assign(self, node):
"""Check that self/cls don't get assigned"""
assign_names = {
target.name
for target in node.targets
if i... |
def run(self):
'''
Runs all enabled tests.
'''
# Run all tests.
for cls in self.get_test_classes():
# Print informational message.
self.logger.info('Running {cls.__name__} test...'.format(cls=cls))
# Create new test instance.
test... | Runs all enabled tests. | Below is the the instruction that describes the task:
### Input:
Runs all enabled tests.
### Response:
def run(self):
'''
Runs all enabled tests.
'''
# Run all tests.
for cls in self.get_test_classes():
# Print informational message.
self.logger.info... |
def update(self, ava):
"""
Implements the dict.update() method
"""
for key, val in ava.items():
self[key] = val | Implements the dict.update() method | Below is the the instruction that describes the task:
### Input:
Implements the dict.update() method
### Response:
def update(self, ava):
"""
Implements the dict.update() method
"""
for key, val in ava.items():
self[key] = val |
def findTextBackward(self, block, column, needle):
"""Search for a needle and return (block, column)
Raise ValueError, if not found
"""
if column is not None:
index = block.text()[:column].rfind(needle)
else:
index = block.text().rfind(needle)
if ... | Search for a needle and return (block, column)
Raise ValueError, if not found | Below is the the instruction that describes the task:
### Input:
Search for a needle and return (block, column)
Raise ValueError, if not found
### Response:
def findTextBackward(self, block, column, needle):
"""Search for a needle and return (block, column)
Raise ValueError, if not found
... |
def setVisible(self, value):
"""Override Qt method to stops timers if widget is not visible."""
if self.timer is not None:
if value:
self.timer.start(self._interval)
else:
self.timer.stop()
super(BaseTimerStatus, self).setVisible(value) | Override Qt method to stops timers if widget is not visible. | Below is the the instruction that describes the task:
### Input:
Override Qt method to stops timers if widget is not visible.
### Response:
def setVisible(self, value):
"""Override Qt method to stops timers if widget is not visible."""
if self.timer is not None:
if value:
... |
def shorrocks_index(A):
r"""
Implements Shorrocks mobility index
Parameters
-----------
A : array_like(float)
Square matrix with transition probabilities (mobility matrix) of
dimension m
Returns
--------
Shorrocks index: float
The Shorrocks mobility index calcul... | r"""
Implements Shorrocks mobility index
Parameters
-----------
A : array_like(float)
Square matrix with transition probabilities (mobility matrix) of
dimension m
Returns
--------
Shorrocks index: float
The Shorrocks mobility index calculated as
.. math::
... | Below is the the instruction that describes the task:
### Input:
r"""
Implements Shorrocks mobility index
Parameters
-----------
A : array_like(float)
Square matrix with transition probabilities (mobility matrix) of
dimension m
Returns
--------
Shorrocks index: float
... |
def get_mac_address_table_input_request_type_get_next_request_mac_address_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_mac_address_table = ET.Element("get_mac_address_table")
config = get_mac_address_table
input = ET.SubElement(get_ma... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_mac_address_table_input_request_type_get_next_request_mac_address_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_mac_address_table = ET.Elem... |
def callback_parent(attr, old, new):
'''Update data directories drop down with new parent directory'''
import os
# Remove accidental white space if copy/pasted
new = new.strip()
parent_input.value = new
# Verify new parent path exists and update `datadirs_select` widget
if os.path.exists(n... | Update data directories drop down with new parent directory | Below is the the instruction that describes the task:
### Input:
Update data directories drop down with new parent directory
### Response:
def callback_parent(attr, old, new):
'''Update data directories drop down with new parent directory'''
import os
# Remove accidental white space if copy/pasted
... |
def sv_variant(store, institute_id, case_name, variant_id=None, variant_obj=None, add_case=True,
get_overlapping=True):
"""Pre-process an SV variant entry for detail page.
Adds information to display variant
Args:
store(scout.adapter.MongoAdapter)
institute_id(str)
c... | Pre-process an SV variant entry for detail page.
Adds information to display variant
Args:
store(scout.adapter.MongoAdapter)
institute_id(str)
case_name(str)
variant_id(str)
variant_obj(dcit)
add_case(bool): If information about case files should be added
R... | Below is the the instruction that describes the task:
### Input:
Pre-process an SV variant entry for detail page.
Adds information to display variant
Args:
store(scout.adapter.MongoAdapter)
institute_id(str)
case_name(str)
variant_id(str)
variant_obj(dcit)
a... |
def charge(self, cart, request):
"""
Use the Stripe token from the request and charge immediately.
This view is invoked by the Javascript function `scope.charge()` delivered
by `get_payment_request`.
"""
token_id = cart.extra['payment_extra_data']['token_id']
if L... | Use the Stripe token from the request and charge immediately.
This view is invoked by the Javascript function `scope.charge()` delivered
by `get_payment_request`. | Below is the the instruction that describes the task:
### Input:
Use the Stripe token from the request and charge immediately.
This view is invoked by the Javascript function `scope.charge()` delivered
by `get_payment_request`.
### Response:
def charge(self, cart, request):
"""
Use ... |
def _ShouldPrintError(category, confidence, linenum):
"""If confidence >= verbose, category passes filter and is not suppressed."""
# There are three ways we might decide not to print an error message:
# a "NOLINT(category)" comment appears in the source,
# the verbosity level isn't high enough, or the filters... | If confidence >= verbose, category passes filter and is not suppressed. | Below is the the instruction that describes the task:
### Input:
If confidence >= verbose, category passes filter and is not suppressed.
### Response:
def _ShouldPrintError(category, confidence, linenum):
"""If confidence >= verbose, category passes filter and is not suppressed."""
# There are three ways we m... |
def get_context(line, pos):
"""
computes start and end position of substring of line that is the
command string under given position
"""
commands = split_commandline(line) + ['']
i = 0
start = 0
end = len(commands[i])
while pos > end:
i... | computes start and end position of substring of line that is the
command string under given position | Below is the the instruction that describes the task:
### Input:
computes start and end position of substring of line that is the
command string under given position
### Response:
def get_context(line, pos):
"""
computes start and end position of substring of line that is the
comman... |
def check_geographic_region(self, ds):
"""
6.1.1 When data is representative of geographic regions which can be identified by names but which have complex
boundaries that cannot practically be specified using longitude and latitude boundary coordinates, a labeled
axis should be used to i... | 6.1.1 When data is representative of geographic regions which can be identified by names but which have complex
boundaries that cannot practically be specified using longitude and latitude boundary coordinates, a labeled
axis should be used to identify the regions.
Recommend that the names be c... | Below is the the instruction that describes the task:
### Input:
6.1.1 When data is representative of geographic regions which can be identified by names but which have complex
boundaries that cannot practically be specified using longitude and latitude boundary coordinates, a labeled
axis should be... |
def save_sequence_rule(self, sequence_rule_form, *args, **kwargs):
"""Pass through to provider SequenceRuleAdminSession.update_sequence_rule"""
# Implemented from kitosid template for -
# osid.resource.ResourceAdminSession.update_resource
if sequence_rule_form.is_for_update():
... | Pass through to provider SequenceRuleAdminSession.update_sequence_rule | Below is the the instruction that describes the task:
### Input:
Pass through to provider SequenceRuleAdminSession.update_sequence_rule
### Response:
def save_sequence_rule(self, sequence_rule_form, *args, **kwargs):
"""Pass through to provider SequenceRuleAdminSession.update_sequence_rule"""
# Imp... |
def element_wise(self, other, op):
"""
Apply an elementwise operation to data.
Both self and other data must have the same mode.
If self is in local mode, other can also be a numpy array.
Self and other must have the same shape, or other must be a scalar.
Parameters
... | Apply an elementwise operation to data.
Both self and other data must have the same mode.
If self is in local mode, other can also be a numpy array.
Self and other must have the same shape, or other must be a scalar.
Parameters
----------
other : Data or numpy array
... | Below is the the instruction that describes the task:
### Input:
Apply an elementwise operation to data.
Both self and other data must have the same mode.
If self is in local mode, other can also be a numpy array.
Self and other must have the same shape, or other must be a scalar.
... |
def update_terminal_regions(self, tree, X, y, residual, y_pred,
sample_weight, sample_mask,
learning_rate=1.0, k=0):
"""Least squares does not need to update terminal regions.
But it has to update the predictions.
"""
# upd... | Least squares does not need to update terminal regions.
But it has to update the predictions. | Below is the the instruction that describes the task:
### Input:
Least squares does not need to update terminal regions.
But it has to update the predictions.
### Response:
def update_terminal_regions(self, tree, X, y, residual, y_pred,
sample_weight, sample_mask,
... |
def _update_srcmap_file(self, sources, overwrite=True):
"""Check the contents of the source map file and generate
source maps for any components that are not present."""
if not os.path.isfile(self.files['srcmap']):
return
hdulist = fits.open(self.files['srcmap'])
hd... | Check the contents of the source map file and generate
source maps for any components that are not present. | Below is the the instruction that describes the task:
### Input:
Check the contents of the source map file and generate
source maps for any components that are not present.
### Response:
def _update_srcmap_file(self, sources, overwrite=True):
"""Check the contents of the source map file and generat... |
def index_list_for_sort_order(x: List[Any], key: Callable[[Any], Any] = None,
reverse: bool = False) -> List[int]:
"""
Returns a list of indexes of ``x``, IF ``x`` WERE TO BE SORTED.
Args:
x: data
key: function to be applied to the data to generate a sort key; ... | Returns a list of indexes of ``x``, IF ``x`` WERE TO BE SORTED.
Args:
x: data
key: function to be applied to the data to generate a sort key; this
function is passed as the ``key=`` parameter to :func:`sorted`;
the default is ``itemgetter(1)``
reverse: reverse the so... | Below is the the instruction that describes the task:
### Input:
Returns a list of indexes of ``x``, IF ``x`` WERE TO BE SORTED.
Args:
x: data
key: function to be applied to the data to generate a sort key; this
function is passed as the ``key=`` parameter to :func:`sorted`;
... |
def _load_scoped_variable_models(self):
""" Adds models for each scoped variable of the state """
self.scoped_variables = []
for scoped_variable in self.state.scoped_variables.values():
self._add_model(self.scoped_variables, scoped_variable, ScopedVariableModel) | Adds models for each scoped variable of the state | Below is the the instruction that describes the task:
### Input:
Adds models for each scoped variable of the state
### Response:
def _load_scoped_variable_models(self):
""" Adds models for each scoped variable of the state """
self.scoped_variables = []
for scoped_variable in self.state.sco... |
def get_renderer(app, id):
"""Retrieve a renderer.
:param app: :class:`~flask.Flask` application to look ``id`` up on
:param id: Internal renderer id-string to look up
"""
renderer = app.extensions.get('nav_renderers', {})[id]
if isinstance(renderer, tuple):
mod_name, cls_name = render... | Retrieve a renderer.
:param app: :class:`~flask.Flask` application to look ``id`` up on
:param id: Internal renderer id-string to look up | Below is the the instruction that describes the task:
### Input:
Retrieve a renderer.
:param app: :class:`~flask.Flask` application to look ``id`` up on
:param id: Internal renderer id-string to look up
### Response:
def get_renderer(app, id):
"""Retrieve a renderer.
:param app: :class:`~flask.Fl... |
def get_extra_radiation(doy, solar_constant=1366.1):
"""
Determine extraterrestrial radiation from day of year (using the spencer method).
Note:
[1] M. Reno, C. Hansen, and J. Stein, "Global Horizontal Irradiance
Clear Sky Models: Implementation and Analysis", Sandia National
Labora... | Determine extraterrestrial radiation from day of year (using the spencer method).
Note:
[1] M. Reno, C. Hansen, and J. Stein, "Global Horizontal Irradiance
Clear Sky Models: Implementation and Analysis", Sandia National
Laboratories, SAND2012-2389, 2012.
[2] <http://solardat.uorego... | Below is the the instruction that describes the task:
### Input:
Determine extraterrestrial radiation from day of year (using the spencer method).
Note:
[1] M. Reno, C. Hansen, and J. Stein, "Global Horizontal Irradiance
Clear Sky Models: Implementation and Analysis", Sandia National
La... |
def get_batch(sequence, size, start=0, endpoint=None, complete=False):
""" create a batched result record out of a sequence (catalog brains)
"""
batch = make_batch(sequence, size, start)
return {
"pagesize": batch.get_pagesize(),
"next": batch.make_next_url(),
"previous": batch... | create a batched result record out of a sequence (catalog brains) | Below is the the instruction that describes the task:
### Input:
create a batched result record out of a sequence (catalog brains)
### Response:
def get_batch(sequence, size, start=0, endpoint=None, complete=False):
""" create a batched result record out of a sequence (catalog brains)
"""
batch = make... |
def _assert_recur_is_tail(node: Node) -> None: # pylint: disable=too-many-branches
"""Assert that `recur` forms only appear in the tail position of this
or child AST nodes.
`recur` forms may only appear in `do` nodes (both literal and synthetic
`do` nodes) and in either the :then or :else expression o... | Assert that `recur` forms only appear in the tail position of this
or child AST nodes.
`recur` forms may only appear in `do` nodes (both literal and synthetic
`do` nodes) and in either the :then or :else expression of an `if` node. | Below is the the instruction that describes the task:
### Input:
Assert that `recur` forms only appear in the tail position of this
or child AST nodes.
`recur` forms may only appear in `do` nodes (both literal and synthetic
`do` nodes) and in either the :then or :else expression of an `if` node.
### Re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.