code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def JoinKeyPath(path_segments):
"""Joins the path segments into key path.
Args:
path_segments (list[str]): Windows Registry key path segments.
Returns:
str: key path.
"""
# This is an optimized way to combine the path segments into a single path
# and combine multiple successive path separators to... | Joins the path segments into key path.
Args:
path_segments (list[str]): Windows Registry key path segments.
Returns:
str: key path. | Below is the the instruction that describes the task:
### Input:
Joins the path segments into key path.
Args:
path_segments (list[str]): Windows Registry key path segments.
Returns:
str: key path.
### Response:
def JoinKeyPath(path_segments):
"""Joins the path segments into key path.
Args:
p... |
def get_link_name (self, tag, attrs, attr):
"""Parse attrs for link name. Return name of link."""
if tag == 'a' and attr == 'href':
# Look for name only up to MAX_NAMELEN characters
data = self.parser.peek(MAX_NAMELEN)
data = data.decode(self.parser.encoding, "ignore"... | Parse attrs for link name. Return name of link. | Below is the the instruction that describes the task:
### Input:
Parse attrs for link name. Return name of link.
### Response:
def get_link_name (self, tag, attrs, attr):
"""Parse attrs for link name. Return name of link."""
if tag == 'a' and attr == 'href':
# Look for name only up to M... |
def is_arabicstring(text):
""" Checks for an Arabic standard Unicode block characters
An arabic string can contain spaces, digits and pounctuation.
but only arabic standard characters, not extended arabic
@param text: input text
@type text: unicode
@return: True if all charaters are in Arabic... | Checks for an Arabic standard Unicode block characters
An arabic string can contain spaces, digits and pounctuation.
but only arabic standard characters, not extended arabic
@param text: input text
@type text: unicode
@return: True if all charaters are in Arabic block
@rtype: Boolean | Below is the the instruction that describes the task:
### Input:
Checks for an Arabic standard Unicode block characters
An arabic string can contain spaces, digits and pounctuation.
but only arabic standard characters, not extended arabic
@param text: input text
@type text: unicode
@return: T... |
def update_policy(self,defaultHeaders):
""" if policy in default but not input still return """
if self.inputs is not None:
for k,v in defaultHeaders.items():
if k not in self.inputs:
self.inputs[k] = v
return self.inputs
else:
return self.inputs | if policy in default but not input still return | Below is the the instruction that describes the task:
### Input:
if policy in default but not input still return
### Response:
def update_policy(self,defaultHeaders):
""" if policy in default but not input still return """
if self.inputs is not None:
for k,v in defaultHeaders.items():
if k not in self.i... |
def execute(self, email):
"""Execute use case handling."""
print('Sign up user {0}'.format(email))
self.email_sender.send(email, 'Welcome, "{}"'.format(email)) | Execute use case handling. | Below is the the instruction that describes the task:
### Input:
Execute use case handling.
### Response:
def execute(self, email):
"""Execute use case handling."""
print('Sign up user {0}'.format(email))
self.email_sender.send(email, 'Welcome, "{}"'.format(email)) |
def moist_static_energy(heights, temperature, specific_humidity):
r"""Calculate the moist static energy of parcels.
This function will calculate the moist static energy following
equation 3.72 in [Hobbs2006]_.
Notes
-----
.. math::\text{moist static energy} = c_{pd} * T + gz + L_v q
* :mat... | r"""Calculate the moist static energy of parcels.
This function will calculate the moist static energy following
equation 3.72 in [Hobbs2006]_.
Notes
-----
.. math::\text{moist static energy} = c_{pd} * T + gz + L_v q
* :math:`T` is temperature
* :math:`z` is height
* :math:`q` is spec... | Below is the the instruction that describes the task:
### Input:
r"""Calculate the moist static energy of parcels.
This function will calculate the moist static energy following
equation 3.72 in [Hobbs2006]_.
Notes
-----
.. math::\text{moist static energy} = c_{pd} * T + gz + L_v q
* :math... |
def find_descriptor(self, uuid):
"""Return the first child descriptor found that has the specified
UUID. Will return None if no descriptor that matches is found.
"""
for desc in self.list_descriptors():
if desc.uuid == uuid:
return desc
return None | Return the first child descriptor found that has the specified
UUID. Will return None if no descriptor that matches is found. | Below is the the instruction that describes the task:
### Input:
Return the first child descriptor found that has the specified
UUID. Will return None if no descriptor that matches is found.
### Response:
def find_descriptor(self, uuid):
"""Return the first child descriptor found that has the spec... |
def get_protein_data_pgrouped(proteindata, p_acc, headerfields):
"""Parses protein data for a certain protein into tsv output
dictionary"""
report = get_protein_data_base(proteindata, p_acc, headerfields)
return get_cov_protnumbers(proteindata, p_acc, report) | Parses protein data for a certain protein into tsv output
dictionary | Below is the the instruction that describes the task:
### Input:
Parses protein data for a certain protein into tsv output
dictionary
### Response:
def get_protein_data_pgrouped(proteindata, p_acc, headerfields):
"""Parses protein data for a certain protein into tsv output
dictionary"""
report = ge... |
def no_wait_release(self, connection: Connection):
'''Synchronous version of :meth:`release`.'''
_logger.debug('No wait check in.')
release_task = asyncio.get_event_loop().create_task(
self.release(connection)
)
self._release_tasks.add(release_task) | Synchronous version of :meth:`release`. | Below is the the instruction that describes the task:
### Input:
Synchronous version of :meth:`release`.
### Response:
def no_wait_release(self, connection: Connection):
'''Synchronous version of :meth:`release`.'''
_logger.debug('No wait check in.')
release_task = asyncio.get_event_loop().... |
def build_absolute_uri(self, uri):
"""
Return a fully qualified absolute url for the given uri.
"""
request = self.context.get('request', None)
return (
request.build_absolute_uri(uri) if request is not None else uri
) | Return a fully qualified absolute url for the given uri. | Below is the the instruction that describes the task:
### Input:
Return a fully qualified absolute url for the given uri.
### Response:
def build_absolute_uri(self, uri):
"""
Return a fully qualified absolute url for the given uri.
"""
request = self.context.get('request', None)
... |
def _format_coredump_stdout(cmd_ret):
'''
Helper function to format the stdout from the get_coredump_network_config function.
cmd_ret
The return dictionary that comes from a cmd.run_all call.
'''
ret_dict = {}
for line in cmd_ret['stdout'].splitlines():
line = line.strip().lower... | Helper function to format the stdout from the get_coredump_network_config function.
cmd_ret
The return dictionary that comes from a cmd.run_all call. | Below is the the instruction that describes the task:
### Input:
Helper function to format the stdout from the get_coredump_network_config function.
cmd_ret
The return dictionary that comes from a cmd.run_all call.
### Response:
def _format_coredump_stdout(cmd_ret):
'''
Helper function to form... |
def gen_blocks(output, ascii_props=False, append=False, prefix=""):
"""Generate Unicode blocks."""
with codecs.open(output, 'a' if append else 'w', 'utf-8') as f:
if not append:
f.write(HEADER)
f.write('%s_blocks = {' % prefix)
no_block = []
last = -1
max_ra... | Generate Unicode blocks. | Below is the the instruction that describes the task:
### Input:
Generate Unicode blocks.
### Response:
def gen_blocks(output, ascii_props=False, append=False, prefix=""):
"""Generate Unicode blocks."""
with codecs.open(output, 'a' if append else 'w', 'utf-8') as f:
if not append:
f.wr... |
def add_bits4subtree_ids(self, relevant_ids):
"""Adds a long integer bits4subtree_ids to each node (Fails cryptically if that field is already present!)
relevant_ids can be a dict of _id to bit representation.
If it is not supplied, a dict will be created by registering the leaf._id into a dict ... | Adds a long integer bits4subtree_ids to each node (Fails cryptically if that field is already present!)
relevant_ids can be a dict of _id to bit representation.
If it is not supplied, a dict will be created by registering the leaf._id into a dict (and returning the dict)
the bits4subtree_ids wil... | Below is the the instruction that describes the task:
### Input:
Adds a long integer bits4subtree_ids to each node (Fails cryptically if that field is already present!)
relevant_ids can be a dict of _id to bit representation.
If it is not supplied, a dict will be created by registering the leaf._id ... |
def delete(self, block_type, block_num):
"""
Deletes a block
:param block_type: Type of block
:param block_num: Bloc number
"""
logger.info("deleting block")
blocktype = snap7.snap7types.block_types[block_type]
result = self.library.Cli_Delete(sel... | Deletes a block
:param block_type: Type of block
:param block_num: Bloc number | Below is the the instruction that describes the task:
### Input:
Deletes a block
:param block_type: Type of block
:param block_num: Bloc number
### Response:
def delete(self, block_type, block_num):
"""
Deletes a block
:param block_type: Type of block
... |
def maps_get_rules_output_rules_policyname(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_rules = ET.Element("maps_get_rules")
config = maps_get_rules
output = ET.SubElement(maps_get_rules, "output")
rules = ET.SubElement(output... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def maps_get_rules_output_rules_policyname(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_rules = ET.Element("maps_get_rules")
config = maps... |
def _assign_udf_desc_extents(descs, start_extent):
# type: (PyCdlib._UDFDescriptors, int) -> None
'''
An internal function to assign a consecutive sequence of extents for the
given set of UDF Descriptors, starting at the given extent.
Parameters:
descs - The PyCdlib._UDFDescriptors object to a... | An internal function to assign a consecutive sequence of extents for the
given set of UDF Descriptors, starting at the given extent.
Parameters:
descs - The PyCdlib._UDFDescriptors object to assign extents for.
start_extent - The starting extent to assign from.
Returns:
Nothing. | Below is the the instruction that describes the task:
### Input:
An internal function to assign a consecutive sequence of extents for the
given set of UDF Descriptors, starting at the given extent.
Parameters:
descs - The PyCdlib._UDFDescriptors object to assign extents for.
start_extent - The st... |
def get_attributes(**kwargs):
"""
Get all attributes
"""
attrs = db.DBSession.query(Attr).order_by(Attr.name).all()
return attrs | Get all attributes | Below is the the instruction that describes the task:
### Input:
Get all attributes
### Response:
def get_attributes(**kwargs):
"""
Get all attributes
"""
attrs = db.DBSession.query(Attr).order_by(Attr.name).all()
return attrs |
def file_matches(filename, patterns):
"""Does this filename match any of the patterns?"""
return any(fnmatch.fnmatch(filename, pat)
or fnmatch.fnmatch(os.path.basename(filename), pat)
for pat in patterns) | Does this filename match any of the patterns? | Below is the the instruction that describes the task:
### Input:
Does this filename match any of the patterns?
### Response:
def file_matches(filename, patterns):
"""Does this filename match any of the patterns?"""
return any(fnmatch.fnmatch(filename, pat)
or fnmatch.fnmatch(os.path.basename... |
def substatements(self) -> List[Statement]:
"""Parse substatements.
Raises:
EndOfInput: If past the end of input.
"""
res = []
self.opt_separator()
while self.peek() != "}":
res.append(self.statement())
self.opt_separator()
sel... | Parse substatements.
Raises:
EndOfInput: If past the end of input. | Below is the the instruction that describes the task:
### Input:
Parse substatements.
Raises:
EndOfInput: If past the end of input.
### Response:
def substatements(self) -> List[Statement]:
"""Parse substatements.
Raises:
EndOfInput: If past the end of input.
... |
def index(self, sub, *args):
"""
Like newstr.find() but raise ValueError when the substring is not
found.
"""
pos = self.find(sub, *args)
if pos == -1:
raise ValueError('substring not found')
return pos | Like newstr.find() but raise ValueError when the substring is not
found. | Below is the the instruction that describes the task:
### Input:
Like newstr.find() but raise ValueError when the substring is not
found.
### Response:
def index(self, sub, *args):
"""
Like newstr.find() but raise ValueError when the substring is not
found.
"""
pos =... |
def remove_board(board_id):
"""remove board.
:param board_id: board id (e.g. 'diecimila')
:rtype: None
"""
log.debug('remove %s', board_id)
lines = boards_txt().lines()
lines = filter(lambda x: not x.strip().startswith(board_id + '.'), lines)
boards_txt().write_lines(lines) | remove board.
:param board_id: board id (e.g. 'diecimila')
:rtype: None | Below is the the instruction that describes the task:
### Input:
remove board.
:param board_id: board id (e.g. 'diecimila')
:rtype: None
### Response:
def remove_board(board_id):
"""remove board.
:param board_id: board id (e.g. 'diecimila')
:rtype: None
"""
log.debug('remove %s', bo... |
def sum(self, phi1, inplace=True):
"""
DiscreteFactor sum with `phi1`.
Parameters
----------
phi1: `DiscreteFactor` instance.
DiscreteFactor to be added.
inplace: boolean
If inplace=True it will modify the factor itself, else would return
... | DiscreteFactor sum with `phi1`.
Parameters
----------
phi1: `DiscreteFactor` instance.
DiscreteFactor to be added.
inplace: boolean
If inplace=True it will modify the factor itself, else would return
a new factor.
Returns
-------
... | Below is the the instruction that describes the task:
### Input:
DiscreteFactor sum with `phi1`.
Parameters
----------
phi1: `DiscreteFactor` instance.
DiscreteFactor to be added.
inplace: boolean
If inplace=True it will modify the factor itself, else would ... |
def ok(self):
"""Validate color selection and destroy dialog."""
rgb, hsv, hexa = self.square.get()
if self.alpha_channel:
hexa = self.hexa.get()
rgb += (self.alpha.get(),)
self.color = rgb, hsv, hexa
self.destroy() | Validate color selection and destroy dialog. | Below is the the instruction that describes the task:
### Input:
Validate color selection and destroy dialog.
### Response:
def ok(self):
"""Validate color selection and destroy dialog."""
rgb, hsv, hexa = self.square.get()
if self.alpha_channel:
hexa = self.hexa.get()
... |
def click_at_coordinates(self, x, y):
"""
Click at (x,y) coordinates.
"""
self.device.click(int(x), int(y)) | Click at (x,y) coordinates. | Below is the the instruction that describes the task:
### Input:
Click at (x,y) coordinates.
### Response:
def click_at_coordinates(self, x, y):
"""
Click at (x,y) coordinates.
"""
self.device.click(int(x), int(y)) |
def dataset_path_iterator(file_path: str) -> Iterator[str]:
"""
An iterator returning file_paths in a directory
containing CONLL-formatted files.
"""
logger.info("Reading CONLL sentences from dataset files at: %s", file_path)
for root, _, files in list(os.walk(file_path))... | An iterator returning file_paths in a directory
containing CONLL-formatted files. | Below is the the instruction that describes the task:
### Input:
An iterator returning file_paths in a directory
containing CONLL-formatted files.
### Response:
def dataset_path_iterator(file_path: str) -> Iterator[str]:
"""
An iterator returning file_paths in a directory
containing... |
def get_or_create_author(self, name: str) -> Author:
"""Get an author by name, or creates one if it does not exist."""
author = self.object_cache_author.get(name)
if author is not None:
self.session.add(author)
return author
author = self.get_author_by_name(name... | Get an author by name, or creates one if it does not exist. | Below is the the instruction that describes the task:
### Input:
Get an author by name, or creates one if it does not exist.
### Response:
def get_or_create_author(self, name: str) -> Author:
"""Get an author by name, or creates one if it does not exist."""
author = self.object_cache_author.get(nam... |
def other_Orange_tables(self):
'''
Returns the related tables as Orange example tables.
:rtype: list
'''
target_table = self.db.target_table
if not self.db.orng_tables:
return [self.convert_table(table, None) for table in self.db.tables if table != ta... | Returns the related tables as Orange example tables.
:rtype: list | Below is the the instruction that describes the task:
### Input:
Returns the related tables as Orange example tables.
:rtype: list
### Response:
def other_Orange_tables(self):
'''
Returns the related tables as Orange example tables.
:rtype: list
'''
tar... |
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(DseOpsCenterCollector, self).get_default_config()
metrics = [
'cf-bf-false-positives',
'cf-bf-false-ratio',
'cf-bf-space-used',
'cf-keycache... | Returns the default collector settings | Below is the the instruction that describes the task:
### Input:
Returns the default collector settings
### Response:
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(DseOpsCenterCollector, self).get_default_config()
metrics = [
... |
def Slot(self, slotnum):
"""
Slot sets the vtable key `voffset` to the current location in the
buffer.
"""
self.assertNested()
self.current_vtable[slotnum] = self.Offset() | Slot sets the vtable key `voffset` to the current location in the
buffer. | Below is the the instruction that describes the task:
### Input:
Slot sets the vtable key `voffset` to the current location in the
buffer.
### Response:
def Slot(self, slotnum):
"""
Slot sets the vtable key `voffset` to the current location in the
buffer.
"""
self.a... |
def default_error_handler(socket, error_name, error_message, endpoint,
msg_id, quiet):
"""This is the default error handler, you can override this when
calling :func:`socketio.socketio_manage`.
It basically sends an event through the socket with the 'error' name.
See document... | This is the default error handler, you can override this when
calling :func:`socketio.socketio_manage`.
It basically sends an event through the socket with the 'error' name.
See documentation for :meth:`Socket.error`.
:param quiet: if quiet, this handler will not send a packet to the
... | Below is the the instruction that describes the task:
### Input:
This is the default error handler, you can override this when
calling :func:`socketio.socketio_manage`.
It basically sends an event through the socket with the 'error' name.
See documentation for :meth:`Socket.error`.
:param quiet: ... |
def write_nexus_files(self, force=False, quiet=False):
"""
Write nexus files to {workdir}/{name}/[0-N].nex, If the directory already
exists an exception will be raised unless you use the force flag which
will remove all files in the directory.
Parameters:
-----------
... | Write nexus files to {workdir}/{name}/[0-N].nex, If the directory already
exists an exception will be raised unless you use the force flag which
will remove all files in the directory.
Parameters:
-----------
force (bool):
If True then all files in {workdir}/{name}... | Below is the the instruction that describes the task:
### Input:
Write nexus files to {workdir}/{name}/[0-N].nex, If the directory already
exists an exception will be raised unless you use the force flag which
will remove all files in the directory.
Parameters:
-----------
... |
def _parse(self, filename):
"""Opens data file and for each line, calls _eat_name_line"""
self.names = {}
with codecs.open(filename, encoding="iso8859-1") as f:
for line in f:
if any(map(lambda c: 128 < ord(c) < 160, line)):
line = line.encode("iso... | Opens data file and for each line, calls _eat_name_line | Below is the the instruction that describes the task:
### Input:
Opens data file and for each line, calls _eat_name_line
### Response:
def _parse(self, filename):
"""Opens data file and for each line, calls _eat_name_line"""
self.names = {}
with codecs.open(filename, encoding="iso8859-1") a... |
def _extract_stack(limit=10):
"""Replacement for traceback.extract_stack() that only does the
necessary work for asyncio debug mode.
"""
frame = sys._getframe().f_back
try:
stack = traceback.StackSummary.extract(
traceback.walk_stack(frame), lookup_lines=False)
finally:
... | Replacement for traceback.extract_stack() that only does the
necessary work for asyncio debug mode. | Below is the the instruction that describes the task:
### Input:
Replacement for traceback.extract_stack() that only does the
necessary work for asyncio debug mode.
### Response:
def _extract_stack(limit=10):
"""Replacement for traceback.extract_stack() that only does the
necessary work for asyncio deb... |
def _all_recall_native_type(self, data, ptitem, prefix):
"""Checks if loaded data has the type it was stored in. If not converts it.
:param data: Data item to be checked and converted
:param ptitem: HDf5 Node or Leaf from where data was loaded
:param prefix: Prefix for recalling the dat... | Checks if loaded data has the type it was stored in. If not converts it.
:param data: Data item to be checked and converted
:param ptitem: HDf5 Node or Leaf from where data was loaded
:param prefix: Prefix for recalling the data type from the hdf5 node attributes
:return:
... | Below is the the instruction that describes the task:
### Input:
Checks if loaded data has the type it was stored in. If not converts it.
:param data: Data item to be checked and converted
:param ptitem: HDf5 Node or Leaf from where data was loaded
:param prefix: Prefix for recalling the da... |
def show_input(self, template_helper, language, seed):
""" Show MatchProblem """
header = ParsableText(self.gettext(language, self._header), "rst",
translation=self._translations.get(language, gettext.NullTranslations()))
return str(DisplayableMatchProblem.get_rende... | Show MatchProblem | Below is the the instruction that describes the task:
### Input:
Show MatchProblem
### Response:
def show_input(self, template_helper, language, seed):
""" Show MatchProblem """
header = ParsableText(self.gettext(language, self._header), "rst",
translation=self._transl... |
def ToScriptHash(self, address):
"""
Retrieve the script_hash based from an address.
Args:
address (str): a base58 encoded address.
Raises:
ValuesError: if an invalid address is supplied or the coin version is incorrect
Exception: if the address stri... | Retrieve the script_hash based from an address.
Args:
address (str): a base58 encoded address.
Raises:
ValuesError: if an invalid address is supplied or the coin version is incorrect
Exception: if the address string does not start with 'A' or the checksum fails
... | Below is the the instruction that describes the task:
### Input:
Retrieve the script_hash based from an address.
Args:
address (str): a base58 encoded address.
Raises:
ValuesError: if an invalid address is supplied or the coin version is incorrect
Exception: if ... |
def print_partlist(input, timeout=20, showgui=False):
'''print partlist text delivered by eagle
:param input: .sch or .brd file name
:param timeout: int
:param showgui: Bool, True -> do not hide eagle GUI
:rtype: None
'''
print raw_partlist(input=input, timeout=timeout, showgui=showgui) | print partlist text delivered by eagle
:param input: .sch or .brd file name
:param timeout: int
:param showgui: Bool, True -> do not hide eagle GUI
:rtype: None | Below is the the instruction that describes the task:
### Input:
print partlist text delivered by eagle
:param input: .sch or .brd file name
:param timeout: int
:param showgui: Bool, True -> do not hide eagle GUI
:rtype: None
### Response:
def print_partlist(input, timeout=20, showgui=False):
... |
def __header(self, line):
"""Build the header (contain the number of CPU).
CPU0 CPU1 CPU2 CPU3
0: 21 0 0 0 IO-APIC 2-edge timer
"""
self.cpu_number = len(line.split())
return self.cpu_number | Build the header (contain the number of CPU).
CPU0 CPU1 CPU2 CPU3
0: 21 0 0 0 IO-APIC 2-edge timer | Below is the the instruction that describes the task:
### Input:
Build the header (contain the number of CPU).
CPU0 CPU1 CPU2 CPU3
0: 21 0 0 0 IO-APIC 2-edge timer
### Response:
def __header(self, line):
"""Build the header (con... |
def cache(self, key, value):
"""
Add an entry to the cache.
A weakref to the value is stored, rather than a direct reference. The
value must have a C{__finalizer__} method that returns a callable which
will be invoked when the weakref is broken.
@param key: The key iden... | Add an entry to the cache.
A weakref to the value is stored, rather than a direct reference. The
value must have a C{__finalizer__} method that returns a callable which
will be invoked when the weakref is broken.
@param key: The key identifying the cache entry.
@param value: T... | Below is the the instruction that describes the task:
### Input:
Add an entry to the cache.
A weakref to the value is stored, rather than a direct reference. The
value must have a C{__finalizer__} method that returns a callable which
will be invoked when the weakref is broken.
@par... |
def callback_liveIn_button_press(red_clicks, blue_clicks, green_clicks,
rc_timestamp, bc_timestamp, gc_timestamp, **kwargs): # pylint: disable=unused-argument
'Input app button pressed, so do something interesting'
if not rc_timestamp:
rc_timestamp = 0
if not bc_tim... | Input app button pressed, so do something interesting | Below is the the instruction that describes the task:
### Input:
Input app button pressed, so do something interesting
### Response:
def callback_liveIn_button_press(red_clicks, blue_clicks, green_clicks,
rc_timestamp, bc_timestamp, gc_timestamp, **kwargs): # pylint: disable=unused... |
def get_list(shapes, types):
"""Get DataDesc list from attribute lists.
Parameters
----------
shapes : a tuple of (name_, shape_)
types : a tuple of (name_, np.dtype)
"""
if types is not None:
type_dict = dict(types)
return [DataDesc(x[0]... | Get DataDesc list from attribute lists.
Parameters
----------
shapes : a tuple of (name_, shape_)
types : a tuple of (name_, np.dtype) | Below is the the instruction that describes the task:
### Input:
Get DataDesc list from attribute lists.
Parameters
----------
shapes : a tuple of (name_, shape_)
types : a tuple of (name_, np.dtype)
### Response:
def get_list(shapes, types):
"""Get DataDesc list from attr... |
def release(self, key, owner):
"""Release lock with given name.
`key` - lock name
`owner` - name of application/component/whatever which held a lock
Raises `MongoLockException` if no such a lock.
"""
status = self.collection.find_and_modify(
{'_id': key, '... | Release lock with given name.
`key` - lock name
`owner` - name of application/component/whatever which held a lock
Raises `MongoLockException` if no such a lock. | Below is the the instruction that describes the task:
### Input:
Release lock with given name.
`key` - lock name
`owner` - name of application/component/whatever which held a lock
Raises `MongoLockException` if no such a lock.
### Response:
def release(self, key, owner):
"""Rele... |
def is_permitted(self, identifiers, permission_s):
"""
If the authorization info cannot be obtained from the accountstore,
permission check tuple yields False.
:type identifiers: subject_abcs.IdentifierCollection
:param permission_s: a collection of one or more permissions, re... | If the authorization info cannot be obtained from the accountstore,
permission check tuple yields False.
:type identifiers: subject_abcs.IdentifierCollection
:param permission_s: a collection of one or more permissions, represented
as string-based permissions or P... | Below is the the instruction that describes the task:
### Input:
If the authorization info cannot be obtained from the accountstore,
permission check tuple yields False.
:type identifiers: subject_abcs.IdentifierCollection
:param permission_s: a collection of one or more permissions, repr... |
def dry(self, *args, **kwargs):
'''Perform a dry-run of the task'''
return 'Would have executed:\n%s%s' % (
self.name, Args(self.spec).explain(*args, **kwargs)) | Perform a dry-run of the task | Below is the the instruction that describes the task:
### Input:
Perform a dry-run of the task
### Response:
def dry(self, *args, **kwargs):
'''Perform a dry-run of the task'''
return 'Would have executed:\n%s%s' % (
self.name, Args(self.spec).explain(*args, **kwargs)) |
def reset(self):
"""Clear ConfigObj instance and restore to 'freshly created' state."""
self.clear()
self._initialise()
# FIXME: Should be done by '_initialise', but ConfigObj constructor (and reload)
# requires an empty dictionary
self.configspec = None
# ... | Clear ConfigObj instance and restore to 'freshly created' state. | Below is the the instruction that describes the task:
### Input:
Clear ConfigObj instance and restore to 'freshly created' state.
### Response:
def reset(self):
"""Clear ConfigObj instance and restore to 'freshly created' state."""
self.clear()
self._initialise()
# FIXME: Should be ... |
def GetRootFileEntry(self):
"""Retrieves the root file entry.
Returns:
OSFileEntry: a file entry or None if not available.
"""
if platform.system() == 'Windows':
# Return the root with the drive letter of the volume the current
# working directory is on.
location = os.getcwd()
... | Retrieves the root file entry.
Returns:
OSFileEntry: a file entry or None if not available. | Below is the the instruction that describes the task:
### Input:
Retrieves the root file entry.
Returns:
OSFileEntry: a file entry or None if not available.
### Response:
def GetRootFileEntry(self):
"""Retrieves the root file entry.
Returns:
OSFileEntry: a file entry or None if not availa... |
def get_delete_security_group_rule_commands(self, sg_id, sg_rule):
"""Commands for removing rule from ACLS"""
return self._get_rule_cmds(sg_id, sg_rule, delete=True) | Commands for removing rule from ACLS | Below is the the instruction that describes the task:
### Input:
Commands for removing rule from ACLS
### Response:
def get_delete_security_group_rule_commands(self, sg_id, sg_rule):
"""Commands for removing rule from ACLS"""
return self._get_rule_cmds(sg_id, sg_rule, delete=True) |
def artists(self, spotify_ids):
"""Get a spotify artists by their IDs.
Parameters
----------
spotify_id : List[str]
The spotify_ids to search with.
"""
route = Route('GET', '/artists')
payload = {'ids': spotify_ids}
return self.request(route, ... | Get a spotify artists by their IDs.
Parameters
----------
spotify_id : List[str]
The spotify_ids to search with. | Below is the the instruction that describes the task:
### Input:
Get a spotify artists by their IDs.
Parameters
----------
spotify_id : List[str]
The spotify_ids to search with.
### Response:
def artists(self, spotify_ids):
"""Get a spotify artists by their IDs.
... |
def get_terminal_converted(self, attr):
"""
Returns the value of the specified attribute converted to a
representation value.
:param attr: Attribute to retrieve.
:type attr: :class:`everest.representers.attributes.MappedAttribute`
:returns: Representation string.
... | Returns the value of the specified attribute converted to a
representation value.
:param attr: Attribute to retrieve.
:type attr: :class:`everest.representers.attributes.MappedAttribute`
:returns: Representation string. | Below is the the instruction that describes the task:
### Input:
Returns the value of the specified attribute converted to a
representation value.
:param attr: Attribute to retrieve.
:type attr: :class:`everest.representers.attributes.MappedAttribute`
:returns: Representation string... |
def iter_steps(self):
"""Iterate over steps in the parsed file."""
for func, decorator in self._iter_step_func_decorators():
step = self._step_decorator_args(decorator)
if step:
yield step, func.name, self._span_for_node(func, True) | Iterate over steps in the parsed file. | Below is the the instruction that describes the task:
### Input:
Iterate over steps in the parsed file.
### Response:
def iter_steps(self):
"""Iterate over steps in the parsed file."""
for func, decorator in self._iter_step_func_decorators():
step = self._step_decorator_args(decorator)
... |
def get_topic_keyword_dictionary():
"""
Opens the topic-keyword map resource file and returns the corresponding python dictionary.
- Input: - file_path: The path pointing to the topic-keyword map resource file.
- Output: - topic_set: A topic to keyword python dictionary.
"""
topic_keyword_dic... | Opens the topic-keyword map resource file and returns the corresponding python dictionary.
- Input: - file_path: The path pointing to the topic-keyword map resource file.
- Output: - topic_set: A topic to keyword python dictionary. | Below is the the instruction that describes the task:
### Input:
Opens the topic-keyword map resource file and returns the corresponding python dictionary.
- Input: - file_path: The path pointing to the topic-keyword map resource file.
- Output: - topic_set: A topic to keyword python dictionary.
### Resp... |
def vq_nearest_neighbor(x, hparams):
"""Find the nearest element in means to elements in x."""
bottleneck_size = 2**hparams.bottleneck_bits
means = hparams.means
x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keepdims=True)
means_norm_sq = tf.reduce_sum(tf.square(means), axis=-1, keepdims=True)
scalar_pro... | Find the nearest element in means to elements in x. | Below is the the instruction that describes the task:
### Input:
Find the nearest element in means to elements in x.
### Response:
def vq_nearest_neighbor(x, hparams):
"""Find the nearest element in means to elements in x."""
bottleneck_size = 2**hparams.bottleneck_bits
means = hparams.means
x_norm_sq = tf... |
def buy_market(self, quantity, **kwargs):
""" Shortcut for ``instrument.order("BUY", ...)`` and accepts all of its
`optional parameters <#qtpylib.instrument.Instrument.order>`_
:Parameters:
quantity : int
Order quantity
"""
kwargs['limit_price'] = 0
... | Shortcut for ``instrument.order("BUY", ...)`` and accepts all of its
`optional parameters <#qtpylib.instrument.Instrument.order>`_
:Parameters:
quantity : int
Order quantity | Below is the the instruction that describes the task:
### Input:
Shortcut for ``instrument.order("BUY", ...)`` and accepts all of its
`optional parameters <#qtpylib.instrument.Instrument.order>`_
:Parameters:
quantity : int
Order quantity
### Response:
def buy_market(se... |
def _get_assistants_snippets(path, name):
'''Get Assistants and Snippets for a given DAP name on a given path'''
result = []
subdirs = {'assistants': 2, 'snippets': 1} # Values used for stripping leading path tokens
for loc in subdirs:
for root, dirs, files in os.walk(os.path.join(path, loc)):
... | Get Assistants and Snippets for a given DAP name on a given path | Below is the the instruction that describes the task:
### Input:
Get Assistants and Snippets for a given DAP name on a given path
### Response:
def _get_assistants_snippets(path, name):
'''Get Assistants and Snippets for a given DAP name on a given path'''
result = []
subdirs = {'assistants': 2, 'snipp... |
def write(self, text):
"""Write text in the terminal without breaking the spinner."""
# similar to tqdm.write()
# https://pypi.python.org/pypi/tqdm#writing-messages
sys.stdout.write("\r")
self._clear_line()
_text = to_unicode(text)
if PY2:
_text = _te... | Write text in the terminal without breaking the spinner. | Below is the the instruction that describes the task:
### Input:
Write text in the terminal without breaking the spinner.
### Response:
def write(self, text):
"""Write text in the terminal without breaking the spinner."""
# similar to tqdm.write()
# https://pypi.python.org/pypi/tqdm#writing... |
def format_sql(self):
"""
Builds the sql in a format that is easy for humans to read and debug
:return: The formatted sql for this query
:rtype: str
"""
# TODO: finish adding the other parts of the sql generation
sql = ''
# build SELECT
select_se... | Builds the sql in a format that is easy for humans to read and debug
:return: The formatted sql for this query
:rtype: str | Below is the the instruction that describes the task:
### Input:
Builds the sql in a format that is easy for humans to read and debug
:return: The formatted sql for this query
:rtype: str
### Response:
def format_sql(self):
"""
Builds the sql in a format that is easy for humans to ... |
def buy_market_order(self, amount):
"""Place a buy order at market price.
:param amount: Amount of major currency to buy at market price.
:type amount: int | float | str | unicode | decimal.Decimal
:return: Order details.
:rtype: dict
"""
amount = str(amount)
... | Place a buy order at market price.
:param amount: Amount of major currency to buy at market price.
:type amount: int | float | str | unicode | decimal.Decimal
:return: Order details.
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Place a buy order at market price.
:param amount: Amount of major currency to buy at market price.
:type amount: int | float | str | unicode | decimal.Decimal
:return: Order details.
:rtype: dict
### Response:
def buy... |
def _initActions(self):
"""Init shortcuts for text editing
"""
def createAction(text, shortcut, slot, iconFileName=None):
"""Create QAction with given parameters and add to the widget
"""
action = QAction(text, self)
if iconFileName is not None:
... | Init shortcuts for text editing | Below is the the instruction that describes the task:
### Input:
Init shortcuts for text editing
### Response:
def _initActions(self):
"""Init shortcuts for text editing
"""
def createAction(text, shortcut, slot, iconFileName=None):
"""Create QAction with given parameters and a... |
def is_all_field_none(self):
"""
:rtype: bool
"""
if self._billing_date is not None:
return False
if self._type_description is not None:
return False
if self._type_description_translated is not None:
return False
if self._un... | :rtype: bool | Below is the the instruction that describes the task:
### Input:
:rtype: bool
### Response:
def is_all_field_none(self):
"""
:rtype: bool
"""
if self._billing_date is not None:
return False
if self._type_description is not None:
return False
... |
def to_dict(self):
"""
Converts the column to a dictionary representation accepted
by the Citrination server.
:return: Dictionary with basic options, plus any column type specific
options held under the "options" key
:rtype: dict
"""
return {
... | Converts the column to a dictionary representation accepted
by the Citrination server.
:return: Dictionary with basic options, plus any column type specific
options held under the "options" key
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Converts the column to a dictionary representation accepted
by the Citrination server.
:return: Dictionary with basic options, plus any column type specific
options held under the "options" key
:rtype: dict
### Res... |
def _cooked_fields(self, dj_fields):
"""
Returns a tuple of cooked fields
:param dj_fields: a list of django name fields
:return:
"""
from django.db import models
valids = []
for field in dj_fields:
try:
dj_field, _, _, _ = sel... | Returns a tuple of cooked fields
:param dj_fields: a list of django name fields
:return: | Below is the the instruction that describes the task:
### Input:
Returns a tuple of cooked fields
:param dj_fields: a list of django name fields
:return:
### Response:
def _cooked_fields(self, dj_fields):
"""
Returns a tuple of cooked fields
:param dj_fields: a list of djang... |
def unregister(self):
"""unregister model at tracking server"""
uuid = self.metadata["tracker"]["uuid"]
# connect to server
result = requests.delete(urljoin(self.tracker, 'models' + "/" + uuid))
logger.debug("unregistered at server %s with %s: %s", self.tracker, uuid, result) | unregister model at tracking server | Below is the the instruction that describes the task:
### Input:
unregister model at tracking server
### Response:
def unregister(self):
"""unregister model at tracking server"""
uuid = self.metadata["tracker"]["uuid"]
# connect to server
result = requests.delete(urljoin(self.tracke... |
def _ixs(self, i, axis=0):
"""
Return the i-th value or values in the SparseSeries by location
Parameters
----------
i : int, slice, or sequence of integers
Returns
-------
value : scalar (int) or Series (slice, sequence)
"""
label = self... | Return the i-th value or values in the SparseSeries by location
Parameters
----------
i : int, slice, or sequence of integers
Returns
-------
value : scalar (int) or Series (slice, sequence) | Below is the the instruction that describes the task:
### Input:
Return the i-th value or values in the SparseSeries by location
Parameters
----------
i : int, slice, or sequence of integers
Returns
-------
value : scalar (int) or Series (slice, sequence)
### Respon... |
def create_from_assocs(self, assocs, **args):
"""
Creates from a list of association objects
"""
amap = defaultdict(list)
subject_label_map = {}
for a in assocs:
subj = a['subject']
subj_id = subj['id']
subj_label = subj['label']
... | Creates from a list of association objects | Below is the the instruction that describes the task:
### Input:
Creates from a list of association objects
### Response:
def create_from_assocs(self, assocs, **args):
"""
Creates from a list of association objects
"""
amap = defaultdict(list)
subject_label_map = {}
... |
def configure_file_logger(name, log_dir, log_level=logging.DEBUG):
"""Configures logging to use the :class:`SizeRotatingFileHandler`"""
from .srothandler import SizeRotatingFileHandler
root = logging.getLogger()
root.setLevel(log_level)
handler = SizeRotatingFileHandler(os.path.join(log_dir, '%s.lo... | Configures logging to use the :class:`SizeRotatingFileHandler` | Below is the the instruction that describes the task:
### Input:
Configures logging to use the :class:`SizeRotatingFileHandler`
### Response:
def configure_file_logger(name, log_dir, log_level=logging.DEBUG):
"""Configures logging to use the :class:`SizeRotatingFileHandler`"""
from .srothandler import Size... |
def insert_one(self, doc, *args, **kwargs):
"""
Inserts one document into the collection
If contains '_id' key it is used, else it is generated.
:param doc: the document
:return: InsertOneResult
"""
if self.table is None:
self.build_table()
if... | Inserts one document into the collection
If contains '_id' key it is used, else it is generated.
:param doc: the document
:return: InsertOneResult | Below is the the instruction that describes the task:
### Input:
Inserts one document into the collection
If contains '_id' key it is used, else it is generated.
:param doc: the document
:return: InsertOneResult
### Response:
def insert_one(self, doc, *args, **kwargs):
"""
I... |
def get_composition_admin_session(self):
"""Gets a composition administration session for creating, updating and deleting compositions.
return: (osid.repository.CompositionAdminSession) - a
``CompositionAdminSession``
raise: OperationFailed - unable to complete request
... | Gets a composition administration session for creating, updating and deleting compositions.
return: (osid.repository.CompositionAdminSession) - a
``CompositionAdminSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_composition_admin... | Below is the the instruction that describes the task:
### Input:
Gets a composition administration session for creating, updating and deleting compositions.
return: (osid.repository.CompositionAdminSession) - a
``CompositionAdminSession``
raise: OperationFailed - unable to complete... |
def get_encodings_from_content(content):
"""
Code from:
https://github.com/sigmavirus24/requests-toolbelt/blob/master/requests_toolbelt/utils/deprecated.py
Return encodings from given content string.
:param content: string to extract encodings from.
"""
if isinstance(content, bytes):
... | Code from:
https://github.com/sigmavirus24/requests-toolbelt/blob/master/requests_toolbelt/utils/deprecated.py
Return encodings from given content string.
:param content: string to extract encodings from. | Below is the the instruction that describes the task:
### Input:
Code from:
https://github.com/sigmavirus24/requests-toolbelt/blob/master/requests_toolbelt/utils/deprecated.py
Return encodings from given content string.
:param content: string to extract encodings from.
### Response:
def get_encodings_f... |
def recCopyElement(oldelement):
"""Generates a copy of an xml element and recursively of all
child elements.
:param oldelement: an instance of lxml.etree._Element
:returns: a copy of the "oldelement"
.. warning::
doesn't copy ``.text`` or ``.tail`` of xml elements
"""
newelement =... | Generates a copy of an xml element and recursively of all
child elements.
:param oldelement: an instance of lxml.etree._Element
:returns: a copy of the "oldelement"
.. warning::
doesn't copy ``.text`` or ``.tail`` of xml elements | Below is the the instruction that describes the task:
### Input:
Generates a copy of an xml element and recursively of all
child elements.
:param oldelement: an instance of lxml.etree._Element
:returns: a copy of the "oldelement"
.. warning::
doesn't copy ``.text`` or ``.tail`` of xml ele... |
def set_mode(self, mode):
"""Set Lupusec alarm mode."""
_LOGGER.debug('State change called from alarm device')
if not mode:
_LOGGER.info('No mode supplied')
elif mode not in CONST.ALL_MODES:
_LOGGER.warning('Invalid mode')
response_object = self._lupusec.s... | Set Lupusec alarm mode. | Below is the the instruction that describes the task:
### Input:
Set Lupusec alarm mode.
### Response:
def set_mode(self, mode):
"""Set Lupusec alarm mode."""
_LOGGER.debug('State change called from alarm device')
if not mode:
_LOGGER.info('No mode supplied')
elif mode n... |
def unknown_command(self, args):
'''handle mode switch by mode name as command'''
mode_mapping = self.master.mode_mapping()
mode = args[0].upper()
if mode in mode_mapping:
self.master.set_mode(mode_mapping[mode])
return True
return False | handle mode switch by mode name as command | Below is the the instruction that describes the task:
### Input:
handle mode switch by mode name as command
### Response:
def unknown_command(self, args):
'''handle mode switch by mode name as command'''
mode_mapping = self.master.mode_mapping()
mode = args[0].upper()
if mode in mod... |
def parameterstep(timestep=None):
"""Define a parameter time step size within a parameter control file.
Argument:
* timestep(|Period|): Time step size.
Function parameterstep should usually be be applied in a line
immediately behind the model import. Defining the step size of time
dependent... | Define a parameter time step size within a parameter control file.
Argument:
* timestep(|Period|): Time step size.
Function parameterstep should usually be be applied in a line
immediately behind the model import. Defining the step size of time
dependent parameters is a prerequisite to access a... | Below is the the instruction that describes the task:
### Input:
Define a parameter time step size within a parameter control file.
Argument:
* timestep(|Period|): Time step size.
Function parameterstep should usually be be applied in a line
immediately behind the model import. Defining the ste... |
def last_page(self_or_cls, max_=None):
"""
Return a query set which requests the last page.
:param max_: Maximum number of items to return.
:type max_: :class:`int` or :data:`None`
:rtype: :class:`ResultSetMetadata`
:return: A new request set up to request the last page.... | Return a query set which requests the last page.
:param max_: Maximum number of items to return.
:type max_: :class:`int` or :data:`None`
:rtype: :class:`ResultSetMetadata`
:return: A new request set up to request the last page. | Below is the the instruction that describes the task:
### Input:
Return a query set which requests the last page.
:param max_: Maximum number of items to return.
:type max_: :class:`int` or :data:`None`
:rtype: :class:`ResultSetMetadata`
:return: A new request set up to request the ... |
def read_raw_table(self, table):
"""
Yield rows in the [incr tsdb()] *table*. A row is a dictionary
mapping column names to values. Data from a profile is decoded
by decode_row(). No filters or applicators are used.
"""
fields = self.table_relations(table) if self.cast el... | Yield rows in the [incr tsdb()] *table*. A row is a dictionary
mapping column names to values. Data from a profile is decoded
by decode_row(). No filters or applicators are used. | Below is the the instruction that describes the task:
### Input:
Yield rows in the [incr tsdb()] *table*. A row is a dictionary
mapping column names to values. Data from a profile is decoded
by decode_row(). No filters or applicators are used.
### Response:
def read_raw_table(self, table):
... |
def _click(x, y, button):
"""Send the mouse click event to Windows by calling the mouse_event() win32
function.
Args:
button (str): The mouse button, either 'left', 'middle', or 'right'
x (int): The x position of the mouse event.
y (int): The y position of the mouse event.
Returns:
... | Send the mouse click event to Windows by calling the mouse_event() win32
function.
Args:
button (str): The mouse button, either 'left', 'middle', or 'right'
x (int): The x position of the mouse event.
y (int): The y position of the mouse event.
Returns:
None | Below is the the instruction that describes the task:
### Input:
Send the mouse click event to Windows by calling the mouse_event() win32
function.
Args:
button (str): The mouse button, either 'left', 'middle', or 'right'
x (int): The x position of the mouse event.
y (int): The y position... |
def cmd_velocity(self, args):
'''velocity x-ms y-ms z-ms'''
if (len(args) != 3):
print("Usage: velocity x y z (m/s)")
return
if (len(args) == 3):
x_mps = float(args[0])
y_mps = float(args[1])
z_mps = float(args[2])
#print("... | velocity x-ms y-ms z-ms | Below is the the instruction that describes the task:
### Input:
velocity x-ms y-ms z-ms
### Response:
def cmd_velocity(self, args):
'''velocity x-ms y-ms z-ms'''
if (len(args) != 3):
print("Usage: velocity x y z (m/s)")
return
if (len(args) == 3):
x_mps... |
def split_bits(value, *bits):
"""
Split integer value into list of ints, according to `bits` list.
For example, split_bits(0x1234, 4, 8, 4) == [0x1, 0x23, 0x4]
"""
result = []
for b in reversed(bits):
mask = (1 << b) - 1
result.append(value & mask)
value = value >> b
... | Split integer value into list of ints, according to `bits` list.
For example, split_bits(0x1234, 4, 8, 4) == [0x1, 0x23, 0x4] | Below is the the instruction that describes the task:
### Input:
Split integer value into list of ints, according to `bits` list.
For example, split_bits(0x1234, 4, 8, 4) == [0x1, 0x23, 0x4]
### Response:
def split_bits(value, *bits):
"""
Split integer value into list of ints, according to `bits` list... |
def update_project(self, org_name, part_name, dci_id=UNKNOWN_DCI_ID,
service_node_ip=UNKNOWN_SRVN_NODE_IP,
vrf_prof=None, desc=None):
"""Update project on the DCNM.
:param org_name: name of organization.
:param part_name: name of partition.
... | Update project on the DCNM.
:param org_name: name of organization.
:param part_name: name of partition.
:param dci_id: Data Center interconnect id.
:param desc: description of project. | Below is the the instruction that describes the task:
### Input:
Update project on the DCNM.
:param org_name: name of organization.
:param part_name: name of partition.
:param dci_id: Data Center interconnect id.
:param desc: description of project.
### Response:
def update_project... |
def map(cls, iterable, func, *a, **kw):
"""
Iterable-first replacement of Python's built-in `map()` function.
"""
return cls(func(x, *a, **kw) for x in iterable) | Iterable-first replacement of Python's built-in `map()` function. | Below is the the instruction that describes the task:
### Input:
Iterable-first replacement of Python's built-in `map()` function.
### Response:
def map(cls, iterable, func, *a, **kw):
"""
Iterable-first replacement of Python's built-in `map()` function.
"""
return cls(func(x, *a, **kw) for x in i... |
def char2hex(a: str):
"""Convert a hex character to its integer value.
'0' becomes 0, '9' becomes 9
'A' becomes 10, 'F' becomes 15
'a' becomes 10, 'f' becomes 15
Returns -1 on error.
"""
if "0" <= a <= "9":
return ord(a) - 48
elif "A" <= a <= "F":
return ord(a) - 55
... | Convert a hex character to its integer value.
'0' becomes 0, '9' becomes 9
'A' becomes 10, 'F' becomes 15
'a' becomes 10, 'f' becomes 15
Returns -1 on error. | Below is the the instruction that describes the task:
### Input:
Convert a hex character to its integer value.
'0' becomes 0, '9' becomes 9
'A' becomes 10, 'F' becomes 15
'a' becomes 10, 'f' becomes 15
Returns -1 on error.
### Response:
def char2hex(a: str):
"""Convert a hex character to its ... |
def validate(table, constraints=None, header=None):
"""
Validate a `table` against a set of `constraints` and/or an expected
`header`, e.g.::
>>> import petl as etl
>>> # define some validation constraints
... header = ('foo', 'bar', 'baz')
>>> constraints = [
... ... | Validate a `table` against a set of `constraints` and/or an expected
`header`, e.g.::
>>> import petl as etl
>>> # define some validation constraints
... header = ('foo', 'bar', 'baz')
>>> constraints = [
... dict(name='foo_int', field='foo', test=int),
... d... | Below is the the instruction that describes the task:
### Input:
Validate a `table` against a set of `constraints` and/or an expected
`header`, e.g.::
>>> import petl as etl
>>> # define some validation constraints
... header = ('foo', 'bar', 'baz')
>>> constraints = [
.... |
def make_params(
key_parts: Sequence[str],
variable_parts: VariablePartsType) -> Dict[str, Union[str, Tuple[str]]]:
"""
Map keys to variables. This map\
URL-pattern variables to\
a URL related parts
:param key_parts: A list of URL parts
:param variable_parts: A linked-list\
... | Map keys to variables. This map\
URL-pattern variables to\
a URL related parts
:param key_parts: A list of URL parts
:param variable_parts: A linked-list\
(ala nested tuples) of URL parts
:return: The param dict with the values\
assigned to the keys
:private: | Below is the the instruction that describes the task:
### Input:
Map keys to variables. This map\
URL-pattern variables to\
a URL related parts
:param key_parts: A list of URL parts
:param variable_parts: A linked-list\
(ala nested tuples) of URL parts
:return: The param dict with the value... |
def decode_tuple(data, encoding=None, errors='strict', keep=False,
normalize=False, preserve_dict_class=False, to_str=False):
'''
Decode all string values to Unicode. Optionally use to_str=True to ensure
strings are str types and not unicode on Python 2.
'''
return tuple(
de... | Decode all string values to Unicode. Optionally use to_str=True to ensure
strings are str types and not unicode on Python 2. | Below is the the instruction that describes the task:
### Input:
Decode all string values to Unicode. Optionally use to_str=True to ensure
strings are str types and not unicode on Python 2.
### Response:
def decode_tuple(data, encoding=None, errors='strict', keep=False,
normalize=False, preser... |
def fixed_width_binning(data=None, bin_width: Union[float, int] = 1, *, range=None, includes_right_edge=False, **kwargs) -> FixedWidthBinning:
"""Construct fixed-width binning schema.
Parameters
----------
bin_width: float
range: Optional[tuple]
(min, max)
align: Optional[float]
... | Construct fixed-width binning schema.
Parameters
----------
bin_width: float
range: Optional[tuple]
(min, max)
align: Optional[float]
Must be multiple of bin_width | Below is the the instruction that describes the task:
### Input:
Construct fixed-width binning schema.
Parameters
----------
bin_width: float
range: Optional[tuple]
(min, max)
align: Optional[float]
Must be multiple of bin_width
### Response:
def fixed_width_binning(data=None, ... |
def fmt_text(text):
""" convert characters that aren't printable to hex format
"""
PRINTABLE_CHAR = set(
list(range(ord(' '), ord('~') + 1)) + [ord('\r'), ord('\n')])
newtext = ("\\x{:02X}".format(
c) if c not in PRINTABLE_CHAR else chr(c) for c in text)
textlines = "\r\n".join(l.str... | convert characters that aren't printable to hex format | Below is the the instruction that describes the task:
### Input:
convert characters that aren't printable to hex format
### Response:
def fmt_text(text):
""" convert characters that aren't printable to hex format
"""
PRINTABLE_CHAR = set(
list(range(ord(' '), ord('~') + 1)) + [ord('\r'), ord('\... |
def ack(self):
"""Acknowledge this message as being processed.,
This will remove the message from the queue.
:raises MessageStateError: If the message has already been
acknowledged/requeued/rejected.
"""
if self.acknowledged:
raise self.MessageStateError... | Acknowledge this message as being processed.,
This will remove the message from the queue.
:raises MessageStateError: If the message has already been
acknowledged/requeued/rejected. | Below is the the instruction that describes the task:
### Input:
Acknowledge this message as being processed.,
This will remove the message from the queue.
:raises MessageStateError: If the message has already been
acknowledged/requeued/rejected.
### Response:
def ack(self):
""... |
def restore(path, password_file=None):
"""
Retrieves a file from the atk vault and restores it to its original
location, re-encrypting it if it has changed.
:param path: path to original file
"""
vault = VaultLib(get_vault_password(password_file))
atk_path = os.path.join(ATK_VAULT, path)
... | Retrieves a file from the atk vault and restores it to its original
location, re-encrypting it if it has changed.
:param path: path to original file | Below is the the instruction that describes the task:
### Input:
Retrieves a file from the atk vault and restores it to its original
location, re-encrypting it if it has changed.
:param path: path to original file
### Response:
def restore(path, password_file=None):
"""
Retrieves a file from the a... |
def listRunSummaries(self, dataset="", run_num=-1):
"""
API to list run summaries, like the maximal lumisection in a run.
:param dataset: dataset name (Optional)
:type dataset: str
:param run_num: Run number (Required)
:type run_num: str, long, int
:rtype: list c... | API to list run summaries, like the maximal lumisection in a run.
:param dataset: dataset name (Optional)
:type dataset: str
:param run_num: Run number (Required)
:type run_num: str, long, int
:rtype: list containing a dictionary with key max_lumi | Below is the the instruction that describes the task:
### Input:
API to list run summaries, like the maximal lumisection in a run.
:param dataset: dataset name (Optional)
:type dataset: str
:param run_num: Run number (Required)
:type run_num: str, long, int
:rtype: list cont... |
def label_from_func(self, func:Callable, label_cls:Callable=None, **kwargs)->'LabelList':
"Apply `func` to every input to get its label."
return self._label_from_list([func(o) for o in self.items], label_cls=label_cls, **kwargs) | Apply `func` to every input to get its label. | Below is the the instruction that describes the task:
### Input:
Apply `func` to every input to get its label.
### Response:
def label_from_func(self, func:Callable, label_cls:Callable=None, **kwargs)->'LabelList':
"Apply `func` to every input to get its label."
return self._label_from_list([func(o... |
def hid(manufacturer: str, serial_number: str, model: str) -> str:
"""Computes the HID for the given properties of a device. The HID is suitable to use to an URI."""
return Naming.url_word(manufacturer) + '-' + Naming.url_word(serial_number) + '-' + Naming.url_word(model) | Computes the HID for the given properties of a device. The HID is suitable to use to an URI. | Below is the the instruction that describes the task:
### Input:
Computes the HID for the given properties of a device. The HID is suitable to use to an URI.
### Response:
def hid(manufacturer: str, serial_number: str, model: str) -> str:
"""Computes the HID for the given properties of a device. The HID is... |
def decode(self, encoded):
""" Decodes an object.
Args:
object_ (object): Encoded object.
Returns:
object: Object decoded.
"""
if self.enforce_reversible:
self.enforce_reversible = False
if self.encode(self.decode(encoded)) != enc... | Decodes an object.
Args:
object_ (object): Encoded object.
Returns:
object: Object decoded. | Below is the the instruction that describes the task:
### Input:
Decodes an object.
Args:
object_ (object): Encoded object.
Returns:
object: Object decoded.
### Response:
def decode(self, encoded):
""" Decodes an object.
Args:
object_ (object):... |
def on_key_release(self, symbol, modifiers):
"""
Pyglet specific key release callback.
Forwards and translates the events to :py:func:`keyboard_event`
"""
self.keyboard_event(symbol, self.keys.ACTION_RELEASE, modifiers) | Pyglet specific key release callback.
Forwards and translates the events to :py:func:`keyboard_event` | Below is the the instruction that describes the task:
### Input:
Pyglet specific key release callback.
Forwards and translates the events to :py:func:`keyboard_event`
### Response:
def on_key_release(self, symbol, modifiers):
"""
Pyglet specific key release callback.
Forwards an... |
def error_response(self, kwargs_lens, kwargs_ps):
"""
returns the 1d array of the error estimate corresponding to the data response
:return: 1d numpy array of response, 2d array of additonal errors (e.g. point source uncertainties)
"""
C_D_response, model_error = [], []
... | returns the 1d array of the error estimate corresponding to the data response
:return: 1d numpy array of response, 2d array of additonal errors (e.g. point source uncertainties) | Below is the the instruction that describes the task:
### Input:
returns the 1d array of the error estimate corresponding to the data response
:return: 1d numpy array of response, 2d array of additonal errors (e.g. point source uncertainties)
### Response:
def error_response(self, kwargs_lens, kwargs_ps):... |
def read_reply(self) -> Reply:
'''Read a reply from the stream.
Returns:
.ftp.request.Reply: The reply
Coroutine.
'''
_logger.debug('Read reply')
reply = Reply()
while True:
line = yield from self._connection.readline()
if l... | Read a reply from the stream.
Returns:
.ftp.request.Reply: The reply
Coroutine. | Below is the the instruction that describes the task:
### Input:
Read a reply from the stream.
Returns:
.ftp.request.Reply: The reply
Coroutine.
### Response:
def read_reply(self) -> Reply:
'''Read a reply from the stream.
Returns:
.ftp.request.Reply: The ... |
def download_reference_files(job, inputs, samples):
"""
Downloads shared files that are used by all samples for alignment, or generates them if they were not provided.
:param JobFunctionWrappingJob job: passed automatically by Toil
:param Namespace inputs: Input arguments (see main)
:param list[lis... | Downloads shared files that are used by all samples for alignment, or generates them if they were not provided.
:param JobFunctionWrappingJob job: passed automatically by Toil
:param Namespace inputs: Input arguments (see main)
:param list[list[str, list[str, str]]] samples: Samples in the format [UUID, [U... | Below is the the instruction that describes the task:
### Input:
Downloads shared files that are used by all samples for alignment, or generates them if they were not provided.
:param JobFunctionWrappingJob job: passed automatically by Toil
:param Namespace inputs: Input arguments (see main)
:param lis... |
async def request(self, method, url, **kwargs):
"""Handles requests to the API"""
rate_limiter = RateLimiter(max_calls=59, period=60, callback=limited)
# handles ratelimits. max_calls is set to 59 because current implementation will retry in 60s after 60 calls is reached. DBL has a 1h block so o... | Handles requests to the API | Below is the the instruction that describes the task:
### Input:
Handles requests to the API
### Response:
async def request(self, method, url, **kwargs):
"""Handles requests to the API"""
rate_limiter = RateLimiter(max_calls=59, period=60, callback=limited)
# handles ratelimits. max_calls ... |
def rebin(a, factor, func=None):
u"""Aggregate data from the input array ``a`` into rectangular tiles.
The output array results from tiling ``a`` and applying `func` to
each tile. ``factor`` specifies the size of the tiles. More
precisely, the returned array ``out`` is such that::
out[i0, i1, ... | u"""Aggregate data from the input array ``a`` into rectangular tiles.
The output array results from tiling ``a`` and applying `func` to
each tile. ``factor`` specifies the size of the tiles. More
precisely, the returned array ``out`` is such that::
out[i0, i1, ...] = func(a[f0*i0:f0*(i0+1), f1*i1:... | Below is the the instruction that describes the task:
### Input:
u"""Aggregate data from the input array ``a`` into rectangular tiles.
The output array results from tiling ``a`` and applying `func` to
each tile. ``factor`` specifies the size of the tiles. More
precisely, the returned array ``out`` is s... |
def _log_begin(self):
""" Log the beginning of the task execution """
self.logger.info("Beginning task: %s", self.__class__.__name__)
if self.salesforce_task and not self.flow:
self.logger.info("%15s %s", "As user:", self.org_config.username)
self.logger.info("%15s %s", "... | Log the beginning of the task execution | Below is the the instruction that describes the task:
### Input:
Log the beginning of the task execution
### Response:
def _log_begin(self):
""" Log the beginning of the task execution """
self.logger.info("Beginning task: %s", self.__class__.__name__)
if self.salesforce_task and not self.f... |
def resize(img, size, interpolation=Image.BILINEAR):
r"""Resize the input PIL Image to the given size.
Args:
img (PIL Image): Image to be resized.
size (sequence or int): Desired output size. If size is a sequence like
(h, w), the output size will be matched to this. If size is an i... | r"""Resize the input PIL Image to the given size.
Args:
img (PIL Image): Image to be resized.
size (sequence or int): Desired output size. If size is a sequence like
(h, w), the output size will be matched to this. If size is an int,
the smaller edge of the image will be mat... | Below is the the instruction that describes the task:
### Input:
r"""Resize the input PIL Image to the given size.
Args:
img (PIL Image): Image to be resized.
size (sequence or int): Desired output size. If size is a sequence like
(h, w), the output size will be matched to this. If ... |
def get_proficiencies(self):
"""Gets the proficiency list resulting from a search.
return: (osid.learning.ProficiencyList) - the proficiency list
raise: IllegalState - list already retrieved
*compliance: mandatory -- This method must be implemented.*
"""
if self.retrie... | Gets the proficiency list resulting from a search.
return: (osid.learning.ProficiencyList) - the proficiency list
raise: IllegalState - list already retrieved
*compliance: mandatory -- This method must be implemented.* | Below is the the instruction that describes the task:
### Input:
Gets the proficiency list resulting from a search.
return: (osid.learning.ProficiencyList) - the proficiency list
raise: IllegalState - list already retrieved
*compliance: mandatory -- This method must be implemented.*
### Re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.