code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def get_device_access_interfaces(devId):
"""Function takes devId as input to RESTFUL call to HP IMC platform
:param devId: requires deviceID as the only input parameter
:return: list of dictionaries containing interfaces configured as access ports
"""
# checks to see if the imc credentials are alrea... | Function takes devId as input to RESTFUL call to HP IMC platform
:param devId: requires deviceID as the only input parameter
:return: list of dictionaries containing interfaces configured as access ports | Below is the the instruction that describes the task:
### Input:
Function takes devId as input to RESTFUL call to HP IMC platform
:param devId: requires deviceID as the only input parameter
:return: list of dictionaries containing interfaces configured as access ports
### Response:
def get_device_access_in... |
def _query_data(data, field_names=None, operators='__eq__'):
"""Create a tinyDB Query object that looks for items that confirms the correspondent operator
from `operators` for each `field_names` field values from `data`.
Parameters
----------
data: dict
The data sample
field_names: str... | Create a tinyDB Query object that looks for items that confirms the correspondent operator
from `operators` for each `field_names` field values from `data`.
Parameters
----------
data: dict
The data sample
field_names: str or list of str
The name of the fields in `data` that will b... | Below is the the instruction that describes the task:
### Input:
Create a tinyDB Query object that looks for items that confirms the correspondent operator
from `operators` for each `field_names` field values from `data`.
Parameters
----------
data: dict
The data sample
field_names: st... |
def shutdown(self):
"""Close all file handles and stop all motors."""
self.stop_balance.set() # Stop balance thread
self.motor_left.stop()
self.motor_right.stop()
self.gyro_file.close()
self.touch_file.close()
self.encoder_left_file.close()
self.encoder_r... | Close all file handles and stop all motors. | Below is the the instruction that describes the task:
### Input:
Close all file handles and stop all motors.
### Response:
def shutdown(self):
"""Close all file handles and stop all motors."""
self.stop_balance.set() # Stop balance thread
self.motor_left.stop()
self.motor_right.sto... |
def get_record_revisions(recid, from_date):
"""Get record revisions."""
try:
from invenio.dbquery import run_sql
except ImportError:
from invenio.legacy.dbquery import run_sql
return run_sql(
'SELECT job_date, marcxml '
'FROM hstRECORD WHERE id_bibrec = %s AND job_date >... | Get record revisions. | Below is the the instruction that describes the task:
### Input:
Get record revisions.
### Response:
def get_record_revisions(recid, from_date):
"""Get record revisions."""
try:
from invenio.dbquery import run_sql
except ImportError:
from invenio.legacy.dbquery import run_sql
retur... |
def _set_packet_timestamp(self, v, load=False):
"""
Setter method for packet_timestamp, mapped from YANG variable /interface/port_channel/system/packet_timestamp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_packet_timestamp is considered as a private
m... | Setter method for packet_timestamp, mapped from YANG variable /interface/port_channel/system/packet_timestamp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_packet_timestamp is considered as a private
method. Backends looking to populate this variable should
... | Below is the the instruction that describes the task:
### Input:
Setter method for packet_timestamp, mapped from YANG variable /interface/port_channel/system/packet_timestamp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_packet_timestamp is considered as a priv... |
def grid_attrs_to_aospy_names(data, grid_attrs=None):
"""Rename grid attributes to be consistent with aospy conventions.
Search all of the dataset's coords and dims looking for matches to known
grid attribute names; any that are found subsequently get renamed to the
aospy name as specified in ``aospy.i... | Rename grid attributes to be consistent with aospy conventions.
Search all of the dataset's coords and dims looking for matches to known
grid attribute names; any that are found subsequently get renamed to the
aospy name as specified in ``aospy.internal_names.GRID_ATTRS``.
Also forces any renamed grid... | Below is the the instruction that describes the task:
### Input:
Rename grid attributes to be consistent with aospy conventions.
Search all of the dataset's coords and dims looking for matches to known
grid attribute names; any that are found subsequently get renamed to the
aospy name as specified in `... |
def insert_object_acl(self, bucket_name, object_name, entity, role, user_project=None):
"""
Creates a new ACL entry on the specified object.
See: https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/insert
:param bucket_name: Name of a bucket_name.
:type bucket... | Creates a new ACL entry on the specified object.
See: https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/insert
:param bucket_name: Name of a bucket_name.
:type bucket_name: str
:param object_name: Name of the object. For information about how to URL encode
... | Below is the the instruction that describes the task:
### Input:
Creates a new ACL entry on the specified object.
See: https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/insert
:param bucket_name: Name of a bucket_name.
:type bucket_name: str
:param object_name: ... |
def path(self):
"""
Serve gzip file if client accept it.
Generate or update the gzip file if needed.
"""
path = self._path()
statobj = os.stat(path)
ae = self.request.META.get('HTTP_ACCEPT_ENCODING', '')
if re_accepts_gzip.search(ae) and getattr(settings, ... | Serve gzip file if client accept it.
Generate or update the gzip file if needed. | Below is the the instruction that describes the task:
### Input:
Serve gzip file if client accept it.
Generate or update the gzip file if needed.
### Response:
def path(self):
"""
Serve gzip file if client accept it.
Generate or update the gzip file if needed.
"""
pa... |
def _cached_results(self, start_time, end_time):
"""
Retrieves cached results for any bucket that has a single cache entry.
If a bucket has two cache entries, there is a chance that two
different writers previously computed and cached a result since
Kronos has no transaction semantics. While it mi... | Retrieves cached results for any bucket that has a single cache entry.
If a bucket has two cache entries, there is a chance that two
different writers previously computed and cached a result since
Kronos has no transaction semantics. While it might be safe to
return one of the cached results if there ... | Below is the the instruction that describes the task:
### Input:
Retrieves cached results for any bucket that has a single cache entry.
If a bucket has two cache entries, there is a chance that two
different writers previously computed and cached a result since
Kronos has no transaction semantics. Whi... |
def __trim_extensions_dot(exts):
"""trim leading dots from extensions and drop any empty strings."""
if exts is None:
return None
res = []
for i in range(0, len(exts)):
if exts[i] == "":
continue
res.append(__trim_extension_dot(exts[i]))
return res | trim leading dots from extensions and drop any empty strings. | Below is the the instruction that describes the task:
### Input:
trim leading dots from extensions and drop any empty strings.
### Response:
def __trim_extensions_dot(exts):
"""trim leading dots from extensions and drop any empty strings."""
if exts is None:
return None
res = []
for i in range(0, len(e... |
def get_disabled():
'''
Return a set of services that are installed but disabled
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled
'''
(enabled_services, disabled_services) = _get_service_list(include_enabled=False,
... | Return a set of services that are installed but disabled
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled | Below is the the instruction that describes the task:
### Input:
Return a set of services that are installed but disabled
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled
### Response:
def get_disabled():
'''
Return a set of services that are installed but disabled
CL... |
def read(self, mode='color', alpha=True):
""" Return array of pixel values in an attached buffer
Parameters
----------
mode : str
The buffer type to read. May be 'color', 'depth', or 'stencil'.
alpha : bool
If True, returns RGBA array. Otherwise, ... | Return array of pixel values in an attached buffer
Parameters
----------
mode : str
The buffer type to read. May be 'color', 'depth', or 'stencil'.
alpha : bool
If True, returns RGBA array. Otherwise, returns RGB.
Returns
-------
... | Below is the the instruction that describes the task:
### Input:
Return array of pixel values in an attached buffer
Parameters
----------
mode : str
The buffer type to read. May be 'color', 'depth', or 'stencil'.
alpha : bool
If True, returns RGBA arr... |
def check_and_set_unreachability(self, hosts, services):
"""
Check if all dependencies are down, if yes set this object
as unreachable.
todo: this function do not care about execution_failure_criteria!
:param hosts: hosts objects, used to get object in act_depend_of
:ty... | Check if all dependencies are down, if yes set this object
as unreachable.
todo: this function do not care about execution_failure_criteria!
:param hosts: hosts objects, used to get object in act_depend_of
:type hosts: alignak.objects.host.Hosts
:param services: services object... | Below is the the instruction that describes the task:
### Input:
Check if all dependencies are down, if yes set this object
as unreachable.
todo: this function do not care about execution_failure_criteria!
:param hosts: hosts objects, used to get object in act_depend_of
:type hosts... |
def render_exception(error):
""" Catch-all renderer for the top-level exception handler """
_, _, category = str.partition(request.path, '/')
qsize = index.queue_length()
if isinstance(error, http_error.NotFound) and qsize:
response = flask.make_response(render_error(
category, "Sit... | Catch-all renderer for the top-level exception handler | Below is the the instruction that describes the task:
### Input:
Catch-all renderer for the top-level exception handler
### Response:
def render_exception(error):
""" Catch-all renderer for the top-level exception handler """
_, _, category = str.partition(request.path, '/')
qsize = index.queue_length... |
def analyze_reply_code(self, xml_response_dict):
"""
Checks the RETS Response Code and handles non-zero answers.
:param xml_response_dict:
:return: None
"""
if 'RETS-STATUS' in xml_response_dict:
attributes = self.get_attributes(xml_response_dict['RETS-STATUS'... | Checks the RETS Response Code and handles non-zero answers.
:param xml_response_dict:
:return: None | Below is the the instruction that describes the task:
### Input:
Checks the RETS Response Code and handles non-zero answers.
:param xml_response_dict:
:return: None
### Response:
def analyze_reply_code(self, xml_response_dict):
"""
Checks the RETS Response Code and handles non-zero ... |
def _read_hdr_dir(self):
"""Read the header for basic information.
Returns
-------
hdr : dict
- 'erd': header of .erd file
- 'stc': general part of .stc file
- 'stamps' : time stamp for each file
Also, it adds the attribute
_basename : Path... | Read the header for basic information.
Returns
-------
hdr : dict
- 'erd': header of .erd file
- 'stc': general part of .stc file
- 'stamps' : time stamp for each file
Also, it adds the attribute
_basename : Path
the name of the files i... | Below is the the instruction that describes the task:
### Input:
Read the header for basic information.
Returns
-------
hdr : dict
- 'erd': header of .erd file
- 'stc': general part of .stc file
- 'stamps' : time stamp for each file
Also, it adds the a... |
def merge(dict_1, dict_2):
"""Merge two dictionaries.
Values that evaluate to true take priority over falsy values.
`dict_1` takes priority over `dict_2`.
"""
return dict((str(key), dict_1.get(key) or dict_2.get(key))
for key in set(dict_2) | set(dict_1)) | Merge two dictionaries.
Values that evaluate to true take priority over falsy values.
`dict_1` takes priority over `dict_2`. | Below is the the instruction that describes the task:
### Input:
Merge two dictionaries.
Values that evaluate to true take priority over falsy values.
`dict_1` takes priority over `dict_2`.
### Response:
def merge(dict_1, dict_2):
"""Merge two dictionaries.
Values that evaluate to true take prior... |
def to_bytes(self):
'''
Return packed byte representation of the Ethernet header.
'''
return struct.pack(Ethernet._PACKFMT, self._dst.packed,
self._src.packed, self._ethertype.value) | Return packed byte representation of the Ethernet header. | Below is the the instruction that describes the task:
### Input:
Return packed byte representation of the Ethernet header.
### Response:
def to_bytes(self):
'''
Return packed byte representation of the Ethernet header.
'''
return struct.pack(Ethernet._PACKFMT, self._dst.packed,
... |
def is_critical_flow(P1, P2, k):
r'''Determines if a flow of a fluid driven by pressure gradient
P1 - P2 is critical, for a fluid with the given isentropic coefficient.
This function calculates critical flow pressure, and checks if this is
larger than P2. If so, the flow is critical and choked.
Par... | r'''Determines if a flow of a fluid driven by pressure gradient
P1 - P2 is critical, for a fluid with the given isentropic coefficient.
This function calculates critical flow pressure, and checks if this is
larger than P2. If so, the flow is critical and choked.
Parameters
----------
P1 : float... | Below is the the instruction that describes the task:
### Input:
r'''Determines if a flow of a fluid driven by pressure gradient
P1 - P2 is critical, for a fluid with the given isentropic coefficient.
This function calculates critical flow pressure, and checks if this is
larger than P2. If so, the flow ... |
def extract(self, member, path=None, pwd=None):
"""Extract a member from the archive to the current working directory,
using its full name. Its file information is extracted as accurately
as possible. `member' may be a filename or a RarInfo object. You can
specify a different di... | Extract a member from the archive to the current working directory,
using its full name. Its file information is extracted as accurately
as possible. `member' may be a filename or a RarInfo object. You can
specify a different directory using `path'. | Below is the the instruction that describes the task:
### Input:
Extract a member from the archive to the current working directory,
using its full name. Its file information is extracted as accurately
as possible. `member' may be a filename or a RarInfo object. You can
specify a di... |
def add_connectionmanager_api(mock):
'''Add org.ofono.ConnectionManager API to a mock'''
iface = 'org.ofono.ConnectionManager'
mock.AddProperties(iface, {
'Attached': _parameters.get('Attached', True),
'Bearer': _parameters.get('Bearer', 'gprs'),
'RoamingAllowed': _parameters.get('R... | Add org.ofono.ConnectionManager API to a mock | Below is the the instruction that describes the task:
### Input:
Add org.ofono.ConnectionManager API to a mock
### Response:
def add_connectionmanager_api(mock):
'''Add org.ofono.ConnectionManager API to a mock'''
iface = 'org.ofono.ConnectionManager'
mock.AddProperties(iface, {
'Attached': _p... |
def QA_fetch_ctp_tick(code, start, end, frequence, format='pd', collections=DATABASE.ctp_tick):
"""仅供存储的ctp tick使用
Arguments:
code {[type]} -- [description]
Keyword Arguments:
format {str} -- [description] (default: {'pd'})
collections {[type]} -- [description] (default: {DATABASE.... | 仅供存储的ctp tick使用
Arguments:
code {[type]} -- [description]
Keyword Arguments:
format {str} -- [description] (default: {'pd'})
collections {[type]} -- [description] (default: {DATABASE.ctp_tick})
Returns:
[type] -- [description] | Below is the the instruction that describes the task:
### Input:
仅供存储的ctp tick使用
Arguments:
code {[type]} -- [description]
Keyword Arguments:
format {str} -- [description] (default: {'pd'})
collections {[type]} -- [description] (default: {DATABASE.ctp_tick})
Returns:
[... |
def add(self, element):
"""Add an element to this set."""
key = self._transform(element)
if key not in self._elements:
self._elements[key] = element | Add an element to this set. | Below is the the instruction that describes the task:
### Input:
Add an element to this set.
### Response:
def add(self, element):
"""Add an element to this set."""
key = self._transform(element)
if key not in self._elements:
self._elements[key] = element |
def brand_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/brands#show-a-brand"
api_path = "/api/v2/brands/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/brands#show-a-brand | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/core/brands#show-a-brand
### Response:
def brand_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/brands#show-a-brand"
api_path = "/api/v2/brands/{id}.json"
... |
def get_instance():
"""Get a resource based on the application environment.
Returns a `Resource` configured for the current environment, or None if the
environment is unknown or unsupported.
:rtype: :class:`opencensus.common.resource.Resource` or None
:return: A `Resource` configured for the curre... | Get a resource based on the application environment.
Returns a `Resource` configured for the current environment, or None if the
environment is unknown or unsupported.
:rtype: :class:`opencensus.common.resource.Resource` or None
:return: A `Resource` configured for the current environment. | Below is the the instruction that describes the task:
### Input:
Get a resource based on the application environment.
Returns a `Resource` configured for the current environment, or None if the
environment is unknown or unsupported.
:rtype: :class:`opencensus.common.resource.Resource` or None
:ret... |
def vote(request, pollId, responseId):
"""Vote for a poll"""
username = request.args.get('ebuio_u_username')
# Remove old votes from the same user on the same poll
curDB.execute('DELETE FROM Vote WHERE username = ? AND responseId IN (SELECT id FROM Response WHERE pollId = ?) ', (username, pollId))
... | Vote for a poll | Below is the the instruction that describes the task:
### Input:
Vote for a poll
### Response:
def vote(request, pollId, responseId):
"""Vote for a poll"""
username = request.args.get('ebuio_u_username')
# Remove old votes from the same user on the same poll
curDB.execute('DELETE FROM Vote WHERE ... |
def add(self, labels, value):
"""Add adds a single observation to the summary."""
if type(value) not in (float, int):
raise TypeError("Summary only works with digits (int, float)")
# We have already a lock for data but not for the estimator
with mutex:
try:
... | Add adds a single observation to the summary. | Below is the the instruction that describes the task:
### Input:
Add adds a single observation to the summary.
### Response:
def add(self, labels, value):
"""Add adds a single observation to the summary."""
if type(value) not in (float, int):
raise TypeError("Summary only works with di... |
def wrap_xml(self, xml, encoding ='ISO-8859-1', standalone='no'):
"""
Method that provides a standard svg header string for a file
"""
header = '''<?xml version="1.0" encoding="%s" standalone="%s"?>''' %(encoding, standalone)
return header+xml | Method that provides a standard svg header string for a file | Below is the the instruction that describes the task:
### Input:
Method that provides a standard svg header string for a file
### Response:
def wrap_xml(self, xml, encoding ='ISO-8859-1', standalone='no'):
"""
Method that provides a standard svg header string for a file
"""
header =... |
def GetMethodConfig(self, method):
"""Returns service cached method config for given method."""
method_config = self._method_configs.get(method)
if method_config:
return method_config
func = getattr(self, method, None)
if func is None:
raise KeyError(metho... | Returns service cached method config for given method. | Below is the the instruction that describes the task:
### Input:
Returns service cached method config for given method.
### Response:
def GetMethodConfig(self, method):
"""Returns service cached method config for given method."""
method_config = self._method_configs.get(method)
if method_co... |
def randomwif(prefix, num):
""" Obtain a random private/public key pair
"""
from bitsharesbase.account import PrivateKey
t = [["wif", "pubkey"]]
for n in range(0, num):
wif = PrivateKey()
t.append([str(wif), format(wif.pubkey, prefix)])
print_table(t) | Obtain a random private/public key pair | Below is the the instruction that describes the task:
### Input:
Obtain a random private/public key pair
### Response:
def randomwif(prefix, num):
""" Obtain a random private/public key pair
"""
from bitsharesbase.account import PrivateKey
t = [["wif", "pubkey"]]
for n in range(0, num):
... |
def max(self, axis=None, skipna=True):
"""
Return the maximum value of the Index.
Parameters
----------
axis : int, optional
For compatibility with NumPy. Only 0 or None are allowed.
skipna : bool, default True
Returns
-------
scalar
... | Return the maximum value of the Index.
Parameters
----------
axis : int, optional
For compatibility with NumPy. Only 0 or None are allowed.
skipna : bool, default True
Returns
-------
scalar
Maximum value.
See Also
------... | Below is the the instruction that describes the task:
### Input:
Return the maximum value of the Index.
Parameters
----------
axis : int, optional
For compatibility with NumPy. Only 0 or None are allowed.
skipna : bool, default True
Returns
-------
... |
def delete_ip_address(context, id):
"""Delete an ip address.
: param context: neutron api request context
: param id: UUID representing the ip address to delete.
"""
LOG.info("delete_ip_address %s for tenant %s" % (id, context.tenant_id))
with context.session.begin():
ip_address = db_ap... | Delete an ip address.
: param context: neutron api request context
: param id: UUID representing the ip address to delete. | Below is the the instruction that describes the task:
### Input:
Delete an ip address.
: param context: neutron api request context
: param id: UUID representing the ip address to delete.
### Response:
def delete_ip_address(context, id):
"""Delete an ip address.
: param context: neutron api reque... |
def collect_api_results(input_data, url, headers, api, batch_size, kwargs):
"""
Optionally split up a single request into a series of requests
to ensure timely HTTP responses.
Could eventually speed up the time required to receive a response by
sending batches to the indico API concurrently
"""... | Optionally split up a single request into a series of requests
to ensure timely HTTP responses.
Could eventually speed up the time required to receive a response by
sending batches to the indico API concurrently | Below is the the instruction that describes the task:
### Input:
Optionally split up a single request into a series of requests
to ensure timely HTTP responses.
Could eventually speed up the time required to receive a response by
sending batches to the indico API concurrently
### Response:
def collect... |
def as_db_get(self, db_number):
"""
This is the asynchronous counterpart of Cli_DBGet.
"""
logger.debug("db_get db_number: %s" % db_number)
_buffer = buffer_type()
result = self.library.Cli_AsDBGet(self.pointer, db_number,
byref(_... | This is the asynchronous counterpart of Cli_DBGet. | Below is the the instruction that describes the task:
### Input:
This is the asynchronous counterpart of Cli_DBGet.
### Response:
def as_db_get(self, db_number):
"""
This is the asynchronous counterpart of Cli_DBGet.
"""
logger.debug("db_get db_number: %s" % db_number)
_buff... |
def execute_command(self, *args, **kwargs):
"""Execute a command on the connected server."""
try:
return self.get_connection().execute_command(*args, **kwargs)
except ConnectionError as e:
logger.warn('trying to reconnect')
self.connect()
logger.wa... | Execute a command on the connected server. | Below is the the instruction that describes the task:
### Input:
Execute a command on the connected server.
### Response:
def execute_command(self, *args, **kwargs):
"""Execute a command on the connected server."""
try:
return self.get_connection().execute_command(*args, **kwargs)
... |
def unix_to_wine(self, in_path):
"""
In: Absolute Unix path
Out: Absolute Wine path
"""
if len(in_path) > MAX_PATH:
raise # TODO
in_path_astr_p = ctypes.pointer(self.__str_to_winastr__(in_path))
out_path_ustr_p = ctypes.pointer(UNICODE_STRING())
ntstatus = self.__unix_to_wine__(
in_path_astr_p,... | In: Absolute Unix path
Out: Absolute Wine path | Below is the the instruction that describes the task:
### Input:
In: Absolute Unix path
Out: Absolute Wine path
### Response:
def unix_to_wine(self, in_path):
"""
In: Absolute Unix path
Out: Absolute Wine path
"""
if len(in_path) > MAX_PATH:
raise # TODO
in_path_astr_p = ctypes.pointer(self.__st... |
def get_ping(self, nonce: Nonce) -> bytes:
""" Returns a signed Ping message.
Note: Ping messages don't have an enforced ordering, so a Ping message
with a higher nonce may be acknowledged first.
"""
message = Ping(
nonce=nonce,
current_protocol_version=c... | Returns a signed Ping message.
Note: Ping messages don't have an enforced ordering, so a Ping message
with a higher nonce may be acknowledged first. | Below is the the instruction that describes the task:
### Input:
Returns a signed Ping message.
Note: Ping messages don't have an enforced ordering, so a Ping message
with a higher nonce may be acknowledged first.
### Response:
def get_ping(self, nonce: Nonce) -> bytes:
""" Returns a signe... |
def whitelisted(argument=None):
"""Decorates a method requiring that the requesting IP address is
whitelisted. Requires a whitelist value as a list in the
Application.settings dictionary. IP addresses can be an individual IP
address or a subnet.
Examples:
['10.0.0.0/8','192.168.1.0/24', '1.... | Decorates a method requiring that the requesting IP address is
whitelisted. Requires a whitelist value as a list in the
Application.settings dictionary. IP addresses can be an individual IP
address or a subnet.
Examples:
['10.0.0.0/8','192.168.1.0/24', '1.2.3.4/32']
:param list argument: L... | Below is the the instruction that describes the task:
### Input:
Decorates a method requiring that the requesting IP address is
whitelisted. Requires a whitelist value as a list in the
Application.settings dictionary. IP addresses can be an individual IP
address or a subnet.
Examples:
['10.... |
def _assert_contains(haystack, needle, invert, escape=False):
"""
Test for existence of ``needle`` regex within ``haystack``.
Say ``escape`` to escape the ``needle`` if you aren't really using the
regex feature & have special characters in it.
"""
myneedle = re.escape(needle) if escape else nee... | Test for existence of ``needle`` regex within ``haystack``.
Say ``escape`` to escape the ``needle`` if you aren't really using the
regex feature & have special characters in it. | Below is the the instruction that describes the task:
### Input:
Test for existence of ``needle`` regex within ``haystack``.
Say ``escape`` to escape the ``needle`` if you aren't really using the
regex feature & have special characters in it.
### Response:
def _assert_contains(haystack, needle, invert, es... |
def get_node_selectable(node, context):
"""Return the Selectable Union[Table, CTE] associated with the node."""
query_path = node.query_path
if query_path not in context.query_path_to_selectable:
raise AssertionError(
u'Unable to find selectable for query path {} with context {}.'.format... | Return the Selectable Union[Table, CTE] associated with the node. | Below is the the instruction that describes the task:
### Input:
Return the Selectable Union[Table, CTE] associated with the node.
### Response:
def get_node_selectable(node, context):
"""Return the Selectable Union[Table, CTE] associated with the node."""
query_path = node.query_path
if query_path not... |
def consumer_initialize_task(processor, consumer_client, shard_id, cursor_position, cursor_start_time, cursor_end_time=None):
"""
return TaskResult if failed, or else, return InitTaskResult
:param processor:
:param consumer_client:
:param shard_id:
:param cursor_position:
:param cursor_start... | return TaskResult if failed, or else, return InitTaskResult
:param processor:
:param consumer_client:
:param shard_id:
:param cursor_position:
:param cursor_start_time:
:return: | Below is the the instruction that describes the task:
### Input:
return TaskResult if failed, or else, return InitTaskResult
:param processor:
:param consumer_client:
:param shard_id:
:param cursor_position:
:param cursor_start_time:
:return:
### Response:
def consumer_initialize_task(proce... |
def is_http_request_sender(self):
"""Checks if a user the HTTP request sender (accessing own info)
Used primarily to load private personal information from the
cache. (A student should see all info on his or her own profile
regardless of how the permissions are set.)
Returns:
... | Checks if a user the HTTP request sender (accessing own info)
Used primarily to load private personal information from the
cache. (A student should see all info on his or her own profile
regardless of how the permissions are set.)
Returns:
Boolean | Below is the the instruction that describes the task:
### Input:
Checks if a user the HTTP request sender (accessing own info)
Used primarily to load private personal information from the
cache. (A student should see all info on his or her own profile
regardless of how the permissions are s... |
def cmu_mocap_35_walk_jog(data_set='cmu_mocap'):
"""Load CMU subject 35's walking and jogging motions, the same data that was used by Taylor, Roweis and Hinton at NIPS 2007. but without their preprocessing. Also used by Lawrence at AISTATS 2007."""
train_motions = ['01', '02', '03', '04', '05', '06',
... | Load CMU subject 35's walking and jogging motions, the same data that was used by Taylor, Roweis and Hinton at NIPS 2007. but without their preprocessing. Also used by Lawrence at AISTATS 2007. | Below is the the instruction that describes the task:
### Input:
Load CMU subject 35's walking and jogging motions, the same data that was used by Taylor, Roweis and Hinton at NIPS 2007. but without their preprocessing. Also used by Lawrence at AISTATS 2007.
### Response:
def cmu_mocap_35_walk_jog(data_set='cmu_mo... |
def shape_factors(n, dim=2):
"""
Returns a :obj:`numpy.ndarray` of factors :samp:`f` such
that :samp:`(len(f) == {dim}) and (numpy.product(f) == {n})`.
The returned factors are as *square* (*cubic*, etc) as possible.
For example::
>>> shape_factors(24, 1)
array([24])
>>> shape_... | Returns a :obj:`numpy.ndarray` of factors :samp:`f` such
that :samp:`(len(f) == {dim}) and (numpy.product(f) == {n})`.
The returned factors are as *square* (*cubic*, etc) as possible.
For example::
>>> shape_factors(24, 1)
array([24])
>>> shape_factors(24, 2)
array([4, 6])
... | Below is the the instruction that describes the task:
### Input:
Returns a :obj:`numpy.ndarray` of factors :samp:`f` such
that :samp:`(len(f) == {dim}) and (numpy.product(f) == {n})`.
The returned factors are as *square* (*cubic*, etc) as possible.
For example::
>>> shape_factors(24, 1)
a... |
def verify_file(self, sign_file, data_filename=None):
'''
Verify given signature
:param sign_file: File-like object containing sign
:param data_filename: Assume signature is detached when not null
:rtype: VerifyResult
'''
if data_filename is None:
ret... | Verify given signature
:param sign_file: File-like object containing sign
:param data_filename: Assume signature is detached when not null
:rtype: VerifyResult | Below is the the instruction that describes the task:
### Input:
Verify given signature
:param sign_file: File-like object containing sign
:param data_filename: Assume signature is detached when not null
:rtype: VerifyResult
### Response:
def verify_file(self, sign_file, data_filename=None... |
def save_as(self, filename: str) -> None:
"""Save the Image to a 32-bit .bmp or .png file.
Args:
filename (Text): File path to same this Image.
"""
lib.TCOD_image_save(self.image_c, filename.encode("utf-8")) | Save the Image to a 32-bit .bmp or .png file.
Args:
filename (Text): File path to same this Image. | Below is the the instruction that describes the task:
### Input:
Save the Image to a 32-bit .bmp or .png file.
Args:
filename (Text): File path to same this Image.
### Response:
def save_as(self, filename: str) -> None:
"""Save the Image to a 32-bit .bmp or .png file.
Args:
... |
def _get_magnitude_scaling_term(self, C, mag):
"""
Returns the magnitude scaling term defined in equation 3
"""
if mag < 6.75:
return C["a1_lo"] + C["a2_lo"] * mag + C["a3"] *\
((8.5 - mag) ** 2.0)
else:
return C["a1_hi"] + C["a2_hi"] * mag... | Returns the magnitude scaling term defined in equation 3 | Below is the the instruction that describes the task:
### Input:
Returns the magnitude scaling term defined in equation 3
### Response:
def _get_magnitude_scaling_term(self, C, mag):
"""
Returns the magnitude scaling term defined in equation 3
"""
if mag < 6.75:
return C... |
def status_light(self):
"""bool: The white Sonos status light between the mute button and the
volume up button on the speaker.
True if on, otherwise False.
"""
result = self.deviceProperties.GetLEDState()
LEDState = result["CurrentLEDState"] # pylint: disable=invalid-na... | bool: The white Sonos status light between the mute button and the
volume up button on the speaker.
True if on, otherwise False. | Below is the the instruction that describes the task:
### Input:
bool: The white Sonos status light between the mute button and the
volume up button on the speaker.
True if on, otherwise False.
### Response:
def status_light(self):
"""bool: The white Sonos status light between the mute but... |
def optimize(thumbnail_file, jpg_command=None, png_command=None,
gif_command=None):
"""
A post processing function to optimize file size. Accepts commands
to optimize JPG, PNG and GIF images as arguments. Example:
THUMBNAILS = {
# Other options...
'POST_PROCESSORS': [
... | A post processing function to optimize file size. Accepts commands
to optimize JPG, PNG and GIF images as arguments. Example:
THUMBNAILS = {
# Other options...
'POST_PROCESSORS': [
{
'processor': 'thumbnails.post_processors.optimize',
'png_command': '... | Below is the the instruction that describes the task:
### Input:
A post processing function to optimize file size. Accepts commands
to optimize JPG, PNG and GIF images as arguments. Example:
THUMBNAILS = {
# Other options...
'POST_PROCESSORS': [
{
'processor': 't... |
def permute(self, qubits: Qubits) -> 'Density':
"""Return a copy of this state with qubit labels permuted"""
vec = self.vec.permute(qubits)
return Density(vec.tensor, vec.qubits, self._memory) | Return a copy of this state with qubit labels permuted | Below is the the instruction that describes the task:
### Input:
Return a copy of this state with qubit labels permuted
### Response:
def permute(self, qubits: Qubits) -> 'Density':
"""Return a copy of this state with qubit labels permuted"""
vec = self.vec.permute(qubits)
return Density(ve... |
def delete_user_contact_list(self, id, contact_list_id, **data):
"""
DELETE /users/:id/contact_lists/:contact_list_id/
Deletes the contact list. Returns ``{"deleted": true}``.
"""
return self.delete("/users/{0}/contact_lists/{0}/".format(id,contact_list_id), data=data) | DELETE /users/:id/contact_lists/:contact_list_id/
Deletes the contact list. Returns ``{"deleted": true}``. | Below is the the instruction that describes the task:
### Input:
DELETE /users/:id/contact_lists/:contact_list_id/
Deletes the contact list. Returns ``{"deleted": true}``.
### Response:
def delete_user_contact_list(self, id, contact_list_id, **data):
"""
DELETE /users/:id/contact_lists/:con... |
def publish(self, msg, exchange, routing_key, mandatory=False,
immediate=False, ticket=None):
'''
publish a message.
'''
args = Writer()
args.write_short(ticket or self.default_ticket).\
write_shortstr(exchange).\
write_shortstr(routing_key... | publish a message. | Below is the the instruction that describes the task:
### Input:
publish a message.
### Response:
def publish(self, msg, exchange, routing_key, mandatory=False,
immediate=False, ticket=None):
'''
publish a message.
'''
args = Writer()
args.write_short(ticket ... |
def temporary_tables(**kwargs):
"""
Temporarily set DataFrames as registered tables.
Tables will be returned to their original state when the context
manager exits. Caching is not enabled for tables registered via
this function.
"""
global _TABLES
original = _TABLES.copy()
for k,... | Temporarily set DataFrames as registered tables.
Tables will be returned to their original state when the context
manager exits. Caching is not enabled for tables registered via
this function. | Below is the the instruction that describes the task:
### Input:
Temporarily set DataFrames as registered tables.
Tables will be returned to their original state when the context
manager exits. Caching is not enabled for tables registered via
this function.
### Response:
def temporary_tables(**kwargs)... |
def make_module(self, vars=None, shared=False, locals=None):
"""This method works like the :attr:`module` attribute when called
without arguments but it will evaluate the template on every call
rather than caching it. It's also possible to provide
a dict which is then used as context. ... | This method works like the :attr:`module` attribute when called
without arguments but it will evaluate the template on every call
rather than caching it. It's also possible to provide
a dict which is then used as context. The arguments are the same
as for the :meth:`new_context` method... | Below is the the instruction that describes the task:
### Input:
This method works like the :attr:`module` attribute when called
without arguments but it will evaluate the template on every call
rather than caching it. It's also possible to provide
a dict which is then used as context. The... |
def process_fish(self, limit=None):
"""
Fish give identifiers to the "effective genotypes" that we create.
We can match these by:
Fish = (intrinsic) genotype + set of morpholinos
We assume here that the intrinsic genotypes and their parts
will be processed separately, pr... | Fish give identifiers to the "effective genotypes" that we create.
We can match these by:
Fish = (intrinsic) genotype + set of morpholinos
We assume here that the intrinsic genotypes and their parts
will be processed separately, prior to calling this function.
:param limit:
... | Below is the the instruction that describes the task:
### Input:
Fish give identifiers to the "effective genotypes" that we create.
We can match these by:
Fish = (intrinsic) genotype + set of morpholinos
We assume here that the intrinsic genotypes and their parts
will be processed s... |
def get_formats(self):
""" Return the available format names for this metadata """
formats = []
for key in (self.FORMAT_DC, self.FORMAT_FGDC, self.FORMAT_ISO):
if hasattr(self, key):
formats.append(key)
return formats | Return the available format names for this metadata | Below is the the instruction that describes the task:
### Input:
Return the available format names for this metadata
### Response:
def get_formats(self):
""" Return the available format names for this metadata """
formats = []
for key in (self.FORMAT_DC, self.FORMAT_FGDC, self.FORMAT_ISO):
... |
def constraint_from_choices(cls, value_type: type, choices: collections.Sequence):
"""
Returns a constraint callable based on choices of a given type
"""
choices_str = ', '.join(map(str, choices))
def constraint(value):
value = value_type(value)
if value ... | Returns a constraint callable based on choices of a given type | Below is the the instruction that describes the task:
### Input:
Returns a constraint callable based on choices of a given type
### Response:
def constraint_from_choices(cls, value_type: type, choices: collections.Sequence):
"""
Returns a constraint callable based on choices of a given type
... |
def set(self, key, value, duration):
"""Save an object in the cache
Arguments:
key (str): Cache key
value (object): object to cache
duration (int): time in seconds to keep object in cache
"""
lock.acquire()
try:
self[key] = CacheO... | Save an object in the cache
Arguments:
key (str): Cache key
value (object): object to cache
duration (int): time in seconds to keep object in cache | Below is the the instruction that describes the task:
### Input:
Save an object in the cache
Arguments:
key (str): Cache key
value (object): object to cache
duration (int): time in seconds to keep object in cache
### Response:
def set(self, key, value, duration):
... |
def list_sensors(name_pattern=Sensor.SYSTEM_DEVICE_NAME_CONVENTION, **kwargs):
"""
This is a generator function that enumerates all sensors that match the
provided arguments.
Parameters:
name_pattern: pattern that device name should match.
For example, 'sensor*'. Default value: '*'.... | This is a generator function that enumerates all sensors that match the
provided arguments.
Parameters:
name_pattern: pattern that device name should match.
For example, 'sensor*'. Default value: '*'.
keyword arguments: used for matching the corresponding device
attribut... | Below is the the instruction that describes the task:
### Input:
This is a generator function that enumerates all sensors that match the
provided arguments.
Parameters:
name_pattern: pattern that device name should match.
For example, 'sensor*'. Default value: '*'.
keyword argum... |
def lambda_handler(event, context):
''' Process a RDS enhenced monitoring DATA_MESSAGE,
coming from CLOUDWATCH LOGS
'''
# event is a dict containing a base64 string gzipped
event = json.loads(gzip.GzipFile(fileobj=StringIO(event['awslogs']['data'].decode('base64'))).read())
account = event[... | Process a RDS enhenced monitoring DATA_MESSAGE,
coming from CLOUDWATCH LOGS | Below is the the instruction that describes the task:
### Input:
Process a RDS enhenced monitoring DATA_MESSAGE,
coming from CLOUDWATCH LOGS
### Response:
def lambda_handler(event, context):
''' Process a RDS enhenced monitoring DATA_MESSAGE,
coming from CLOUDWATCH LOGS
'''
# event is a... |
def conceal_member(self, login):
"""Conceal ``login``'s membership in this organization.
:returns: bool
"""
url = self._build_url('public_members', login, base_url=self._api)
return self._boolean(self._delete(url), 204, 404) | Conceal ``login``'s membership in this organization.
:returns: bool | Below is the the instruction that describes the task:
### Input:
Conceal ``login``'s membership in this organization.
:returns: bool
### Response:
def conceal_member(self, login):
"""Conceal ``login``'s membership in this organization.
:returns: bool
"""
url = self._build_... |
def serialize(obj):
"""JSON serializer that accepts datetime & date"""
from datetime import datetime, date, time
if isinstance(obj, date) and not isinstance(obj, datetime):
obj = datetime.combine(obj, time.min)
if isinstance(obj, datetime):
return obj.isoformat() | JSON serializer that accepts datetime & date | Below is the the instruction that describes the task:
### Input:
JSON serializer that accepts datetime & date
### Response:
def serialize(obj):
"""JSON serializer that accepts datetime & date"""
from datetime import datetime, date, time
if isinstance(obj, date) and not isinstance(obj, datetime):
... |
def putout(ofile, keylist, Rec):
"""
writes out a magic format record to ofile
"""
pmag_out = open(ofile, 'a')
outstring = ""
for key in keylist:
try:
outstring = outstring + '\t' + str(Rec[key]).strip()
except:
print(key, Rec[key])
# raw_input... | writes out a magic format record to ofile | Below is the the instruction that describes the task:
### Input:
writes out a magic format record to ofile
### Response:
def putout(ofile, keylist, Rec):
"""
writes out a magic format record to ofile
"""
pmag_out = open(ofile, 'a')
outstring = ""
for key in keylist:
try:
... |
def report(self, req_handler):
"Send a response corresponding to this error to the client"
if self.exc:
req_handler.send_exception(self.code, self.exc, self.headers)
return
text = (self.text
or BaseHTTPRequestHandler.responses[self.code][1]
... | Send a response corresponding to this error to the client | Below is the the instruction that describes the task:
### Input:
Send a response corresponding to this error to the client
### Response:
def report(self, req_handler):
"Send a response corresponding to this error to the client"
if self.exc:
req_handler.send_exception(self.code, self.exc... |
def create(self):
"""POST /mapfiles: Create a new item."""
# get json content from POST request
content = request.environ['wsgi.input'].read(int(request.environ['CONTENT_LENGTH']))
#content = content.decode('utf8') mapfile interface don't like unicode strings... bad...
# load ... | POST /mapfiles: Create a new item. | Below is the the instruction that describes the task:
### Input:
POST /mapfiles: Create a new item.
### Response:
def create(self):
"""POST /mapfiles: Create a new item."""
# get json content from POST request
content = request.environ['wsgi.input'].read(int(request.environ['CONTENT_LENGTH'... |
def color_palette_dict(self, alpha=0.35):
"""
Helper function to assign each facet a unique color using a dictionary.
Args:
alpha (float): Degree of transparency
return (dict): Dictionary of colors (r,g,b,a) when plotting surface
energy stability. The keys are i... | Helper function to assign each facet a unique color using a dictionary.
Args:
alpha (float): Degree of transparency
return (dict): Dictionary of colors (r,g,b,a) when plotting surface
energy stability. The keys are individual surface entries where
clean surfaces hav... | Below is the the instruction that describes the task:
### Input:
Helper function to assign each facet a unique color using a dictionary.
Args:
alpha (float): Degree of transparency
return (dict): Dictionary of colors (r,g,b,a) when plotting surface
energy stability. The key... |
def mass_inform(self, msg):
"""Send an inform message to all clients.
Parameters
----------
msg : Message object
The inform message to send.
"""
assert (msg.mtype == Message.INFORM)
self._server.mass_send_message_from_thread(msg) | Send an inform message to all clients.
Parameters
----------
msg : Message object
The inform message to send. | Below is the the instruction that describes the task:
### Input:
Send an inform message to all clients.
Parameters
----------
msg : Message object
The inform message to send.
### Response:
def mass_inform(self, msg):
"""Send an inform message to all clients.
Pa... |
def io_priority(self):
"""
IO priority for this instance.
"""
return (
self._iocb.aio_reqprio
if self._iocb.u.c.flags & libaio.IOCB_FLAG_IOPRIO else
None
) | IO priority for this instance. | Below is the the instruction that describes the task:
### Input:
IO priority for this instance.
### Response:
def io_priority(self):
"""
IO priority for this instance.
"""
return (
self._iocb.aio_reqprio
if self._iocb.u.c.flags & libaio.IOCB_FLAG_IOPRIO else
... |
def _cast_expected_to_returned_type(expected, returned):
'''
Determine the type of variable returned
Cast the expected to the type of variable returned
'''
ret_type = type(returned)
new_expected = expected
if expected == "False" and ret_type == bool:
e... | Determine the type of variable returned
Cast the expected to the type of variable returned | Below is the the instruction that describes the task:
### Input:
Determine the type of variable returned
Cast the expected to the type of variable returned
### Response:
def _cast_expected_to_returned_type(expected, returned):
'''
Determine the type of variable returned
Cast the exp... |
def wait_lock(path, lock_fn=None, timeout=5, sleep=0.1, time_start=None):
'''
Obtain a write lock. If one exists, wait for it to release first
'''
if not isinstance(path, six.string_types):
raise FileLockError('path must be a string')
if lock_fn is None:
lock_fn = path + '.w'
if ... | Obtain a write lock. If one exists, wait for it to release first | Below is the the instruction that describes the task:
### Input:
Obtain a write lock. If one exists, wait for it to release first
### Response:
def wait_lock(path, lock_fn=None, timeout=5, sleep=0.1, time_start=None):
'''
Obtain a write lock. If one exists, wait for it to release first
'''
if not i... |
def main(args=None, prog=None):
"""Generates a C header file"""
args = args if args is not None else sys.argv[1:]
prog = prog if prog is not None else sys.argv[0]
# Prevent broken pipe exception from being raised.
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
stdin = sys.stdin.buffer if hasattr(... | Generates a C header file | Below is the the instruction that describes the task:
### Input:
Generates a C header file
### Response:
def main(args=None, prog=None):
"""Generates a C header file"""
args = args if args is not None else sys.argv[1:]
prog = prog if prog is not None else sys.argv[0]
# Prevent broken pipe exception... |
def from_variant_and_transcript(
cls,
variant,
transcript,
context_size):
"""
Extracts the reference sequence around a variant locus on a particular
transcript and determines the reading frame at the start of that
sequence context.
... | Extracts the reference sequence around a variant locus on a particular
transcript and determines the reading frame at the start of that
sequence context.
Parameters
----------
variant : varcode.Variant
transcript : pyensembl.Transcript
context_size : int
... | Below is the the instruction that describes the task:
### Input:
Extracts the reference sequence around a variant locus on a particular
transcript and determines the reading frame at the start of that
sequence context.
Parameters
----------
variant : varcode.Variant
... |
def get_path_signature(self, path):
"""generate a unique signature for file contained in path
"""
if not os.path.exists(path):
return None
if os.path.isdir(path):
merge = {}
for root, dirs, files in os.walk(path):
for name in files:
... | generate a unique signature for file contained in path | Below is the the instruction that describes the task:
### Input:
generate a unique signature for file contained in path
### Response:
def get_path_signature(self, path):
"""generate a unique signature for file contained in path
"""
if not os.path.exists(path):
return None
... |
def mtxm(m1, m2):
"""
Multiply the transpose of a 3x3 matrix and a 3x3 matrix.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mtxm_c.html
:param m1: 3x3 double precision matrix.
:type m1: 3x3-Element Array of floats
:param m2: 3x3 double precision matrix.
:type m2: 3x3-Element Arr... | Multiply the transpose of a 3x3 matrix and a 3x3 matrix.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mtxm_c.html
:param m1: 3x3 double precision matrix.
:type m1: 3x3-Element Array of floats
:param m2: 3x3 double precision matrix.
:type m2: 3x3-Element Array of floats
:return: The ... | Below is the the instruction that describes the task:
### Input:
Multiply the transpose of a 3x3 matrix and a 3x3 matrix.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mtxm_c.html
:param m1: 3x3 double precision matrix.
:type m1: 3x3-Element Array of floats
:param m2: 3x3 double precisio... |
def _set_member_entry(self, v, load=False):
"""
Setter method for member_entry, mapped from YANG variable /rbridge_id/secpolicy/defined_policy/policies/member_entry (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_member_entry is considered as a private
method.... | Setter method for member_entry, mapped from YANG variable /rbridge_id/secpolicy/defined_policy/policies/member_entry (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_member_entry is considered as a private
method. Backends looking to populate this variable should
d... | Below is the the instruction that describes the task:
### Input:
Setter method for member_entry, mapped from YANG variable /rbridge_id/secpolicy/defined_policy/policies/member_entry (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_member_entry is considered as a privat... |
def run(self):
""" starts the REPL """
from .progress import ShellProgressView
self.cli_ctx.get_progress_controller().init_progress(ShellProgressView())
self.cli_ctx.get_progress_controller = self.progress_patch
self.command_table_thread = LoadCommandTableThread(self.restart_com... | starts the REPL | Below is the the instruction that describes the task:
### Input:
starts the REPL
### Response:
def run(self):
""" starts the REPL """
from .progress import ShellProgressView
self.cli_ctx.get_progress_controller().init_progress(ShellProgressView())
self.cli_ctx.get_progress_controlle... |
def parse_transaction_id(self, data):
"return transaction_id"
if data[0] == TDS_ERROR_TOKEN:
raise self.parse_error('begin()', data)
t, data = _parse_byte(data)
assert t == TDS_ENVCHANGE_TOKEN
_, data = _parse_int(data, 2) # packet length
e, data = _parse_by... | return transaction_id | Below is the the instruction that describes the task:
### Input:
return transaction_id
### Response:
def parse_transaction_id(self, data):
"return transaction_id"
if data[0] == TDS_ERROR_TOKEN:
raise self.parse_error('begin()', data)
t, data = _parse_byte(data)
assert t ... |
def _rough_shake(self, x, normals, values, error):
'''Take a robust, but not very efficient step towards the constraints.
Arguments:
| ``x`` -- The unknowns.
| ``normals`` -- A numpy array with the gradients of the active
constraints. Each row is ... | Take a robust, but not very efficient step towards the constraints.
Arguments:
| ``x`` -- The unknowns.
| ``normals`` -- A numpy array with the gradients of the active
constraints. Each row is one gradient.
| ``values`` -- A numpy array with t... | Below is the the instruction that describes the task:
### Input:
Take a robust, but not very efficient step towards the constraints.
Arguments:
| ``x`` -- The unknowns.
| ``normals`` -- A numpy array with the gradients of the active
constraints. Each ... |
def _populate_sub_entity(self, entity, type_name):
"""
Simple API-backed cache for populating MyGeotab entities
:param entity: The entity to populate a sub-entity for
:param type_name: The type of the sub-entity to populate
"""
key = type_name.lower()
if isinstan... | Simple API-backed cache for populating MyGeotab entities
:param entity: The entity to populate a sub-entity for
:param type_name: The type of the sub-entity to populate | Below is the the instruction that describes the task:
### Input:
Simple API-backed cache for populating MyGeotab entities
:param entity: The entity to populate a sub-entity for
:param type_name: The type of the sub-entity to populate
### Response:
def _populate_sub_entity(self, entity, type_name):... |
def transfer(self, data, assert_ss=True, deassert_ss=True):
"""Full-duplex SPI read and write. If assert_ss is true, the SS line
will be asserted low, the specified bytes will be clocked out the MOSI
line while bytes will also be read from the MISO line, and if
deassert_ss is true the S... | Full-duplex SPI read and write. If assert_ss is true, the SS line
will be asserted low, the specified bytes will be clocked out the MOSI
line while bytes will also be read from the MISO line, and if
deassert_ss is true the SS line will be put back high. Bytes which are
read will be ret... | Below is the the instruction that describes the task:
### Input:
Full-duplex SPI read and write. If assert_ss is true, the SS line
will be asserted low, the specified bytes will be clocked out the MOSI
line while bytes will also be read from the MISO line, and if
deassert_ss is true the SS ... |
def _get_cores_and_type(numcores, paralleltype, scheduler):
"""Return core and parallelization approach from command line providing sane defaults.
"""
if scheduler is not None:
paralleltype = "ipython"
if paralleltype is None:
paralleltype = "local"
if not numcores or int(numcores) <... | Return core and parallelization approach from command line providing sane defaults. | Below is the the instruction that describes the task:
### Input:
Return core and parallelization approach from command line providing sane defaults.
### Response:
def _get_cores_and_type(numcores, paralleltype, scheduler):
"""Return core and parallelization approach from command line providing sane defaults.
... |
def copy_file_data(src_file, dst_file, chunk_size=None):
# type: (IO, IO, Optional[int]) -> None
"""Copy data from one file object to another.
Arguments:
src_file (io.IOBase): File open for reading.
dst_file (io.IOBase): File open for writing.
chunk_size (int): Number of bytes to co... | Copy data from one file object to another.
Arguments:
src_file (io.IOBase): File open for reading.
dst_file (io.IOBase): File open for writing.
chunk_size (int): Number of bytes to copy at
a time (or `None` to use sensible default). | Below is the the instruction that describes the task:
### Input:
Copy data from one file object to another.
Arguments:
src_file (io.IOBase): File open for reading.
dst_file (io.IOBase): File open for writing.
chunk_size (int): Number of bytes to copy at
a time (or `None` to ... |
def from_terms_dict(terms_dict):
"""For internal use."""
return Expr(tuple(Term(k, v) for k, v in terms_dict.items() if v)) | For internal use. | Below is the the instruction that describes the task:
### Input:
For internal use.
### Response:
def from_terms_dict(terms_dict):
"""For internal use."""
return Expr(tuple(Term(k, v) for k, v in terms_dict.items() if v)) |
def itransform_define(transform):
"""
This function links the user's choice of transformation with its inverse
"""
if transform == 'tanh':
return np.arctanh
elif transform == 'exp':
return np.log
elif transform == 'logit':
return Family... | This function links the user's choice of transformation with its inverse | Below is the the instruction that describes the task:
### Input:
This function links the user's choice of transformation with its inverse
### Response:
def itransform_define(transform):
"""
This function links the user's choice of transformation with its inverse
"""
if transform == ... |
def make_annotations(f, globals_d=None):
# type: (Callable, Dict) -> Dict[str, Any]
"""Create an annotations dictionary from Python2 type comments
http://mypy.readthedocs.io/en/latest/python2.html
Args:
f: The function to examine for type comments
globals_d: The globals dictionary to g... | Create an annotations dictionary from Python2 type comments
http://mypy.readthedocs.io/en/latest/python2.html
Args:
f: The function to examine for type comments
globals_d: The globals dictionary to get type idents from. If not
specified then make the annotations dict contain string... | Below is the the instruction that describes the task:
### Input:
Create an annotations dictionary from Python2 type comments
http://mypy.readthedocs.io/en/latest/python2.html
Args:
f: The function to examine for type comments
globals_d: The globals dictionary to get type idents from. If no... |
def generate_data(self, data_dir, tmp_dir, task_id=-1):
"""The function generating the data."""
filepath_fns = {
problem.DatasetSplit.TRAIN: self.training_filepaths,
problem.DatasetSplit.EVAL: self.dev_filepaths,
problem.DatasetSplit.TEST: self.test_filepaths,
}
# We set shuffle... | The function generating the data. | Below is the the instruction that describes the task:
### Input:
The function generating the data.
### Response:
def generate_data(self, data_dir, tmp_dir, task_id=-1):
"""The function generating the data."""
filepath_fns = {
problem.DatasetSplit.TRAIN: self.training_filepaths,
problem.Data... |
def calc_hazard_curves(
groups, ss_filter, imtls, gsim_by_trt, truncation_level=None,
apply=sequential_apply, filter_distance='rjb', reqv=None):
"""
Compute hazard curves on a list of sites, given a set of seismic source
groups and a dictionary of ground shaking intensity models (one per
... | Compute hazard curves on a list of sites, given a set of seismic source
groups and a dictionary of ground shaking intensity models (one per
tectonic region type).
Probability of ground motion exceedance is computed in different ways
depending if the sources are independent or mutually exclusive.
:... | Below is the the instruction that describes the task:
### Input:
Compute hazard curves on a list of sites, given a set of seismic source
groups and a dictionary of ground shaking intensity models (one per
tectonic region type).
Probability of ground motion exceedance is computed in different ways
d... |
def to(self, fmt=None, filename=None, **kwargs):
"""
Outputs the structure to a file or string.
Args:
fmt (str): Format to output to. Defaults to JSON unless filename
is provided. If fmt is specifies, it overrides whatever the
filename is. Options inc... | Outputs the structure to a file or string.
Args:
fmt (str): Format to output to. Defaults to JSON unless filename
is provided. If fmt is specifies, it overrides whatever the
filename is. Options include "cif", "poscar", "cssr", "json".
Non-case sensit... | Below is the the instruction that describes the task:
### Input:
Outputs the structure to a file or string.
Args:
fmt (str): Format to output to. Defaults to JSON unless filename
is provided. If fmt is specifies, it overrides whatever the
filename is. Options inc... |
def _set_options(self):
"sets the graph ploting options"
# this is aweful
# FIXME: Axis options should be passed completly by a GraphOption
if 'xaxis' in self._options.keys():
self._options['xaxis'].update(
{'mode' : self._get_axis_mode(XAxis._var_name... | sets the graph ploting options | Below is the the instruction that describes the task:
### Input:
sets the graph ploting options
### Response:
def _set_options(self):
"sets the graph ploting options"
# this is aweful
# FIXME: Axis options should be passed completly by a GraphOption
if 'xaxis' in self._options.keys(... |
def ParseFileDownloadedRow(
self, parser_mediator, query, row, **unused_kwargs):
"""Parses a file downloaded row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
... | Parses a file downloaded row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row. | Below is the the instruction that describes the task:
### Input:
Parses a file downloaded row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): r... |
def mass_mailing_recipients():
"""
Returns iterable of all mass email recipients.
Default behavior will be to return list of all active users' emails.
This can be changed by providing callback in settings return some other list of users,
when user emails are stored in many, non default models.
T... | Returns iterable of all mass email recipients.
Default behavior will be to return list of all active users' emails.
This can be changed by providing callback in settings return some other list of users,
when user emails are stored in many, non default models.
To accomplish that add constant MASS_EMAIL_R... | Below is the the instruction that describes the task:
### Input:
Returns iterable of all mass email recipients.
Default behavior will be to return list of all active users' emails.
This can be changed by providing callback in settings return some other list of users,
when user emails are stored in many,... |
def get_mechs_available():
"""
Returns a list of auth mechanisms that are available to the local
GSSAPI instance. Because we are interacting with Windows, we only
care if SPNEGO, Kerberos and NTLM are available where NTLM is the
only wildcard that may not be available by default.... | Returns a list of auth mechanisms that are available to the local
GSSAPI instance. Because we are interacting with Windows, we only
care if SPNEGO, Kerberos and NTLM are available where NTLM is the
only wildcard that may not be available by default.
The only NTLM implementation that wor... | Below is the the instruction that describes the task:
### Input:
Returns a list of auth mechanisms that are available to the local
GSSAPI instance. Because we are interacting with Windows, we only
care if SPNEGO, Kerberos and NTLM are available where NTLM is the
only wildcard that may not be... |
def gf_mult_noLUT(x, y, prim=0, field_charac_full=256, carryless=True):
'''Galois Field integer multiplication using Russian Peasant Multiplication algorithm (faster than the standard multiplication + modular reduction).
If prim is 0 and carryless=False, then the function produces the result for a standard inte... | Galois Field integer multiplication using Russian Peasant Multiplication algorithm (faster than the standard multiplication + modular reduction).
If prim is 0 and carryless=False, then the function produces the result for a standard integers multiplication (no carry-less arithmetics nor modular reduction). | Below is the the instruction that describes the task:
### Input:
Galois Field integer multiplication using Russian Peasant Multiplication algorithm (faster than the standard multiplication + modular reduction).
If prim is 0 and carryless=False, then the function produces the result for a standard integers multi... |
def receive_message(source, auth=None, timeout=0, debug=False):
"""Receive a single message from an AMQP endpoint.
:param source: The AMQP source endpoint to receive from.
:type source: str, bytes or ~uamqp.address.Source
:param auth: The authentication credentials for the endpoint.
This should be... | Receive a single message from an AMQP endpoint.
:param source: The AMQP source endpoint to receive from.
:type source: str, bytes or ~uamqp.address.Source
:param auth: The authentication credentials for the endpoint.
This should be one of the subclasses of uamqp.authentication.AMQPAuth. Currently
... | Below is the the instruction that describes the task:
### Input:
Receive a single message from an AMQP endpoint.
:param source: The AMQP source endpoint to receive from.
:type source: str, bytes or ~uamqp.address.Source
:param auth: The authentication credentials for the endpoint.
This should be o... |
def ProcessMessages(self, active_notifications, queue_manager, time_limit=0):
"""Processes all the flows in the messages.
Precondition: All tasks come from the same queue.
Note that the server actually completes the requests in the
flow when receiving the messages from the client. We do not really
... | Processes all the flows in the messages.
Precondition: All tasks come from the same queue.
Note that the server actually completes the requests in the
flow when receiving the messages from the client. We do not really
look at the messages here at all any more - we just work from the
completed mess... | Below is the the instruction that describes the task:
### Input:
Processes all the flows in the messages.
Precondition: All tasks come from the same queue.
Note that the server actually completes the requests in the
flow when receiving the messages from the client. We do not really
look at the mes... |
def fit(self, X, y, recycle=True, **grow_params):
"""Build a linear mixed forest of trees from the training set (X, y).
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The training input samples.
y : array-like, shape = [n_samples] or [n_sam... | Build a linear mixed forest of trees from the training set (X, y).
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The training input samples.
y : array-like, shape = [n_samples] or [n_samples, 1]
The real valued targets
Returns
... | Below is the the instruction that describes the task:
### Input:
Build a linear mixed forest of trees from the training set (X, y).
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The training input samples.
y : array-like, shape = [n_samples] or... |
def echo_detected_environment(env_name, env_vars):
"""Print a helper note about how the environment was determined."""
env_override_name = 'DEPLOY_ENVIRONMENT'
LOGGER.info("")
if env_override_name in env_vars:
LOGGER.info("Environment \"%s\" was determined from the %s environment variable.",
... | Print a helper note about how the environment was determined. | Below is the the instruction that describes the task:
### Input:
Print a helper note about how the environment was determined.
### Response:
def echo_detected_environment(env_name, env_vars):
"""Print a helper note about how the environment was determined."""
env_override_name = 'DEPLOY_ENVIRONMENT'
LO... |
def stop_Note(self, note):
"""Add a note_off event for note to event_track."""
velocity = 64
channel = 1
if hasattr(note, 'dynamics'):
if 'velocity' in note.dynamics:
velocity = note.dynamics['velocity']
if 'channel' in note.dynamics:
... | Add a note_off event for note to event_track. | Below is the the instruction that describes the task:
### Input:
Add a note_off event for note to event_track.
### Response:
def stop_Note(self, note):
"""Add a note_off event for note to event_track."""
velocity = 64
channel = 1
if hasattr(note, 'dynamics'):
if 'velocit... |
def get_user_token():
"""Return the authenticated user's auth token"""
if not hasattr(stack.top, 'current_user'):
return ''
current_user = stack.top.current_user
return current_user.get('token', '') | Return the authenticated user's auth token | Below is the the instruction that describes the task:
### Input:
Return the authenticated user's auth token
### Response:
def get_user_token():
"""Return the authenticated user's auth token"""
if not hasattr(stack.top, 'current_user'):
return ''
current_user = stack.top.current_user
return ... |
def penn_treebank_dataset(
directory='data/penn-treebank',
train=False,
dev=False,
test=False,
train_filename='ptb.train.txt',
dev_filename='ptb.valid.txt',
test_filename='ptb.test.txt',
check_files=['ptb.train.txt'],
urls=[
'https://ra... | Load the Penn Treebank dataset.
This is the Penn Treebank Project: Release 2 CDROM, featuring a million words of 1989 Wall
Street Journal material.
**Reference:** https://catalog.ldc.upenn.edu/ldc99t42
**Citation:**
Marcus, Mitchell P., Marcinkiewicz, Mary Ann & Santorini, Beatrice (1993).
Bu... | Below is the the instruction that describes the task:
### Input:
Load the Penn Treebank dataset.
This is the Penn Treebank Project: Release 2 CDROM, featuring a million words of 1989 Wall
Street Journal material.
**Reference:** https://catalog.ldc.upenn.edu/ldc99t42
**Citation:**
Marcus, Mitc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.