code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _getrsyncoptions(self):
"""Get options to be passed for rsync."""
ignores = list(self.DEFAULT_IGNORES)
ignores += self.config.option.rsyncignore
ignores += self.config.getini("rsyncignore")
return {"ignores": ignores, "verbose": self.config.option.verbose} | Get options to be passed for rsync. | Below is the the instruction that describes the task:
### Input:
Get options to be passed for rsync.
### Response:
def _getrsyncoptions(self):
"""Get options to be passed for rsync."""
ignores = list(self.DEFAULT_IGNORES)
ignores += self.config.option.rsyncignore
ignores += self.con... |
def available():
"""Returns True if a deep water model can be built, or False otherwise."""
builder_json = h2o.api("GET /3/ModelBuilders", data={"algo": "deepwater"})
visibility = builder_json["model_builders"]["deepwater"]["visibility"]
if visibility == "Experimental":
print... | Returns True if a deep water model can be built, or False otherwise. | Below is the the instruction that describes the task:
### Input:
Returns True if a deep water model can be built, or False otherwise.
### Response:
def available():
"""Returns True if a deep water model can be built, or False otherwise."""
builder_json = h2o.api("GET /3/ModelBuilders", data={"algo"... |
def describe(self):
'''Provide a dictionary with information describing itself.'''
description = {
'description': self._description,
'type': self.name,
}
description.update(self.extra_params)
return description | Provide a dictionary with information describing itself. | Below is the the instruction that describes the task:
### Input:
Provide a dictionary with information describing itself.
### Response:
def describe(self):
'''Provide a dictionary with information describing itself.'''
description = {
'description': self._description,
'type'... |
def read_locked(*args, **kwargs):
"""Acquires & releases a read lock around call into decorated method.
NOTE(harlowja): if no attribute name is provided then by default the
attribute named '_lock' is looked for (this attribute is expected to be
a :py:class:`.ReaderWriterLock`) in the instance object th... | Acquires & releases a read lock around call into decorated method.
NOTE(harlowja): if no attribute name is provided then by default the
attribute named '_lock' is looked for (this attribute is expected to be
a :py:class:`.ReaderWriterLock`) in the instance object this decorator
is attached to. | Below is the the instruction that describes the task:
### Input:
Acquires & releases a read lock around call into decorated method.
NOTE(harlowja): if no attribute name is provided then by default the
attribute named '_lock' is looked for (this attribute is expected to be
a :py:class:`.ReaderWriterLock... |
def autosave_all(self):
"""Autosave all opened files."""
for index in range(self.stack.get_stack_count()):
self.autosave(index) | Autosave all opened files. | Below is the the instruction that describes the task:
### Input:
Autosave all opened files.
### Response:
def autosave_all(self):
"""Autosave all opened files."""
for index in range(self.stack.get_stack_count()):
self.autosave(index) |
def access_required(config=None):
"""
Authenticates a HTTP method handler based on a custom set of arguments
"""
def _access_required(http_method_handler):
def secure_http_method_handler(self, *args, **kwargs):
# authentication context must be set
if not self.__provide... | Authenticates a HTTP method handler based on a custom set of arguments | Below is the the instruction that describes the task:
### Input:
Authenticates a HTTP method handler based on a custom set of arguments
### Response:
def access_required(config=None):
"""
Authenticates a HTTP method handler based on a custom set of arguments
"""
def _access_required(http_method_ha... |
def connection_id_to_public_key(self, connection_id):
"""
Get stored public key for a connection.
"""
with self._connections_lock:
try:
connection_info = self._connections[connection_id]
return connection_info.public_key
except KeyE... | Get stored public key for a connection. | Below is the the instruction that describes the task:
### Input:
Get stored public key for a connection.
### Response:
def connection_id_to_public_key(self, connection_id):
"""
Get stored public key for a connection.
"""
with self._connections_lock:
try:
... |
def get_pages(url):
"""
Return the 'pages' from the starting url
Technically, look for the 'next 50' link, yield and download it, repeat
"""
while True:
yield url
doc = html.parse(url).find("body")
links = [a for a in doc.findall(".//a") if a.text and a.text.startswith("next... | Return the 'pages' from the starting url
Technically, look for the 'next 50' link, yield and download it, repeat | Below is the the instruction that describes the task:
### Input:
Return the 'pages' from the starting url
Technically, look for the 'next 50' link, yield and download it, repeat
### Response:
def get_pages(url):
"""
Return the 'pages' from the starting url
Technically, look for the 'next 50' link,... |
def debug(self, i: int=None) -> str:
"""
Returns a debug message
"""
head = "[" + colors.yellow("debug") + "]"
if i is not None:
head = str(i) + " " + head
return head | Returns a debug message | Below is the the instruction that describes the task:
### Input:
Returns a debug message
### Response:
def debug(self, i: int=None) -> str:
"""
Returns a debug message
"""
head = "[" + colors.yellow("debug") + "]"
if i is not None:
head = str(i) + " " + head
... |
def _insert_additionals(self, fmtos, seen=None):
"""
Insert additional formatoptions into `fmtos`.
This method inserts those formatoptions into `fmtos` that are required
because one of the following criteria is fullfilled:
1. The :attr:`replot` attribute is True
2. Any ... | Insert additional formatoptions into `fmtos`.
This method inserts those formatoptions into `fmtos` that are required
because one of the following criteria is fullfilled:
1. The :attr:`replot` attribute is True
2. Any formatoption with START priority is in `fmtos`
3. A dependenc... | Below is the the instruction that describes the task:
### Input:
Insert additional formatoptions into `fmtos`.
This method inserts those formatoptions into `fmtos` that are required
because one of the following criteria is fullfilled:
1. The :attr:`replot` attribute is True
2. Any ... |
def _add_graph_level(graph, level, parent_ids, names, scores, normalized_scores,
include_pad):
"""Adds a level to the passed graph"""
for i, parent_id in enumerate(parent_ids):
if not include_pad and names[i] == PAD_TOKEN:
continue
new_node = (level, i)
p... | Adds a level to the passed graph | Below is the the instruction that describes the task:
### Input:
Adds a level to the passed graph
### Response:
def _add_graph_level(graph, level, parent_ids, names, scores, normalized_scores,
include_pad):
"""Adds a level to the passed graph"""
for i, parent_id in enumerate(parent_ids... |
def set_property(self, key, value):
'''Set a new (or updating existing) key value pair.
Args:
key: A string containing the key namespace
value: A str, int, or bool value
Raises:
NotImplementedError: an unsupported value-type was provided
'''
... | Set a new (or updating existing) key value pair.
Args:
key: A string containing the key namespace
value: A str, int, or bool value
Raises:
NotImplementedError: an unsupported value-type was provided | Below is the the instruction that describes the task:
### Input:
Set a new (or updating existing) key value pair.
Args:
key: A string containing the key namespace
value: A str, int, or bool value
Raises:
NotImplementedError: an unsupported value-type was provide... |
def columnOptions( self, tableType ):
"""
Returns the column options for the inputed table type.
:param tableType | <subclass of orb.Table>
:return [<str>, ..]
"""
if ( not tableType ):
return []
schema = ... | Returns the column options for the inputed table type.
:param tableType | <subclass of orb.Table>
:return [<str>, ..] | Below is the the instruction that describes the task:
### Input:
Returns the column options for the inputed table type.
:param tableType | <subclass of orb.Table>
:return [<str>, ..]
### Response:
def columnOptions( self, tableType ):
"""
Returns the... |
def _convert_priority(p_priority):
"""
Converts todo.txt priority to an iCalendar priority (RFC 2445).
Priority A gets priority 1, priority B gets priority 5 and priority C-F get
priorities 6-9. This scheme makes sure that clients that use "high",
"medium" and "low" show the correct priority.
"... | Converts todo.txt priority to an iCalendar priority (RFC 2445).
Priority A gets priority 1, priority B gets priority 5 and priority C-F get
priorities 6-9. This scheme makes sure that clients that use "high",
"medium" and "low" show the correct priority. | Below is the the instruction that describes the task:
### Input:
Converts todo.txt priority to an iCalendar priority (RFC 2445).
Priority A gets priority 1, priority B gets priority 5 and priority C-F get
priorities 6-9. This scheme makes sure that clients that use "high",
"medium" and "low" show the c... |
def getOffsetFromRva(self, rva):
"""
Converts an offset to an RVA.
@type rva: int
@param rva: The RVA to be converted.
@rtype: int
@return: An integer value representing an offset in the PE file.
"""
offset = -1
s = self.getSectio... | Converts an offset to an RVA.
@type rva: int
@param rva: The RVA to be converted.
@rtype: int
@return: An integer value representing an offset in the PE file. | Below is the the instruction that describes the task:
### Input:
Converts an offset to an RVA.
@type rva: int
@param rva: The RVA to be converted.
@rtype: int
@return: An integer value representing an offset in the PE file.
### Response:
def getOffsetFromRva(self, ... |
def extract_data(self, page):
"""Extract the AppNexus object or list of objects from the response"""
response_keys = set(page.keys())
uncommon_keys = response_keys - self.common_keys
for possible_data_key in uncommon_keys:
element = page[possible_data_key]
if isi... | Extract the AppNexus object or list of objects from the response | Below is the the instruction that describes the task:
### Input:
Extract the AppNexus object or list of objects from the response
### Response:
def extract_data(self, page):
"""Extract the AppNexus object or list of objects from the response"""
response_keys = set(page.keys())
uncommon_keys... |
def dumps(post, handler=None, **kwargs):
"""
Serialize a :py:class:`post <frontmatter.Post>` to a string and return text.
This always returns unicode text, which can then be encoded.
Passing ``handler`` will change how metadata is turned into text. A handler
passed as an argument will override ``p... | Serialize a :py:class:`post <frontmatter.Post>` to a string and return text.
This always returns unicode text, which can then be encoded.
Passing ``handler`` will change how metadata is turned into text. A handler
passed as an argument will override ``post.handler``, with
:py:class:`YAMLHandler <fron... | Below is the the instruction that describes the task:
### Input:
Serialize a :py:class:`post <frontmatter.Post>` to a string and return text.
This always returns unicode text, which can then be encoded.
Passing ``handler`` will change how metadata is turned into text. A handler
passed as an argument w... |
def get_document_length(self, document):
"""
Returns the number of terms found within the specified document.
"""
if document in self._documents:
return self._documents[document]
else:
raise IndexError(DOCUMENT_DOES_NOT_EXIST) | Returns the number of terms found within the specified document. | Below is the the instruction that describes the task:
### Input:
Returns the number of terms found within the specified document.
### Response:
def get_document_length(self, document):
"""
Returns the number of terms found within the specified document.
"""
if document in self._docu... |
def hicexplorer_basic_statistics(self):
"""Create the general statistics for HiCExplorer."""
data = {}
for file in self.mod_data:
max_distance_key = 'Max rest. site distance'
total_pairs = self.mod_data[file]['Pairs considered'][0]
try:
self.mo... | Create the general statistics for HiCExplorer. | Below is the the instruction that describes the task:
### Input:
Create the general statistics for HiCExplorer.
### Response:
def hicexplorer_basic_statistics(self):
"""Create the general statistics for HiCExplorer."""
data = {}
for file in self.mod_data:
max_distance_key = 'Max... |
def pad_length(x, d):
"""Return a vector appropriate to a dimensional space, using an input vector
as a prompt depending on its type:
- If the input is a vector, return that vector.
- If the input is a scalar, return a vector filled with that value.
Useful when a function expects an array ... | Return a vector appropriate to a dimensional space, using an input vector
as a prompt depending on its type:
- If the input is a vector, return that vector.
- If the input is a scalar, return a vector filled with that value.
Useful when a function expects an array specifying values along each ... | Below is the the instruction that describes the task:
### Input:
Return a vector appropriate to a dimensional space, using an input vector
as a prompt depending on its type:
- If the input is a vector, return that vector.
- If the input is a scalar, return a vector filled with that value.
... |
def doLog(self, level, where, format, *args, **kwargs):
"""
Log a message at the given level, with the possibility of going
higher up in the stack.
@param level: log level
@type level: int
@param where: how many frames to go back from the last log frame;
... | Log a message at the given level, with the possibility of going
higher up in the stack.
@param level: log level
@type level: int
@param where: how many frames to go back from the last log frame;
or a function (to log for a future call)
@type where: int (n... | Below is the the instruction that describes the task:
### Input:
Log a message at the given level, with the possibility of going
higher up in the stack.
@param level: log level
@type level: int
@param where: how many frames to go back from the last log frame;
... |
def get_all(cls, include_disabled=True):
"""Returns a list of all accounts of a given type
Args:
include_disabled (`bool`): Include disabled accounts. Default: `True`
Returns:
list of account objects
"""
if cls == BaseAccount:
raise Inquisito... | Returns a list of all accounts of a given type
Args:
include_disabled (`bool`): Include disabled accounts. Default: `True`
Returns:
list of account objects | Below is the the instruction that describes the task:
### Input:
Returns a list of all accounts of a given type
Args:
include_disabled (`bool`): Include disabled accounts. Default: `True`
Returns:
list of account objects
### Response:
def get_all(cls, include_disabled=True... |
def call_api(self, resource_path, method,
path_params=None, query_params=None, header_params=None,
body=None, post_params=None, files=None,
response_type=None, auth_settings=None, asynchronous=None,
_return_http_data_only=None, collection_formats=None,... | Makes the HTTP request (synchronous) and return the deserialized data.
To make an async request, set the asynchronous parameter.
:param resource_path: Path to method endpoint.
:param method: Method to call.
:param path_params: Path parameters in the url.
:param query_params: Que... | Below is the the instruction that describes the task:
### Input:
Makes the HTTP request (synchronous) and return the deserialized data.
To make an async request, set the asynchronous parameter.
:param resource_path: Path to method endpoint.
:param method: Method to call.
:param path... |
def _empathy_status(status, message):
""" Updates status and message for Empathy IM application.
`status`
Status type.
`message`
Status message.
"""
ACCT_IFACE = 'org.freedesktop.Telepathy.Account'
DBUS_PROP_IFACE = 'org.freedesktop.DBus.Properties'
ACCT... | Updates status and message for Empathy IM application.
`status`
Status type.
`message`
Status message. | Below is the the instruction that describes the task:
### Input:
Updates status and message for Empathy IM application.
`status`
Status type.
`message`
Status message.
### Response:
def _empathy_status(status, message):
""" Updates status and message for Empathy IM appl... |
def get_api_date(self):
'''
Figure out the date to use for API requests. Assumes yesterday's date
if between midnight and 10am Eastern time. Override this function in a
subclass to change how the API date is calculated.
'''
# NOTE: If you are writing your own function to ... | Figure out the date to use for API requests. Assumes yesterday's date
if between midnight and 10am Eastern time. Override this function in a
subclass to change how the API date is calculated. | Below is the the instruction that describes the task:
### Input:
Figure out the date to use for API requests. Assumes yesterday's date
if between midnight and 10am Eastern time. Override this function in a
subclass to change how the API date is calculated.
### Response:
def get_api_date(self):
... |
def _item_list(profile=None):
'''
Template for writing list functions
Return a list of available items (glance items-list)
CLI Example:
.. code-block:: bash
salt '*' glance.item_list
'''
g_client = _auth(profile)
ret = []
for item in g_client.items.list():
ret.appe... | Template for writing list functions
Return a list of available items (glance items-list)
CLI Example:
.. code-block:: bash
salt '*' glance.item_list | Below is the the instruction that describes the task:
### Input:
Template for writing list functions
Return a list of available items (glance items-list)
CLI Example:
.. code-block:: bash
salt '*' glance.item_list
### Response:
def _item_list(profile=None):
'''
Template for writing l... |
def installed(name, default=False, user=None, opts=None, env=None):
'''
Verify that the specified ruby is installed with RVM. RVM is
installed when necessary.
name
The version of ruby to install
default : False
Whether to make this ruby the default.
user: None
The user... | Verify that the specified ruby is installed with RVM. RVM is
installed when necessary.
name
The version of ruby to install
default : False
Whether to make this ruby the default.
user: None
The user to run rvm as.
env: None
A list of environment variables to set (i... | Below is the the instruction that describes the task:
### Input:
Verify that the specified ruby is installed with RVM. RVM is
installed when necessary.
name
The version of ruby to install
default : False
Whether to make this ruby the default.
user: None
The user to run rvm... |
def deleteSettings(self, groupName=None):
""" Deletes registry items from the persistent store.
"""
groupName = groupName if groupName else self.settingsGroupName
settings = QtCore.QSettings()
logger.info("Deleting {} from: {}".format(groupName, settings.fileName()))
remo... | Deletes registry items from the persistent store. | Below is the the instruction that describes the task:
### Input:
Deletes registry items from the persistent store.
### Response:
def deleteSettings(self, groupName=None):
""" Deletes registry items from the persistent store.
"""
groupName = groupName if groupName else self.settingsGroupName... |
def assoc(_d, key, value):
"""Associate a key with a value in a dictionary
:param _d: a dictionary
:param key: a key in the dictionary
:param value: a value for the key
:returns: a new dictionary
>>> data = {}
>>> new_data = assoc(data, 'name', 'Holy Grail')
>>> new_data
{'name': '... | Associate a key with a value in a dictionary
:param _d: a dictionary
:param key: a key in the dictionary
:param value: a value for the key
:returns: a new dictionary
>>> data = {}
>>> new_data = assoc(data, 'name', 'Holy Grail')
>>> new_data
{'name': 'Holy Grail'}
>>> data
{}
... | Below is the the instruction that describes the task:
### Input:
Associate a key with a value in a dictionary
:param _d: a dictionary
:param key: a key in the dictionary
:param value: a value for the key
:returns: a new dictionary
>>> data = {}
>>> new_data = assoc(data, 'name', 'Holy Grai... |
def get_supply_voltage(self, dest_addr_long=None):
"""
Fetches the value of %V and returns it as volts.
"""
value = self._get_parameter(b"%V", dest_addr_long=dest_addr_long)
return (hex_to_int(value) * (1200/1024.0)) / 1000 | Fetches the value of %V and returns it as volts. | Below is the the instruction that describes the task:
### Input:
Fetches the value of %V and returns it as volts.
### Response:
def get_supply_voltage(self, dest_addr_long=None):
"""
Fetches the value of %V and returns it as volts.
"""
value = self._get_parameter(b"%V", dest_addr_lo... |
def cell_arrays(self):
""" Returns the all cell arrays """
cdata = self.GetCellData()
narr = cdata.GetNumberOfArrays()
# Update data if necessary
if hasattr(self, '_cell_arrays'):
keys = list(self._cell_arrays.keys())
if narr == len(keys):
... | Returns the all cell arrays | Below is the the instruction that describes the task:
### Input:
Returns the all cell arrays
### Response:
def cell_arrays(self):
""" Returns the all cell arrays """
cdata = self.GetCellData()
narr = cdata.GetNumberOfArrays()
# Update data if necessary
if hasattr(self, '_ce... |
def init(image, root=None):
'''
Mount the named image via qemu-nbd and return the mounted roots
CLI Example:
.. code-block:: bash
salt '*' qemu_nbd.init /srv/image.qcow2
'''
nbd = connect(image)
if not nbd:
return ''
return mount(nbd, root) | Mount the named image via qemu-nbd and return the mounted roots
CLI Example:
.. code-block:: bash
salt '*' qemu_nbd.init /srv/image.qcow2 | Below is the the instruction that describes the task:
### Input:
Mount the named image via qemu-nbd and return the mounted roots
CLI Example:
.. code-block:: bash
salt '*' qemu_nbd.init /srv/image.qcow2
### Response:
def init(image, root=None):
'''
Mount the named image via qemu-nbd and ... |
def can_create_catalog_with_record_types(self, catalog_record_types):
"""Tests if this user can create a single ``Catalog`` using the desired record types.
While ``CatalogingManager.getCatalogRecordTypes()`` can be used
to examine which records are supported, this method tests which
rec... | Tests if this user can create a single ``Catalog`` using the desired record types.
While ``CatalogingManager.getCatalogRecordTypes()`` can be used
to examine which records are supported, this method tests which
record(s) are required for creating a specific ``Catalog``.
Providing an emp... | Below is the the instruction that describes the task:
### Input:
Tests if this user can create a single ``Catalog`` using the desired record types.
While ``CatalogingManager.getCatalogRecordTypes()`` can be used
to examine which records are supported, this method tests which
record(s) are r... |
def is_point_layer(layer):
"""Check if a QGIS layer is vector and its geometries are points.
:param layer: A vector layer.
:type layer: QgsVectorLayer, QgsMapLayer
:returns: True if the layer contains points, otherwise False.
:rtype: bool
"""
try:
return (layer.type() == QgsMapLaye... | Check if a QGIS layer is vector and its geometries are points.
:param layer: A vector layer.
:type layer: QgsVectorLayer, QgsMapLayer
:returns: True if the layer contains points, otherwise False.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Check if a QGIS layer is vector and its geometries are points.
:param layer: A vector layer.
:type layer: QgsVectorLayer, QgsMapLayer
:returns: True if the layer contains points, otherwise False.
:rtype: bool
### Response:
def is_po... |
def normalize_ext_rename(filepath):
""" normalize file ext like '.tgz' -> '.tar.gz' and '300d.txt' -> '300d.glove.txt' and rename the file
>>> pth = os.path.join(DATA_PATH, 'sms_slang_dict.txt')
>>> pth == normalize_ext_rename(pth)
True
"""
logger.debug('normalize_ext.filepath=' + str(filepath)... | normalize file ext like '.tgz' -> '.tar.gz' and '300d.txt' -> '300d.glove.txt' and rename the file
>>> pth = os.path.join(DATA_PATH, 'sms_slang_dict.txt')
>>> pth == normalize_ext_rename(pth)
True | Below is the the instruction that describes the task:
### Input:
normalize file ext like '.tgz' -> '.tar.gz' and '300d.txt' -> '300d.glove.txt' and rename the file
>>> pth = os.path.join(DATA_PATH, 'sms_slang_dict.txt')
>>> pth == normalize_ext_rename(pth)
True
### Response:
def normalize_ext_rename(f... |
async def connect(self, retry=2):
"""Connect to Mill."""
# pylint: disable=too-many-return-statements
url = API_ENDPOINT_1 + 'login'
headers = {
"Content-Type": "application/x-zc-object",
"Connection": "Keep-Alive",
"X-Zc-Major-Domain": "seanywell",
... | Connect to Mill. | Below is the the instruction that describes the task:
### Input:
Connect to Mill.
### Response:
async def connect(self, retry=2):
"""Connect to Mill."""
# pylint: disable=too-many-return-statements
url = API_ENDPOINT_1 + 'login'
headers = {
"Content-Type": "application/x... |
def tabulate(lol, headers, eol='\n'):
"""Use the pypi tabulate package instead!"""
yield '| %s |' % ' | '.join(headers) + eol
yield '| %s:|' % ':| '.join(['-' * len(w) for w in headers]) + eol
for row in lol:
yield '| %s |' % ' | '.join(str(c) for c in row) + eol | Use the pypi tabulate package instead! | Below is the the instruction that describes the task:
### Input:
Use the pypi tabulate package instead!
### Response:
def tabulate(lol, headers, eol='\n'):
"""Use the pypi tabulate package instead!"""
yield '| %s |' % ' | '.join(headers) + eol
yield '| %s:|' % ':| '.join(['-' * len(w) for w in headers]... |
def get_range(self, ignore_blank_lines=True):
"""
Gets the fold region range (start and end line).
.. note:: Start line do no encompass the trigger line.
:param ignore_blank_lines: True to ignore blank lines at the end of the
scope (the method will rewind to find that last ... | Gets the fold region range (start and end line).
.. note:: Start line do no encompass the trigger line.
:param ignore_blank_lines: True to ignore blank lines at the end of the
scope (the method will rewind to find that last meaningful block
that is part of the fold scope).
... | Below is the the instruction that describes the task:
### Input:
Gets the fold region range (start and end line).
.. note:: Start line do no encompass the trigger line.
:param ignore_blank_lines: True to ignore blank lines at the end of the
scope (the method will rewind to find that la... |
def get_body(self, msg):
""" Extracts and returns the decoded body from an EmailMessage object"""
body = ""
charset = ""
if msg.is_multipart():
for part in msg.walk():
ctype = part.get_content_type()
cdispo = str(part.get('Content-Disposition... | Extracts and returns the decoded body from an EmailMessage object | Below is the the instruction that describes the task:
### Input:
Extracts and returns the decoded body from an EmailMessage object
### Response:
def get_body(self, msg):
""" Extracts and returns the decoded body from an EmailMessage object"""
body = ""
charset = ""
if msg.is_multi... |
def shutdown(self):
"""
Disconnect all cached connections.
@returns: a deferred that fires once all connection are disconnected.
@rtype: L{Deferred}
"""
self._shuttingDown = {key: Deferred()
for key in self.cachedConnections.keys()}
... | Disconnect all cached connections.
@returns: a deferred that fires once all connection are disconnected.
@rtype: L{Deferred} | Below is the the instruction that describes the task:
### Input:
Disconnect all cached connections.
@returns: a deferred that fires once all connection are disconnected.
@rtype: L{Deferred}
### Response:
def shutdown(self):
"""
Disconnect all cached connections.
@returns: ... |
def select_larva(self):
"""Select all larva."""
action = sc_pb.Action()
action.action_ui.select_larva.SetInParent() # Adds the empty proto field.
return action | Select all larva. | Below is the the instruction that describes the task:
### Input:
Select all larva.
### Response:
def select_larva(self):
"""Select all larva."""
action = sc_pb.Action()
action.action_ui.select_larva.SetInParent() # Adds the empty proto field.
return action |
def backoff(
max_tries=constants.BACKOFF_DEFAULT_MAXTRIES,
delay=constants.BACKOFF_DEFAULT_DELAY,
factor=constants.BACKOFF_DEFAULT_FACTOR,
exceptions=None):
"""Implements an exponential backoff decorator which will retry decorated
function upon given exceptions. This implementati... | Implements an exponential backoff decorator which will retry decorated
function upon given exceptions. This implementation is based on
`Retry <https://wiki.python.org/moin/PythonDecoratorLibrary#Retry>`_ from
the *Python Decorator Library*.
:param int max_tries: Number of tries before give up. Defaults... | Below is the the instruction that describes the task:
### Input:
Implements an exponential backoff decorator which will retry decorated
function upon given exceptions. This implementation is based on
`Retry <https://wiki.python.org/moin/PythonDecoratorLibrary#Retry>`_ from
the *Python Decorator Library*... |
def list(self, request, *args, **kwargs):
"""
To get a list of projects, run **GET** against */api/projects/* as authenticated user.
Here you can also check actual value for project quotas and project usage
Note that a user can only see connected projects:
- projects that the u... | To get a list of projects, run **GET** against */api/projects/* as authenticated user.
Here you can also check actual value for project quotas and project usage
Note that a user can only see connected projects:
- projects that the user owns as a customer
- projects where user has any r... | Below is the the instruction that describes the task:
### Input:
To get a list of projects, run **GET** against */api/projects/* as authenticated user.
Here you can also check actual value for project quotas and project usage
Note that a user can only see connected projects:
- projects tha... |
def by_current_session(cls):
""" Returns current user session """
session = Session.current_session()
if session is None:
return None
return cls.where_id(session.user_id) | Returns current user session | Below is the the instruction that describes the task:
### Input:
Returns current user session
### Response:
def by_current_session(cls):
""" Returns current user session """
session = Session.current_session()
if session is None:
return None
return cls.where_id(sess... |
def generate_raml_resource_types(module):
"""Compile a Pale module's resource documentation into RAML format.
RAML calls Pale resources 'resourceTypes'. This function converts Pale
resources into the RAML resourceType format.
The returned string should be appended to the RAML documentation string
... | Compile a Pale module's resource documentation into RAML format.
RAML calls Pale resources 'resourceTypes'. This function converts Pale
resources into the RAML resourceType format.
The returned string should be appended to the RAML documentation string
before it is returned. | Below is the the instruction that describes the task:
### Input:
Compile a Pale module's resource documentation into RAML format.
RAML calls Pale resources 'resourceTypes'. This function converts Pale
resources into the RAML resourceType format.
The returned string should be appended to the RAML docum... |
def request_stop(self, message='', exit_code=0):
"""Stop the Arbiter daemon
:return: None
"""
# Only a master arbiter can stop the daemons
if self.is_master:
# Stop the daemons
self.daemons_stop(timeout=self.conf.daemons_stop_timeout)
# Request t... | Stop the Arbiter daemon
:return: None | Below is the the instruction that describes the task:
### Input:
Stop the Arbiter daemon
:return: None
### Response:
def request_stop(self, message='', exit_code=0):
"""Stop the Arbiter daemon
:return: None
"""
# Only a master arbiter can stop the daemons
if self.i... |
def qemu_rebase(target, backing_file, safe=True, fail_on_error=True):
"""
changes the backing file of 'source' to 'backing_file'
If backing_file is specified as "" (the empty string),
then the image is rebased onto no backing file
(i.e. it will exist independently of any backing file).
(Taken fr... | changes the backing file of 'source' to 'backing_file'
If backing_file is specified as "" (the empty string),
then the image is rebased onto no backing file
(i.e. it will exist independently of any backing file).
(Taken from qemu-img man page)
Args:
target(str): Path to the source disk
... | Below is the the instruction that describes the task:
### Input:
changes the backing file of 'source' to 'backing_file'
If backing_file is specified as "" (the empty string),
then the image is rebased onto no backing file
(i.e. it will exist independently of any backing file).
(Taken from qemu-img m... |
def to_canstrat(self, key, log, lith_field, filename=None, as_text=False):
"""
Make a Canstrat DAT (aka ASCII) file.
TODO:
The data part should probably belong to striplog, and only the
header should be written by the well.
Args:
filename (str)
... | Make a Canstrat DAT (aka ASCII) file.
TODO:
The data part should probably belong to striplog, and only the
header should be written by the well.
Args:
filename (str)
key (str)
log (str): the log name, should be 6 characters.
lith_fiel... | Below is the the instruction that describes the task:
### Input:
Make a Canstrat DAT (aka ASCII) file.
TODO:
The data part should probably belong to striplog, and only the
header should be written by the well.
Args:
filename (str)
key (str)
... |
def tau_reduction(ms, rate, n_per_decade):
"""Reduce the number of taus to maximum of n per decade (Helper function)
takes in a tau list and reduces the number of taus to a maximum amount per
decade. This is only useful if more than the "decade" and "octave" but
less than the "all" taus are wanted. E.g... | Reduce the number of taus to maximum of n per decade (Helper function)
takes in a tau list and reduces the number of taus to a maximum amount per
decade. This is only useful if more than the "decade" and "octave" but
less than the "all" taus are wanted. E.g. to show certain features of
the data one mig... | Below is the the instruction that describes the task:
### Input:
Reduce the number of taus to maximum of n per decade (Helper function)
takes in a tau list and reduces the number of taus to a maximum amount per
decade. This is only useful if more than the "decade" and "octave" but
less than the "all" t... |
def clean_build(self):
"""Delete the build directory and all ingested files """
import shutil
if self.build_fs.exists:
try:
shutil.rmtree(self.build_fs.getsyspath('/'))
except NoSysPathError:
pass | Delete the build directory and all ingested files | Below is the the instruction that describes the task:
### Input:
Delete the build directory and all ingested files
### Response:
def clean_build(self):
"""Delete the build directory and all ingested files """
import shutil
if self.build_fs.exists:
try:
shutil.rm... |
async def main():
"""Run."""
async with ClientSession() as websession:
try:
# Create a client:
client = Client('<EMAIL>', '<PASSWORD>', websession)
await client.async_init()
print('Showing active Tiles:')
print(await client.tiles.all())
... | Run. | Below is the the instruction that describes the task:
### Input:
Run.
### Response:
async def main():
"""Run."""
async with ClientSession() as websession:
try:
# Create a client:
client = Client('<EMAIL>', '<PASSWORD>', websession)
await client.async_init()
... |
def plan_results(self, project_key, plan_key, expand=None, favourite=False, clover_enabled=False, label=None,
issue_key=None, start_index=0, max_results=25):
"""
Get Plan results
:param project_key:
:param plan_key:
:param expand:
:param favourite:
... | Get Plan results
:param project_key:
:param plan_key:
:param expand:
:param favourite:
:param clover_enabled:
:param label:
:param issue_key:
:param start_index:
:param max_results:
:return: | Below is the the instruction that describes the task:
### Input:
Get Plan results
:param project_key:
:param plan_key:
:param expand:
:param favourite:
:param clover_enabled:
:param label:
:param issue_key:
:param start_index:
:param max_result... |
def port_tag_details(cls, tags):
# type: (Sequence[str]) -> Union[Tuple[bool, Port, str], None]
"""Search tags for port info, returning it
Args:
tags: A list of tags to check
Returns:
None or (is_source, port, connected_value|disconnected_value)
wher... | Search tags for port info, returning it
Args:
tags: A list of tags to check
Returns:
None or (is_source, port, connected_value|disconnected_value)
where port is one of the Enum entries of Port | Below is the the instruction that describes the task:
### Input:
Search tags for port info, returning it
Args:
tags: A list of tags to check
Returns:
None or (is_source, port, connected_value|disconnected_value)
where port is one of the Enum entries of Port
### ... |
def _configure(cls, **defaults):
"""Updates class-level defaults for :class:`_Options` container."""
for attr in defaults:
setattr(cls, attr, defaults[attr]) | Updates class-level defaults for :class:`_Options` container. | Below is the the instruction that describes the task:
### Input:
Updates class-level defaults for :class:`_Options` container.
### Response:
def _configure(cls, **defaults):
"""Updates class-level defaults for :class:`_Options` container."""
for attr in defaults:
setattr(cls, attr, defa... |
def moduli_to_velocities(rho, K_s, G):
"""
convert moduli to velocities
mainly to support Burnman operations
:param rho: density in kg/m^3
:param v_phi: adiabatic bulk modulus in Pa
:param v_s: shear modulus in Pa
:return: bulk sound speed and shear velocity
"""
return np.sqrt(K_s /... | convert moduli to velocities
mainly to support Burnman operations
:param rho: density in kg/m^3
:param v_phi: adiabatic bulk modulus in Pa
:param v_s: shear modulus in Pa
:return: bulk sound speed and shear velocity | Below is the the instruction that describes the task:
### Input:
convert moduli to velocities
mainly to support Burnman operations
:param rho: density in kg/m^3
:param v_phi: adiabatic bulk modulus in Pa
:param v_s: shear modulus in Pa
:return: bulk sound speed and shear velocity
### Response: ... |
def segment_content_handler():
"""Build a `~xml.sax.handlers.ContentHandler` to read segment XML tables
"""
from ligo.lw.lsctables import (SegmentTable, SegmentDefTable,
SegmentSumTable)
from ligo.lw.ligolw import PartialLIGOLWContentHandler
def _filter(name, attr... | Build a `~xml.sax.handlers.ContentHandler` to read segment XML tables | Below is the the instruction that describes the task:
### Input:
Build a `~xml.sax.handlers.ContentHandler` to read segment XML tables
### Response:
def segment_content_handler():
"""Build a `~xml.sax.handlers.ContentHandler` to read segment XML tables
"""
from ligo.lw.lsctables import (SegmentTable, S... |
def group_join(
self,
inner_enumerable,
outer_key=lambda x: x,
inner_key=lambda x: x,
result_func=lambda x: x
):
"""
Return enumerable of group join between two enumerables
:param inner_enumerable: inner enumerable to join to self
... | Return enumerable of group join between two enumerables
:param inner_enumerable: inner enumerable to join to self
:param outer_key: key selector of outer enumerable as lambda expression
:param inner_key: key selector of inner enumerable as lambda expression
:param result_func: lambda exp... | Below is the the instruction that describes the task:
### Input:
Return enumerable of group join between two enumerables
:param inner_enumerable: inner enumerable to join to self
:param outer_key: key selector of outer enumerable as lambda expression
:param inner_key: key selector of inner e... |
def _unicode(self):
'''This returns a printable representation of the screen as a unicode
string (which, under Python 3.x, is the same as 'str'). The end of each
screen line is terminated by a newline.'''
return u'\n'.join ([ u''.join(c) for c in self.w ]) | This returns a printable representation of the screen as a unicode
string (which, under Python 3.x, is the same as 'str'). The end of each
screen line is terminated by a newline. | Below is the the instruction that describes the task:
### Input:
This returns a printable representation of the screen as a unicode
string (which, under Python 3.x, is the same as 'str'). The end of each
screen line is terminated by a newline.
### Response:
def _unicode(self):
'''This retur... |
def term_with_coeff(term, coeff):
"""
Change the coefficient of a PauliTerm.
:param PauliTerm term: A PauliTerm object
:param Number coeff: The coefficient to set on the PauliTerm
:returns: A new PauliTerm that duplicates term but sets coeff
:rtype: PauliTerm
"""
if not isinstance(coeff... | Change the coefficient of a PauliTerm.
:param PauliTerm term: A PauliTerm object
:param Number coeff: The coefficient to set on the PauliTerm
:returns: A new PauliTerm that duplicates term but sets coeff
:rtype: PauliTerm | Below is the the instruction that describes the task:
### Input:
Change the coefficient of a PauliTerm.
:param PauliTerm term: A PauliTerm object
:param Number coeff: The coefficient to set on the PauliTerm
:returns: A new PauliTerm that duplicates term but sets coeff
:rtype: PauliTerm
### Response... |
def _assert_explicit_vr(dicom_input):
"""
Assert that explicit vr is used
"""
if settings.validate_multiframe_implicit:
header = dicom_input[0]
if header.file_meta[0x0002, 0x0010].value == '1.2.840.10008.1.2':
raise ConversionError('IMPLICIT_VR_ENHANCED_DICOM') | Assert that explicit vr is used | Below is the the instruction that describes the task:
### Input:
Assert that explicit vr is used
### Response:
def _assert_explicit_vr(dicom_input):
"""
Assert that explicit vr is used
"""
if settings.validate_multiframe_implicit:
header = dicom_input[0]
if header.file_meta[0x0002, ... |
def is_equivalent(self, other):
"""
Return ``True`` if the IPA character is equivalent to the ``other`` object.
The ``other`` object can be:
1. a Unicode string, containing the representation of the IPA character,
2. a Unicode string, containing a space-separated list of descri... | Return ``True`` if the IPA character is equivalent to the ``other`` object.
The ``other`` object can be:
1. a Unicode string, containing the representation of the IPA character,
2. a Unicode string, containing a space-separated list of descriptors,
3. a list of Unicode strings, contain... | Below is the the instruction that describes the task:
### Input:
Return ``True`` if the IPA character is equivalent to the ``other`` object.
The ``other`` object can be:
1. a Unicode string, containing the representation of the IPA character,
2. a Unicode string, containing a space-separat... |
def _find_spelling_errors_in_chunks(chunks,
contents,
valid_words_dictionary=None,
technical_words_dictionary=None,
user_dictionary_words=None):
"""For each chunk and a set... | For each chunk and a set of valid and technical words, find errors. | Below is the the instruction that describes the task:
### Input:
For each chunk and a set of valid and technical words, find errors.
### Response:
def _find_spelling_errors_in_chunks(chunks,
contents,
valid_words_dictionary=None,
... |
def set_as_error(self, color=Qt.red):
"""
Highlights text as a syntax error.
:param color: Underline color
:type color: QtGui.QColor
"""
self.format.setUnderlineStyle(
QTextCharFormat.WaveUnderline)
self.format.setUnderlineColor(color) | Highlights text as a syntax error.
:param color: Underline color
:type color: QtGui.QColor | Below is the the instruction that describes the task:
### Input:
Highlights text as a syntax error.
:param color: Underline color
:type color: QtGui.QColor
### Response:
def set_as_error(self, color=Qt.red):
"""
Highlights text as a syntax error.
:param color: Underline co... |
def choose_parent_view(self, request):
"""
Instantiates a class-based view to provide a view that allows a parent
page to be chosen for a new object, where the assigned model extends
Wagtail's Page model, and there is more than one potential parent for
new instances. The view cla... | Instantiates a class-based view to provide a view that allows a parent
page to be chosen for a new object, where the assigned model extends
Wagtail's Page model, and there is more than one potential parent for
new instances. The view class used can be overridden by changing the
'choose_p... | Below is the the instruction that describes the task:
### Input:
Instantiates a class-based view to provide a view that allows a parent
page to be chosen for a new object, where the assigned model extends
Wagtail's Page model, and there is more than one potential parent for
new instances. Th... |
def order_by(self, order_attribute):
''' Return the list of items in a certain order '''
to_return = []
for f in sorted(self.items, key=lambda i: getattr(i, order_attribute)):
to_return.append(f)
return to_return | Return the list of items in a certain order | Below is the the instruction that describes the task:
### Input:
Return the list of items in a certain order
### Response:
def order_by(self, order_attribute):
''' Return the list of items in a certain order '''
to_return = []
for f in sorted(self.items, key=lambda i: getattr(i, order_attri... |
def MakeSuiteFromHist(hist, name=None):
"""Makes a normalized suite from a Hist object.
Args:
hist: Hist object
name: string name
Returns:
Suite object
"""
if name is None:
name = hist.name
# make a copy of the dictionary
d = dict(hist.GetDict())
return... | Makes a normalized suite from a Hist object.
Args:
hist: Hist object
name: string name
Returns:
Suite object | Below is the the instruction that describes the task:
### Input:
Makes a normalized suite from a Hist object.
Args:
hist: Hist object
name: string name
Returns:
Suite object
### Response:
def MakeSuiteFromHist(hist, name=None):
"""Makes a normalized suite from a Hist object.
... |
def clean(args):
"""
%prog clean
Removes all symlinks from current folder
"""
p = OptionParser(clean.__doc__)
opts, args = p.parse_args(args)
for link_name in os.listdir(os.getcwd()):
if not op.islink(link_name):
continue
logging.debug("remove symlink `{0}`".for... | %prog clean
Removes all symlinks from current folder | Below is the the instruction that describes the task:
### Input:
%prog clean
Removes all symlinks from current folder
### Response:
def clean(args):
"""
%prog clean
Removes all symlinks from current folder
"""
p = OptionParser(clean.__doc__)
opts, args = p.parse_args(args)
for li... |
def prefix_items(self, prefix, strip_prefix=False):
"""Get all (key, value) pairs with keys that begin with ``prefix``.
:param prefix: Lexical prefix for keys to search.
:type prefix: bytes
:param strip_prefix: True to strip the prefix from yielded items.
:type strip_prefix: bo... | Get all (key, value) pairs with keys that begin with ``prefix``.
:param prefix: Lexical prefix for keys to search.
:type prefix: bytes
:param strip_prefix: True to strip the prefix from yielded items.
:type strip_prefix: bool
:yields: All (key, value) pairs in the store where ... | Below is the the instruction that describes the task:
### Input:
Get all (key, value) pairs with keys that begin with ``prefix``.
:param prefix: Lexical prefix for keys to search.
:type prefix: bytes
:param strip_prefix: True to strip the prefix from yielded items.
:type strip_pref... |
def action(args):
"""Roll back commands on a refpkg.
*args* should be an argparse object with fields refpkg (giving the
path to the refpkg to operate on) and n (giving the number of
operations to roll back).
"""
log.info('loading reference package')
r = refpkg.Refpkg(args.refpkg, create=Fa... | Roll back commands on a refpkg.
*args* should be an argparse object with fields refpkg (giving the
path to the refpkg to operate on) and n (giving the number of
operations to roll back). | Below is the the instruction that describes the task:
### Input:
Roll back commands on a refpkg.
*args* should be an argparse object with fields refpkg (giving the
path to the refpkg to operate on) and n (giving the number of
operations to roll back).
### Response:
def action(args):
"""Roll back c... |
def on_created(self, event, dry_run=False, remove_uploaded=True):
'Called when a file (or directory) is created. '
super(ArchiveEventHandler, self).on_created(event)
log.info("created: %s", event) | Called when a file (or directory) is created. | Below is the the instruction that describes the task:
### Input:
Called when a file (or directory) is created.
### Response:
def on_created(self, event, dry_run=False, remove_uploaded=True):
'Called when a file (or directory) is created. '
super(ArchiveEventHandler, self).on_created(event)
... |
def mouseUp(x=None, y=None, button='left', duration=0.0, tween=linear, pause=None, _pause=True):
"""Performs releasing a mouse button up (but not down beforehand).
The x and y parameters detail where the mouse event happens. If None, the
current mouse position is used. If a float value, it is rounded down.... | Performs releasing a mouse button up (but not down beforehand).
The x and y parameters detail where the mouse event happens. If None, the
current mouse position is used. If a float value, it is rounded down. If
outside the boundaries of the screen, the event happens at edge of the
screen.
Args:
... | Below is the the instruction that describes the task:
### Input:
Performs releasing a mouse button up (but not down beforehand).
The x and y parameters detail where the mouse event happens. If None, the
current mouse position is used. If a float value, it is rounded down. If
outside the boundaries of t... |
def value(self):
"""returns object as dictionary"""
return {
"type" : "simple",
"symbol" : self.symbol.value,
"label" : self.label,
"description" : self.description,
"rotationType": self.rotationType,
"rotationExpression"... | returns object as dictionary | Below is the the instruction that describes the task:
### Input:
returns object as dictionary
### Response:
def value(self):
"""returns object as dictionary"""
return {
"type" : "simple",
"symbol" : self.symbol.value,
"label" : self.label,
"des... |
async def get_box_ids_json(self) -> str:
"""
Return json object on lists of all unique box identifiers for credentials in wallet:
schema identifiers, credential definition identifiers, and revocation registry identifiers; e.g.,
::
{
"schema_id": [
"R... | Return json object on lists of all unique box identifiers for credentials in wallet:
schema identifiers, credential definition identifiers, and revocation registry identifiers; e.g.,
::
{
"schema_id": [
"R17v42T4pk...:2:tombstone:1.2",
"9cHbp54C8n...... | Below is the the instruction that describes the task:
### Input:
Return json object on lists of all unique box identifiers for credentials in wallet:
schema identifiers, credential definition identifiers, and revocation registry identifiers; e.g.,
::
{
"schema_id": [
... |
def move(src, dest, user=None):
"""
Move or rename src to dest.
"""
src_host, src_port, src_path = path.split(src, user)
dest_host, dest_port, dest_path = path.split(dest, user)
src_fs = hdfs(src_host, src_port, user)
dest_fs = hdfs(dest_host, dest_port, user)
try:
retval = src_f... | Move or rename src to dest. | Below is the the instruction that describes the task:
### Input:
Move or rename src to dest.
### Response:
def move(src, dest, user=None):
"""
Move or rename src to dest.
"""
src_host, src_port, src_path = path.split(src, user)
dest_host, dest_port, dest_path = path.split(dest, user)
src_fs... |
def do_flipper(parser, token):
"""The flipper tag takes two arguments: the user to look up and the feature
to compare against.
"""
nodelist = parser.parse(('endflipper',))
tag_name, user_key, feature = token.split_contents()
parser.delete_first_token()
return FlipperNode(nodelist, user_key, ... | The flipper tag takes two arguments: the user to look up and the feature
to compare against. | Below is the the instruction that describes the task:
### Input:
The flipper tag takes two arguments: the user to look up and the feature
to compare against.
### Response:
def do_flipper(parser, token):
"""The flipper tag takes two arguments: the user to look up and the feature
to compare against.
... |
def validate_values(self, definition):
"""This function checks that the fields have the correct values.
:param definition: the dictionary containing the scalar properties.
:raises ParserError: if a scalar definition field contains an unexpected value.
"""
if not self._strict_ty... | This function checks that the fields have the correct values.
:param definition: the dictionary containing the scalar properties.
:raises ParserError: if a scalar definition field contains an unexpected value. | Below is the the instruction that describes the task:
### Input:
This function checks that the fields have the correct values.
:param definition: the dictionary containing the scalar properties.
:raises ParserError: if a scalar definition field contains an unexpected value.
### Response:
def valid... |
def draw_noisy_time_series(self, SNR=1.0, red_noise_ratio=0.25, outlier_ratio=0.0):
"""
A function to draw a noisy time series based on the clean model
such that
y_noisy = y + yw + yr,
where yw is white noise, yr is red noise and y will be rescaled
so that y_noisy ... | A function to draw a noisy time series based on the clean model
such that
y_noisy = y + yw + yr,
where yw is white noise, yr is red noise and y will be rescaled
so that y_noisy complies with the specified signal-to-noise
ratio (SNR).
Parameters
-... | Below is the the instruction that describes the task:
### Input:
A function to draw a noisy time series based on the clean model
such that
y_noisy = y + yw + yr,
where yw is white noise, yr is red noise and y will be rescaled
so that y_noisy complies with the specified signal-... |
def remove_task_db(self, fid, force=False):
'''将任务从数据库中删除'''
self.remove_slice_db(fid)
sql = 'DELETE FROM upload WHERE fid=?'
self.cursor.execute(sql, [fid, ])
self.check_commit(force=force) | 将任务从数据库中删除 | Below is the the instruction that describes the task:
### Input:
将任务从数据库中删除
### Response:
def remove_task_db(self, fid, force=False):
'''将任务从数据库中删除'''
self.remove_slice_db(fid)
sql = 'DELETE FROM upload WHERE fid=?'
self.cursor.execute(sql, [fid, ])
self.check_commit(force=f... |
def migrate_abci_chain(self):
"""Generate and record a new ABCI chain ID. New blocks are not
accepted until we receive an InitChain ABCI request with
the matching chain ID and validator set.
Chain ID is generated based on the current chain and height.
`chain-X` => `chain-X-migra... | Generate and record a new ABCI chain ID. New blocks are not
accepted until we receive an InitChain ABCI request with
the matching chain ID and validator set.
Chain ID is generated based on the current chain and height.
`chain-X` => `chain-X-migrated-at-height-5`.
`chain-X-migrat... | Below is the the instruction that describes the task:
### Input:
Generate and record a new ABCI chain ID. New blocks are not
accepted until we receive an InitChain ABCI request with
the matching chain ID and validator set.
Chain ID is generated based on the current chain and height.
... |
def dict_to_source(dict):
'''
Transform a dict with key 'citation' into a :class:`Source`.
If the argument passed is already a :class:`Source`, this method just
returns the argument.
'''
if isinstance(dict, Source):
return dict
return Source(
dict['citation'],
dict.... | Transform a dict with key 'citation' into a :class:`Source`.
If the argument passed is already a :class:`Source`, this method just
returns the argument. | Below is the the instruction that describes the task:
### Input:
Transform a dict with key 'citation' into a :class:`Source`.
If the argument passed is already a :class:`Source`, this method just
returns the argument.
### Response:
def dict_to_source(dict):
'''
Transform a dict with key 'citation'... |
def GetFileSystems():
"""Make syscalls to get the mounted filesystems.
Returns:
A list of Struct objects.
Based on the information for getfsstat
http://developer.apple.com/library/mac/#documentation/Darwin/
Reference/ManPages/man2/getfsstat.2.html
"""
version = OSXVersion()
major, minor = ve... | Make syscalls to get the mounted filesystems.
Returns:
A list of Struct objects.
Based on the information for getfsstat
http://developer.apple.com/library/mac/#documentation/Darwin/
Reference/ManPages/man2/getfsstat.2.html | Below is the the instruction that describes the task:
### Input:
Make syscalls to get the mounted filesystems.
Returns:
A list of Struct objects.
Based on the information for getfsstat
http://developer.apple.com/library/mac/#documentation/Darwin/
Reference/ManPages/man2/getfsstat.2.html
### Resp... |
def get_parent_until(path):
"""
Given a file path, determine the full module path.
e.g. '/usr/lib/python2.7/dist-packages/numpy/core/__init__.pyc' yields
'numpy.core'
"""
dirname = osp.dirname(path)
try:
mod = osp.basename(path)
mod = osp.splitext(mod)[0]
imp.find_mo... | Given a file path, determine the full module path.
e.g. '/usr/lib/python2.7/dist-packages/numpy/core/__init__.pyc' yields
'numpy.core' | Below is the the instruction that describes the task:
### Input:
Given a file path, determine the full module path.
e.g. '/usr/lib/python2.7/dist-packages/numpy/core/__init__.pyc' yields
'numpy.core'
### Response:
def get_parent_until(path):
"""
Given a file path, determine the full module path.
... |
def report_idle_after(seconds):
"""Report_idle_after after certain number of seconds."""
def decorator(func):
def wrapper(*args, **kwargs):
def _handle_timeout(signum, frame):
config = get_config()
if not config.ready:
config.load()
... | Report_idle_after after certain number of seconds. | Below is the the instruction that describes the task:
### Input:
Report_idle_after after certain number of seconds.
### Response:
def report_idle_after(seconds):
"""Report_idle_after after certain number of seconds."""
def decorator(func):
def wrapper(*args, **kwargs):
def _handle_time... |
def union(self, other, left_name="LEFT", right_name="RIGHT"):
"""
*Wrapper of* ``UNION``
The UNION operation is used to integrate homogeneous or heterogeneous samples of two
datasets within a single dataset; for each sample of either one of the input datasets, a
sample is create... | *Wrapper of* ``UNION``
The UNION operation is used to integrate homogeneous or heterogeneous samples of two
datasets within a single dataset; for each sample of either one of the input datasets, a
sample is created in the result as follows:
* its metadata are the same as in... | Below is the the instruction that describes the task:
### Input:
*Wrapper of* ``UNION``
The UNION operation is used to integrate homogeneous or heterogeneous samples of two
datasets within a single dataset; for each sample of either one of the input datasets, a
sample is created in the resu... |
def get_uncompleted_tasks(self):
"""Return a list of all uncompleted tasks in this project.
.. warning:: Requires Todoist premium.
:return: A list of all uncompleted tasks in this project.
:rtype: list of :class:`pytodoist.todoist.Task`
>>> from pytodoist import todoist
... | Return a list of all uncompleted tasks in this project.
.. warning:: Requires Todoist premium.
:return: A list of all uncompleted tasks in this project.
:rtype: list of :class:`pytodoist.todoist.Task`
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.c... | Below is the the instruction that describes the task:
### Input:
Return a list of all uncompleted tasks in this project.
.. warning:: Requires Todoist premium.
:return: A list of all uncompleted tasks in this project.
:rtype: list of :class:`pytodoist.todoist.Task`
>>> from pytodo... |
def concretize_load_idx(self, idx, strategies=None):
"""
Concretizes a load index.
:param idx: An expression for the index.
:param strategies: A list of concretization strategies (to override the default).
:param min_idx: Minimum value for a concretized ... | Concretizes a load index.
:param idx: An expression for the index.
:param strategies: A list of concretization strategies (to override the default).
:param min_idx: Minimum value for a concretized index (inclusive).
:param max_idx: Maximum value for a co... | Below is the the instruction that describes the task:
### Input:
Concretizes a load index.
:param idx: An expression for the index.
:param strategies: A list of concretization strategies (to override the default).
:param min_idx: Minimum value for a concretized inde... |
def parse_data_df(data_dset, ridx, cidx, row_meta, col_meta):
"""
Parses in data_df from hdf5, subsetting if specified.
Input:
-data_dset (h5py dset): HDF5 dataset from which to read data_df
-ridx (list): list of indexes to subset from data_df
(may be all of them if no subsettin... | Parses in data_df from hdf5, subsetting if specified.
Input:
-data_dset (h5py dset): HDF5 dataset from which to read data_df
-ridx (list): list of indexes to subset from data_df
(may be all of them if no subsetting)
-cidx (list): list of indexes to subset from data_df
... | Below is the the instruction that describes the task:
### Input:
Parses in data_df from hdf5, subsetting if specified.
Input:
-data_dset (h5py dset): HDF5 dataset from which to read data_df
-ridx (list): list of indexes to subset from data_df
(may be all of them if no subsetting)
... |
def ms_panset(self, viewer, event, data_x, data_y,
msg=True):
"""An interactive way to set the pan position. The location
(data_x, data_y) will be centered in the window.
"""
if self.canpan and (event.state == 'down'):
self._panset(viewer, data_x, data_y, m... | An interactive way to set the pan position. The location
(data_x, data_y) will be centered in the window. | Below is the the instruction that describes the task:
### Input:
An interactive way to set the pan position. The location
(data_x, data_y) will be centered in the window.
### Response:
def ms_panset(self, viewer, event, data_x, data_y,
msg=True):
"""An interactive way to set the ... |
def capture_output_from_running_process(context: RunContext) -> None:
"""
Parses output from a running sub-process
Decodes and filters the process output line by line, buffering it
If "mute" is False, sends the output back in real time
:param context: run context
:type context: _RunContext
... | Parses output from a running sub-process
Decodes and filters the process output line by line, buffering it
If "mute" is False, sends the output back in real time
:param context: run context
:type context: _RunContext | Below is the the instruction that describes the task:
### Input:
Parses output from a running sub-process
Decodes and filters the process output line by line, buffering it
If "mute" is False, sends the output back in real time
:param context: run context
:type context: _RunContext
### Response:
... |
def compare_last_two_snapshots(obj, raw=False):
"""Helper to compare the last two snapshots directly
"""
if get_snapshot_count(obj) < 2:
return {}
version = get_version(obj)
snap1 = get_snapshot_by_version(obj, version - 1)
snap2 = get_snapshot_by_version(obj, version)
return com... | Helper to compare the last two snapshots directly | Below is the the instruction that describes the task:
### Input:
Helper to compare the last two snapshots directly
### Response:
def compare_last_two_snapshots(obj, raw=False):
"""Helper to compare the last two snapshots directly
"""
if get_snapshot_count(obj) < 2:
return {}
version = get... |
def get_scalingip(context, id, fields=None):
"""Retrieve a scaling IP.
:param context: neutron api request context.
:param id: The UUID of the scaling IP.
:param fields: a list of strings that are valid keys in a
scaling IP dictionary as listed in the RESOURCE_ATTRIBUTE_MAP
object in ne... | Retrieve a scaling IP.
:param context: neutron api request context.
:param id: The UUID of the scaling IP.
:param fields: a list of strings that are valid keys in a
scaling IP dictionary as listed in the RESOURCE_ATTRIBUTE_MAP
object in neutron/api/v2/attributes.py. Only these fields
... | Below is the the instruction that describes the task:
### Input:
Retrieve a scaling IP.
:param context: neutron api request context.
:param id: The UUID of the scaling IP.
:param fields: a list of strings that are valid keys in a
scaling IP dictionary as listed in the RESOURCE_ATTRIBUTE_MAP
... |
def conservtion_profile_pid(region, genome_alignment,
mi_seqs=MissingSequenceHandler.TREAT_AS_ALL_GAPS,
species=None):
"""
build a conservation profile for the given region using the genome alignment.
The scores in the profile will be the percent of bases i... | build a conservation profile for the given region using the genome alignment.
The scores in the profile will be the percent of bases identical to the
reference sequence.
:param miss_seqs: how to treat sequence with no actual sequence data for
the column.
:return: a list of the same length ... | Below is the the instruction that describes the task:
### Input:
build a conservation profile for the given region using the genome alignment.
The scores in the profile will be the percent of bases identical to the
reference sequence.
:param miss_seqs: how to treat sequence with no actual sequence data for
... |
def parse_attr_signature(sig):
""" Parse an attribute signature """
match = ATTR_SIG_RE.match(sig.strip())
if not match:
raise RuntimeError('Attribute signature invalid, got ' + sig)
name, _, params = match.groups()
if params is not None and params.strip() != '':
params = split_sig(p... | Parse an attribute signature | Below is the the instruction that describes the task:
### Input:
Parse an attribute signature
### Response:
def parse_attr_signature(sig):
""" Parse an attribute signature """
match = ATTR_SIG_RE.match(sig.strip())
if not match:
raise RuntimeError('Attribute signature invalid, got ' + sig)
... |
def TriToBin(self, x, y, z):
'''
Turn an x-y-z triangular coord to an a-b coord.
if z is negative, calc with its abs then return (a, -b).
:param x,y,z: the three numbers of the triangular coord
:type x,y,z: float or double are both OK, just numbers
:return: the correspo... | Turn an x-y-z triangular coord to an a-b coord.
if z is negative, calc with its abs then return (a, -b).
:param x,y,z: the three numbers of the triangular coord
:type x,y,z: float or double are both OK, just numbers
:return: the corresponding a-b coord
:rtype: a tuple consist ... | Below is the the instruction that describes the task:
### Input:
Turn an x-y-z triangular coord to an a-b coord.
if z is negative, calc with its abs then return (a, -b).
:param x,y,z: the three numbers of the triangular coord
:type x,y,z: float or double are both OK, just numbers
:re... |
def validate_oath_hotp(self, params):
"""
Validate OATH-HOTP code using YubiHSM HMAC-SHA1 hashing with token keys
secured in AEAD's that we have stored in an SQLite3 database.
"""
from_key = params["hotp"][0]
if not re.match(hotp_valid_input, from_key):
self.log_error("IN: %s, Invalid OA... | Validate OATH-HOTP code using YubiHSM HMAC-SHA1 hashing with token keys
secured in AEAD's that we have stored in an SQLite3 database. | Below is the the instruction that describes the task:
### Input:
Validate OATH-HOTP code using YubiHSM HMAC-SHA1 hashing with token keys
secured in AEAD's that we have stored in an SQLite3 database.
### Response:
def validate_oath_hotp(self, params):
"""
Validate OATH-HOTP code using YubiHSM HMAC-SHA1 ... |
def smooth_n_point(scalar_grid, n=5, passes=1):
"""Filter with normal distribution of weights.
Parameters
----------
scalar_grid : array-like or `pint.Quantity`
Some 2D scalar grid to be smoothed.
n: int
The number of points to use in smoothing, only valid inputs
are 5 and ... | Filter with normal distribution of weights.
Parameters
----------
scalar_grid : array-like or `pint.Quantity`
Some 2D scalar grid to be smoothed.
n: int
The number of points to use in smoothing, only valid inputs
are 5 and 9. Defaults to 5.
passes : int
The number ... | Below is the the instruction that describes the task:
### Input:
Filter with normal distribution of weights.
Parameters
----------
scalar_grid : array-like or `pint.Quantity`
Some 2D scalar grid to be smoothed.
n: int
The number of points to use in smoothing, only valid inputs
... |
def credits(self, **kwargs):
"""
Get the TV episode credits by combination of season and episode number.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_series_id_season_number_episode_number_path('credits')
response =... | Get the TV episode credits by combination of season and episode number.
Returns:
A dict respresentation of the JSON returned from the API. | Below is the the instruction that describes the task:
### Input:
Get the TV episode credits by combination of season and episode number.
Returns:
A dict respresentation of the JSON returned from the API.
### Response:
def credits(self, **kwargs):
"""
Get the TV episode credits ... |
def _totals(self, query):
""" General method for returning total counts
"""
self.add_parameters(limit=1)
query = self._build_query(query)
self._retrieve_data(query)
self.url_params = None
# extract the 'total items' figure
return int(self.request.headers["... | General method for returning total counts | Below is the the instruction that describes the task:
### Input:
General method for returning total counts
### Response:
def _totals(self, query):
""" General method for returning total counts
"""
self.add_parameters(limit=1)
query = self._build_query(query)
self._retrieve_d... |
def manual_dir(self):
"""Returns the directory containing the manually extracted data."""
if not tf.io.gfile.exists(self._manual_dir):
raise AssertionError(
'Manual directory {} does not exist. Create it and download/extract '
'dataset artifacts in there.'.format(self._manual_dir))
... | Returns the directory containing the manually extracted data. | Below is the the instruction that describes the task:
### Input:
Returns the directory containing the manually extracted data.
### Response:
def manual_dir(self):
"""Returns the directory containing the manually extracted data."""
if not tf.io.gfile.exists(self._manual_dir):
raise AssertionError(
... |
def is_mutating(status):
"""Determines if the statement is mutating based on the status."""
if not status:
return False
mutating = set(['insert', 'update', 'delete', 'alter', 'create', 'drop',
'replace', 'truncate', 'load'])
return status.split(None, 1)[0].lower() in mutatin... | Determines if the statement is mutating based on the status. | Below is the the instruction that describes the task:
### Input:
Determines if the statement is mutating based on the status.
### Response:
def is_mutating(status):
"""Determines if the statement is mutating based on the status."""
if not status:
return False
mutating = set(['insert', 'update'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.