code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def add_item(self, key, value, cache_name=None):
"""Add an item into the given cache.
This is a commodity option (mainly useful for testing) allowing you
to store an item in a uWSGI cache during startup.
:param str|unicode key:
:param value:
:param str|unicode cache_n... | Add an item into the given cache.
This is a commodity option (mainly useful for testing) allowing you
to store an item in a uWSGI cache during startup.
:param str|unicode key:
:param value:
:param str|unicode cache_name: If not set, default will be used. | Below is the the instruction that describes the task:
### Input:
Add an item into the given cache.
This is a commodity option (mainly useful for testing) allowing you
to store an item in a uWSGI cache during startup.
:param str|unicode key:
:param value:
:param str|unicod... |
def add_string_as_file(self, content, filename, pred=None):
"""Add a string to the archive as a file named `filename`"""
# Generate summary string for logging
summary = content.splitlines()[0] if content else ''
if not isinstance(summary, six.string_types):
summary = content... | Add a string to the archive as a file named `filename` | Below is the the instruction that describes the task:
### Input:
Add a string to the archive as a file named `filename`
### Response:
def add_string_as_file(self, content, filename, pred=None):
"""Add a string to the archive as a file named `filename`"""
# Generate summary string for logging
... |
def com_google_fonts_check_name_line_breaks(ttFont):
"""Name table entries should not contain line-breaks."""
failed = False
for name in ttFont["name"].names:
string = name.string.decode(name.getEncoding())
if "\n" in string:
failed = True
yield FAIL, ("Name entry {} on platform {} contains"
... | Name table entries should not contain line-breaks. | Below is the the instruction that describes the task:
### Input:
Name table entries should not contain line-breaks.
### Response:
def com_google_fonts_check_name_line_breaks(ttFont):
"""Name table entries should not contain line-breaks."""
failed = False
for name in ttFont["name"].names:
string = name.st... |
def main_help_text(self, commands_only=False):
"""
Returns the script's main help text, as a string.
"""
if commands_only:
usage = sorted(get_commands().keys())
else:
usage = [
"",
"Type '%s help <subcommand>' for help on a ... | Returns the script's main help text, as a string. | Below is the the instruction that describes the task:
### Input:
Returns the script's main help text, as a string.
### Response:
def main_help_text(self, commands_only=False):
"""
Returns the script's main help text, as a string.
"""
if commands_only:
usage = sorted(get_... |
def is_scalar(self, typ: Type = _Any) -> bool:
"""Returns True iff this represents a scalar node.
If a type is given, checks that the ScalarNode represents this \
type. Type may be `str`, `int`, `float`, `bool`, or `None`.
If no type is given, any ScalarNode will return True.
"... | Returns True iff this represents a scalar node.
If a type is given, checks that the ScalarNode represents this \
type. Type may be `str`, `int`, `float`, `bool`, or `None`.
If no type is given, any ScalarNode will return True. | Below is the the instruction that describes the task:
### Input:
Returns True iff this represents a scalar node.
If a type is given, checks that the ScalarNode represents this \
type. Type may be `str`, `int`, `float`, `bool`, or `None`.
If no type is given, any ScalarNode will return True... |
def dumps(obj, startindex=1, separator=DEFAULT, index_separator=DEFAULT):
'''Dump an object in req format to a string.
:param Mapping obj: The object to serialize. Must have a keys method.
:param separator: The separator between key and value. Defaults to u'|' or b'|', depending on the types.
:param ... | Dump an object in req format to a string.
:param Mapping obj: The object to serialize. Must have a keys method.
:param separator: The separator between key and value. Defaults to u'|' or b'|', depending on the types.
:param index_separator: The separator between key and index. Defaults to u'_' or b'_', ... | Below is the the instruction that describes the task:
### Input:
Dump an object in req format to a string.
:param Mapping obj: The object to serialize. Must have a keys method.
:param separator: The separator between key and value. Defaults to u'|' or b'|', depending on the types.
:param index_separa... |
def _create_prefix_notification(outgoing_msg, rpc_session):
"""Constructs prefix notification with data from given outgoing message.
Given RPC session is used to create RPC notification message.
"""
assert outgoing_msg
path = outgoing_msg.path
assert path
vpn_nlri = path.nlri
assert pa... | Constructs prefix notification with data from given outgoing message.
Given RPC session is used to create RPC notification message. | Below is the the instruction that describes the task:
### Input:
Constructs prefix notification with data from given outgoing message.
Given RPC session is used to create RPC notification message.
### Response:
def _create_prefix_notification(outgoing_msg, rpc_session):
"""Constructs prefix notification w... |
def extract_packing_plan(self, topology):
"""
Returns the representation of packing plan that will
be returned from Tracker.
"""
packingPlan = {
"id": "",
"container_plans": []
}
if not topology.packing_plan:
return packingPlan
container_plans = topology.packing_p... | Returns the representation of packing plan that will
be returned from Tracker. | Below is the the instruction that describes the task:
### Input:
Returns the representation of packing plan that will
be returned from Tracker.
### Response:
def extract_packing_plan(self, topology):
"""
Returns the representation of packing plan that will
be returned from Tracker.
"""
pack... |
def upsert_users(cursor, user_ids):
"""Given a set of user identifiers (``user_ids``),
upsert them into the database after checking accounts for
the latest information.
"""
accounts = get_current_registry().getUtility(IOpenstaxAccounts)
def lookup_profile(username):
profile = accounts.g... | Given a set of user identifiers (``user_ids``),
upsert them into the database after checking accounts for
the latest information. | Below is the the instruction that describes the task:
### Input:
Given a set of user identifiers (``user_ids``),
upsert them into the database after checking accounts for
the latest information.
### Response:
def upsert_users(cursor, user_ids):
"""Given a set of user identifiers (``user_ids``),
ups... |
def check_size_all(self):
"""
Get size of homedir and update data on the server
"""
result = self.rpc_srv.get_all_account(self.token)
print "debug: %s" % result
for it in result:
size = getFolderSize(it["path"])
result = self.rpc_srv.set_account_si... | Get size of homedir and update data on the server | Below is the the instruction that describes the task:
### Input:
Get size of homedir and update data on the server
### Response:
def check_size_all(self):
"""
Get size of homedir and update data on the server
"""
result = self.rpc_srv.get_all_account(self.token)
print "debug... |
def text(self):
"""Parses problems.txt and returns problem text"""
def _problem_iter(problem_num):
problem_file = os.path.join(EULER_DATA, 'problems.txt')
with open(problem_file) as f:
is_problem = False
last_line = ''
for line in... | Parses problems.txt and returns problem text | Below is the the instruction that describes the task:
### Input:
Parses problems.txt and returns problem text
### Response:
def text(self):
"""Parses problems.txt and returns problem text"""
def _problem_iter(problem_num):
problem_file = os.path.join(EULER_DATA, 'problems.txt')
... |
def secure_items(self, section):
"""Like items() but only return secure items.
:param section: section id
:type section: string
"""
return [x
for x in self.items(section)
if self.is_secure_option(section, x[0])] | Like items() but only return secure items.
:param section: section id
:type section: string | Below is the the instruction that describes the task:
### Input:
Like items() but only return secure items.
:param section: section id
:type section: string
### Response:
def secure_items(self, section):
"""Like items() but only return secure items.
:param section: section id
... |
def count(index,h):
'''
Gives count of the documents stored in Elasticsearch. If index option is
provided, it will provide document count of that index.
'''
try:
response = base.es.cat.count(index,h=h)
table = base.draw_table(response)
except Exception as e:
click.echo(e)... | Gives count of the documents stored in Elasticsearch. If index option is
provided, it will provide document count of that index. | Below is the the instruction that describes the task:
### Input:
Gives count of the documents stored in Elasticsearch. If index option is
provided, it will provide document count of that index.
### Response:
def count(index,h):
'''
Gives count of the documents stored in Elasticsearch. If index option i... |
def reset_sequence(app_label):
"""
Reset the primary key sequence for the tables in an application.
This is necessary if any local edits have happened to the table.
"""
puts("Resetting primary key sequence for {0}".format(app_label))
cursor = connection.cursor()
cmd = get_reset_command(app... | Reset the primary key sequence for the tables in an application.
This is necessary if any local edits have happened to the table. | Below is the the instruction that describes the task:
### Input:
Reset the primary key sequence for the tables in an application.
This is necessary if any local edits have happened to the table.
### Response:
def reset_sequence(app_label):
"""
Reset the primary key sequence for the tables in an applica... |
def strip_pdb(pdb_path, chains = [], strip_hetatms = False):
'''Takes a PDB file and strips all lines except ATOM and HETATM records. If chains is specified, only those chains are kept. If strip_hetatms is True then HETATM lines are also stripped.
Returns (True, a path to the stripped PDB file) on success an... | Takes a PDB file and strips all lines except ATOM and HETATM records. If chains is specified, only those chains are kept. If strip_hetatms is True then HETATM lines are also stripped.
Returns (True, a path to the stripped PDB file) on success and (False, a list of errors) on failure. | Below is the the instruction that describes the task:
### Input:
Takes a PDB file and strips all lines except ATOM and HETATM records. If chains is specified, only those chains are kept. If strip_hetatms is True then HETATM lines are also stripped.
Returns (True, a path to the stripped PDB file) on success a... |
def get_acronyms(manuscript=os.path.expanduser('~/code/nlpia/lane/manuscript')):
""" Find all the 2 and 3-letter acronyms in the manuscript and return as a sorted list of tuples """
acronyms = []
for f, lines in get_lines(manuscript):
for line in lines:
matches = CRE_ACRONYM.finditer(lin... | Find all the 2 and 3-letter acronyms in the manuscript and return as a sorted list of tuples | Below is the the instruction that describes the task:
### Input:
Find all the 2 and 3-letter acronyms in the manuscript and return as a sorted list of tuples
### Response:
def get_acronyms(manuscript=os.path.expanduser('~/code/nlpia/lane/manuscript')):
""" Find all the 2 and 3-letter acronyms in the manuscript... |
def eval(self):
""" Returns a filename to be used for script output. """
if self.magic:
return self.magic
if not self.filename:
return file_pattern.format(self.alias, self.ext)
return self.path | Returns a filename to be used for script output. | Below is the the instruction that describes the task:
### Input:
Returns a filename to be used for script output.
### Response:
def eval(self):
""" Returns a filename to be used for script output. """
if self.magic:
return self.magic
if not self.filename:
return file... |
def namedb_get_namespace( cur, namespace_id, current_block, include_expired=False, include_history=True, only_revealed=True):
"""
Get a namespace (revealed or ready) and optionally its history.
Only return an expired namespace if asked.
If current_block is None, any namespace is returned (expired or not... | Get a namespace (revealed or ready) and optionally its history.
Only return an expired namespace if asked.
If current_block is None, any namespace is returned (expired or not)
If current_block is not None and only_revealed is False, then a namespace can be returned before it was revealed.
-- if include_... | Below is the the instruction that describes the task:
### Input:
Get a namespace (revealed or ready) and optionally its history.
Only return an expired namespace if asked.
If current_block is None, any namespace is returned (expired or not)
If current_block is not None and only_revealed is False, then a... |
def getDetail(self, row, detail_field):
"""Gets the value of the detail *detail_field* of paramter
at index *row* from its selected components `auto_details`.
All of the selected components value for *detail_field* must
match
:param row: the ith parameter number
:type ro... | Gets the value of the detail *detail_field* of paramter
at index *row* from its selected components `auto_details`.
All of the selected components value for *detail_field* must
match
:param row: the ith parameter number
:type row: int
:param detail_field: auto_details me... | Below is the the instruction that describes the task:
### Input:
Gets the value of the detail *detail_field* of paramter
at index *row* from its selected components `auto_details`.
All of the selected components value for *detail_field* must
match
:param row: the ith parameter numbe... |
def models_descriptive(self):
""" list all stored models in given file.
Returns
-------
dict: {model_name: {'repr' : 'string representation, 'created': 'human readable date', ...}
"""
f = self._parent
return {name: {a: f[name].attrs[a]
for... | list all stored models in given file.
Returns
-------
dict: {model_name: {'repr' : 'string representation, 'created': 'human readable date', ...} | Below is the the instruction that describes the task:
### Input:
list all stored models in given file.
Returns
-------
dict: {model_name: {'repr' : 'string representation, 'created': 'human readable date', ...}
### Response:
def models_descriptive(self):
""" list all stored models ... |
def validate_specs_from_path(specs_path):
"""
Validates Dusty specs at the given path. The following checks are performed:
-That the given path exists
-That there are bundles in the given path
-That the fields in the specs match those allowed in our schemas
-That references to ap... | Validates Dusty specs at the given path. The following checks are performed:
-That the given path exists
-That there are bundles in the given path
-That the fields in the specs match those allowed in our schemas
-That references to apps, libs, and services point at defined specs
... | Below is the the instruction that describes the task:
### Input:
Validates Dusty specs at the given path. The following checks are performed:
-That the given path exists
-That there are bundles in the given path
-That the fields in the specs match those allowed in our schemas
-That r... |
def transmit(self, channel, msg):
r"""
Transmit the message (or action) and return what was transmitted.
>>> ap = LoggingCommandBot.action_pattern
>>> ap.match('foo').groups()
(None, 'foo')
>>> ap.match('foo\nbar\n').group(2)
'foo\nbar\n'
>>> is_action, msg = ap.match('/me is feeling fine today').grou... | r"""
Transmit the message (or action) and return what was transmitted.
>>> ap = LoggingCommandBot.action_pattern
>>> ap.match('foo').groups()
(None, 'foo')
>>> ap.match('foo\nbar\n').group(2)
'foo\nbar\n'
>>> is_action, msg = ap.match('/me is feeling fine today').groups()
>>> bool(is_action)
True
... | Below is the the instruction that describes the task:
### Input:
r"""
Transmit the message (or action) and return what was transmitted.
>>> ap = LoggingCommandBot.action_pattern
>>> ap.match('foo').groups()
(None, 'foo')
>>> ap.match('foo\nbar\n').group(2)
'foo\nbar\n'
>>> is_action, msg = ap.match('... |
def clone_wire(old_wire, name=None):
"""
Makes a copy of any existing wire
:param old_wire: The wire to clone
:param name: a name fo rhte new wire
Note that this function is mainly intended to be used when the
two wires are from different blocks. Making two wires with the
same name in the ... | Makes a copy of any existing wire
:param old_wire: The wire to clone
:param name: a name fo rhte new wire
Note that this function is mainly intended to be used when the
two wires are from different blocks. Making two wires with the
same name in the same block is not allowed | Below is the the instruction that describes the task:
### Input:
Makes a copy of any existing wire
:param old_wire: The wire to clone
:param name: a name fo rhte new wire
Note that this function is mainly intended to be used when the
two wires are from different blocks. Making two wires with the
... |
def _get_valid_model_table(self, ros):
"""
Returns a list that represents the table with the rowspans.
:param ros: The list that represents the table without the rowspans.
:type ros: list(list(hatemile.util.html.htmldomelement.HTMLDOMElement))
:return The list that represents th... | Returns a list that represents the table with the rowspans.
:param ros: The list that represents the table without the rowspans.
:type ros: list(list(hatemile.util.html.htmldomelement.HTMLDOMElement))
:return The list that represents the table with the rowspans.
:rtype: list(list(hatemi... | Below is the the instruction that describes the task:
### Input:
Returns a list that represents the table with the rowspans.
:param ros: The list that represents the table without the rowspans.
:type ros: list(list(hatemile.util.html.htmldomelement.HTMLDOMElement))
:return The list that rep... |
def DEFINE_enum_class( # pylint: disable=invalid-name,redefined-builtin
name, default, enum_class, help, flag_values=_flagvalues.FLAGS,
module_name=None, **args):
"""Registers a flag whose value can be the name of enum members.
Args:
name: str, the flag name.
default: Enum|str|None, the default va... | Registers a flag whose value can be the name of enum members.
Args:
name: str, the flag name.
default: Enum|str|None, the default value of the flag.
enum_class: class, the Enum class with all the possible values for the flag.
help: str, the help message.
flag_values: FlagValues, the FlagValues in... | Below is the the instruction that describes the task:
### Input:
Registers a flag whose value can be the name of enum members.
Args:
name: str, the flag name.
default: Enum|str|None, the default value of the flag.
enum_class: class, the Enum class with all the possible values for the flag.
help: ... |
def heart_beat(self, project, logstore, consumer_group, consumer, shards=None):
""" Heatbeat consumer group
:type project: string
:param project: project name
:type logstore: string
:param logstore: logstore name
:type consumer_group: string
:param co... | Heatbeat consumer group
:type project: string
:param project: project name
:type logstore: string
:param logstore: logstore name
:type consumer_group: string
:param consumer_group: consumer group name
:type consumer: string
:param consumer:... | Below is the the instruction that describes the task:
### Input:
Heatbeat consumer group
:type project: string
:param project: project name
:type logstore: string
:param logstore: logstore name
:type consumer_group: string
:param consumer_group: consumer g... |
def expects_none(options):
"""
Returns whether the given query options expect a possible count of zero.
Args:
options (Dict[str, int | Iterable[int]]): A dictionary of query options.
Returns:
bool: Whether a possible count of zero is expected.
"""
if any(options.get(key) is no... | Returns whether the given query options expect a possible count of zero.
Args:
options (Dict[str, int | Iterable[int]]): A dictionary of query options.
Returns:
bool: Whether a possible count of zero is expected. | Below is the the instruction that describes the task:
### Input:
Returns whether the given query options expect a possible count of zero.
Args:
options (Dict[str, int | Iterable[int]]): A dictionary of query options.
Returns:
bool: Whether a possible count of zero is expected.
### Response... |
def _is_program_selected(progs):
"""Determine if the program is enabled in the settings."""
mode = False
for prog in progs:
if getattr(Settings, prog.__name__):
mode = True
break
return mode | Determine if the program is enabled in the settings. | Below is the the instruction that describes the task:
### Input:
Determine if the program is enabled in the settings.
### Response:
def _is_program_selected(progs):
"""Determine if the program is enabled in the settings."""
mode = False
for prog in progs:
if getattr(Settings, prog.__name__):
... |
def _get_specification_positions(self):
"""
Returns a tuple with the start and end line numbers of the stored routine specification.
:rtype: tuple
"""
start = -1
for (i, line) in enumerate(self._routine_source_code_lines):
if self._is_start_of_stored_routine(... | Returns a tuple with the start and end line numbers of the stored routine specification.
:rtype: tuple | Below is the the instruction that describes the task:
### Input:
Returns a tuple with the start and end line numbers of the stored routine specification.
:rtype: tuple
### Response:
def _get_specification_positions(self):
"""
Returns a tuple with the start and end line numbers of the store... |
def make_zip_archive(self,
dst=None,
filters=all_true,
compress=True,
overwrite=False,
makedirs=False,
verbose=False): # pragma: no cover
"""
Make a zip ... | Make a zip archive.
:param dst: output file path. if not given, will be automatically assigned.
:param filters: custom path filter. By default it allows any file.
:param compress: compress or not.
:param overwrite: overwrite exists or not.
:param verbose: display log or not.
... | Below is the the instruction that describes the task:
### Input:
Make a zip archive.
:param dst: output file path. if not given, will be automatically assigned.
:param filters: custom path filter. By default it allows any file.
:param compress: compress or not.
:param overwrite: ove... |
def TransformerEncoder(vocab_size,
num_classes=10,
feature_depth=512,
feedforward_depth=2048,
num_layers=6,
num_heads=8,
dropout=0.1,
max_len=2048,
... | Transformer encoder.
Args:
vocab_size: int: vocab size
num_classes: how many classes on output
feature_depth: int: depth of embedding
feedforward_depth: int: depth of feed-forward layer
num_layers: int: number of encoder/decoder layers
num_heads: int: number of attention heads
dropout: f... | Below is the the instruction that describes the task:
### Input:
Transformer encoder.
Args:
vocab_size: int: vocab size
num_classes: how many classes on output
feature_depth: int: depth of embedding
feedforward_depth: int: depth of feed-forward layer
num_layers: int: number of encoder/decode... |
def execute(self, requests, resp_generator, *args, **kwargs):
'''
Calls the resp_generator for all the requests in sequential order.
'''
return [resp_generator(request) for request in requests] | Calls the resp_generator for all the requests in sequential order. | Below is the the instruction that describes the task:
### Input:
Calls the resp_generator for all the requests in sequential order.
### Response:
def execute(self, requests, resp_generator, *args, **kwargs):
'''
Calls the resp_generator for all the requests in sequential order.
'''
... |
def get_rdataset(self, rdclass, rdtype, covers=dns.rdatatype.NONE,
create=False):
"""Get an rdataset matching the specified properties in the
current node.
None is returned if an rdataset of the specified type and
class does not exist and I{create} is not True.
... | Get an rdataset matching the specified properties in the
current node.
None is returned if an rdataset of the specified type and
class does not exist and I{create} is not True.
@param rdclass: The class of the rdataset
@type rdclass: int
@param rdtype: The type of the r... | Below is the the instruction that describes the task:
### Input:
Get an rdataset matching the specified properties in the
current node.
None is returned if an rdataset of the specified type and
class does not exist and I{create} is not True.
@param rdclass: The class of the rdatase... |
def trend(self, **kwargs):
'''Calculate a trend for all series in the group. See the
`TimeSeries.trend()` method for more information.'''
return DataFrame({ name: series.trend(**kwargs) \
for name, series in self.groups.iteritems() }) | Calculate a trend for all series in the group. See the
`TimeSeries.trend()` method for more information. | Below is the the instruction that describes the task:
### Input:
Calculate a trend for all series in the group. See the
`TimeSeries.trend()` method for more information.
### Response:
def trend(self, **kwargs):
'''Calculate a trend for all series in the group. See the
`TimeSeries.trend()` m... |
def effstim(self, flux_unit=None, wavelengths=None, area=None,
vegaspec=None):
"""Calculate :ref:`effective stimulus <synphot-formula-effstim>`
for given flux unit.
Parameters
----------
flux_unit : str or `~astropy.units.core.Unit` or `None`
The unit... | Calculate :ref:`effective stimulus <synphot-formula-effstim>`
for given flux unit.
Parameters
----------
flux_unit : str or `~astropy.units.core.Unit` or `None`
The unit of effective stimulus.
COUNT gives result in count/s (see :meth:`countrate` for more
... | Below is the the instruction that describes the task:
### Input:
Calculate :ref:`effective stimulus <synphot-formula-effstim>`
for given flux unit.
Parameters
----------
flux_unit : str or `~astropy.units.core.Unit` or `None`
The unit of effective stimulus.
C... |
def _cmdloop(self) -> bool:
"""Repeatedly issue a prompt, accept input, parse an initial prefix
off the received input, and dispatch to action methods, passing them
the remainder of the line as argument.
This serves the same role as cmd.cmdloop().
:return: True implies the enti... | Repeatedly issue a prompt, accept input, parse an initial prefix
off the received input, and dispatch to action methods, passing them
the remainder of the line as argument.
This serves the same role as cmd.cmdloop().
:return: True implies the entire application should exit. | Below is the the instruction that describes the task:
### Input:
Repeatedly issue a prompt, accept input, parse an initial prefix
off the received input, and dispatch to action methods, passing them
the remainder of the line as argument.
This serves the same role as cmd.cmdloop().
... |
def replace_validation(self):
"""Replace the validation configuration in the selected profile.
TODO: Update this method.
"""
self.validate_profile_exists()
profile_data = self.profiles.get(self.args.profile_name)
# check redis
# if redis is None:
# ... | Replace the validation configuration in the selected profile.
TODO: Update this method. | Below is the the instruction that describes the task:
### Input:
Replace the validation configuration in the selected profile.
TODO: Update this method.
### Response:
def replace_validation(self):
"""Replace the validation configuration in the selected profile.
TODO: Update this method.
... |
def getroot(self):
"""Return the root element of the figure.
The root element is a group of elements after stripping the toplevel
``<svg>`` tag.
Returns
-------
GroupElement
All elements of the figure without the ``<svg>`` tag.
"""
if 'class'... | Return the root element of the figure.
The root element is a group of elements after stripping the toplevel
``<svg>`` tag.
Returns
-------
GroupElement
All elements of the figure without the ``<svg>`` tag. | Below is the the instruction that describes the task:
### Input:
Return the root element of the figure.
The root element is a group of elements after stripping the toplevel
``<svg>`` tag.
Returns
-------
GroupElement
All elements of the figure without the ``<svg... |
def encode_endian(text, encoding, errors="strict", le=True):
"""Like text.encode(encoding) but always returns little endian/big endian
BOMs instead of the system one.
Args:
text (text)
encoding (str)
errors (str)
le (boolean): if little endian
Returns:
bytes
... | Like text.encode(encoding) but always returns little endian/big endian
BOMs instead of the system one.
Args:
text (text)
encoding (str)
errors (str)
le (boolean): if little endian
Returns:
bytes
Raises:
UnicodeEncodeError
LookupError | Below is the the instruction that describes the task:
### Input:
Like text.encode(encoding) but always returns little endian/big endian
BOMs instead of the system one.
Args:
text (text)
encoding (str)
errors (str)
le (boolean): if little endian
Returns:
bytes
... |
def _make_graph(self, max_insert):
'''helper function to construct graph from current state of object'''
if len(self.partial_links) != 0:
raise Error('Error in _make_graph(). Cannot continue because there are partial links')
self.contig_links = {}
for key in self.lin... | helper function to construct graph from current state of object | Below is the the instruction that describes the task:
### Input:
helper function to construct graph from current state of object
### Response:
def _make_graph(self, max_insert):
'''helper function to construct graph from current state of object'''
if len(self.partial_links) != 0:
raise ... |
def smart_insert(engine, table, data, minimal_size=5):
"""
An optimized Insert strategy. Guarantee successful and highest insertion
speed. But ATOMIC WRITE IS NOT ENSURED IF THE PROGRAM IS INTERRUPTED.
**中文文档**
在Insert中, 如果已经预知不会出现IntegrityError, 那么使用Bulk Insert的速度要
远远快于逐条Insert。而如果无法预知, 那么我们采... | An optimized Insert strategy. Guarantee successful and highest insertion
speed. But ATOMIC WRITE IS NOT ENSURED IF THE PROGRAM IS INTERRUPTED.
**中文文档**
在Insert中, 如果已经预知不会出现IntegrityError, 那么使用Bulk Insert的速度要
远远快于逐条Insert。而如果无法预知, 那么我们采用如下策略:
1. 尝试Bulk Insert, Bulk Insert由于在结束前不Commit, 所以速度很快。
... | Below is the the instruction that describes the task:
### Input:
An optimized Insert strategy. Guarantee successful and highest insertion
speed. But ATOMIC WRITE IS NOT ENSURED IF THE PROGRAM IS INTERRUPTED.
**中文文档**
在Insert中, 如果已经预知不会出现IntegrityError, 那么使用Bulk Insert的速度要
远远快于逐条Insert。而如果无法预知, 那么我... |
def capacity_method_selector(sl, fd, method, **kwargs):
"""
Calculates the bearing capacity of a foundation on soil using the specified method.
:param sl: Soil Object
:param fd: Foundation Object
:param method: Method
:param kwargs:
:return:
"""
if method == 'vesics':
capaci... | Calculates the bearing capacity of a foundation on soil using the specified method.
:param sl: Soil Object
:param fd: Foundation Object
:param method: Method
:param kwargs:
:return: | Below is the the instruction that describes the task:
### Input:
Calculates the bearing capacity of a foundation on soil using the specified method.
:param sl: Soil Object
:param fd: Foundation Object
:param method: Method
:param kwargs:
:return:
### Response:
def capacity_method_selector(sl, f... |
def herp_derp_interp(place):
"""simple interpolation of GFS forecast"""
lat, lon = place
#begin=2014-02-14T00%3A00%3A00&end=2018-02-22T00%3A00%3A00
fmt = '%Y-%m-%dT00:00:00'
fmt = '%Y-%m-%dT%H:%M:00'
begin = (datetime.datetime.now()-datetime.timedelta(hours=12)).strftime(fmt)
#end=(datetime.... | simple interpolation of GFS forecast | Below is the the instruction that describes the task:
### Input:
simple interpolation of GFS forecast
### Response:
def herp_derp_interp(place):
"""simple interpolation of GFS forecast"""
lat, lon = place
#begin=2014-02-14T00%3A00%3A00&end=2018-02-22T00%3A00%3A00
fmt = '%Y-%m-%dT00:00:00'
fmt =... |
def wait(hotkey=None, suppress=False, trigger_on_release=False):
"""
Blocks the program execution until the given hotkey is pressed or,
if given no parameters, blocks forever.
"""
if hotkey:
lock = _Event()
remove = add_hotkey(hotkey, lambda: lock.set(), suppress=suppress, trigger_on... | Blocks the program execution until the given hotkey is pressed or,
if given no parameters, blocks forever. | Below is the the instruction that describes the task:
### Input:
Blocks the program execution until the given hotkey is pressed or,
if given no parameters, blocks forever.
### Response:
def wait(hotkey=None, suppress=False, trigger_on_release=False):
"""
Blocks the program execution until the given hot... |
def _archive_write_data(archive, data):
"""Write data to archive. This will only be called with a non-empty string.
"""
n = libarchive.calls.archive_write.c_archive_write_data(
archive,
ctypes.cast(ctypes.c_char_p(data), ctypes.c_void_p),
len(data))
if n == 0:
... | Write data to archive. This will only be called with a non-empty string. | Below is the the instruction that describes the task:
### Input:
Write data to archive. This will only be called with a non-empty string.
### Response:
def _archive_write_data(archive, data):
"""Write data to archive. This will only be called with a non-empty string.
"""
n = libarchive.calls.archive_w... |
def get_idb_graph():
"""Export IDB to a NetworkX graph.
Use xrefs to and from functions to build a DiGraph containing all
the functions in the IDB and all the links between them.
The graph can later be used to perform analysis on the IDB.
:return: nx.DiGraph()
"""
digraph = nx.DiGraph()
... | Export IDB to a NetworkX graph.
Use xrefs to and from functions to build a DiGraph containing all
the functions in the IDB and all the links between them.
The graph can later be used to perform analysis on the IDB.
:return: nx.DiGraph() | Below is the the instruction that describes the task:
### Input:
Export IDB to a NetworkX graph.
Use xrefs to and from functions to build a DiGraph containing all
the functions in the IDB and all the links between them.
The graph can later be used to perform analysis on the IDB.
:return: nx.DiGrap... |
def statistics(self):
"""
Access the statistics
:returns: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsList
:rtype: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsList
"""
if self._statistics is None:
self._stat... | Access the statistics
:returns: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsList
:rtype: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsList | Below is the the instruction that describes the task:
### Input:
Access the statistics
:returns: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsList
:rtype: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsList
### Response:
def statistics(self):
... |
def all_legal_moves(self):
'Returns a np.array of size go.N**2 + 1, with 1 = legal, 0 = illegal'
# by default, every move is legal
legal_moves = np.ones([N, N], dtype=np.int8)
# ...unless there is already a stone there
legal_moves[self.board != EMPTY] = 0
# calculate whic... | Returns a np.array of size go.N**2 + 1, with 1 = legal, 0 = illegal | Below is the the instruction that describes the task:
### Input:
Returns a np.array of size go.N**2 + 1, with 1 = legal, 0 = illegal
### Response:
def all_legal_moves(self):
'Returns a np.array of size go.N**2 + 1, with 1 = legal, 0 = illegal'
# by default, every move is legal
legal_moves =... |
def _start_drone(self):
"""
Restarts the drone
"""
with open(self.config_file, 'r') as config_file:
self.config = json.load(config_file, object_hook=asciify)
mode = None
if self.config['general']['mode'] == '' or self.config['general']['mode'] is None:
... | Restarts the drone | Below is the the instruction that describes the task:
### Input:
Restarts the drone
### Response:
def _start_drone(self):
"""
Restarts the drone
"""
with open(self.config_file, 'r') as config_file:
self.config = json.load(config_file, object_hook=asciify)
mode ... |
def extract_emoji(text):
'''
Parameters
----------
text, str
Returns
-------
List of 5.0-compliant emojis that occur in text.
'''
found_emojis = []
len_text = len(text)
i = 0
while i < len_text:
cur_char = ord(text[i])
try:
VALID_EMOJIS[cur_char]
except:
i += 1
continue
found = False
for... | Parameters
----------
text, str
Returns
-------
List of 5.0-compliant emojis that occur in text. | Below is the the instruction that describes the task:
### Input:
Parameters
----------
text, str
Returns
-------
List of 5.0-compliant emojis that occur in text.
### Response:
def extract_emoji(text):
'''
Parameters
----------
text, str
Returns
-------
List of 5.0-compliant emojis that occur in text.... |
def update_item(self, tablename, key, updates, returns=NONE,
return_capacity=None, expect_or=False, **kwargs):
"""
Update a single item in a table
This uses the older version of the DynamoDB API.
See also: :meth:`~.update_item2`.
Parameters
---------... | Update a single item in a table
This uses the older version of the DynamoDB API.
See also: :meth:`~.update_item2`.
Parameters
----------
tablename : str
Name of the table to update
key : dict
Primary key dict specifying the hash key and, if appli... | Below is the the instruction that describes the task:
### Input:
Update a single item in a table
This uses the older version of the DynamoDB API.
See also: :meth:`~.update_item2`.
Parameters
----------
tablename : str
Name of the table to update
key : di... |
def main(event_loop=None):
"""Scriptworker entry point: get everything set up, then enter the main loop.
Args:
event_loop (asyncio.BaseEventLoop, optional): the event loop to use.
If None, use ``asyncio.get_event_loop()``. Defaults to None.
"""
context, credentials = get_context_fr... | Scriptworker entry point: get everything set up, then enter the main loop.
Args:
event_loop (asyncio.BaseEventLoop, optional): the event loop to use.
If None, use ``asyncio.get_event_loop()``. Defaults to None. | Below is the the instruction that describes the task:
### Input:
Scriptworker entry point: get everything set up, then enter the main loop.
Args:
event_loop (asyncio.BaseEventLoop, optional): the event loop to use.
If None, use ``asyncio.get_event_loop()``. Defaults to None.
### Response:
... |
def parse_json(value: str, sig_params: List[inspect.Parameter] = None) -> dict:
"""Parse a value as JSON.
This is just a wrapper around json.loads which re-raises any errors as a
ParseError instead.
:param str value: JSON string.
:param dict sig_params: The logic function's signature parameters.
... | Parse a value as JSON.
This is just a wrapper around json.loads which re-raises any errors as a
ParseError instead.
:param str value: JSON string.
:param dict sig_params: The logic function's signature parameters.
:returns: the parsed JSON value | Below is the the instruction that describes the task:
### Input:
Parse a value as JSON.
This is just a wrapper around json.loads which re-raises any errors as a
ParseError instead.
:param str value: JSON string.
:param dict sig_params: The logic function's signature parameters.
:returns: the p... |
def _find_current_phase(self, global_step):
"""Determine the current phase based on the global step.
This ensures continuing the correct phase after restoring checkoints.
Args:
global_step: The global number of steps performed across all phases.
Returns:
Tuple of phase object, epoch numbe... | Determine the current phase based on the global step.
This ensures continuing the correct phase after restoring checkoints.
Args:
global_step: The global number of steps performed across all phases.
Returns:
Tuple of phase object, epoch number, and phase steps within the epoch. | Below is the the instruction that describes the task:
### Input:
Determine the current phase based on the global step.
This ensures continuing the correct phase after restoring checkoints.
Args:
global_step: The global number of steps performed across all phases.
Returns:
Tuple of phase o... |
def targetSigma2(self,R,log=False):
"""
NAME:
targetSigma2
PURPOSE:
evaluate the target Sigma_R^2(R)
INPUT:
R - radius at which to evaluate (can be Quantity)
OUTPUT:
target Sigma_R^2(R)
log - if True, return the log ... | NAME:
targetSigma2
PURPOSE:
evaluate the target Sigma_R^2(R)
INPUT:
R - radius at which to evaluate (can be Quantity)
OUTPUT:
target Sigma_R^2(R)
log - if True, return the log (default: False)
HISTORY:
2010-03-2... | Below is the the instruction that describes the task:
### Input:
NAME:
targetSigma2
PURPOSE:
evaluate the target Sigma_R^2(R)
INPUT:
R - radius at which to evaluate (can be Quantity)
OUTPUT:
target Sigma_R^2(R)
log - if True, re... |
def import_data(self, dataset, dry_run=False, raise_errors=False,
use_transactions=None, collect_failed_rows=False, **kwargs):
"""
Imports data from ``tablib.Dataset``. Refer to :doc:`import_workflow`
for a more complete description of the whole import process.
:para... | Imports data from ``tablib.Dataset``. Refer to :doc:`import_workflow`
for a more complete description of the whole import process.
:param dataset: A ``tablib.Dataset``
:param raise_errors: Whether errors should be printed to the end user
or raised regularly.
:param use_tra... | Below is the the instruction that describes the task:
### Input:
Imports data from ``tablib.Dataset``. Refer to :doc:`import_workflow`
for a more complete description of the whole import process.
:param dataset: A ``tablib.Dataset``
:param raise_errors: Whether errors should be printed to ... |
def _write_openjp2(self, img_array, verbose=False):
"""
Write JPEG 2000 file using OpenJPEG 2.x interface.
"""
if img_array.ndim == 2:
# Force the image to be 3D. Just makes things easier later on.
numrows, numcols = img_array.shape
img_array = img_ar... | Write JPEG 2000 file using OpenJPEG 2.x interface. | Below is the the instruction that describes the task:
### Input:
Write JPEG 2000 file using OpenJPEG 2.x interface.
### Response:
def _write_openjp2(self, img_array, verbose=False):
"""
Write JPEG 2000 file using OpenJPEG 2.x interface.
"""
if img_array.ndim == 2:
# Forc... |
def add_next_tick_callback(self, callback, callback_id=None):
""" Adds a callback to be run on the next tick.
Returns an ID that can be used with remove_next_tick_callback."""
def wrapper(*args, **kwargs):
# this 'removed' flag is a hack because Tornado has no way
# to re... | Adds a callback to be run on the next tick.
Returns an ID that can be used with remove_next_tick_callback. | Below is the the instruction that describes the task:
### Input:
Adds a callback to be run on the next tick.
Returns an ID that can be used with remove_next_tick_callback.
### Response:
def add_next_tick_callback(self, callback, callback_id=None):
""" Adds a callback to be run on the next tick.
... |
def summary(self):
"""
m.summary() -- Return a text string one-line summary of motif and its metrics
"""
m = self
txt = "%-34s (Bits: %5.2f MAP: %7.2f D: %5.3f %3d) E: %7.3f"%(
m, m.totalbits, m.MAP, m.seeddist, m.seednum, nlog10(m.pvalue))
if m.binomial!... | m.summary() -- Return a text string one-line summary of motif and its metrics | Below is the the instruction that describes the task:
### Input:
m.summary() -- Return a text string one-line summary of motif and its metrics
### Response:
def summary(self):
"""
m.summary() -- Return a text string one-line summary of motif and its metrics
"""
m = self
txt ... |
def is_protected_type(obj):
"""Determine if the object instance is of a protected type.
Objects of protected types are preserved as-is when passed to
force_text(strings_only=True).
"""
return isinstance(obj, six.integer_types + (type(None), float, Decimal,
datetime.datetime, datetime.date, ... | Determine if the object instance is of a protected type.
Objects of protected types are preserved as-is when passed to
force_text(strings_only=True). | Below is the the instruction that describes the task:
### Input:
Determine if the object instance is of a protected type.
Objects of protected types are preserved as-is when passed to
force_text(strings_only=True).
### Response:
def is_protected_type(obj):
"""Determine if the object instance is of a p... |
def new_root(self, vd, seqnum, log_block_size):
# type: (headervd.PrimaryOrSupplementaryVD, int, int) -> None
'''
Create a new root Directory Record.
Parameters:
vd - The Volume Descriptor this record is part of.
seqnum - The sequence number for this directory record.
... | Create a new root Directory Record.
Parameters:
vd - The Volume Descriptor this record is part of.
seqnum - The sequence number for this directory record.
log_block_size - The logical block size to use.
Returns:
Nothing. | Below is the the instruction that describes the task:
### Input:
Create a new root Directory Record.
Parameters:
vd - The Volume Descriptor this record is part of.
seqnum - The sequence number for this directory record.
log_block_size - The logical block size to use.
Retu... |
def dl_files(db, dl_dir, files, keep_subdirs=True, overwrite=False):
"""
Download specified files from a Physiobank database.
Parameters
----------
db : str
The Physiobank database directory to download. eg. For database:
'http://physionet.org/physiobank/database/mitdb', db='mitdb'.... | Download specified files from a Physiobank database.
Parameters
----------
db : str
The Physiobank database directory to download. eg. For database:
'http://physionet.org/physiobank/database/mitdb', db='mitdb'.
dl_dir : str
The full local directory path in which to download the ... | Below is the the instruction that describes the task:
### Input:
Download specified files from a Physiobank database.
Parameters
----------
db : str
The Physiobank database directory to download. eg. For database:
'http://physionet.org/physiobank/database/mitdb', db='mitdb'.
dl_dir ... |
def get_public_orders(self, group=False):
"""Return public orders that are currently open.
:param group: If set to True (default: False), orders with the same
price are grouped.
:type group: bool
:return: Public orders currently open.
:rtype: dict
"""
... | Return public orders that are currently open.
:param group: If set to True (default: False), orders with the same
price are grouped.
:type group: bool
:return: Public orders currently open.
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Return public orders that are currently open.
:param group: If set to True (default: False), orders with the same
price are grouped.
:type group: bool
:return: Public orders currently open.
:rtype: dict
###... |
def __compute_stdrange(self, images):
r"""
Computes a common standard intensity range over a number of images.
Depending on the settings of the internal self.__stdrange variable,
either (1) the already fixed values are returned, (2) a complete standard
intensity range is... | r"""
Computes a common standard intensity range over a number of images.
Depending on the settings of the internal self.__stdrange variable,
either (1) the already fixed values are returned, (2) a complete standard
intensity range is computed from the supplied images, (3) an int... | Below is the the instruction that describes the task:
### Input:
r"""
Computes a common standard intensity range over a number of images.
Depending on the settings of the internal self.__stdrange variable,
either (1) the already fixed values are returned, (2) a complete standard
... |
def span(route):
"""Optional decorator for Flask routes.
If you don't want to trace all routes using `Flask.before_request()' and 'Flask.after_request()'
you can use this decorator as an alternative way to handle incoming B3 headers:
@app.route('/instrumented')
@span
def instrument... | Optional decorator for Flask routes.
If you don't want to trace all routes using `Flask.before_request()' and 'Flask.after_request()'
you can use this decorator as an alternative way to handle incoming B3 headers:
@app.route('/instrumented')
@span
def instrumented():
...
... | Below is the the instruction that describes the task:
### Input:
Optional decorator for Flask routes.
If you don't want to trace all routes using `Flask.before_request()' and 'Flask.after_request()'
you can use this decorator as an alternative way to handle incoming B3 headers:
@app.route('/instru... |
def transform(self):
'''P⃗,Q⃗,W⃗'''
i = self.inclination
Ω = self.longitude_of_ascending_node
ω = self.argument_of_periapsis
si = sin(i)
ci = cos(i)
sΩ = sin(Ω)
cΩ = cos(Ω)
sω = sin(ω)
cω = cos(ω)
Q = np.array([
[-sΩ*... | P⃗,Q⃗,W⃗ | Below is the the instruction that describes the task:
### Input:
P⃗,Q⃗,W⃗
### Response:
def transform(self):
'''P⃗,Q⃗,W⃗'''
i = self.inclination
Ω = self.longitude_of_ascending_node
ω = self.argument_of_periapsis
si = sin(i)
ci = cos(i)
sΩ = sin(Ω)
c... |
def loss_maps_dt(self, dtype=F32):
"""
Return a composite data type for loss maps
"""
ltypes = self.loss_dt(dtype).names
lst = [('poe-%s' % poe, dtype) for poe in self.conditional_loss_poes]
return numpy.dtype([(lt, lst) for lt in ltypes]) | Return a composite data type for loss maps | Below is the the instruction that describes the task:
### Input:
Return a composite data type for loss maps
### Response:
def loss_maps_dt(self, dtype=F32):
"""
Return a composite data type for loss maps
"""
ltypes = self.loss_dt(dtype).names
lst = [('poe-%s' % poe, dtype) f... |
def retry_erroneous(self, name, properties_update=None):
# type: (str, dict) -> int
"""
Removes the ERRONEOUS state of the given component, and retries a
validation
:param name: Name of the component to retry
:param properties_update: A dictionary to update the initial p... | Removes the ERRONEOUS state of the given component, and retries a
validation
:param name: Name of the component to retry
:param properties_update: A dictionary to update the initial properties
of the component
:return: The new state of the component
... | Below is the the instruction that describes the task:
### Input:
Removes the ERRONEOUS state of the given component, and retries a
validation
:param name: Name of the component to retry
:param properties_update: A dictionary to update the initial properties
... |
def get_argflag(argstr_, default=False, help_='', return_specified=None,
need_prefix=True, return_was_specified=False, argv=None,
debug=None,
**kwargs):
"""
Checks if the commandline has a flag or a corresponding noflag
Args:
argstr_ (str, list, or tu... | Checks if the commandline has a flag or a corresponding noflag
Args:
argstr_ (str, list, or tuple): the flag to look for
default (bool): dont use this (default = False)
help_ (str): a help string (default = '')
return_specified (bool): returns if flag was specified or not (default =... | Below is the the instruction that describes the task:
### Input:
Checks if the commandline has a flag or a corresponding noflag
Args:
argstr_ (str, list, or tuple): the flag to look for
default (bool): dont use this (default = False)
help_ (str): a help string (default = '')
ret... |
def get_console_output(
name=None,
location=None,
instance_id=None,
call=None,
kwargs=None,
):
'''
Show the console output from the instance.
By default, returns decoded data, not the Base64-encoded data that is
actually returned from the EC2 API.
'''
... | Show the console output from the instance.
By default, returns decoded data, not the Base64-encoded data that is
actually returned from the EC2 API. | Below is the the instruction that describes the task:
### Input:
Show the console output from the instance.
By default, returns decoded data, not the Base64-encoded data that is
actually returned from the EC2 API.
### Response:
def get_console_output(
name=None,
location=None,
inst... |
def mkfs(*devices, **kwargs):
'''
Create a file system on the specified device. By default wipes out with force.
General options:
* **allocsize**: Specify the BTRFS offset from the start of the device.
* **bytecount**: Specify the size of the resultant filesystem.
* **nodesize**: Node size.
... | Create a file system on the specified device. By default wipes out with force.
General options:
* **allocsize**: Specify the BTRFS offset from the start of the device.
* **bytecount**: Specify the size of the resultant filesystem.
* **nodesize**: Node size.
* **leafsize**: Specify the nodesize, th... | Below is the the instruction that describes the task:
### Input:
Create a file system on the specified device. By default wipes out with force.
General options:
* **allocsize**: Specify the BTRFS offset from the start of the device.
* **bytecount**: Specify the size of the resultant filesystem.
* ... |
async def create(cls, user_id: Union[int, str],
is_active: bool = True,
is_admin: bool = False,
resource_policy: str = None,
rate_limit: int = None,
fields: Iterable[str] = None) -> dict:
'''
Creates... | Creates a new keypair with the given options.
You need an admin privilege for this operation. | Below is the the instruction that describes the task:
### Input:
Creates a new keypair with the given options.
You need an admin privilege for this operation.
### Response:
async def create(cls, user_id: Union[int, str],
is_active: bool = True,
is_admin: bool = Fal... |
def search(self, patterns, start=30, limit=1000, include_category=False):
"""Performs pattern searches against the Investigate database.
Args:
patterns: An enumerable of RegEx domain patterns to search for
start: How far back results extend from in days (max is 30)
... | Performs pattern searches against the Investigate database.
Args:
patterns: An enumerable of RegEx domain patterns to search for
start: How far back results extend from in days (max is 30)
limit: Number of results to show (max is 1000)
include_category: Inclu... | Below is the the instruction that describes the task:
### Input:
Performs pattern searches against the Investigate database.
Args:
patterns: An enumerable of RegEx domain patterns to search for
start: How far back results extend from in days (max is 30)
limit: Number... |
def filter_and_copy_table(tab, to_remove):
""" Filter and copy a FITS table.
Parameters
----------
tab : FITS Table object
to_remove : [int ...}
list of indices to remove from the table
returns FITS Table object
"""
nsrcs = len(tab)
mask = np.zeros((nsrcs), '?')
mas... | Filter and copy a FITS table.
Parameters
----------
tab : FITS Table object
to_remove : [int ...}
list of indices to remove from the table
returns FITS Table object | Below is the the instruction that describes the task:
### Input:
Filter and copy a FITS table.
Parameters
----------
tab : FITS Table object
to_remove : [int ...}
list of indices to remove from the table
returns FITS Table object
### Response:
def filter_and_copy_table(tab, to_rem... |
def create(self, data=None, uri=None, timeout=-1, force=True):
"""Makes a POST request to create a resource when a request body is required.
Args:
data: Additional fields can be passed to create the resource.
uri: Resouce uri
timeout: Timeout in seconds. Wait for tas... | Makes a POST request to create a resource when a request body is required.
Args:
data: Additional fields can be passed to create the resource.
uri: Resouce uri
timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
... | Below is the the instruction that describes the task:
### Input:
Makes a POST request to create a resource when a request body is required.
Args:
data: Additional fields can be passed to create the resource.
uri: Resouce uri
timeout: Timeout in seconds. Wait for task com... |
def get_wide_unicode(self, i):
"""Get narrow Unicode."""
value = []
for x in range(3):
c = next(i)
if c == '0':
value.append(c)
else: # pragma: no cover
raise SyntaxError('Invalid wide Unicode character at %d!' % (i.index - 1)... | Get narrow Unicode. | Below is the the instruction that describes the task:
### Input:
Get narrow Unicode.
### Response:
def get_wide_unicode(self, i):
"""Get narrow Unicode."""
value = []
for x in range(3):
c = next(i)
if c == '0':
value.append(c)
else: # pr... |
def decompress(images, delete_png=False, delete_json=False, folder=None):
"""Reverse compression from tif to png and save them in original format
(ome.tif). TIFF-tags are gotten from json-files named the same as given
images.
Parameters
----------
images : list of filenames
Image to de... | Reverse compression from tif to png and save them in original format
(ome.tif). TIFF-tags are gotten from json-files named the same as given
images.
Parameters
----------
images : list of filenames
Image to decompress.
delete_png : bool
Wheter to delete PNG images.
delete_j... | Below is the the instruction that describes the task:
### Input:
Reverse compression from tif to png and save them in original format
(ome.tif). TIFF-tags are gotten from json-files named the same as given
images.
Parameters
----------
images : list of filenames
Image to decompress.
... |
def disk_set(device, flag, state):
'''
Changes a flag on selected device.
A flag can be either "on" or "off" (make sure to use proper
quoting, see :ref:`YAML Idiosyncrasies
<yaml-idiosyncrasies>`). Some or all of these flags will be
available, depending on what disk label you are using.
Va... | Changes a flag on selected device.
A flag can be either "on" or "off" (make sure to use proper
quoting, see :ref:`YAML Idiosyncrasies
<yaml-idiosyncrasies>`). Some or all of these flags will be
available, depending on what disk label you are using.
Valid flags are:
* cylinder_alignment
... | Below is the the instruction that describes the task:
### Input:
Changes a flag on selected device.
A flag can be either "on" or "off" (make sure to use proper
quoting, see :ref:`YAML Idiosyncrasies
<yaml-idiosyncrasies>`). Some or all of these flags will be
available, depending on what disk label ... |
def get_processed_path(self):
"""Returns the processed file path from the storage backend.
:returns: File path from the storage backend.
:rtype: :py:class:`unicode`
"""
location = self.get_storage().location
return self.get_processed_key_name()[len(location):] | Returns the processed file path from the storage backend.
:returns: File path from the storage backend.
:rtype: :py:class:`unicode` | Below is the the instruction that describes the task:
### Input:
Returns the processed file path from the storage backend.
:returns: File path from the storage backend.
:rtype: :py:class:`unicode`
### Response:
def get_processed_path(self):
"""Returns the processed file path from the stora... |
def _determine_profiles(self):
"""
Determine the WBEM management profiles advertised by the WBEM server,
by communicating with it and enumerating the instances of
`CIM_RegisteredProfile`.
If the profiles could be determined, this method sets the
:attr:`profiles` property... | Determine the WBEM management profiles advertised by the WBEM server,
by communicating with it and enumerating the instances of
`CIM_RegisteredProfile`.
If the profiles could be determined, this method sets the
:attr:`profiles` property of this object to the list of
`CIM_Registe... | Below is the the instruction that describes the task:
### Input:
Determine the WBEM management profiles advertised by the WBEM server,
by communicating with it and enumerating the instances of
`CIM_RegisteredProfile`.
If the profiles could be determined, this method sets the
:attr:`... |
def contacted(self):
"""
:retuns: A boolean indicating whether the logged in user has contacted
the owner of this profile.
"""
try:
contacted_span = self._contacted_xpb.one_(self.profile_tree)
except:
return False
else:
... | :retuns: A boolean indicating whether the logged in user has contacted
the owner of this profile. | Below is the the instruction that describes the task:
### Input:
:retuns: A boolean indicating whether the logged in user has contacted
the owner of this profile.
### Response:
def contacted(self):
"""
:retuns: A boolean indicating whether the logged in user has contacted
... |
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
... | .. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
### Response:
def get_operation_status(kw... |
def draw(self, points, can=None):
"""Parameter <points> specifies the
list of points the arrow traverses through.
It should contain at least two points, i.e.,
the tail and tip. Parameter
<can> is an optional parameter that specifies the output.
<<canvas>>
"""
... | Parameter <points> specifies the
list of points the arrow traverses through.
It should contain at least two points, i.e.,
the tail and tip. Parameter
<can> is an optional parameter that specifies the output.
<<canvas>> | Below is the the instruction that describes the task:
### Input:
Parameter <points> specifies the
list of points the arrow traverses through.
It should contain at least two points, i.e.,
the tail and tip. Parameter
<can> is an optional parameter that specifies the output.
<<c... |
def status(self, all_instances=None, instance_ids=None, filters=None):
"""List instance info."""
params = {}
if filters:
params["filters"] = make_filters(filters)
if instance_ids:
params['InstanceIds'] = instance_ids
if all_instances is not None:
... | List instance info. | Below is the the instruction that describes the task:
### Input:
List instance info.
### Response:
def status(self, all_instances=None, instance_ids=None, filters=None):
"""List instance info."""
params = {}
if filters:
params["filters"] = make_filters(filters)
if instan... |
def get_object(self, queryset=None):
""" Returns the considered object. """
user = super().get_object(queryset)
profile, dummy = ForumProfile.objects.get_or_create(user=user)
return profile | Returns the considered object. | Below is the the instruction that describes the task:
### Input:
Returns the considered object.
### Response:
def get_object(self, queryset=None):
""" Returns the considered object. """
user = super().get_object(queryset)
profile, dummy = ForumProfile.objects.get_or_create(user=user)
... |
def lock(self, key, lease_time=-1):
"""
Acquires the lock for the specified key infinitely or for the specified lease time if provided.
If the lock is not available, the current thread becomes disabled for thread scheduling purposes and lies
dormant until the lock has been acquired.
... | Acquires the lock for the specified key infinitely or for the specified lease time if provided.
If the lock is not available, the current thread becomes disabled for thread scheduling purposes and lies
dormant until the lock has been acquired.
Scope of the lock is this map only. Acquired lock ... | Below is the the instruction that describes the task:
### Input:
Acquires the lock for the specified key infinitely or for the specified lease time if provided.
If the lock is not available, the current thread becomes disabled for thread scheduling purposes and lies
dormant until the lock has been ... |
def SetFileContext(self, file_name, row_num, row, headers):
"""Save the current context to be output with any errors.
Args:
file_name: string
row_num: int
row: list of strings
headers: list of column headers, its order corresponding to row's
"""
self._context = (file_name, row_n... | Save the current context to be output with any errors.
Args:
file_name: string
row_num: int
row: list of strings
headers: list of column headers, its order corresponding to row's | Below is the the instruction that describes the task:
### Input:
Save the current context to be output with any errors.
Args:
file_name: string
row_num: int
row: list of strings
headers: list of column headers, its order corresponding to row's
### Response:
def SetFileContext(self, fil... |
def get_message(self, object_id=None, query=None, *, download_attachments=False):
""" Get one message from the query result.
A shortcut to get_messages with limit=1
:param object_id: the message id to be retrieved.
:param query: applies a filter to the request such as
"displayN... | Get one message from the query result.
A shortcut to get_messages with limit=1
:param object_id: the message id to be retrieved.
:param query: applies a filter to the request such as
"displayName eq 'HelloFolder'"
:type query: Query or str
:param bool download_attachmen... | Below is the the instruction that describes the task:
### Input:
Get one message from the query result.
A shortcut to get_messages with limit=1
:param object_id: the message id to be retrieved.
:param query: applies a filter to the request such as
"displayName eq 'HelloFolder'"
... |
def delete(self, model_class, **where):
'''
Session().delete(Employee, id=1, name='John Doe')
'''
assert hasattr(model_class, '_fields'), 'Not a valid class'
table = model_class.__name__.lower()
with Session() as conn:
SQL = f'DELETE FROM {table} WHERE'
... | Session().delete(Employee, id=1, name='John Doe') | Below is the the instruction that describes the task:
### Input:
Session().delete(Employee, id=1, name='John Doe')
### Response:
def delete(self, model_class, **where):
'''
Session().delete(Employee, id=1, name='John Doe')
'''
assert hasattr(model_class, '_fields'), 'Not a valid cla... |
def add_menu_item(self, command, title):
"""
Add mouse right click menu item.
Args:
command (callable): function that will be called after left mouse click on title
title (str): label that will be shown in menu
"""
m_item = Gtk.MenuItem()
m_item.set_la... | Add mouse right click menu item.
Args:
command (callable): function that will be called after left mouse click on title
title (str): label that will be shown in menu | Below is the the instruction that describes the task:
### Input:
Add mouse right click menu item.
Args:
command (callable): function that will be called after left mouse click on title
title (str): label that will be shown in menu
### Response:
def add_menu_item(self, command, title):
... |
def get_project(self, project_name):
""" get project
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:return: GetProjectResponse
:raise: LogException
"""
headers = {}
... | get project
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:return: GetProjectResponse
:raise: LogException | Below is the the instruction that describes the task:
### Input:
get project
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:return: GetProjectResponse
:raise: LogException
### Response:
def ge... |
def _fields(self):
"""
Fields used for hashing, string representation, equality comparison
"""
return (
('reference_name', self.reference_name,),
('annotation_name', self.annotation_name),
('annotation_version', self.annotation_version),
('... | Fields used for hashing, string representation, equality comparison | Below is the the instruction that describes the task:
### Input:
Fields used for hashing, string representation, equality comparison
### Response:
def _fields(self):
"""
Fields used for hashing, string representation, equality comparison
"""
return (
('reference_name', s... |
def from_shapely(sgeom, srid=None):
"""
Create a Geometry from a Shapely geometry and the specified SRID.
The Shapely geometry will not be modified.
"""
if SHAPELY:
WKBWriter.defaults["include_srid"] = True
if srid:
lgeos.GEOSSetSRID(sgeom... | Create a Geometry from a Shapely geometry and the specified SRID.
The Shapely geometry will not be modified. | Below is the the instruction that describes the task:
### Input:
Create a Geometry from a Shapely geometry and the specified SRID.
The Shapely geometry will not be modified.
### Response:
def from_shapely(sgeom, srid=None):
"""
Create a Geometry from a Shapely geometry and the specified SR... |
def interpretDQvalue(input):
"""
Converts an integer 'input' into its component bit values as a list of
power of 2 integers.
For example, the bit value 1027 would return [1, 2, 1024]
"""
nbits = 16
# We will only support integer values up to 2**128
for iexp in [16, 32, 64, 128]:
... | Converts an integer 'input' into its component bit values as a list of
power of 2 integers.
For example, the bit value 1027 would return [1, 2, 1024] | Below is the the instruction that describes the task:
### Input:
Converts an integer 'input' into its component bit values as a list of
power of 2 integers.
For example, the bit value 1027 would return [1, 2, 1024]
### Response:
def interpretDQvalue(input):
"""
Converts an integer 'input' into its... |
def GetAccounts(self):
"""Return the client accounts associated with the user's manager account.
Returns:
list List of ManagedCustomer data objects.
"""
selector = {
'fields': ['CustomerId', 'CanManageClients']
}
accounts = self.client.GetService('ManagedCustomerService').get(sel... | Return the client accounts associated with the user's manager account.
Returns:
list List of ManagedCustomer data objects. | Below is the the instruction that describes the task:
### Input:
Return the client accounts associated with the user's manager account.
Returns:
list List of ManagedCustomer data objects.
### Response:
def GetAccounts(self):
"""Return the client accounts associated with the user's manager account.
... |
def read_authentication_config (self):
"""Read configuration options in section "authentication"."""
section = "authentication"
password_fields = []
if self.has_option(section, "entry"):
for val in read_multiline(self.get(section, "entry")):
auth = val.split()... | Read configuration options in section "authentication". | Below is the the instruction that describes the task:
### Input:
Read configuration options in section "authentication".
### Response:
def read_authentication_config (self):
"""Read configuration options in section "authentication"."""
section = "authentication"
password_fields = []
... |
def update_insight(self, project_key, insight_id, **kwargs):
"""Update an insight.
**Note that only elements included in the request will be updated. All
omitted elements will remain untouched.
:param project_key: Projrct identifier, in the form of
projectOwner/projectid
... | Update an insight.
**Note that only elements included in the request will be updated. All
omitted elements will remain untouched.
:param project_key: Projrct identifier, in the form of
projectOwner/projectid
:type project_key: str
:param insight_id: Insight unique identi... | Below is the the instruction that describes the task:
### Input:
Update an insight.
**Note that only elements included in the request will be updated. All
omitted elements will remain untouched.
:param project_key: Projrct identifier, in the form of
projectOwner/projectid
:t... |
def pagedsearch(self, ldap_filter, attributes):
"""
Performs a paged search on the AD, using the filter and attributes as a normal query does.
Needs to connect to the server first!
ldap_filter: str : LDAP query filter
attributes: list : Attributes list to recieve in the result
"""
logger.debug('Paged sear... | Performs a paged search on the AD, using the filter and attributes as a normal query does.
Needs to connect to the server first!
ldap_filter: str : LDAP query filter
attributes: list : Attributes list to recieve in the result | Below is the the instruction that describes the task:
### Input:
Performs a paged search on the AD, using the filter and attributes as a normal query does.
Needs to connect to the server first!
ldap_filter: str : LDAP query filter
attributes: list : Attributes list to recieve in the result
### Response:
def ... |
def read_item(self, from_date=None):
"""Read items and return them one by one.
:param from_date: start date for incremental reading.
:return: next single item when any available.
:raises ValueError: `metadata__timestamp` field not found in index
:raises NotFoundError: index not ... | Read items and return them one by one.
:param from_date: start date for incremental reading.
:return: next single item when any available.
:raises ValueError: `metadata__timestamp` field not found in index
:raises NotFoundError: index not found in ElasticSearch | Below is the the instruction that describes the task:
### Input:
Read items and return them one by one.
:param from_date: start date for incremental reading.
:return: next single item when any available.
:raises ValueError: `metadata__timestamp` field not found in index
:raises NotF... |
def print_languages(ctx, param, value):
"""Callback for <all> flag.
Prints formatted sorted list of supported languages and exits
"""
if not value or ctx.resilient_parsing:
return
try:
langs = tts_langs()
langs_str_list = sorted("{}: {}".format(k, langs[k]) for k in langs)
... | Callback for <all> flag.
Prints formatted sorted list of supported languages and exits | Below is the the instruction that describes the task:
### Input:
Callback for <all> flag.
Prints formatted sorted list of supported languages and exits
### Response:
def print_languages(ctx, param, value):
"""Callback for <all> flag.
Prints formatted sorted list of supported languages and exits
"""... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.