code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def create(self, **kwargs):
'''Add trusted peers to the root bigip device.
When adding a trusted device to a device, the trust is reflexive. That
is, the truster trusts the trustee and the trustee trusts the truster.
So we only need to add the trusted devices to one device.
:pa... | Add trusted peers to the root bigip device.
When adding a trusted device to a device, the trust is reflexive. That
is, the truster trusts the trustee and the trustee trusts the truster.
So we only need to add the trusted devices to one device.
:param kwargs: dict -- devices and partiti... | Below is the the instruction that describes the task:
### Input:
Add trusted peers to the root bigip device.
When adding a trusted device to a device, the trust is reflexive. That
is, the truster trusts the trustee and the trustee trusts the truster.
So we only need to add the trusted devic... |
def handshake_headers(self):
"""
List of headers appropriate for the upgrade
handshake.
"""
headers = [
('Host', self.host),
('Connection', 'Upgrade'),
('Upgrade', 'WebSocket'),
('Sec-WebSocket-Key', self.key.decode('utf-8')),
... | List of headers appropriate for the upgrade
handshake. | Below is the the instruction that describes the task:
### Input:
List of headers appropriate for the upgrade
handshake.
### Response:
def handshake_headers(self):
"""
List of headers appropriate for the upgrade
handshake.
"""
headers = [
('Host', self.hos... |
def remove_subscriber(self, message):
"""
Remove a subscriber based on token.
:param message: the message
"""
logger.debug("Remove Subcriber")
host, port = message.destination
key_token = hash(str(host) + str(port) + str(message.token))
try:
s... | Remove a subscriber based on token.
:param message: the message | Below is the the instruction that describes the task:
### Input:
Remove a subscriber based on token.
:param message: the message
### Response:
def remove_subscriber(self, message):
"""
Remove a subscriber based on token.
:param message: the message
"""
logger.debug... |
def id_pools(self):
"""
Gets the IdPools API client.
Returns:
IdPools:
"""
if not self.__id_pools:
self.__id_pools = IdPools(self.__connection)
return self.__id_pools | Gets the IdPools API client.
Returns:
IdPools: | Below is the the instruction that describes the task:
### Input:
Gets the IdPools API client.
Returns:
IdPools:
### Response:
def id_pools(self):
"""
Gets the IdPools API client.
Returns:
IdPools:
"""
if not self.__id_pools:
self... |
def compress_for_rename(paths):
"""Returns a set containing the paths that need to be renamed.
This set may include directories when the original sequence of paths
included every file on disk.
"""
case_map = dict((os.path.normcase(p), p) for p in paths)
remaining = set(case_map)
unchecked =... | Returns a set containing the paths that need to be renamed.
This set may include directories when the original sequence of paths
included every file on disk. | Below is the the instruction that describes the task:
### Input:
Returns a set containing the paths that need to be renamed.
This set may include directories when the original sequence of paths
included every file on disk.
### Response:
def compress_for_rename(paths):
"""Returns a set containing the p... |
def append(self, resultFile, resultElem, all_columns=False):
"""
Append the result for one run. Needs to be called before collect_data().
"""
self._xml_results += [(result, resultFile) for result in _get_run_tags_from_xml(resultElem)]
for attrib, values in RunSetResult._extract_a... | Append the result for one run. Needs to be called before collect_data(). | Below is the the instruction that describes the task:
### Input:
Append the result for one run. Needs to be called before collect_data().
### Response:
def append(self, resultFile, resultElem, all_columns=False):
"""
Append the result for one run. Needs to be called before collect_data().
"... |
def _delete_vlan_profile(self, handle, vlan_id, ucsm_ip):
"""Deletes VLAN Profile from UCS Manager."""
vlan_name = self.make_vlan_name(vlan_id)
vlan_profile_dest = (const.VLAN_PATH + const.VLAN_PROFILE_PATH_PREFIX +
vlan_name)
try:
obj = handle.qu... | Deletes VLAN Profile from UCS Manager. | Below is the the instruction that describes the task:
### Input:
Deletes VLAN Profile from UCS Manager.
### Response:
def _delete_vlan_profile(self, handle, vlan_id, ucsm_ip):
"""Deletes VLAN Profile from UCS Manager."""
vlan_name = self.make_vlan_name(vlan_id)
vlan_profile_dest = (const.VL... |
def next_blocks(self, quantity=-1):
"""Get the next blocks in order."""
blocks = (EighthBlock.objects.get_blocks_this_year().order_by(
"date", "block_letter").filter(Q(date__gt=self.date) | (Q(date=self.date) & Q(block_letter__gt=self.block_letter))))
if quantity == -1:
r... | Get the next blocks in order. | Below is the the instruction that describes the task:
### Input:
Get the next blocks in order.
### Response:
def next_blocks(self, quantity=-1):
"""Get the next blocks in order."""
blocks = (EighthBlock.objects.get_blocks_this_year().order_by(
"date", "block_letter").filter(Q(date__gt=s... |
def _negotiate_SOCKS5(self, *dest_addr):
"""
Negotiates a stream connection through a SOCKS5 server.
"""
CONNECT = b"\x01"
self.proxy_peername, self.proxy_sockname = self._SOCKS5_request(self,
CONNECT, dest_addr) | Negotiates a stream connection through a SOCKS5 server. | Below is the the instruction that describes the task:
### Input:
Negotiates a stream connection through a SOCKS5 server.
### Response:
def _negotiate_SOCKS5(self, *dest_addr):
"""
Negotiates a stream connection through a SOCKS5 server.
"""
CONNECT = b"\x01"
self.proxy_peerna... |
def atmost(cls, lits, weights=None, bound=1, top_id=None,
encoding=EncType.best):
"""
A synonim for :meth:`PBEnc.leq`.
"""
return cls.leq(lits, weights, bound, top_id, encoding) | A synonim for :meth:`PBEnc.leq`. | Below is the the instruction that describes the task:
### Input:
A synonim for :meth:`PBEnc.leq`.
### Response:
def atmost(cls, lits, weights=None, bound=1, top_id=None,
encoding=EncType.best):
"""
A synonim for :meth:`PBEnc.leq`.
"""
return cls.leq(lits, weights, b... |
def update_layers_esri_mapserver(service, greedy_opt=False):
"""
Update layers for an ESRI REST MapServer.
Sample endpoint: https://gis.ngdc.noaa.gov/arcgis/rest/services/SampleWorldCities/MapServer/?f=json
"""
try:
esri_service = ArcMapService(service.url)
# set srs
# both m... | Update layers for an ESRI REST MapServer.
Sample endpoint: https://gis.ngdc.noaa.gov/arcgis/rest/services/SampleWorldCities/MapServer/?f=json | Below is the the instruction that describes the task:
### Input:
Update layers for an ESRI REST MapServer.
Sample endpoint: https://gis.ngdc.noaa.gov/arcgis/rest/services/SampleWorldCities/MapServer/?f=json
### Response:
def update_layers_esri_mapserver(service, greedy_opt=False):
"""
Update layers for... |
def create_dir(path, dir_dict={}):
'''
Tries to create a new directory in the given path.
**create_dir** can also create subfolders according to the dictionnary given as second argument.
Parameters
----------
path : string
string giving the path of the location to create the directory, ... | Tries to create a new directory in the given path.
**create_dir** can also create subfolders according to the dictionnary given as second argument.
Parameters
----------
path : string
string giving the path of the location to create the directory, either absolute or relative.
dir_dict : dic... | Below is the the instruction that describes the task:
### Input:
Tries to create a new directory in the given path.
**create_dir** can also create subfolders according to the dictionnary given as second argument.
Parameters
----------
path : string
string giving the path of the location to ... |
def get_attachments(self, include_fields=None, exclude_fields=None):
"""
Helper call to Bugzilla.get_attachments. If you want to fetch
specific attachment IDs, use that function instead
"""
if "attachments" in self.__dict__:
return self.attachments
data = sel... | Helper call to Bugzilla.get_attachments. If you want to fetch
specific attachment IDs, use that function instead | Below is the the instruction that describes the task:
### Input:
Helper call to Bugzilla.get_attachments. If you want to fetch
specific attachment IDs, use that function instead
### Response:
def get_attachments(self, include_fields=None, exclude_fields=None):
"""
Helper call to Bugzilla.ge... |
def pack_value(self, val):
"""Convert 8-byte string into 16-byte list"""
if isinstance(val, bytes):
val = list(iterbytes(val))
slen = len(val)
if self.pad:
pad = b'\0\0' * (slen % 2)
else:
pad = b''
return struct.pack('>' + 'H' * sle... | Convert 8-byte string into 16-byte list | Below is the the instruction that describes the task:
### Input:
Convert 8-byte string into 16-byte list
### Response:
def pack_value(self, val):
"""Convert 8-byte string into 16-byte list"""
if isinstance(val, bytes):
val = list(iterbytes(val))
slen = len(val)
if self... |
def contents(self):
"""The raw file contents as a string."""
if not self._contents:
if self._path:
# Read file into memory so we don't run out of file descriptors
f = open(self._path, "rb")
self._contents = f.read()
f.close()
... | The raw file contents as a string. | Below is the the instruction that describes the task:
### Input:
The raw file contents as a string.
### Response:
def contents(self):
"""The raw file contents as a string."""
if not self._contents:
if self._path:
# Read file into memory so we don't run out of file descri... |
def post(url, data=None, json=None, **kwargs):
"""A wrapper for ``requests.post``."""
_set_content_type(kwargs)
if _content_type_is_json(kwargs) and data is not None:
data = dumps(data)
_log_request('POST', url, kwargs, data)
response = requests.post(url, data, json, **kwargs)
_log_respo... | A wrapper for ``requests.post``. | Below is the the instruction that describes the task:
### Input:
A wrapper for ``requests.post``.
### Response:
def post(url, data=None, json=None, **kwargs):
"""A wrapper for ``requests.post``."""
_set_content_type(kwargs)
if _content_type_is_json(kwargs) and data is not None:
data = dumps(dat... |
def _pack_bits_into_byte(iterable):
"""\
Packs eight bits into one byte.
If the length of the iterable is not a multiple of eight, ``0x0`` is used
to fill-up the missing values.
"""
return (reduce(lambda x, y: (x << 1) + y, e)
for e in zip_longest(*[iter(iterable)] * 8, fillvalue=0x... | \
Packs eight bits into one byte.
If the length of the iterable is not a multiple of eight, ``0x0`` is used
to fill-up the missing values. | Below is the the instruction that describes the task:
### Input:
\
Packs eight bits into one byte.
If the length of the iterable is not a multiple of eight, ``0x0`` is used
to fill-up the missing values.
### Response:
def _pack_bits_into_byte(iterable):
"""\
Packs eight bits into one byte.
... |
def render_core(url_prefix, auth_header, resources):
"""Generate res.core.js"""
code = ''
code += "function(root, init) {\n"
code += " var q = init('%(auth_header)s', '%(url_prefix)s');\n" %\
{'url_prefix': url_prefix, 'auth_header': auth_header}
code += " var r = null;\n"
for key in r... | Generate res.core.js | Below is the the instruction that describes the task:
### Input:
Generate res.core.js
### Response:
def render_core(url_prefix, auth_header, resources):
"""Generate res.core.js"""
code = ''
code += "function(root, init) {\n"
code += " var q = init('%(auth_header)s', '%(url_prefix)s');\n" %\
... |
def connect(server, port, username, password):
"""This function might be something coming from your ORM"""
print("-" * 79)
print("Connecting to: {}".format(server))
print("At port: {}".format(port))
print("Using username: {}".format(username))
print("Using password: {}".format(password))
pri... | This function might be something coming from your ORM | Below is the the instruction that describes the task:
### Input:
This function might be something coming from your ORM
### Response:
def connect(server, port, username, password):
"""This function might be something coming from your ORM"""
print("-" * 79)
print("Connecting to: {}".format(server))
p... |
def table_schema(self):
"""
Returns the table schema.
:returns: dict
"""
if self.__dict__.get('_table_schema') is None:
self._table_schema = None
table_schema = {}
for row in self.query_schema():
name, default, dtype = self.db(... | Returns the table schema.
:returns: dict | Below is the the instruction that describes the task:
### Input:
Returns the table schema.
:returns: dict
### Response:
def table_schema(self):
"""
Returns the table schema.
:returns: dict
"""
if self.__dict__.get('_table_schema') is None:
self._table_s... |
def MAKE_WPARAM(wParam):
"""
Convert arguments to the WPARAM type.
Used automatically by SendMessage, PostMessage, etc.
You shouldn't need to call this function.
"""
wParam = ctypes.cast(wParam, LPVOID).value
if wParam is None:
wParam = 0
return wParam | Convert arguments to the WPARAM type.
Used automatically by SendMessage, PostMessage, etc.
You shouldn't need to call this function. | Below is the the instruction that describes the task:
### Input:
Convert arguments to the WPARAM type.
Used automatically by SendMessage, PostMessage, etc.
You shouldn't need to call this function.
### Response:
def MAKE_WPARAM(wParam):
"""
Convert arguments to the WPARAM type.
Used automatical... |
def get_all_route_tables(self, route_table_ids=None, filters=None):
"""
Retrieve information about your routing tables. You can filter results
to return information only about those route tables that match your
search parameters. Otherwise, all route tables associated with your
a... | Retrieve information about your routing tables. You can filter results
to return information only about those route tables that match your
search parameters. Otherwise, all route tables associated with your
account are returned.
:type route_table_ids: list
:param route_table_ids... | Below is the the instruction that describes the task:
### Input:
Retrieve information about your routing tables. You can filter results
to return information only about those route tables that match your
search parameters. Otherwise, all route tables associated with your
account are returned... |
def _findregex(self, reg_ex, start, end, bytealigned):
"""Find first occurrence of a compiled regular expression.
Note that this doesn't support arbitrary regexes, in particular they
must match a known length.
"""
p = start
length = len(reg_ex.pattern)
# We grab... | Find first occurrence of a compiled regular expression.
Note that this doesn't support arbitrary regexes, in particular they
must match a known length. | Below is the the instruction that describes the task:
### Input:
Find first occurrence of a compiled regular expression.
Note that this doesn't support arbitrary regexes, in particular they
must match a known length.
### Response:
def _findregex(self, reg_ex, start, end, bytealigned):
"""F... |
def do_roles(self, service):
"""
Role information
Usage:
> roles <servicename> Display role information for service
> roles all Display all role information for cluster
"""
if not self.has_cluster():
return None
if not se... | Role information
Usage:
> roles <servicename> Display role information for service
> roles all Display all role information for cluster | Below is the the instruction that describes the task:
### Input:
Role information
Usage:
> roles <servicename> Display role information for service
> roles all Display all role information for cluster
### Response:
def do_roles(self, service):
"""
Role ... |
def get_object(self, queryset=None):
"""
Fetch the object using a translated slug.
"""
if queryset is None:
queryset = self.get_queryset()
slug = self.kwargs[self.slug_url_kwarg]
choices = self.get_language_choices()
obj = None
using_fallback... | Fetch the object using a translated slug. | Below is the the instruction that describes the task:
### Input:
Fetch the object using a translated slug.
### Response:
def get_object(self, queryset=None):
"""
Fetch the object using a translated slug.
"""
if queryset is None:
queryset = self.get_queryset()
sl... |
def update_search_space(self, search_space):
"""TODO: this is urgly, we put all the initialization work in this method, because initialization relies
on search space, also because update_search_space is called at the beginning.
NOTE: updating search space is not supported.
Parameters
... | TODO: this is urgly, we put all the initialization work in this method, because initialization relies
on search space, also because update_search_space is called at the beginning.
NOTE: updating search space is not supported.
Parameters
----------
search_space:
searc... | Below is the the instruction that describes the task:
### Input:
TODO: this is urgly, we put all the initialization work in this method, because initialization relies
on search space, also because update_search_space is called at the beginning.
NOTE: updating search space is not supported.
... |
def compact_bucket(db, buck_key, limit):
"""
Perform the compaction operation. This reads in the bucket
information from the database, builds a compacted bucket record,
inserts that record in the appropriate place in the database, then
removes outdated updates.
:param db: A database handle for... | Perform the compaction operation. This reads in the bucket
information from the database, builds a compacted bucket record,
inserts that record in the appropriate place in the database, then
removes outdated updates.
:param db: A database handle for the Redis database.
:param buck_key: A turnstile... | Below is the the instruction that describes the task:
### Input:
Perform the compaction operation. This reads in the bucket
information from the database, builds a compacted bucket record,
inserts that record in the appropriate place in the database, then
removes outdated updates.
:param db: A dat... |
def make_ref_target_directive(ref_type, indextemplates=None, **kwargs):
"""
Create and return a L{BBRefTargetDirective} subclass.
"""
class_vars = dict(ref_type=ref_type, indextemplates=indextemplates)
class_vars.update(kwargs)
return type("BB%sRefTargetDirective" % (ref_type.capitalize(),),
... | Create and return a L{BBRefTargetDirective} subclass. | Below is the the instruction that describes the task:
### Input:
Create and return a L{BBRefTargetDirective} subclass.
### Response:
def make_ref_target_directive(ref_type, indextemplates=None, **kwargs):
"""
Create and return a L{BBRefTargetDirective} subclass.
"""
class_vars = dict(ref_type=ref_t... |
def _raise_redirect_exceptions(response):
"""Return the new url or None if there are no redirects.
Raise exceptions if appropriate.
"""
if response.status_code not in [301, 302, 307]:
return None
new_url = urljoin(response.url, response.headers['location'])
if 'reddits/search' in new_u... | Return the new url or None if there are no redirects.
Raise exceptions if appropriate. | Below is the the instruction that describes the task:
### Input:
Return the new url or None if there are no redirects.
Raise exceptions if appropriate.
### Response:
def _raise_redirect_exceptions(response):
"""Return the new url or None if there are no redirects.
Raise exceptions if appropriate.
... |
def __find_rows(self, find_url, **attributes):
"""
:param find_url: URL of the find api
:type find_url: string
:return: The Response returned by requests including the list of documents based on find_url
:rtype: Response object
"""
req = self.url +... | :param find_url: URL of the find api
:type find_url: string
:return: The Response returned by requests including the list of documents based on find_url
:rtype: Response object | Below is the the instruction that describes the task:
### Input:
:param find_url: URL of the find api
:type find_url: string
:return: The Response returned by requests including the list of documents based on find_url
:rtype: Response object
### Response:
def __find_rows(self, f... |
def _adjacent_tri(self, edge, i):
"""
Given a triangle formed by edge and i, return the triangle that shares
edge. *i* may be either a point or the entire triangle.
"""
if not np.isscalar(i):
i = [x for x in i if x not in edge][0]
try:
pt1 = self.... | Given a triangle formed by edge and i, return the triangle that shares
edge. *i* may be either a point or the entire triangle. | Below is the the instruction that describes the task:
### Input:
Given a triangle formed by edge and i, return the triangle that shares
edge. *i* may be either a point or the entire triangle.
### Response:
def _adjacent_tri(self, edge, i):
"""
Given a triangle formed by edge and i, return t... |
def SendUnicodeChar(char: str) -> int:
"""
Type a single unicode char.
char: str, len(char) must equal to 1.
Return int, the number of events that it successfully inserted into the keyboard or mouse input stream.
If the function returns zero, the input was already blocked by another thre... | Type a single unicode char.
char: str, len(char) must equal to 1.
Return int, the number of events that it successfully inserted into the keyboard or mouse input stream.
If the function returns zero, the input was already blocked by another thread. | Below is the the instruction that describes the task:
### Input:
Type a single unicode char.
char: str, len(char) must equal to 1.
Return int, the number of events that it successfully inserted into the keyboard or mouse input stream.
If the function returns zero, the input was already block... |
async def update(self):
"""Fetch the latest data from IP Webcam."""
status_data = await self._request('/status.json?show_avail=1')
if status_data:
self.status_data = status_data
sensor_data = await self._request('/sensors.json')
if sensor_data:
... | Fetch the latest data from IP Webcam. | Below is the the instruction that describes the task:
### Input:
Fetch the latest data from IP Webcam.
### Response:
async def update(self):
"""Fetch the latest data from IP Webcam."""
status_data = await self._request('/status.json?show_avail=1')
if status_data:
self.status_da... |
def reset(self):
"""
Clear the active cells.
"""
self.activePhases = np.empty((0,2), dtype="float")
self.phaseDisplacement = np.empty((0,2), dtype="float")
self.cellsForActivePhases = np.empty(0, dtype="int")
self.activeCells = np.empty(0, dtype="int")
self.sensoryAssociatedCells = np.em... | Clear the active cells. | Below is the the instruction that describes the task:
### Input:
Clear the active cells.
### Response:
def reset(self):
"""
Clear the active cells.
"""
self.activePhases = np.empty((0,2), dtype="float")
self.phaseDisplacement = np.empty((0,2), dtype="float")
self.cellsForActivePhases = np.e... |
def _find_path(self, search_dirs, file_name):
"""
Search for the given file, and return the path.
Returns None if the file is not found.
"""
for dir_path in search_dirs:
file_path = os.path.join(dir_path, file_name)
if os.path.exists(file_path):
... | Search for the given file, and return the path.
Returns None if the file is not found. | Below is the the instruction that describes the task:
### Input:
Search for the given file, and return the path.
Returns None if the file is not found.
### Response:
def _find_path(self, search_dirs, file_name):
"""
Search for the given file, and return the path.
Returns None if t... |
def compile(expression, escape_funcs=None, unescape_funcs=None):
"""
Compile grammar (given as regex string), returning a `CompiledGrammar`
instance.
"""
return _compile_from_parse_tree(
parse_regex(tokenize_regex(expression)),
escape_funcs=escape_funcs,
unescape_funcs=unesca... | Compile grammar (given as regex string), returning a `CompiledGrammar`
instance. | Below is the the instruction that describes the task:
### Input:
Compile grammar (given as regex string), returning a `CompiledGrammar`
instance.
### Response:
def compile(expression, escape_funcs=None, unescape_funcs=None):
"""
Compile grammar (given as regex string), returning a `CompiledGrammar`
... |
def segment_pofile(filename, segments):
"""Segment a .po file using patterns in `segments`.
The .po file at `filename` is read, and the occurrence locations of its
messages are examined. `segments` is a dictionary: the keys are segment
.po filenames, the values are lists of patterns::
{
... | Segment a .po file using patterns in `segments`.
The .po file at `filename` is read, and the occurrence locations of its
messages are examined. `segments` is a dictionary: the keys are segment
.po filenames, the values are lists of patterns::
{
'django-studio.po': [
'c... | Below is the the instruction that describes the task:
### Input:
Segment a .po file using patterns in `segments`.
The .po file at `filename` is read, and the occurrence locations of its
messages are examined. `segments` is a dictionary: the keys are segment
.po filenames, the values are lists of patte... |
def login(self, username, password, strict=True):
""" Login as specified user
Args:
username (str): The username to log in with
password (str): The password for the user
strict (bool): `True` to thow an error on failure
Returns:
... | Login as specified user
Args:
username (str): The username to log in with
password (str): The password for the user
strict (bool): `True` to thow an error on failure
Returns:
bool: `True` if successfully logged in; `False` otherwis... | Below is the the instruction that describes the task:
### Input:
Login as specified user
Args:
username (str): The username to log in with
password (str): The password for the user
strict (bool): `True` to thow an error on failure
Returns:
... |
def can_use_cached_output(self, contentitem):
"""
Read the cached output - only when search needs it.
"""
return contentitem.plugin.search_output and not contentitem.plugin.search_fields \
and super(SearchRenderingPipe, self).can_use_cached_output(contentitem) | Read the cached output - only when search needs it. | Below is the the instruction that describes the task:
### Input:
Read the cached output - only when search needs it.
### Response:
def can_use_cached_output(self, contentitem):
"""
Read the cached output - only when search needs it.
"""
return contentitem.plugin.search_output and no... |
async def init(app, loop):
"""Sends a message to the webhook channel when server starts."""
app.session = aiohttp.ClientSession(loop=loop) # to make web requests
app.webhook = Webhook.Async(webhook_url, session=app.session)
em = Embed(color=0x2ecc71)
em.set_author('[INFO] Starting Worker')
em.... | Sends a message to the webhook channel when server starts. | Below is the the instruction that describes the task:
### Input:
Sends a message to the webhook channel when server starts.
### Response:
async def init(app, loop):
"""Sends a message to the webhook channel when server starts."""
app.session = aiohttp.ClientSession(loop=loop) # to make web requests
ap... |
def send_message(chat_id):
"""Send a message to a chat
If a media file is found, send_media is called, else a simple text message
is sent
"""
files = request.files
if files:
res = send_media(chat_id, request)
else:
message = request.form.get('message')
res = g.drive... | Send a message to a chat
If a media file is found, send_media is called, else a simple text message
is sent | Below is the the instruction that describes the task:
### Input:
Send a message to a chat
If a media file is found, send_media is called, else a simple text message
is sent
### Response:
def send_message(chat_id):
"""Send a message to a chat
If a media file is found, send_media is called, else a si... |
def delete(self, response_choice=1, async=False, callback=None):
""" Delete object and call given callback in case of call.
Args:
response_choice (int): Automatically send a response choice when confirmation is needed
async (bool): Boolean to make an asynchronous cal... | Delete object and call given callback in case of call.
Args:
response_choice (int): Automatically send a response choice when confirmation is needed
async (bool): Boolean to make an asynchronous call. Default is False
callback (function): Callback method that... | Below is the the instruction that describes the task:
### Input:
Delete object and call given callback in case of call.
Args:
response_choice (int): Automatically send a response choice when confirmation is needed
async (bool): Boolean to make an asynchronous call. Defau... |
def send_batches(self, batch_list):
"""Sends a list of batches to the validator.
Args:
batch_list (:obj:`BatchList`): the list of batches
Returns:
dict: the json result data, as a dict
"""
if isinstance(batch_list, BaseMessage):
batch_list = ... | Sends a list of batches to the validator.
Args:
batch_list (:obj:`BatchList`): the list of batches
Returns:
dict: the json result data, as a dict | Below is the the instruction that describes the task:
### Input:
Sends a list of batches to the validator.
Args:
batch_list (:obj:`BatchList`): the list of batches
Returns:
dict: the json result data, as a dict
### Response:
def send_batches(self, batch_list):
"""S... |
def main():
"""
Check Dependencies, download files, integrity check
"""
# vars
tar_file = TMPDIR + '/' + BINARY_URL.split('/')[-1]
chksum = TMPDIR + '/' + MD5_URL.split('/')[-1]
# pre-run validation + execution
if precheck() and os_packages(distro.linux_distribution()):
stdout_me... | Check Dependencies, download files, integrity check | Below is the the instruction that describes the task:
### Input:
Check Dependencies, download files, integrity check
### Response:
def main():
"""
Check Dependencies, download files, integrity check
"""
# vars
tar_file = TMPDIR + '/' + BINARY_URL.split('/')[-1]
chksum = TMPDIR + '/' + MD5_U... |
def uriunsplit(uri):
"""
Reverse of urisplit()
>>> uriunsplit(('scheme','authority','path','query','fragment'))
"scheme://authority/path?query#fragment"
"""
(scheme, authority, path, query, fragment) = uri
result = ''
if scheme:
result += scheme + ':'
if authority:
... | Reverse of urisplit()
>>> uriunsplit(('scheme','authority','path','query','fragment'))
"scheme://authority/path?query#fragment" | Below is the the instruction that describes the task:
### Input:
Reverse of urisplit()
>>> uriunsplit(('scheme','authority','path','query','fragment'))
"scheme://authority/path?query#fragment"
### Response:
def uriunsplit(uri):
"""
Reverse of urisplit()
>>> uriunsplit(('scheme','a... |
def get_model_string(model_name):
"""
Returns the model string notation Django uses for lazily loaded ForeignKeys
(eg 'auth.User') to prevent circular imports.
This is needed to allow our crazy custom model usage.
"""
setting_name = "LINGUIST_%s_MODEL" % model_name.upper().replace("_", "")
c... | Returns the model string notation Django uses for lazily loaded ForeignKeys
(eg 'auth.User') to prevent circular imports.
This is needed to allow our crazy custom model usage. | Below is the the instruction that describes the task:
### Input:
Returns the model string notation Django uses for lazily loaded ForeignKeys
(eg 'auth.User') to prevent circular imports.
This is needed to allow our crazy custom model usage.
### Response:
def get_model_string(model_name):
"""
Return... |
def set_copyright_registration(self, registration):
"""Sets the copyright registration.
arg: registration (string): the new copyright registration
raise: InvalidArgument - ``copyright`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument ... | Sets the copyright registration.
arg: registration (string): the new copyright registration
raise: InvalidArgument - ``copyright`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``copyright`` is ``null``
*compliance: mandatory -- T... | Below is the the instruction that describes the task:
### Input:
Sets the copyright registration.
arg: registration (string): the new copyright registration
raise: InvalidArgument - ``copyright`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArg... |
def closest_point_of_approach(
self,
lateral_separation: float,
vertical_separation: float,
projection: Union[pyproj.Proj, crs.Projection, None] = None,
round_t: str = "d",
max_workers: int = 4,
) -> "CPA":
"""
Computes a CPA dataframe for all pairs of... | Computes a CPA dataframe for all pairs of trajectories candidates for
being separated by less than lateral_separation in vertical_separation.
In order to be computed efficiently, the method needs the following
parameters:
- projection: a first filtering is applied on the bounding boxes... | Below is the the instruction that describes the task:
### Input:
Computes a CPA dataframe for all pairs of trajectories candidates for
being separated by less than lateral_separation in vertical_separation.
In order to be computed efficiently, the method needs the following
parameters:
... |
def close(self, timeout: int = 5) -> None:
"""Stop a ffmpeg instance.
Return a coroutine
"""
if self._read_task is not None and not self._read_task.cancelled():
self._read_task.cancel()
return super().close(timeout) | Stop a ffmpeg instance.
Return a coroutine | Below is the the instruction that describes the task:
### Input:
Stop a ffmpeg instance.
Return a coroutine
### Response:
def close(self, timeout: int = 5) -> None:
"""Stop a ffmpeg instance.
Return a coroutine
"""
if self._read_task is not None and not self._read_task.can... |
def get_command(self, ctx, cmd_name):
"""
gets the Click Commands underneath a service name
Parameters
----------
ctx: Context
context object passed in
cmd_name: string
the service name
Returns
-------
cmd: Click.Command
... | gets the Click Commands underneath a service name
Parameters
----------
ctx: Context
context object passed in
cmd_name: string
the service name
Returns
-------
cmd: Click.Command
the Click Commands that can be called from the C... | Below is the the instruction that describes the task:
### Input:
gets the Click Commands underneath a service name
Parameters
----------
ctx: Context
context object passed in
cmd_name: string
the service name
Returns
-------
cmd: Click... |
def execute_script_actions(
self, resource_group_name, cluster_name, persist_on_success, script_actions=None, custom_headers=None, raw=False, polling=True, **operation_config):
"""Executes script actions on the specified HDInsight cluster.
:param resource_group_name: The name of the resourc... | Executes script actions on the specified HDInsight cluster.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param cluster_name: The name of the cluster.
:type cluster_name: str
:param persist_on_success: Gets or sets if the scripts nee... | Below is the the instruction that describes the task:
### Input:
Executes script actions on the specified HDInsight cluster.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param cluster_name: The name of the cluster.
:type cluster_name: s... |
def main(catalog):
"""Permite validar un catálogo por línea de comandos.
Args:
catalog (str): Path local o URL a un catálogo.
"""
res = validate_catalog(catalog, only_errors=True, fmt="list",
export_path=None, validator=None)
print("")
print("=== Errores a niv... | Permite validar un catálogo por línea de comandos.
Args:
catalog (str): Path local o URL a un catálogo. | Below is the the instruction that describes the task:
### Input:
Permite validar un catálogo por línea de comandos.
Args:
catalog (str): Path local o URL a un catálogo.
### Response:
def main(catalog):
"""Permite validar un catálogo por línea de comandos.
Args:
catalog (str): Path loc... |
def _step7func(self, samples, force, ipyclient):
""" Step 7: Filter and write output files """
## Get sample objects from list of strings
samples = _get_samples(self, samples)
if self._headers:
print("\n Step 7: Filter and write output files for {} Samples".\
... | Step 7: Filter and write output files | Below is the the instruction that describes the task:
### Input:
Step 7: Filter and write output files
### Response:
def _step7func(self, samples, force, ipyclient):
""" Step 7: Filter and write output files """
## Get sample objects from list of strings
samples = _get_samples(self, sample... |
def pid(self):
"""Get PID object for the Release record."""
if self.model.status == ReleaseStatus.PUBLISHED and self.record:
fetcher = current_pidstore.fetchers[
current_app.config.get('GITHUB_PID_FETCHER')]
return fetcher(self.record.id, self.record) | Get PID object for the Release record. | Below is the the instruction that describes the task:
### Input:
Get PID object for the Release record.
### Response:
def pid(self):
"""Get PID object for the Release record."""
if self.model.status == ReleaseStatus.PUBLISHED and self.record:
fetcher = current_pidstore.fetchers[
... |
def _check_grad_measurement_matrices(dM, state_dim, grad_params_no, measurement_dim, which = 'dH'):
"""
Function checks (mostly check dimensions) matrices for marginal likelihood
gradient parameters calculation. It check dH, dR matrices.
Input:
-------------
dM: None... | Function checks (mostly check dimensions) matrices for marginal likelihood
gradient parameters calculation. It check dH, dR matrices.
Input:
-------------
dM: None, scaler or 3D matrix
It is supposed to be
(measurement_dim ,state_dim,grad_params_no) f... | Below is the the instruction that describes the task:
### Input:
Function checks (mostly check dimensions) matrices for marginal likelihood
gradient parameters calculation. It check dH, dR matrices.
Input:
-------------
dM: None, scaler or 3D matrix
It is suppose... |
def parse_version_string(version_string):
"""Parses a semver version string, stripping off "rc" stuff if present."""
string_parts = version_string.split(".")
version_parts = [
int(re.match("([0-9]*)", string_parts[0]).group(0)),
int(re.match("([0-9]*)", string_parts[1]).group(0)),
i... | Parses a semver version string, stripping off "rc" stuff if present. | Below is the the instruction that describes the task:
### Input:
Parses a semver version string, stripping off "rc" stuff if present.
### Response:
def parse_version_string(version_string):
"""Parses a semver version string, stripping off "rc" stuff if present."""
string_parts = version_string.split(".")
... |
def wait(self, operation):
"""Awaits for Google Cloud Dataproc Operation to complete."""
submitted = _DataProcOperation(self.get_conn(), operation,
self.num_retries)
submitted.wait_for_done() | Awaits for Google Cloud Dataproc Operation to complete. | Below is the the instruction that describes the task:
### Input:
Awaits for Google Cloud Dataproc Operation to complete.
### Response:
def wait(self, operation):
"""Awaits for Google Cloud Dataproc Operation to complete."""
submitted = _DataProcOperation(self.get_conn(), operation,
... |
def merge_layouts(layouts):
''' Utility function for merging multiple layouts.
Args:
layouts (list): A list of BIDSLayout instances to merge.
Returns:
A BIDSLayout containing merged files and entities.
Notes:
Layouts will be merged in the order of the elements in the list. I.e.,... | Utility function for merging multiple layouts.
Args:
layouts (list): A list of BIDSLayout instances to merge.
Returns:
A BIDSLayout containing merged files and entities.
Notes:
Layouts will be merged in the order of the elements in the list. I.e.,
the first Layout will be up... | Below is the the instruction that describes the task:
### Input:
Utility function for merging multiple layouts.
Args:
layouts (list): A list of BIDSLayout instances to merge.
Returns:
A BIDSLayout containing merged files and entities.
Notes:
Layouts will be merged in the order o... |
def get(self, sid):
"""
Constructs a DeploymentContext
:param sid: The sid
:returns: twilio.rest.serverless.v1.service.environment.deployment.DeploymentContext
:rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentContext
"""
return Deployme... | Constructs a DeploymentContext
:param sid: The sid
:returns: twilio.rest.serverless.v1.service.environment.deployment.DeploymentContext
:rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentContext | Below is the the instruction that describes the task:
### Input:
Constructs a DeploymentContext
:param sid: The sid
:returns: twilio.rest.serverless.v1.service.environment.deployment.DeploymentContext
:rtype: twilio.rest.serverless.v1.service.environment.deployment.DeploymentContext
### Re... |
def getReadNoiseImage(self, chip):
"""
Notes
=====
Method for returning the readnoise image of a detector
(in electrons).
The method will return an array of the same shape as the image.
:units: electrons
"""
sci_chip = self._image[self.scienceEx... | Notes
=====
Method for returning the readnoise image of a detector
(in electrons).
The method will return an array of the same shape as the image.
:units: electrons | Below is the the instruction that describes the task:
### Input:
Notes
=====
Method for returning the readnoise image of a detector
(in electrons).
The method will return an array of the same shape as the image.
:units: electrons
### Response:
def getReadNoiseImage(self, c... |
def deferred_write(bucket):
"""Context manager for deferring writes of a :py:class:`Bucket` within a
block.
Parameters:
bucket (:py:class:`Bucket`): Bucket to defer writes for within context.
Returns:
Bucket to use within context.
:rtype: :py:class:`DeferredWriteBucket`
When ... | Context manager for deferring writes of a :py:class:`Bucket` within a
block.
Parameters:
bucket (:py:class:`Bucket`): Bucket to defer writes for within context.
Returns:
Bucket to use within context.
:rtype: :py:class:`DeferredWriteBucket`
When the context is closed, the stored o... | Below is the the instruction that describes the task:
### Input:
Context manager for deferring writes of a :py:class:`Bucket` within a
block.
Parameters:
bucket (:py:class:`Bucket`): Bucket to defer writes for within context.
Returns:
Bucket to use within context.
:rtype: :py:clas... |
def is_unicode(value):
""" Check if a value is a valid unicode string, compatible with python 2 and python 3
>>> is_unicode(u'foo')
True
>>> is_unicode(u'✌')
True
>>> is_unicode(b'foo')
False
>>> is_unicode(42)
False
>>> is_unicode(('abc',))
False
"""
python_version ... | Check if a value is a valid unicode string, compatible with python 2 and python 3
>>> is_unicode(u'foo')
True
>>> is_unicode(u'✌')
True
>>> is_unicode(b'foo')
False
>>> is_unicode(42)
False
>>> is_unicode(('abc',))
False | Below is the the instruction that describes the task:
### Input:
Check if a value is a valid unicode string, compatible with python 2 and python 3
>>> is_unicode(u'foo')
True
>>> is_unicode(u'✌')
True
>>> is_unicode(b'foo')
False
>>> is_unicode(42)
False
>>> is_unicode(('abc',))... |
def run(self, cmd):
'''
Execute the salt command given by cmd dict.
cmd is a dictionary of the following form:
{
'mode': 'modestring',
'fun' : 'modulefunctionstring',
'kwarg': functionkeywordargdictionary,
'tgt' : 'targetpatternstring',
... | Execute the salt command given by cmd dict.
cmd is a dictionary of the following form:
{
'mode': 'modestring',
'fun' : 'modulefunctionstring',
'kwarg': functionkeywordargdictionary,
'tgt' : 'targetpatternstring',
'tgt_type' : 'targetpatternty... | Below is the the instruction that describes the task:
### Input:
Execute the salt command given by cmd dict.
cmd is a dictionary of the following form:
{
'mode': 'modestring',
'fun' : 'modulefunctionstring',
'kwarg': functionkeywordargdictionary,
'tg... |
def p_if_statement(self, p):
'''statement : IF expression block elif_list else_clause END_IF'''
p[0] = IfNode(expression=p[2],
block=p[3],
elif_list=p[4],
else_clause=p[5]) | statement : IF expression block elif_list else_clause END_IF | Below is the the instruction that describes the task:
### Input:
statement : IF expression block elif_list else_clause END_IF
### Response:
def p_if_statement(self, p):
'''statement : IF expression block elif_list else_clause END_IF'''
p[0] = IfNode(expression=p[2],
block=p[3]... |
def handle_audio(obj, wait=False):
"""Handle an audio event.
This function plays an audio file.
Currently only `.wav` format is supported.
:param obj: An :py:class:`~turberfield.dialogue.model.Model.Audio`
object.
:param bool wait: Force a blocking wait until playba... | Handle an audio event.
This function plays an audio file.
Currently only `.wav` format is supported.
:param obj: An :py:class:`~turberfield.dialogue.model.Model.Audio`
object.
:param bool wait: Force a blocking wait until playback is complete.
:return: The supplied ... | Below is the the instruction that describes the task:
### Input:
Handle an audio event.
This function plays an audio file.
Currently only `.wav` format is supported.
:param obj: An :py:class:`~turberfield.dialogue.model.Model.Audio`
object.
:param bool wait: Force a blo... |
def fillna(series_or_arr, missing_value=0.0):
"""Fill missing values in pandas objects and numpy arrays.
Arguments
---------
series_or_arr : pandas.Series, numpy.ndarray
The numpy array or pandas series for which the missing values
need to be replaced.
missing_value : float, int, st... | Fill missing values in pandas objects and numpy arrays.
Arguments
---------
series_or_arr : pandas.Series, numpy.ndarray
The numpy array or pandas series for which the missing values
need to be replaced.
missing_value : float, int, str
The value to replace the missing value with... | Below is the the instruction that describes the task:
### Input:
Fill missing values in pandas objects and numpy arrays.
Arguments
---------
series_or_arr : pandas.Series, numpy.ndarray
The numpy array or pandas series for which the missing values
need to be replaced.
missing_value ... |
def update_record(self, name, new_data, condition, update_only=False,
debug=False):
"""
Find the first row in self.df with index == name
and condition == True.
Update that record with new_data, then delete any
additional records where index == name and condi... | Find the first row in self.df with index == name
and condition == True.
Update that record with new_data, then delete any
additional records where index == name and condition == True.
Change is inplace | Below is the the instruction that describes the task:
### Input:
Find the first row in self.df with index == name
and condition == True.
Update that record with new_data, then delete any
additional records where index == name and condition == True.
Change is inplace
### Response:
de... |
def _apply_all_time_reductions(self, data):
"""Apply all requested time reductions to the data."""
logging.info(self._print_verbose("Applying desired time-"
"reduction methods."))
reduc_specs = [r.split('.') for r in self.dtype_out_time]
reduced =... | Apply all requested time reductions to the data. | Below is the the instruction that describes the task:
### Input:
Apply all requested time reductions to the data.
### Response:
def _apply_all_time_reductions(self, data):
"""Apply all requested time reductions to the data."""
logging.info(self._print_verbose("Applying desired time-"
... |
def read32(bytestream):
"""Read 4 bytes from bytestream as an unsigned 32-bit integer."""
dt = np.dtype(np.uint32).newbyteorder('>')
return np.frombuffer(bytestream.read(4), dtype=dt)[0] | Read 4 bytes from bytestream as an unsigned 32-bit integer. | Below is the the instruction that describes the task:
### Input:
Read 4 bytes from bytestream as an unsigned 32-bit integer.
### Response:
def read32(bytestream):
"""Read 4 bytes from bytestream as an unsigned 32-bit integer."""
dt = np.dtype(np.uint32).newbyteorder('>')
return np.frombuffer(bytestream.read(... |
def init_conv_weight(layer):
'''initilize conv layer weight.
'''
n_filters = layer.filters
filter_shape = (layer.kernel_size,) * get_n_dim(layer)
weight = np.zeros((n_filters, n_filters) + filter_shape)
center = tuple(map(lambda x: int((x - 1) / 2), filter_shape))
for i in range(n_filters):... | initilize conv layer weight. | Below is the the instruction that describes the task:
### Input:
initilize conv layer weight.
### Response:
def init_conv_weight(layer):
'''initilize conv layer weight.
'''
n_filters = layer.filters
filter_shape = (layer.kernel_size,) * get_n_dim(layer)
weight = np.zeros((n_filters, n_filters) ... |
def float_to_latex(x, format="%.2g"): # pylint: disable=redefined-builtin
# pylint: disable=anomalous-backslash-in-string
r"""Convert a floating point number to a latex representation.
In particular, scientific notation is handled gracefully: e -> 10^
Parameters
----------
x : `float`
... | r"""Convert a floating point number to a latex representation.
In particular, scientific notation is handled gracefully: e -> 10^
Parameters
----------
x : `float`
the number to represent
format : `str`, optional
the output string format
Returns
-------
tex : `str`
... | Below is the the instruction that describes the task:
### Input:
r"""Convert a floating point number to a latex representation.
In particular, scientific notation is handled gracefully: e -> 10^
Parameters
----------
x : `float`
the number to represent
format : `str`, optional
... |
def add_account_alias(self, account, alias):
"""
:param account: an account object to be used as a selector
:param alias: email alias address
:returns: None (the API itself returns nothing)
"""
self.request('AddAccountAlias', {
'id': self._get_or_... | :param account: an account object to be used as a selector
:param alias: email alias address
:returns: None (the API itself returns nothing) | Below is the the instruction that describes the task:
### Input:
:param account: an account object to be used as a selector
:param alias: email alias address
:returns: None (the API itself returns nothing)
### Response:
def add_account_alias(self, account, alias):
"""
:... |
def error(self):
"""
Class property: Sum of the squared errors,
:math:`E = \sum_i (D_i - M_i(\\theta))^2`
"""
r = self.residuals.ravel()
return np.dot(r,r) | Class property: Sum of the squared errors,
:math:`E = \sum_i (D_i - M_i(\\theta))^2` | Below is the the instruction that describes the task:
### Input:
Class property: Sum of the squared errors,
:math:`E = \sum_i (D_i - M_i(\\theta))^2`
### Response:
def error(self):
"""
Class property: Sum of the squared errors,
:math:`E = \sum_i (D_i - M_i(\\theta))^2`
"""
... |
def download_pic(self, filename: str, url: str, mtime: datetime,
filename_suffix: Optional[str] = None, _attempt: int = 1) -> bool:
"""Downloads and saves picture with given url under given directory with given timestamp.
Returns true, if file was actually downloaded, i.e. updated."... | Downloads and saves picture with given url under given directory with given timestamp.
Returns true, if file was actually downloaded, i.e. updated. | Below is the the instruction that describes the task:
### Input:
Downloads and saves picture with given url under given directory with given timestamp.
Returns true, if file was actually downloaded, i.e. updated.
### Response:
def download_pic(self, filename: str, url: str, mtime: datetime,
... |
def ReplaceStopTimeObject(self, stoptime, schedule=None):
"""Replace a StopTime object from this trip with the given one.
Keys the StopTime object to be replaced by trip_id, stop_sequence
and stop_id as 'stoptime', with the object 'stoptime'.
"""
if schedule is None:
schedule = self._schedul... | Replace a StopTime object from this trip with the given one.
Keys the StopTime object to be replaced by trip_id, stop_sequence
and stop_id as 'stoptime', with the object 'stoptime'. | Below is the the instruction that describes the task:
### Input:
Replace a StopTime object from this trip with the given one.
Keys the StopTime object to be replaced by trip_id, stop_sequence
and stop_id as 'stoptime', with the object 'stoptime'.
### Response:
def ReplaceStopTimeObject(self, stoptime, sch... |
def enable_page_breakpoint(self, dwProcessId, address):
"""
Enables the page breakpoint at the given address.
@see:
L{define_page_breakpoint},
L{has_page_breakpoint},
L{get_page_breakpoint},
L{enable_one_shot_page_breakpoint},
L{disabl... | Enables the page breakpoint at the given address.
@see:
L{define_page_breakpoint},
L{has_page_breakpoint},
L{get_page_breakpoint},
L{enable_one_shot_page_breakpoint},
L{disable_page_breakpoint}
L{erase_page_breakpoint},
@type dwP... | Below is the the instruction that describes the task:
### Input:
Enables the page breakpoint at the given address.
@see:
L{define_page_breakpoint},
L{has_page_breakpoint},
L{get_page_breakpoint},
L{enable_one_shot_page_breakpoint},
L{disable_page_... |
def get_scores(course_id, student_id):
"""Return a dict mapping item_ids to scores.
Scores are represented by serialized Score objects in JSON-like dict
format.
This method would be used by an LMS to find all the scores for a given
student in a given course.
Scores that are "hidden" (because ... | Return a dict mapping item_ids to scores.
Scores are represented by serialized Score objects in JSON-like dict
format.
This method would be used by an LMS to find all the scores for a given
student in a given course.
Scores that are "hidden" (because they have points earned set to zero)
are e... | Below is the the instruction that describes the task:
### Input:
Return a dict mapping item_ids to scores.
Scores are represented by serialized Score objects in JSON-like dict
format.
This method would be used by an LMS to find all the scores for a given
student in a given course.
Scores that... |
def _queue_management_worker(self):
""" TODO: docstring """
logger.debug("[MTHREAD] queue management worker starting")
while True:
task_id, buf = self.incoming_q.get() # TODO: why does this hang?
msg = deserialize_object(buf)[0]
# TODO: handle exceptions
... | TODO: docstring | Below is the the instruction that describes the task:
### Input:
TODO: docstring
### Response:
def _queue_management_worker(self):
""" TODO: docstring """
logger.debug("[MTHREAD] queue management worker starting")
while True:
task_id, buf = self.incoming_q.get() # TODO: why do... |
def _ndays(self, start_date, ndays):
"""
Compute an end date given a start date and a number of days.
"""
if not getattr(self.args, 'start-date') and not self.config.get('start-date', None):
raise Exception('start-date must be provided when ndays is used.')
d = date(... | Compute an end date given a start date and a number of days. | Below is the the instruction that describes the task:
### Input:
Compute an end date given a start date and a number of days.
### Response:
def _ndays(self, start_date, ndays):
"""
Compute an end date given a start date and a number of days.
"""
if not getattr(self.args, 'start-date... |
def activate(self, engine):
"""
Activates the Component.
:param engine: Engine to attach the Component to.
:type engine: QObject
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Activating '{0}' Component.".format(self.__class__.__name__))
... | Activates the Component.
:param engine: Engine to attach the Component to.
:type engine: QObject
:return: Method success.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Activates the Component.
:param engine: Engine to attach the Component to.
:type engine: QObject
:return: Method success.
:rtype: bool
### Response:
def activate(self, engine):
"""
Activates the Compon... |
def urls(self):
"""
The decoded URL list for this MIME::Type.
The special URL value IANA will be translated into:
http://www.iana.org/assignments/media-types/<mediatype>/<subtype>
The special URL value RFC### will be translated into:
http://www.rfc-editor.org/rfc/rfc#... | The decoded URL list for this MIME::Type.
The special URL value IANA will be translated into:
http://www.iana.org/assignments/media-types/<mediatype>/<subtype>
The special URL value RFC### will be translated into:
http://www.rfc-editor.org/rfc/rfc###.txt
The special URL value... | Below is the the instruction that describes the task:
### Input:
The decoded URL list for this MIME::Type.
The special URL value IANA will be translated into:
http://www.iana.org/assignments/media-types/<mediatype>/<subtype>
The special URL value RFC### will be translated into:
h... |
def _get_optimal_threshold(arr, quantized_dtype, num_bins=8001, num_quantized_bins=255):
"""Given a dataset, find the optimal threshold for quantizing it.
The reference distribution is `q`, and the candidate distribution is `p`.
`q` is a truncated version of the original distribution.
Ref: http://on-de... | Given a dataset, find the optimal threshold for quantizing it.
The reference distribution is `q`, and the candidate distribution is `p`.
`q` is a truncated version of the original distribution.
Ref: http://on-demand.gputechconf.com/gtc/2017/presentation/s7310-8-bit-inference-with-tensorrt.pdf | Below is the the instruction that describes the task:
### Input:
Given a dataset, find the optimal threshold for quantizing it.
The reference distribution is `q`, and the candidate distribution is `p`.
`q` is a truncated version of the original distribution.
Ref: http://on-demand.gputechconf.com/gtc/20... |
def ide(self):
"""
Generates a IDE number (9 digits).
http://www.bfs.admin.ch/bfs/portal/fr/index/themen/00/05/blank/03/02.html
"""
def _checksum(digits):
factors = (5, 4, 3, 2, 7, 6, 5, 4)
sum_ = 0
for i in range(len(digits)):
... | Generates a IDE number (9 digits).
http://www.bfs.admin.ch/bfs/portal/fr/index/themen/00/05/blank/03/02.html | Below is the the instruction that describes the task:
### Input:
Generates a IDE number (9 digits).
http://www.bfs.admin.ch/bfs/portal/fr/index/themen/00/05/blank/03/02.html
### Response:
def ide(self):
"""
Generates a IDE number (9 digits).
http://www.bfs.admin.ch/bfs/portal/fr/ind... |
def filter_repos(config, repo_dir=None, vcs_url=None, name=None):
"""Return a :py:obj:`list` list of repos from (expanded) config file.
repo_dir, vcs_url and name all support fnmatch.
:param config: the expanded repo config in :py:class:`dict` format.
:type config: dict
:param repo_dir: directory ... | Return a :py:obj:`list` list of repos from (expanded) config file.
repo_dir, vcs_url and name all support fnmatch.
:param config: the expanded repo config in :py:class:`dict` format.
:type config: dict
:param repo_dir: directory of checkout location, fnmatch pattern supported
:type repo_dir: str o... | Below is the the instruction that describes the task:
### Input:
Return a :py:obj:`list` list of repos from (expanded) config file.
repo_dir, vcs_url and name all support fnmatch.
:param config: the expanded repo config in :py:class:`dict` format.
:type config: dict
:param repo_dir: directory of c... |
def getExpiresIn(self, now=None):
"""
This returns the number of seconds this association is still
valid for, or C{0} if the association is no longer valid.
@return: The number of seconds this association is still valid
for, or C{0} if the association is no longer valid.
... | This returns the number of seconds this association is still
valid for, or C{0} if the association is no longer valid.
@return: The number of seconds this association is still valid
for, or C{0} if the association is no longer valid.
@rtype: C{int} | Below is the the instruction that describes the task:
### Input:
This returns the number of seconds this association is still
valid for, or C{0} if the association is no longer valid.
@return: The number of seconds this association is still valid
for, or C{0} if the association is no l... |
def get_cart_deformed_cell(base_cryst, axis=0, size=1):
'''Return the cell deformed along one of the cartesian directions
Creates new deformed structure. The deformation is based on the
base structure and is performed along single axis. The axis is
specified as follows: 0,1,2 = x,y,z ; sheers: 3,4,5 = ... | Return the cell deformed along one of the cartesian directions
Creates new deformed structure. The deformation is based on the
base structure and is performed along single axis. The axis is
specified as follows: 0,1,2 = x,y,z ; sheers: 3,4,5 = yz, xz, xy.
The size of the deformation is in percent and d... | Below is the the instruction that describes the task:
### Input:
Return the cell deformed along one of the cartesian directions
Creates new deformed structure. The deformation is based on the
base structure and is performed along single axis. The axis is
specified as follows: 0,1,2 = x,y,z ; sheers: 3,... |
def _guess_record(self, rtype, name=None, content=None):
"""Tries to find existing unique record by type, name and content"""
records = self._list_records_internal(
identifier=None, rtype=rtype, name=name, content=content)
if len(records) == 1:
return records[0]
i... | Tries to find existing unique record by type, name and content | Below is the the instruction that describes the task:
### Input:
Tries to find existing unique record by type, name and content
### Response:
def _guess_record(self, rtype, name=None, content=None):
"""Tries to find existing unique record by type, name and content"""
records = self._list_records_in... |
def autocovariance(self, num_autocov=16):
"""
Compute the autocovariance function from the ARMA parameters
over the integers range(num_autocov) using the spectral density
and the inverse Fourier transform.
Parameters
----------
num_autocov : scalar(int), optional... | Compute the autocovariance function from the ARMA parameters
over the integers range(num_autocov) using the spectral density
and the inverse Fourier transform.
Parameters
----------
num_autocov : scalar(int), optional(default=16)
The number of autocovariances to calc... | Below is the the instruction that describes the task:
### Input:
Compute the autocovariance function from the ARMA parameters
over the integers range(num_autocov) using the spectral density
and the inverse Fourier transform.
Parameters
----------
num_autocov : scalar(int), o... |
def create(cls, path):
"""Create a new repository"""
try:
os.makedirs(path)
except OSError as e:
if not e.errno == errno.EEXIST:
raise
cmd = [SVNADMIN, 'create', path]
subprocess.check_call(cmd)
return cls(path) | Create a new repository | Below is the the instruction that describes the task:
### Input:
Create a new repository
### Response:
def create(cls, path):
"""Create a new repository"""
try:
os.makedirs(path)
except OSError as e:
if not e.errno == errno.EEXIST:
raise
cmd =... |
def send(self, message):
"""
发送基本文字消息
:param message: (必填|str) - 需要发送的文本消息
:return: * status:发送状态,True 发送成,False 发送失败
* message:发送失败详情
"""
url = '{0}message'.format(self.remote)
data = self._wrap_post_data(content=message)
res = requests.... | 发送基本文字消息
:param message: (必填|str) - 需要发送的文本消息
:return: * status:发送状态,True 发送成,False 发送失败
* message:发送失败详情 | Below is the the instruction that describes the task:
### Input:
发送基本文字消息
:param message: (必填|str) - 需要发送的文本消息
:return: * status:发送状态,True 发送成,False 发送失败
* message:发送失败详情
### Response:
def send(self, message):
"""
发送基本文字消息
:param message: (必填|str) - 需要发送的文... |
def __grabHotkeys(self):
"""
Run during startup to grab global and specific hotkeys in all open windows
"""
c = self.app.configManager
hotkeys = c.hotKeys + c.hotKeyFolders
# Grab global hotkeys in root window
for item in c.globalHotkeys:
if item.enab... | Run during startup to grab global and specific hotkeys in all open windows | Below is the the instruction that describes the task:
### Input:
Run during startup to grab global and specific hotkeys in all open windows
### Response:
def __grabHotkeys(self):
"""
Run during startup to grab global and specific hotkeys in all open windows
"""
c = self.app.configMa... |
def generate_order_template(self, quote_id, extra, quantity=1):
"""Generate a complete order template.
:param int quote_id: ID of target quote
:param dictionary extra: Overrides for the defaults of SoftLayer_Container_Product_Order
:param int quantity: Number of items to order.
... | Generate a complete order template.
:param int quote_id: ID of target quote
:param dictionary extra: Overrides for the defaults of SoftLayer_Container_Product_Order
:param int quantity: Number of items to order. | Below is the the instruction that describes the task:
### Input:
Generate a complete order template.
:param int quote_id: ID of target quote
:param dictionary extra: Overrides for the defaults of SoftLayer_Container_Product_Order
:param int quantity: Number of items to order.
### Response: ... |
def predict(self, X_feat, X_seq):
"""
Predict the response variable :py:attr:`y` for new input data (:py:attr:`X_feat`, :py:attr:`X_seq`).
Args:
X_feat: Feature design matrix. Same format as :py:attr:`X_feat` in :py:meth:`train`
X_seq: Sequenc design matrix. Same format... | Predict the response variable :py:attr:`y` for new input data (:py:attr:`X_feat`, :py:attr:`X_seq`).
Args:
X_feat: Feature design matrix. Same format as :py:attr:`X_feat` in :py:meth:`train`
X_seq: Sequenc design matrix. Same format as :py:attr:`X_seq` in :py:meth:`train` | Below is the the instruction that describes the task:
### Input:
Predict the response variable :py:attr:`y` for new input data (:py:attr:`X_feat`, :py:attr:`X_seq`).
Args:
X_feat: Feature design matrix. Same format as :py:attr:`X_feat` in :py:meth:`train`
X_seq: Sequenc design matr... |
def UpdateTaskAsPendingMerge(self, task):
"""Updates the task manager to reflect the task is ready to be merged.
Args:
task (Task): task.
Raises:
KeyError: if the task was not queued, processing or abandoned, or
the task was abandoned and has a retry task.
"""
with self._lock... | Updates the task manager to reflect the task is ready to be merged.
Args:
task (Task): task.
Raises:
KeyError: if the task was not queued, processing or abandoned, or
the task was abandoned and has a retry task. | Below is the the instruction that describes the task:
### Input:
Updates the task manager to reflect the task is ready to be merged.
Args:
task (Task): task.
Raises:
KeyError: if the task was not queued, processing or abandoned, or
the task was abandoned and has a retry task.
### Res... |
def process_vm_json( self, json_dict, **kwargs ):
''' Executes the preprocessing pipeline on vabamorf's JSON, given as a dict;
Returns a list: lines of analyses in the VISL CG3 input format;
'''
mrf_lines = convert_vm_json_to_mrf( json_dict )
return self.process_mrf_lines( ... | Executes the preprocessing pipeline on vabamorf's JSON, given as a dict;
Returns a list: lines of analyses in the VISL CG3 input format; | Below is the the instruction that describes the task:
### Input:
Executes the preprocessing pipeline on vabamorf's JSON, given as a dict;
Returns a list: lines of analyses in the VISL CG3 input format;
### Response:
def process_vm_json( self, json_dict, **kwargs ):
''' Executes the preprocessi... |
def shareproject(self, project_id, group_id, group_access):
"""
Allow to share project with group.
:param project_id: The ID of a project
:param group_id: The ID of a group
:param group_access: Level of permissions for sharing
:return: True is success
"""
... | Allow to share project with group.
:param project_id: The ID of a project
:param group_id: The ID of a group
:param group_access: Level of permissions for sharing
:return: True is success | Below is the the instruction that describes the task:
### Input:
Allow to share project with group.
:param project_id: The ID of a project
:param group_id: The ID of a group
:param group_access: Level of permissions for sharing
:return: True is success
### Response:
def shareprojec... |
def run_id(self):
'''Run name without whitespace
'''
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', self.__class__.__name__)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() | Run name without whitespace | Below is the the instruction that describes the task:
### Input:
Run name without whitespace
### Response:
def run_id(self):
'''Run name without whitespace
'''
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', self.__class__.__name__)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() |
def from_yaml(cls, yaml_str=None, str_or_buffer=None):
"""
Create a SegmentedMNLDiscreteChoiceModel instance from a saved YAML
configuration. Arguments are mutally exclusive.
Parameters
----------
yaml_str : str, optional
A YAML string from which to load mode... | Create a SegmentedMNLDiscreteChoiceModel instance from a saved YAML
configuration. Arguments are mutally exclusive.
Parameters
----------
yaml_str : str, optional
A YAML string from which to load model.
str_or_buffer : str or file like, optional
File name... | Below is the the instruction that describes the task:
### Input:
Create a SegmentedMNLDiscreteChoiceModel instance from a saved YAML
configuration. Arguments are mutally exclusive.
Parameters
----------
yaml_str : str, optional
A YAML string from which to load model.
... |
def _output_format_sector(func, override=None):
""" Decorator in charge of giving the output its right format, either
json or pandas (replacing the % for usable floats, range 0-1.0)
Keyword Arguments:
func: The function to be decorated
override: Override the internal for... | Decorator in charge of giving the output its right format, either
json or pandas (replacing the % for usable floats, range 0-1.0)
Keyword Arguments:
func: The function to be decorated
override: Override the internal format of the call, default None
Returns:
A... | Below is the the instruction that describes the task:
### Input:
Decorator in charge of giving the output its right format, either
json or pandas (replacing the % for usable floats, range 0-1.0)
Keyword Arguments:
func: The function to be decorated
override: Override the int... |
def get_lyrics_letssingit(song_name):
'''
Scrapes the lyrics of a song since spotify does not provide lyrics
takes song title as arguement
'''
lyrics = ""
url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \
quote(song_name.encode('utf-8'))
html =... | Scrapes the lyrics of a song since spotify does not provide lyrics
takes song title as arguement | Below is the the instruction that describes the task:
### Input:
Scrapes the lyrics of a song since spotify does not provide lyrics
takes song title as arguement
### Response:
def get_lyrics_letssingit(song_name):
'''
Scrapes the lyrics of a song since spotify does not provide lyrics
takes song tit... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.