code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def register_pretty(type=None, predicate=None):
"""Returns a decorator that registers the decorated function
as the pretty printer for instances of ``type``.
:param type: the type to register the pretty printer for, or a ``str``
to indicate the module and name, e.g.: ``'collections.Counter... | Returns a decorator that registers the decorated function
as the pretty printer for instances of ``type``.
:param type: the type to register the pretty printer for, or a ``str``
to indicate the module and name, e.g.: ``'collections.Counter'``.
:param predicate: a predicate function that ta... | Below is the the instruction that describes the task:
### Input:
Returns a decorator that registers the decorated function
as the pretty printer for instances of ``type``.
:param type: the type to register the pretty printer for, or a ``str``
to indicate the module and name, e.g.: ``'colle... |
def update_ipsec_site_connection(self, ipsecsite_conn, body=None):
"""Updates an IPsecSiteConnection."""
return self.put(
self.ipsec_site_connection_path % (ipsecsite_conn), body=body
) | Updates an IPsecSiteConnection. | Below is the the instruction that describes the task:
### Input:
Updates an IPsecSiteConnection.
### Response:
def update_ipsec_site_connection(self, ipsecsite_conn, body=None):
"""Updates an IPsecSiteConnection."""
return self.put(
self.ipsec_site_connection_path % (ipsecsite_conn), bo... |
def dictlist_convert_to_float(dict_list: Iterable[Dict], key: str) -> None:
"""
Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to a float. If that fails, convert it to ``None``.
"""
for d in dict_list:
try:
d[key] = float(d[key])
... | Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to a float. If that fails, convert it to ``None``. | Below is the the instruction that describes the task:
### Input:
Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to a float. If that fails, convert it to ``None``.
### Response:
def dictlist_convert_to_float(dict_list: Iterable[Dict], key: str) -> None:
"""
... |
def PlayWaveFile(filePath: str = r'C:\Windows\Media\notify.wav', isAsync: bool = False, isLoop: bool = False) -> bool:
"""
Call PlaySound from Win32.
filePath: str, if emtpy, stop playing the current sound.
isAsync: bool, if True, the sound is played asynchronously and returns immediately.
isLoop: b... | Call PlaySound from Win32.
filePath: str, if emtpy, stop playing the current sound.
isAsync: bool, if True, the sound is played asynchronously and returns immediately.
isLoop: bool, if True, the sound plays repeatedly until PlayWaveFile(None) is called again, must also set isAsync to True.
Return bool, ... | Below is the the instruction that describes the task:
### Input:
Call PlaySound from Win32.
filePath: str, if emtpy, stop playing the current sound.
isAsync: bool, if True, the sound is played asynchronously and returns immediately.
isLoop: bool, if True, the sound plays repeatedly until PlayWaveFile(No... |
def get_config(self):
"""Returns ownCloud config information
:returns: array of tuples (key, value) for each information
e.g. [('version', '1.7'), ('website', 'ownCloud'), ('host', 'cloud.example.com'),
('contact', ''), ('ssl', 'false')]
:raises: HTTPResponseError in case... | Returns ownCloud config information
:returns: array of tuples (key, value) for each information
e.g. [('version', '1.7'), ('website', 'ownCloud'), ('host', 'cloud.example.com'),
('contact', ''), ('ssl', 'false')]
:raises: HTTPResponseError in case an HTTP error status was returne... | Below is the the instruction that describes the task:
### Input:
Returns ownCloud config information
:returns: array of tuples (key, value) for each information
e.g. [('version', '1.7'), ('website', 'ownCloud'), ('host', 'cloud.example.com'),
('contact', ''), ('ssl', 'false')]
... |
def _geom_type(self, source):
"""gets geometry type(s) of specified layer"""
if isinstance(source, AbstractLayer):
query = source.orig_query
else:
query = 'SELECT * FROM "{table}"'.format(table=source)
resp = self.sql_client.send(
utils.minify_sql((
... | gets geometry type(s) of specified layer | Below is the the instruction that describes the task:
### Input:
gets geometry type(s) of specified layer
### Response:
def _geom_type(self, source):
"""gets geometry type(s) of specified layer"""
if isinstance(source, AbstractLayer):
query = source.orig_query
else:
... |
def _check_1st_line(line, **kwargs):
"""First line check.
Check that the first line has a known component name followed by a colon
and then a short description of the commit.
:param line: first line
:type line: str
:param components: list of known component names
:type line: list
:para... | First line check.
Check that the first line has a known component name followed by a colon
and then a short description of the commit.
:param line: first line
:type line: str
:param components: list of known component names
:type line: list
:param max_first_line: maximum length of the firs... | Below is the the instruction that describes the task:
### Input:
First line check.
Check that the first line has a known component name followed by a colon
and then a short description of the commit.
:param line: first line
:type line: str
:param components: list of known component names
:... |
def describe(path):
"""
Return a textual description of the file pointed by this path.
Options:
- "symbolic link"
- "directory"
- "'.' directory"
- "'..' directory"
- "regular file"
- "regular empty file"
- "non existent"
- "entry"
"""
if os.path.islink(path):... | Return a textual description of the file pointed by this path.
Options:
- "symbolic link"
- "directory"
- "'.' directory"
- "'..' directory"
- "regular file"
- "regular empty file"
- "non existent"
- "entry" | Below is the the instruction that describes the task:
### Input:
Return a textual description of the file pointed by this path.
Options:
- "symbolic link"
- "directory"
- "'.' directory"
- "'..' directory"
- "regular file"
- "regular empty file"
- "non existent"
- "entry"... |
def get_pp_name(self):
'''Determine the pseudopotential names from the output'''
ppnames = []
# Find the number of atom types
natomtypes = int(self._get_line('number of atomic types', self.outputf).split()[5])
# Find the pseudopotential names
with open(self.outputf) as fp... | Determine the pseudopotential names from the output | Below is the the instruction that describes the task:
### Input:
Determine the pseudopotential names from the output
### Response:
def get_pp_name(self):
'''Determine the pseudopotential names from the output'''
ppnames = []
# Find the number of atom types
natomtypes = int(self._get... |
def _ParseCmdItem(self, cmd_input, template_file=None):
"""Creates Texttable with output of command.
Args:
cmd_input: String, Device response.
template_file: File object, template to parse with.
Returns:
TextTable containing command output.
Raises:
CliTableError: A template wa... | Creates Texttable with output of command.
Args:
cmd_input: String, Device response.
template_file: File object, template to parse with.
Returns:
TextTable containing command output.
Raises:
CliTableError: A template was not found for the given command. | Below is the the instruction that describes the task:
### Input:
Creates Texttable with output of command.
Args:
cmd_input: String, Device response.
template_file: File object, template to parse with.
Returns:
TextTable containing command output.
Raises:
CliTableError: A templ... |
def tag(value):
"""
Add a tag with generated id.
:param value: everything working with the str() function
"""
rdict = load_feedback()
tests = rdict.setdefault("tests", {})
tests["*auto-tag-" + str(hash(str(value)))] = str(value)
save_feedback(rdict) | Add a tag with generated id.
:param value: everything working with the str() function | Below is the the instruction that describes the task:
### Input:
Add a tag with generated id.
:param value: everything working with the str() function
### Response:
def tag(value):
"""
Add a tag with generated id.
:param value: everything working with the str() function
"""
rdict = load_fee... |
def check_state(self, pair, state):
"""
Updates the state of a check.
"""
self.__log_info('Check %s %s -> %s', pair, pair.state, state)
pair.state = state | Updates the state of a check. | Below is the the instruction that describes the task:
### Input:
Updates the state of a check.
### Response:
def check_state(self, pair, state):
"""
Updates the state of a check.
"""
self.__log_info('Check %s %s -> %s', pair, pair.state, state)
pair.state = state |
def get_existing_thumbnail(self, thumbnail_options, high_resolution=False):
"""
Return a ``ThumbnailFile`` containing an existing thumbnail for a set
of thumbnail options, or ``None`` if not found.
"""
thumbnail_options = self.get_options(thumbnail_options)
names = [
... | Return a ``ThumbnailFile`` containing an existing thumbnail for a set
of thumbnail options, or ``None`` if not found. | Below is the the instruction that describes the task:
### Input:
Return a ``ThumbnailFile`` containing an existing thumbnail for a set
of thumbnail options, or ``None`` if not found.
### Response:
def get_existing_thumbnail(self, thumbnail_options, high_resolution=False):
"""
Return a ``Thu... |
def launch_background_job(self, job, on_error=None, on_success=None):
"""Launch the callable job in background thread.
Succes or failure are controlled by on_error and on_success
"""
if not self.main.mode_online:
self.sortie_erreur_GUI(
"Local mode activated. ... | Launch the callable job in background thread.
Succes or failure are controlled by on_error and on_success | Below is the the instruction that describes the task:
### Input:
Launch the callable job in background thread.
Succes or failure are controlled by on_error and on_success
### Response:
def launch_background_job(self, job, on_error=None, on_success=None):
"""Launch the callable job in background thr... |
def clear_trace_filter_cache():
'''
Clear the trace filter cache.
Call this after reloading.
'''
global should_trace_hook
try:
# Need to temporarily disable a hook because otherwise
# _filename_to_ignored_lines.clear() will never complete.
old_hook = should_trace_hook
... | Clear the trace filter cache.
Call this after reloading. | Below is the the instruction that describes the task:
### Input:
Clear the trace filter cache.
Call this after reloading.
### Response:
def clear_trace_filter_cache():
'''
Clear the trace filter cache.
Call this after reloading.
'''
global should_trace_hook
try:
# Need to tempor... |
def remove_all(self, key):
"""
Transactional implementation of :func:`MultiMap.remove_all(key)
<hazelcast.proxy.multi_map.MultiMap.remove_all>`
:param key: (object), the key of the entries to remove.
:return: (list), the collection of the values associated with the key.
... | Transactional implementation of :func:`MultiMap.remove_all(key)
<hazelcast.proxy.multi_map.MultiMap.remove_all>`
:param key: (object), the key of the entries to remove.
:return: (list), the collection of the values associated with the key. | Below is the the instruction that describes the task:
### Input:
Transactional implementation of :func:`MultiMap.remove_all(key)
<hazelcast.proxy.multi_map.MultiMap.remove_all>`
:param key: (object), the key of the entries to remove.
:return: (list), the collection of the values associated ... |
def pretty_print_counters(counters):
"""print counters hierarchically.
Each counter is a pair of a string and a number.
The string can have slashes, meaning that the number also counts towards
each prefix. e.g. "parameters/trainable" counts towards both "parameters"
and "parameters/trainable".
Args:
... | print counters hierarchically.
Each counter is a pair of a string and a number.
The string can have slashes, meaning that the number also counts towards
each prefix. e.g. "parameters/trainable" counts towards both "parameters"
and "parameters/trainable".
Args:
counters: a list of (string, number) pair... | Below is the the instruction that describes the task:
### Input:
print counters hierarchically.
Each counter is a pair of a string and a number.
The string can have slashes, meaning that the number also counts towards
each prefix. e.g. "parameters/trainable" counts towards both "parameters"
and "paramete... |
def fetch_reference_restriction(self, ):
"""Fetch whether referencing is restricted
:returns: True, if referencing is restricted
:rtype: :class:`bool`
:raises: None
"""
inter = self.get_refobjinter()
restricted = self.status() is not None
return restricte... | Fetch whether referencing is restricted
:returns: True, if referencing is restricted
:rtype: :class:`bool`
:raises: None | Below is the the instruction that describes the task:
### Input:
Fetch whether referencing is restricted
:returns: True, if referencing is restricted
:rtype: :class:`bool`
:raises: None
### Response:
def fetch_reference_restriction(self, ):
"""Fetch whether referencing is restricte... |
def whoami(self,
note=None,
loglevel=logging.DEBUG):
"""Returns the current user by executing "whoami".
@param note: See send()
@return: the output of "whoami"
@rtype: string
"""
shutit = self.shutit
shutit.handle_note(note)
res = self.send_and_get_output(' command whoami',... | Returns the current user by executing "whoami".
@param note: See send()
@return: the output of "whoami"
@rtype: string | Below is the the instruction that describes the task:
### Input:
Returns the current user by executing "whoami".
@param note: See send()
@return: the output of "whoami"
@rtype: string
### Response:
def whoami(self,
note=None,
loglevel=logging.DEBUG):
"""Returns the current use... |
def _filesystems(config='/etc/filesystems', leading_key=True):
'''
Return the contents of the filesystems in an OrderedDict
config
File containing filesystem infomation
leading_key
True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded)... | Return the contents of the filesystems in an OrderedDict
config
File containing filesystem infomation
leading_key
True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded)
OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', ...... | Below is the the instruction that describes the task:
### Input:
Return the contents of the filesystems in an OrderedDict
config
File containing filesystem infomation
leading_key
True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded)
... |
async def callproc(self, procname, args=()):
"""Execute stored procedure procname with args
Compatibility warning: PEP-249 specifies that any modified
parameters must be returned. This is currently impossible
as they are only available by storing them in a server
variable and th... | Execute stored procedure procname with args
Compatibility warning: PEP-249 specifies that any modified
parameters must be returned. This is currently impossible
as they are only available by storing them in a server
variable and then retrieved by a query. Since stored
procedures... | Below is the the instruction that describes the task:
### Input:
Execute stored procedure procname with args
Compatibility warning: PEP-249 specifies that any modified
parameters must be returned. This is currently impossible
as they are only available by storing them in a server
va... |
def indent(self, levels, first_line=None):
"""Increase indentation by ``levels`` levels."""
self._indentation_levels.append(levels)
self._indent_first_line.append(first_line) | Increase indentation by ``levels`` levels. | Below is the the instruction that describes the task:
### Input:
Increase indentation by ``levels`` levels.
### Response:
def indent(self, levels, first_line=None):
"""Increase indentation by ``levels`` levels."""
self._indentation_levels.append(levels)
self._indent_first_line.append(first_... |
def update(self, level):
"""Update the current scope by going back `level` levels.
Parameters
----------
level : int or None, optional, default None
"""
sl = level + 1
# add sl frames to the scope starting with the
# most distant and overwriting with mor... | Update the current scope by going back `level` levels.
Parameters
----------
level : int or None, optional, default None | Below is the the instruction that describes the task:
### Input:
Update the current scope by going back `level` levels.
Parameters
----------
level : int or None, optional, default None
### Response:
def update(self, level):
"""Update the current scope by going back `level` levels.... |
def enable_qt4(self, app=None):
"""Enable event loop integration with PyQt4.
Parameters
----------
app : Qt Application, optional.
Running application to use. If not given, we probe Qt for an
existing application object, and create a new one if none is f... | Enable event loop integration with PyQt4.
Parameters
----------
app : Qt Application, optional.
Running application to use. If not given, we probe Qt for an
existing application object, and create a new one if none is found.
Notes
-----
... | Below is the the instruction that describes the task:
### Input:
Enable event loop integration with PyQt4.
Parameters
----------
app : Qt Application, optional.
Running application to use. If not given, we probe Qt for an
existing application object, and cre... |
def links_to(self, other, tpe):
"""
adds a link from this thing to other thing
using type (is_a, has_a, uses, contains, part_of)
"""
if self.check_type(tpe):
self.links.append([other, tpe])
else:
raise Exception('aikif.core_data cannot process this... | adds a link from this thing to other thing
using type (is_a, has_a, uses, contains, part_of) | Below is the the instruction that describes the task:
### Input:
adds a link from this thing to other thing
using type (is_a, has_a, uses, contains, part_of)
### Response:
def links_to(self, other, tpe):
"""
adds a link from this thing to other thing
using type (is_a, has_a, uses, c... |
def catch_gzip_errors(f):
"""
A decorator to handle gzip encoding errors which have been known to
happen during hydration.
"""
def new_f(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except requests.exceptions.ContentDecodingError as e:
log.warn... | A decorator to handle gzip encoding errors which have been known to
happen during hydration. | Below is the the instruction that describes the task:
### Input:
A decorator to handle gzip encoding errors which have been known to
happen during hydration.
### Response:
def catch_gzip_errors(f):
"""
A decorator to handle gzip encoding errors which have been known to
happen during hydration.
... |
def yVal_xml(self):
"""
Return the ``<c:yVal>`` element for this series as unicode text. This
element contains the Y values for this series.
"""
return self._yVal_tmpl.format(**{
'nsdecls': '',
'numRef_xml': self.numRef_xml(
self._series... | Return the ``<c:yVal>`` element for this series as unicode text. This
element contains the Y values for this series. | Below is the the instruction that describes the task:
### Input:
Return the ``<c:yVal>`` element for this series as unicode text. This
element contains the Y values for this series.
### Response:
def yVal_xml(self):
"""
Return the ``<c:yVal>`` element for this series as unicode text. This
... |
def get_user_matches(session, user_id, from_timestamp=None, limit=None):
"""Get recent matches by user."""
return get_recent_matches(session, '{}{}/{}/Matches/games/matches/user/{}/0'.format(
session.auth.base_url, PROFILE_URL, user_id, user_id), from_timestamp, limit) | Get recent matches by user. | Below is the the instruction that describes the task:
### Input:
Get recent matches by user.
### Response:
def get_user_matches(session, user_id, from_timestamp=None, limit=None):
"""Get recent matches by user."""
return get_recent_matches(session, '{}{}/{}/Matches/games/matches/user/{}/0'.format(
... |
def throw_to(self, target, *a):
self.ready.append((getcurrent(), ()))
"""
if len(a) == 1 and isinstance(a[0], preserve_exception):
return target.throw(a[0].typ, a[0].val, a[0].tb)
"""
return target.throw(*a) | if len(a) == 1 and isinstance(a[0], preserve_exception):
return target.throw(a[0].typ, a[0].val, a[0].tb) | Below is the the instruction that describes the task:
### Input:
if len(a) == 1 and isinstance(a[0], preserve_exception):
return target.throw(a[0].typ, a[0].val, a[0].tb)
### Response:
def throw_to(self, target, *a):
self.ready.append((getcurrent(), ()))
"""
if len(a) == 1 and i... |
def bat_to_sh(file_path):
"""Convert honeybee .bat file to .sh file.
WARNING: This is a very simple function and doesn't handle any edge cases.
"""
sh_file = file_path[:-4] + '.sh'
with open(file_path, 'rb') as inf, open(sh_file, 'wb') as outf:
outf.write('#!/usr/bin/env bash\n\n')
... | Convert honeybee .bat file to .sh file.
WARNING: This is a very simple function and doesn't handle any edge cases. | Below is the the instruction that describes the task:
### Input:
Convert honeybee .bat file to .sh file.
WARNING: This is a very simple function and doesn't handle any edge cases.
### Response:
def bat_to_sh(file_path):
"""Convert honeybee .bat file to .sh file.
WARNING: This is a very simple functio... |
def operations(nsteps):
'''Returns the number of operations needed for nsteps of GMRES'''
return {'A': 1 + nsteps,
'M': 2 + nsteps,
'Ml': 2 + nsteps,
'Mr': 1 + nsteps,
'ip_B': 2 + nsteps + nsteps*(nsteps+1)/2,
'axpy': 4 + 2*... | Returns the number of operations needed for nsteps of GMRES | Below is the the instruction that describes the task:
### Input:
Returns the number of operations needed for nsteps of GMRES
### Response:
def operations(nsteps):
'''Returns the number of operations needed for nsteps of GMRES'''
return {'A': 1 + nsteps,
'M': 2 + nsteps,
... |
def _run_select_solution(ploidy_outdirs, work_dir, data):
"""Select optimal
"""
out_file = os.path.join(work_dir, "optimalClusters.txt")
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
ploidy_inputs = " ".join(["--ploidyRun%s=%s" % (p, d) for... | Select optimal | Below is the the instruction that describes the task:
### Input:
Select optimal
### Response:
def _run_select_solution(ploidy_outdirs, work_dir, data):
"""Select optimal
"""
out_file = os.path.join(work_dir, "optimalClusters.txt")
if not utils.file_exists(out_file):
with file_transaction(da... |
def getFileAndName(self, *args, **kwargs):
'''
Give a requested page (note: the arguments for this call are forwarded to getpage()),
return the content at the target URL and the filename for the target content as a
2-tuple (pgctnt, hName) for the content at the target URL.
The filename specified in the conte... | Give a requested page (note: the arguments for this call are forwarded to getpage()),
return the content at the target URL and the filename for the target content as a
2-tuple (pgctnt, hName) for the content at the target URL.
The filename specified in the content-disposition header is used, if present. Otherwis... | Below is the the instruction that describes the task:
### Input:
Give a requested page (note: the arguments for this call are forwarded to getpage()),
return the content at the target URL and the filename for the target content as a
2-tuple (pgctnt, hName) for the content at the target URL.
The filename spec... |
def open_recruitment(self, n=1):
"""Return initial experiment URL list.
"""
logger.info("Multi recruitment running for {} participants".format(n))
recruitments = []
messages = {}
remaining = n
for recruiter, count in self.recruiters(n):
if not count:
... | Return initial experiment URL list. | Below is the the instruction that describes the task:
### Input:
Return initial experiment URL list.
### Response:
def open_recruitment(self, n=1):
"""Return initial experiment URL list.
"""
logger.info("Multi recruitment running for {} participants".format(n))
recruitments = []
... |
def muc(clusters, mention_to_gold):
"""
Counts the mentions in each predicted cluster which need to be re-allocated in
order for each predicted cluster to be contained by the respective gold cluster.
<http://aclweb.org/anthology/M/M95/M95-1005.pdf>
"""
true_p, all_p = 0, ... | Counts the mentions in each predicted cluster which need to be re-allocated in
order for each predicted cluster to be contained by the respective gold cluster.
<http://aclweb.org/anthology/M/M95/M95-1005.pdf> | Below is the the instruction that describes the task:
### Input:
Counts the mentions in each predicted cluster which need to be re-allocated in
order for each predicted cluster to be contained by the respective gold cluster.
<http://aclweb.org/anthology/M/M95/M95-1005.pdf>
### Response:
def muc(clu... |
def select_window(pymux, variables):
"""
Select a window. E.g: select-window -t :3
"""
window_id = variables['<target-window>']
def invalid_window():
raise CommandException('Invalid window: %s' % window_id)
if window_id.startswith(':'):
try:
number = int(window_id[... | Select a window. E.g: select-window -t :3 | Below is the the instruction that describes the task:
### Input:
Select a window. E.g: select-window -t :3
### Response:
def select_window(pymux, variables):
"""
Select a window. E.g: select-window -t :3
"""
window_id = variables['<target-window>']
def invalid_window():
raise Command... |
def rolling(self, *args, **kwargs):
"""
Return a rolling grouper, providing rolling functionality per group.
"""
from pandas.core.window import RollingGroupby
return RollingGroupby(self, *args, **kwargs) | Return a rolling grouper, providing rolling functionality per group. | Below is the the instruction that describes the task:
### Input:
Return a rolling grouper, providing rolling functionality per group.
### Response:
def rolling(self, *args, **kwargs):
"""
Return a rolling grouper, providing rolling functionality per group.
"""
from pandas.core.windo... |
def get_search_results(portal_type=None, uid=None, **kw):
"""Search the catalog and return the results
:returns: Catalog search results
:rtype: iterable
"""
# If we have an UID, return the object immediately
if uid is not None:
logger.info("UID '%s' found, returning the object immediat... | Search the catalog and return the results
:returns: Catalog search results
:rtype: iterable | Below is the the instruction that describes the task:
### Input:
Search the catalog and return the results
:returns: Catalog search results
:rtype: iterable
### Response:
def get_search_results(portal_type=None, uid=None, **kw):
"""Search the catalog and return the results
:returns: Catalog searc... |
def record_results(self, results):
"""
Record the results of this experiment, by updating the tag.
:param results: A dictionary containing the results of the experiment.
:type results: dict
"""
repository = Repo(self.__repository_directory, search_parent_directories=True)... | Record the results of this experiment, by updating the tag.
:param results: A dictionary containing the results of the experiment.
:type results: dict | Below is the the instruction that describes the task:
### Input:
Record the results of this experiment, by updating the tag.
:param results: A dictionary containing the results of the experiment.
:type results: dict
### Response:
def record_results(self, results):
"""
Record the res... |
def get_datatype_str(self, element, length):
'''get_datatype_str
High-level api: Produce a string that indicates the data type of a node.
Parameters
----------
element : `Element`
A node in model tree.
length : `int`
String length that has been... | get_datatype_str
High-level api: Produce a string that indicates the data type of a node.
Parameters
----------
element : `Element`
A node in model tree.
length : `int`
String length that has been consumed.
Returns
-------
str... | Below is the the instruction that describes the task:
### Input:
get_datatype_str
High-level api: Produce a string that indicates the data type of a node.
Parameters
----------
element : `Element`
A node in model tree.
length : `int`
String length ... |
def EnableNetworkInterfaces(
self, interfaces, logger, dhclient_script=None):
"""Enable the list of network interfaces.
Args:
interfaces: list of string, the output device names to enable.
logger: logger object, used to write to SysLog and serial port.
dhclient_script: string, the path ... | Enable the list of network interfaces.
Args:
interfaces: list of string, the output device names to enable.
logger: logger object, used to write to SysLog and serial port.
dhclient_script: string, the path to a dhclient script used by dhclient. | Below is the the instruction that describes the task:
### Input:
Enable the list of network interfaces.
Args:
interfaces: list of string, the output device names to enable.
logger: logger object, used to write to SysLog and serial port.
dhclient_script: string, the path to a dhclient script u... |
def fileopenbox(msg=None, title=None, default='*', filetypes=None, multiple=False):
"""
A dialog to get a file name.
**About the "default" argument**
The "default" argument specifies a filepath that (normally)
contains one or more wildcards.
fileopenbox will display only files that match the d... | A dialog to get a file name.
**About the "default" argument**
The "default" argument specifies a filepath that (normally)
contains one or more wildcards.
fileopenbox will display only files that match the default filepath.
If omitted, defaults to "\*" (all files in the current directory).
WIN... | Below is the the instruction that describes the task:
### Input:
A dialog to get a file name.
**About the "default" argument**
The "default" argument specifies a filepath that (normally)
contains one or more wildcards.
fileopenbox will display only files that match the default filepath.
If omi... |
def setCovariance(self, cov):
""" makes lowrank approximation of cov """
assert cov.shape[0]==self.dim, 'Dimension mismatch.'
S, U = la.eigh(cov)
U = U[:,::-1]
S = S[::-1]
_X = U[:, :self.rank] * sp.sqrt(S[:self.rank])
self.X = _X | makes lowrank approximation of cov | Below is the the instruction that describes the task:
### Input:
makes lowrank approximation of cov
### Response:
def setCovariance(self, cov):
""" makes lowrank approximation of cov """
assert cov.shape[0]==self.dim, 'Dimension mismatch.'
S, U = la.eigh(cov)
U = U[:,::-1]
S... |
def channel(layer, n_channel, batch=None):
"""Visualize a single channel"""
if batch is None:
return lambda T: tf.reduce_mean(T(layer)[..., n_channel])
else:
return lambda T: tf.reduce_mean(T(layer)[batch, ..., n_channel]) | Visualize a single channel | Below is the the instruction that describes the task:
### Input:
Visualize a single channel
### Response:
def channel(layer, n_channel, batch=None):
"""Visualize a single channel"""
if batch is None:
return lambda T: tf.reduce_mean(T(layer)[..., n_channel])
else:
return lambda T: tf.reduce_mean(T(lay... |
def adjust_for_length(self, key, r, kwargs):
"""
Converts the response to a string and compares its length to a max
length specified in settings. If the response is too long, an error is
logged, and an abbreviated response is returned instead.
"""
length = len(str(kwargs)... | Converts the response to a string and compares its length to a max
length specified in settings. If the response is too long, an error is
logged, and an abbreviated response is returned instead. | Below is the the instruction that describes the task:
### Input:
Converts the response to a string and compares its length to a max
length specified in settings. If the response is too long, an error is
logged, and an abbreviated response is returned instead.
### Response:
def adjust_for_length(sel... |
def _convertPointsToSegments(points, willBeReversed=False):
"""
Compile points into InputSegment objects.
"""
# get the last on curve
previousOnCurve = None
for point in reversed(points):
if point.segmentType is not None:
previousOnCurve = point.coordinates
break
... | Compile points into InputSegment objects. | Below is the the instruction that describes the task:
### Input:
Compile points into InputSegment objects.
### Response:
def _convertPointsToSegments(points, willBeReversed=False):
"""
Compile points into InputSegment objects.
"""
# get the last on curve
previousOnCurve = None
for point in ... |
def OnApprove(self, event):
"""File approve event handler"""
if not self.main_window.safe_mode:
return
msg = _(u"You are going to approve and trust a file that\n"
u"you have not created yourself.\n"
u"After proceeding, the file is executed.\n \n"
... | File approve event handler | Below is the the instruction that describes the task:
### Input:
File approve event handler
### Response:
def OnApprove(self, event):
"""File approve event handler"""
if not self.main_window.safe_mode:
return
msg = _(u"You are going to approve and trust a file that\n"
... |
def merge_overlaps(self, data_reducer=None, data_initializer=None, strict=True):
"""
Finds all intervals with overlapping ranges and merges them
into a single interval. If provided, uses data_reducer and
data_initializer with similar semantics to Python's built-in
reduce(reducer_... | Finds all intervals with overlapping ranges and merges them
into a single interval. If provided, uses data_reducer and
data_initializer with similar semantics to Python's built-in
reduce(reducer_func[, initializer]), as follows:
If data_reducer is set to a function, combines the data
... | Below is the the instruction that describes the task:
### Input:
Finds all intervals with overlapping ranges and merges them
into a single interval. If provided, uses data_reducer and
data_initializer with similar semantics to Python's built-in
reduce(reducer_func[, initializer]), as follows... |
def regex_lexer(regex_pat):
"""
generate token names' cache
"""
if isinstance(regex_pat, str):
regex_pat = re.compile(regex_pat)
def f(inp_str, pos):
m = regex_pat.match(inp_str, pos)
return m.group() if m else None
elif hasattr(regex_pat, 'match'):
... | generate token names' cache | Below is the the instruction that describes the task:
### Input:
generate token names' cache
### Response:
def regex_lexer(regex_pat):
"""
generate token names' cache
"""
if isinstance(regex_pat, str):
regex_pat = re.compile(regex_pat)
def f(inp_str, pos):
m = regex_pa... |
def entity_list(args):
""" List entities in a workspace. """
r = fapi.get_entities_with_type(args.project, args.workspace)
fapi._check_response_code(r, 200)
return [ '{0}\t{1}'.format(e['entityType'], e['name']) for e in r.json() ] | List entities in a workspace. | Below is the the instruction that describes the task:
### Input:
List entities in a workspace.
### Response:
def entity_list(args):
""" List entities in a workspace. """
r = fapi.get_entities_with_type(args.project, args.workspace)
fapi._check_response_code(r, 200)
return [ '{0}\t{1}'.format(e['ent... |
def listdir(search_base, followlinks=False, filter='*',
relpath=False, bestprefix=False, system=NIST):
"""This is a generator which recurses the directory tree
`search_base`, yielding 2-tuples of:
* The absolute/relative path to a discovered file
* A bitmath instance representing the "apparent size" of... | This is a generator which recurses the directory tree
`search_base`, yielding 2-tuples of:
* The absolute/relative path to a discovered file
* A bitmath instance representing the "apparent size" of the file.
- `search_base` - The directory to begin walking down.
- `followlinks` - Whether or not to follow symb... | Below is the the instruction that describes the task:
### Input:
This is a generator which recurses the directory tree
`search_base`, yielding 2-tuples of:
* The absolute/relative path to a discovered file
* A bitmath instance representing the "apparent size" of the file.
- `search_base` - The directory to be... |
def size(self):
"""The size of the element."""
size = {}
if self._w3c:
size = self._execute(Command.GET_ELEMENT_RECT)['value']
else:
size = self._execute(Command.GET_ELEMENT_SIZE)['value']
new_size = {"height": size["height"],
"width": ... | The size of the element. | Below is the the instruction that describes the task:
### Input:
The size of the element.
### Response:
def size(self):
"""The size of the element."""
size = {}
if self._w3c:
size = self._execute(Command.GET_ELEMENT_RECT)['value']
else:
size = self._execute(C... |
def combine_first(self, other):
"""
Combine Series values, choosing the calling Series's values
first. Result index will be the union of the two indexes
Parameters
----------
other : Series
Returns
-------
y : Series
"""
if isinst... | Combine Series values, choosing the calling Series's values
first. Result index will be the union of the two indexes
Parameters
----------
other : Series
Returns
-------
y : Series | Below is the the instruction that describes the task:
### Input:
Combine Series values, choosing the calling Series's values
first. Result index will be the union of the two indexes
Parameters
----------
other : Series
Returns
-------
y : Series
### Response... |
def decrypt(self, text, appid):
"""对解密后的明文进行补位删除
@param text: 密文
@return: 删除填充补位后的明文
"""
try:
cryptor = AES.new(self.key, self.mode, self.key[:16])
# 使用BASE64对密文进行解码,然后AES-CBC解密
plain_text = cryptor.decrypt(base64.b64decode(text))
exce... | 对解密后的明文进行补位删除
@param text: 密文
@return: 删除填充补位后的明文 | Below is the the instruction that describes the task:
### Input:
对解密后的明文进行补位删除
@param text: 密文
@return: 删除填充补位后的明文
### Response:
def decrypt(self, text, appid):
"""对解密后的明文进行补位删除
@param text: 密文
@return: 删除填充补位后的明文
"""
try:
cryptor = AES.new(self... |
def _rpartition(entity, sep):
"""Python2.4 doesn't have an rpartition method so we provide
our own that mimics str.rpartition from later releases.
Split the string at the last occurrence of sep, and return a
3-tuple containing the part before the separator, the separator
itself, and the part after ... | Python2.4 doesn't have an rpartition method so we provide
our own that mimics str.rpartition from later releases.
Split the string at the last occurrence of sep, and return a
3-tuple containing the part before the separator, the separator
itself, and the part after the separator. If the separator is no... | Below is the the instruction that describes the task:
### Input:
Python2.4 doesn't have an rpartition method so we provide
our own that mimics str.rpartition from later releases.
Split the string at the last occurrence of sep, and return a
3-tuple containing the part before the separator, the separator... |
def get_int(errmsg, arg, default=1, cmdname=None):
"""If arg is an int, use that otherwise take default."""
if arg:
try:
# eval() is used so we will allow arithmetic expressions,
# variables etc.
default = int(eval(arg))
except (SyntaxError, NameError, ValueEr... | If arg is an int, use that otherwise take default. | Below is the the instruction that describes the task:
### Input:
If arg is an int, use that otherwise take default.
### Response:
def get_int(errmsg, arg, default=1, cmdname=None):
"""If arg is an int, use that otherwise take default."""
if arg:
try:
# eval() is used so we will allow ar... |
def parse_date(dt, ignoretz=True, as_tz=None):
"""
:param dt: string datetime to convert into datetime object.
:return: date object if the string can be parsed into a date. Otherwise,
return None.
:see: http://labix.org/python-dateutil
Examples:
>>> parse_date('2011-12-30')
dateti... | :param dt: string datetime to convert into datetime object.
:return: date object if the string can be parsed into a date. Otherwise,
return None.
:see: http://labix.org/python-dateutil
Examples:
>>> parse_date('2011-12-30')
datetime.date(2011, 12, 30)
>>> parse_date('12/30/2011')
... | Below is the the instruction that describes the task:
### Input:
:param dt: string datetime to convert into datetime object.
:return: date object if the string can be parsed into a date. Otherwise,
return None.
:see: http://labix.org/python-dateutil
Examples:
>>> parse_date('2011-12-30')
... |
def delete_user_avatar(self, username, avatar):
"""Delete a user's avatar.
:param username: the user to delete the avatar from
:param avatar: ID of the avatar to remove
"""
params = {'username': username}
url = self._get_url('user/avatar/' + avatar)
return self._... | Delete a user's avatar.
:param username: the user to delete the avatar from
:param avatar: ID of the avatar to remove | Below is the the instruction that describes the task:
### Input:
Delete a user's avatar.
:param username: the user to delete the avatar from
:param avatar: ID of the avatar to remove
### Response:
def delete_user_avatar(self, username, avatar):
"""Delete a user's avatar.
:param us... |
def dbus_readBytesFD(self, fd, byte_count):
"""
Reads byte_count bytes from fd and returns them.
"""
f = os.fdopen(fd, 'rb')
result = f.read(byte_count)
f.close()
return bytearray(result) | Reads byte_count bytes from fd and returns them. | Below is the the instruction that describes the task:
### Input:
Reads byte_count bytes from fd and returns them.
### Response:
def dbus_readBytesFD(self, fd, byte_count):
"""
Reads byte_count bytes from fd and returns them.
"""
f = os.fdopen(fd, 'rb')
result = f.read(byte_c... |
def peek(self, n=None, constructor=list):
"""
Sees/peeks the next few items in the Stream, without removing them.
Besides that this functions keeps the Stream items, it's the same to the
``Stream.take()`` method.
See Also
--------
Stream.take :
Returns the n first elements from the S... | Sees/peeks the next few items in the Stream, without removing them.
Besides that this functions keeps the Stream items, it's the same to the
``Stream.take()`` method.
See Also
--------
Stream.take :
Returns the n first elements from the Stream, removing them.
Note
----
When appl... | Below is the the instruction that describes the task:
### Input:
Sees/peeks the next few items in the Stream, without removing them.
Besides that this functions keeps the Stream items, it's the same to the
``Stream.take()`` method.
See Also
--------
Stream.take :
Returns the n first elem... |
def solve(self, graph, timeout, debug=False, anim=None):
"""Solves the CVRP problem using Clarke and Wright Savings methods
Parameters
----------
graph: :networkx:`NetworkX Graph Obj< >`
A NetworkX graaph is used.
timeout: int
max processing time in secon... | Solves the CVRP problem using Clarke and Wright Savings methods
Parameters
----------
graph: :networkx:`NetworkX Graph Obj< >`
A NetworkX graaph is used.
timeout: int
max processing time in seconds
debug: bool, defaults to False
If True, infor... | Below is the the instruction that describes the task:
### Input:
Solves the CVRP problem using Clarke and Wright Savings methods
Parameters
----------
graph: :networkx:`NetworkX Graph Obj< >`
A NetworkX graaph is used.
timeout: int
max processing time in seco... |
def replaceWith(self, *nodes: Union[AbstractNode, str]) -> None:
"""Replace this node with nodes.
If nodes contains ``str``, it will be converted to Text node.
"""
if self.parentNode:
node = _to_node_list(nodes)
self.parentNode.replaceChild(node, self) | Replace this node with nodes.
If nodes contains ``str``, it will be converted to Text node. | Below is the the instruction that describes the task:
### Input:
Replace this node with nodes.
If nodes contains ``str``, it will be converted to Text node.
### Response:
def replaceWith(self, *nodes: Union[AbstractNode, str]) -> None:
"""Replace this node with nodes.
If nodes contains ``... |
def _set_alignment(self, group_size, bit_offset=0, auto_align=False):
""" Sets the alignment of the ``Decimal`` field.
:param int group_size: size of the aligned `Field` group in bytes,
can be between ``1`` and ``8``.
:param int bit_offset: bit offset of the `Decimal` field within t... | Sets the alignment of the ``Decimal`` field.
:param int group_size: size of the aligned `Field` group in bytes,
can be between ``1`` and ``8``.
:param int bit_offset: bit offset of the `Decimal` field within the
aligned `Field` group, can be between ``0`` and ``63``.
:pa... | Below is the the instruction that describes the task:
### Input:
Sets the alignment of the ``Decimal`` field.
:param int group_size: size of the aligned `Field` group in bytes,
can be between ``1`` and ``8``.
:param int bit_offset: bit offset of the `Decimal` field within the
... |
def _inferSchema(self, rdd, samplingRatio=None, names=None):
"""
Infer schema from an RDD of Row or tuple.
:param rdd: an RDD of Row or tuple
:param samplingRatio: sampling ratio, or no sampling (default)
:return: :class:`pyspark.sql.types.StructType`
"""
first =... | Infer schema from an RDD of Row or tuple.
:param rdd: an RDD of Row or tuple
:param samplingRatio: sampling ratio, or no sampling (default)
:return: :class:`pyspark.sql.types.StructType` | Below is the the instruction that describes the task:
### Input:
Infer schema from an RDD of Row or tuple.
:param rdd: an RDD of Row or tuple
:param samplingRatio: sampling ratio, or no sampling (default)
:return: :class:`pyspark.sql.types.StructType`
### Response:
def _inferSchema(self, r... |
def analyse_cache_dir(self, jobhandler=None, batchsize=1, **kwargs):
"""
Scan the cache directory and launch analysis for all unscored alignments
using associated task handler. KWargs are passed to the tree calculating
task managed by the TaskInterface in self.task_interface.
Exa... | Scan the cache directory and launch analysis for all unscored alignments
using associated task handler. KWargs are passed to the tree calculating
task managed by the TaskInterface in self.task_interface.
Example kwargs:
TreeCollectionTaskInterface: scale=1, guide_tree=None,
... | Below is the the instruction that describes the task:
### Input:
Scan the cache directory and launch analysis for all unscored alignments
using associated task handler. KWargs are passed to the tree calculating
task managed by the TaskInterface in self.task_interface.
Example kwargs:
... |
def loads(data, validate=False, **kwargs):
"""Load a PPMP message from the JSON-formatted string in `data`. When
`validate` is set, raise `ValidationError`. Additional keyword
arguments are the same that are accepted by `json.loads`,
e.g. `indent` to get a pretty output.
"""
d = json.loads(data,... | Load a PPMP message from the JSON-formatted string in `data`. When
`validate` is set, raise `ValidationError`. Additional keyword
arguments are the same that are accepted by `json.loads`,
e.g. `indent` to get a pretty output. | Below is the the instruction that describes the task:
### Input:
Load a PPMP message from the JSON-formatted string in `data`. When
`validate` is set, raise `ValidationError`. Additional keyword
arguments are the same that are accepted by `json.loads`,
e.g. `indent` to get a pretty output.
### Response:... |
def confirm(self, question, default=False, true_answer_regex="(?i)^y"):
"""
Confirm a question with the user.
"""
return self._io.confirm(question, default, true_answer_regex) | Confirm a question with the user. | Below is the the instruction that describes the task:
### Input:
Confirm a question with the user.
### Response:
def confirm(self, question, default=False, true_answer_regex="(?i)^y"):
"""
Confirm a question with the user.
"""
return self._io.confirm(question, default, true_answer_r... |
def set_euid():
"""
Set settings.DROPLET_USER effective UID for the current process
This adds some security, but nothing magic, an attacker can still
gain root access, but at least we only elevate privileges when needed
See root context manager
"""
current = os.geteuid()
logger.debug("... | Set settings.DROPLET_USER effective UID for the current process
This adds some security, but nothing magic, an attacker can still
gain root access, but at least we only elevate privileges when needed
See root context manager | Below is the the instruction that describes the task:
### Input:
Set settings.DROPLET_USER effective UID for the current process
This adds some security, but nothing magic, an attacker can still
gain root access, but at least we only elevate privileges when needed
See root context manager
### Response... |
def _instance_callable(obj):
"""Given an object, return True if the object is callable.
For classes, return True if instances would be callable."""
if not isinstance(obj, ClassTypes):
# already an instance
return getattr(obj, '__call__', None) is not None
klass = obj
# uses __bases_... | Given an object, return True if the object is callable.
For classes, return True if instances would be callable. | Below is the the instruction that describes the task:
### Input:
Given an object, return True if the object is callable.
For classes, return True if instances would be callable.
### Response:
def _instance_callable(obj):
"""Given an object, return True if the object is callable.
For classes, return Tru... |
def read_version(version_file):
"Read the `(version-string, version-info)` from `version_file`."
vars = {}
with open(version_file) as f:
exec(f.read(), {}, vars)
return (vars['__version__'], vars['__version_info__']) | Read the `(version-string, version-info)` from `version_file`. | Below is the the instruction that describes the task:
### Input:
Read the `(version-string, version-info)` from `version_file`.
### Response:
def read_version(version_file):
"Read the `(version-string, version-info)` from `version_file`."
vars = {}
with open(version_file) as f:
exec(f.read(), {... |
def set_state_data(cls, entity, data):
"""
Sets the state data for the given entity to the given data.
This also works for unmanaged entities.
"""
attr_names = get_domain_class_attribute_names(type(entity))
nested_items = []
for attr, new_attr_value in iteritems_... | Sets the state data for the given entity to the given data.
This also works for unmanaged entities. | Below is the the instruction that describes the task:
### Input:
Sets the state data for the given entity to the given data.
This also works for unmanaged entities.
### Response:
def set_state_data(cls, entity, data):
"""
Sets the state data for the given entity to the given data.
... |
def check_classes(self, scope=-1):
""" Check if pending identifiers are defined or not. If not,
returns a syntax error. If no scope is given, the current
one is checked.
"""
for entry in self[scope].values():
if entry.class_ is None:
syntax_error(entry... | Check if pending identifiers are defined or not. If not,
returns a syntax error. If no scope is given, the current
one is checked. | Below is the the instruction that describes the task:
### Input:
Check if pending identifiers are defined or not. If not,
returns a syntax error. If no scope is given, the current
one is checked.
### Response:
def check_classes(self, scope=-1):
""" Check if pending identifiers are defined o... |
async def get_participant(self, p_id: int, force_update=False) -> Participant:
""" get a participant by its id
|methcoro|
Args:
p_id: participant id
force_update (dfault=False): True to force an update to the Challonge API
Returns:
Participant: None... | get a participant by its id
|methcoro|
Args:
p_id: participant id
force_update (dfault=False): True to force an update to the Challonge API
Returns:
Participant: None if not found
Raises:
APIException | Below is the the instruction that describes the task:
### Input:
get a participant by its id
|methcoro|
Args:
p_id: participant id
force_update (dfault=False): True to force an update to the Challonge API
Returns:
Participant: None if not found
... |
def import_object(object_name):
"""Import an object from its Fully Qualified Name."""
package, name = object_name.rsplit('.', 1)
return getattr(importlib.import_module(package), name) | Import an object from its Fully Qualified Name. | Below is the the instruction that describes the task:
### Input:
Import an object from its Fully Qualified Name.
### Response:
def import_object(object_name):
"""Import an object from its Fully Qualified Name."""
package, name = object_name.rsplit('.', 1)
return getattr(importlib.import_module(package)... |
def capture_reset_password_requests(reset_password_sent_at=None):
"""Testing utility for capturing password reset requests.
:param reset_password_sent_at: An optional datetime object to set the
user's `reset_password_sent_at` to
"""
reset_requests = []
def _on(ap... | Testing utility for capturing password reset requests.
:param reset_password_sent_at: An optional datetime object to set the
user's `reset_password_sent_at` to | Below is the the instruction that describes the task:
### Input:
Testing utility for capturing password reset requests.
:param reset_password_sent_at: An optional datetime object to set the
user's `reset_password_sent_at` to
### Response:
def capture_reset_password_requests(... |
def _send_start_ok(self, frame_in):
"""Send Start OK frame.
:param specification.Connection.Start frame_in: Amqp frame.
:return:
"""
mechanisms = try_utf8_decode(frame_in.mechanisms)
if 'EXTERNAL' in mechanisms:
mechanism = 'EXTERNAL'
credentials ... | Send Start OK frame.
:param specification.Connection.Start frame_in: Amqp frame.
:return: | Below is the the instruction that describes the task:
### Input:
Send Start OK frame.
:param specification.Connection.Start frame_in: Amqp frame.
:return:
### Response:
def _send_start_ok(self, frame_in):
"""Send Start OK frame.
:param specification.Connection.Start frame_in: Amqp... |
def valid_return_codes(self, *codes):
""" Sets codes which are considered valid when returned from
command modules. The default is (0, ).
Should be used as a context::
with api.valid_return_codes(0, 1):
api.shell('test -e /tmp/log && rm /tmp/log')
"""
... | Sets codes which are considered valid when returned from
command modules. The default is (0, ).
Should be used as a context::
with api.valid_return_codes(0, 1):
api.shell('test -e /tmp/log && rm /tmp/log') | Below is the the instruction that describes the task:
### Input:
Sets codes which are considered valid when returned from
command modules. The default is (0, ).
Should be used as a context::
with api.valid_return_codes(0, 1):
api.shell('test -e /tmp/log && rm /tmp/log')... |
def matches(self, tokenJson):
'''Determines whether given token (tokenJson) satisfies all the rules listed
in the WordTemplate. If the rules describe tokenJson[ANALYSIS], it is
required that at least one item in the list tokenJson[ANALYSIS] satisfies
all the rules (but it... | Determines whether given token (tokenJson) satisfies all the rules listed
in the WordTemplate. If the rules describe tokenJson[ANALYSIS], it is
required that at least one item in the list tokenJson[ANALYSIS] satisfies
all the rules (but it is not required that all the items should... | Below is the the instruction that describes the task:
### Input:
Determines whether given token (tokenJson) satisfies all the rules listed
in the WordTemplate. If the rules describe tokenJson[ANALYSIS], it is
required that at least one item in the list tokenJson[ANALYSIS] satisfies
... |
def is_conditional(self, include_loop=True):
"""
Check if the node is a conditional node
A conditional node is either a IF or a require/assert or a RETURN bool
Returns:
bool: True if the node is a conditional node
"""
if self.contains_if(include_loop) ... | Check if the node is a conditional node
A conditional node is either a IF or a require/assert or a RETURN bool
Returns:
bool: True if the node is a conditional node | Below is the the instruction that describes the task:
### Input:
Check if the node is a conditional node
A conditional node is either a IF or a require/assert or a RETURN bool
Returns:
bool: True if the node is a conditional node
### Response:
def is_conditional(self, include_loop=T... |
def search(self, query, category=None, orientation=None, page=1, per_page=10):
"""
Get a single page from a photo search.
Optionally limit your search to a set of categories by supplying the category ID’s.
Note: If supplying multiple category ID’s,
the resulting photos will be t... | Get a single page from a photo search.
Optionally limit your search to a set of categories by supplying the category ID’s.
Note: If supplying multiple category ID’s,
the resulting photos will be those that match all of the given categories,
not ones that match any category.
:pa... | Below is the the instruction that describes the task:
### Input:
Get a single page from a photo search.
Optionally limit your search to a set of categories by supplying the category ID’s.
Note: If supplying multiple category ID’s,
the resulting photos will be those that match all of the giv... |
def set(self, key, val, timeout=None, using=None):
"""
Set will be using the generational key, so if another thread
bumps this key, the localstore version will still be invalid.
If the key is bumped during a transaction it will be new
to the global cache on commit, so it will sti... | Set will be using the generational key, so if another thread
bumps this key, the localstore version will still be invalid.
If the key is bumped during a transaction it will be new
to the global cache on commit, so it will still be a bump. | Below is the the instruction that describes the task:
### Input:
Set will be using the generational key, so if another thread
bumps this key, the localstore version will still be invalid.
If the key is bumped during a transaction it will be new
to the global cache on commit, so it will still... |
def user_saw_task(self, username, courseid, taskid):
""" Set in the database that the user has viewed this task """
self._database.user_tasks.update({"username": username, "courseid": courseid, "taskid": taskid},
{"$setOnInsert": {"username": username, "courseid"... | Set in the database that the user has viewed this task | Below is the the instruction that describes the task:
### Input:
Set in the database that the user has viewed this task
### Response:
def user_saw_task(self, username, courseid, taskid):
""" Set in the database that the user has viewed this task """
self._database.user_tasks.update({"username": use... |
def client_list_entries_multi_project(
client, to_delete
): # pylint: disable=unused-argument
"""List entries via client across multiple projects."""
# [START client_list_entries_multi_project]
PROJECT_IDS = ["one-project", "another-project"]
for entry in client.list_entries(project_ids=PROJECT_ID... | List entries via client across multiple projects. | Below is the the instruction that describes the task:
### Input:
List entries via client across multiple projects.
### Response:
def client_list_entries_multi_project(
client, to_delete
): # pylint: disable=unused-argument
"""List entries via client across multiple projects."""
# [START client_list_e... |
def is_oriented(self):
"""
Returns whether or not the current box is rotated at all.
"""
if util.is_shape(self.primitive.transform, (4, 4)):
return not np.allclose(self.primitive.transform[
0:3, 0:3], np.eye(3))
else:
ret... | Returns whether or not the current box is rotated at all. | Below is the the instruction that describes the task:
### Input:
Returns whether or not the current box is rotated at all.
### Response:
def is_oriented(self):
"""
Returns whether or not the current box is rotated at all.
"""
if util.is_shape(self.primitive.transform, (4, 4)):
... |
def import_(self, data):
"""Read JSON from `data`."""
return self.__import(json.loads(data, **self.kwargs)) | Read JSON from `data`. | Below is the the instruction that describes the task:
### Input:
Read JSON from `data`.
### Response:
def import_(self, data):
"""Read JSON from `data`."""
return self.__import(json.loads(data, **self.kwargs)) |
def expand(self, local_search=False):
'''Create successors.'''
new_nodes = []
for action in self.problem.actions(self.state):
new_state = self.problem.result(self.state, action)
cost = self.problem.cost(self.state,
action,
... | Create successors. | Below is the the instruction that describes the task:
### Input:
Create successors.
### Response:
def expand(self, local_search=False):
'''Create successors.'''
new_nodes = []
for action in self.problem.actions(self.state):
new_state = self.problem.result(self.state, action)
... |
def dump(self):
"""Dump the image data"""
scan_lines = bytearray()
for y in range(self.height):
scan_lines.append(0) # filter type 0 (None)
scan_lines.extend(
self.canvas[(y * self.width * 4):((y + 1) * self.width * 4)]
)
# image repre... | Dump the image data | Below is the the instruction that describes the task:
### Input:
Dump the image data
### Response:
def dump(self):
"""Dump the image data"""
scan_lines = bytearray()
for y in range(self.height):
scan_lines.append(0) # filter type 0 (None)
scan_lines.extend(
... |
def list_descriptors(self):
"""Return list of GATT descriptors that have been discovered for this
characteristic.
"""
paths = self._props.Get(_CHARACTERISTIC_INTERFACE, 'Descriptors')
return map(BluezGattDescriptor,
get_provider()._get_objects_by_path(paths)) | Return list of GATT descriptors that have been discovered for this
characteristic. | Below is the the instruction that describes the task:
### Input:
Return list of GATT descriptors that have been discovered for this
characteristic.
### Response:
def list_descriptors(self):
"""Return list of GATT descriptors that have been discovered for this
characteristic.
"""
... |
def get_apps_api():
"""
Create instance of Apps V1 API of kubernetes:
https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/AppsV1Api.md
:return: instance of client
"""
global apps_api
if apps_api is None:
config.load_kube_config()
if API_KEY is not None:
... | Create instance of Apps V1 API of kubernetes:
https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/AppsV1Api.md
:return: instance of client | Below is the the instruction that describes the task:
### Input:
Create instance of Apps V1 API of kubernetes:
https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/AppsV1Api.md
:return: instance of client
### Response:
def get_apps_api():
"""
Create instance of Apps V1 API of kub... |
def interpolate_sysenv(line, defaults={}):
'''
Format line system environment variables + defaults
'''
map = ChainMap(os.environ, defaults)
return line.format(**map) | Format line system environment variables + defaults | Below is the the instruction that describes the task:
### Input:
Format line system environment variables + defaults
### Response:
def interpolate_sysenv(line, defaults={}):
'''
Format line system environment variables + defaults
'''
map = ChainMap(os.environ, defaults)
return line.format(**map... |
def container_query(self, query, quiet=False):
'''search for a specific container.
This function would likely be similar to the above, but have different
filter criteria from the user (based on the query)
'''
results = self._list_containers()
matches = []
for result in results:
... | search for a specific container.
This function would likely be similar to the above, but have different
filter criteria from the user (based on the query) | Below is the the instruction that describes the task:
### Input:
search for a specific container.
This function would likely be similar to the above, but have different
filter criteria from the user (based on the query)
### Response:
def container_query(self, query, quiet=False):
'''search for a ... |
def notify_created(room, event, user):
"""Notifies about the creation of a chatroom.
:param room: the chatroom
:param event: the event
:param user: the user performing the action
"""
tpl = get_plugin_template_module('emails/created.txt', chatroom=room, event=event, user=user)
_send(event, t... | Notifies about the creation of a chatroom.
:param room: the chatroom
:param event: the event
:param user: the user performing the action | Below is the the instruction that describes the task:
### Input:
Notifies about the creation of a chatroom.
:param room: the chatroom
:param event: the event
:param user: the user performing the action
### Response:
def notify_created(room, event, user):
"""Notifies about the creation of a chatroo... |
def chains(xs, labels=None, truths=None, truth_color=u"#4682b4", burn=None,
alpha=0.5, fig=None):
"""
Create a plot showing the walker values for each parameter at every step.
:param xs:
The samples. This should be a 3D :class:`numpy.ndarray` of size
(``n_walkers``, ``n_steps``, ``n_pa... | Create a plot showing the walker values for each parameter at every step.
:param xs:
The samples. This should be a 3D :class:`numpy.ndarray` of size
(``n_walkers``, ``n_steps``, ``n_parameters``).
:type xs:
:class:`numpy.ndarray`
:param labels: [optional]
Labels for all t... | Below is the the instruction that describes the task:
### Input:
Create a plot showing the walker values for each parameter at every step.
:param xs:
The samples. This should be a 3D :class:`numpy.ndarray` of size
(``n_walkers``, ``n_steps``, ``n_parameters``).
:type xs:
:class:`n... |
def read_code(self, address, size=1):
"""
Read size byte from bytecode.
If less than size bytes are available result will be pad with \x00
"""
assert address < len(self.bytecode)
value = self.bytecode[address:address + size]
if len(value) < size:
value... | Read size byte from bytecode.
If less than size bytes are available result will be pad with \x00 | Below is the the instruction that describes the task:
### Input:
Read size byte from bytecode.
If less than size bytes are available result will be pad with \x00
### Response:
def read_code(self, address, size=1):
"""
Read size byte from bytecode.
If less than size bytes are availab... |
def pad(text, bits=32):
"""
Pads the inputted text to ensure it fits the proper block length
for encryption.
:param text | <str>
bits | <int>
:return <str>
"""
return text + (bits - len(text) % bits) * chr(bits - len(text) % bits) | Pads the inputted text to ensure it fits the proper block length
for encryption.
:param text | <str>
bits | <int>
:return <str> | Below is the the instruction that describes the task:
### Input:
Pads the inputted text to ensure it fits the proper block length
for encryption.
:param text | <str>
bits | <int>
:return <str>
### Response:
def pad(text, bits=32):
"""
Pads the inputted text to... |
def tree(string, token=[WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA]):
""" Transforms the output of parse() into a Text object.
The token parameter lists the order of tags in each token in the input string.
"""
return Text(string, token) | Transforms the output of parse() into a Text object.
The token parameter lists the order of tags in each token in the input string. | Below is the the instruction that describes the task:
### Input:
Transforms the output of parse() into a Text object.
The token parameter lists the order of tags in each token in the input string.
### Response:
def tree(string, token=[WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA]):
""" Transforms the outp... |
def url_to_tile(url):
"""
Extracts tile name, date and AWS index from tile url on AWS.
:param url: class input parameter 'metafiles'
:type url: str
:return: Name of tile, date and AWS index which uniquely identifies tile on AWS
:rtype: (str, str, int)
"""
... | Extracts tile name, date and AWS index from tile url on AWS.
:param url: class input parameter 'metafiles'
:type url: str
:return: Name of tile, date and AWS index which uniquely identifies tile on AWS
:rtype: (str, str, int) | Below is the the instruction that describes the task:
### Input:
Extracts tile name, date and AWS index from tile url on AWS.
:param url: class input parameter 'metafiles'
:type url: str
:return: Name of tile, date and AWS index which uniquely identifies tile on AWS
:rtype: (str, st... |
def split_unescaped(char, string, include_empty_strings=False):
'''
:param char: The character on which to split the string
:type char: string
:param string: The string to split
:type string: string
:returns: List of substrings of *string*
:rtype: list of strings
Splits *string* wheneve... | :param char: The character on which to split the string
:type char: string
:param string: The string to split
:type string: string
:returns: List of substrings of *string*
:rtype: list of strings
Splits *string* whenever *char* appears without an odd number of
backslashes ('\\') preceding i... | Below is the the instruction that describes the task:
### Input:
:param char: The character on which to split the string
:type char: string
:param string: The string to split
:type string: string
:returns: List of substrings of *string*
:rtype: list of strings
Splits *string* whenever *char... |
def fast_sync_sign_snapshot( snapshot_path, private_key, first=False ):
"""
Append a signature to the end of a snapshot path
with the given private key.
If first is True, then don't expect the signature trailer.
Return True on success
Return False on error
"""
if not os.path.exists... | Append a signature to the end of a snapshot path
with the given private key.
If first is True, then don't expect the signature trailer.
Return True on success
Return False on error | Below is the the instruction that describes the task:
### Input:
Append a signature to the end of a snapshot path
with the given private key.
If first is True, then don't expect the signature trailer.
Return True on success
Return False on error
### Response:
def fast_sync_sign_snapshot( snapshot... |
def skips(self, user):
"""
Skips for user. Zendesk API `Reference <https://developer.zendesk.com/rest_api/docs/core/ticket_skips>`__.
"""
return self._get(self._build_url(self.endpoint.skips(id=user))) | Skips for user. Zendesk API `Reference <https://developer.zendesk.com/rest_api/docs/core/ticket_skips>`__. | Below is the the instruction that describes the task:
### Input:
Skips for user. Zendesk API `Reference <https://developer.zendesk.com/rest_api/docs/core/ticket_skips>`__.
### Response:
def skips(self, user):
"""
Skips for user. Zendesk API `Reference <https://developer.zendesk.com/rest_api/docs/co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.