code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def decode_terminated(data, encoding, strict=True):
"""Returns the decoded data until the first NULL terminator
and all data after it.
Args:
data (bytes): data to decode
encoding (str): The codec to use
strict (bool): If True will raise ValueError in case no NULL is found
... | Returns the decoded data until the first NULL terminator
and all data after it.
Args:
data (bytes): data to decode
encoding (str): The codec to use
strict (bool): If True will raise ValueError in case no NULL is found
but the available data decoded successfully.
Returns:... | Below is the the instruction that describes the task:
### Input:
Returns the decoded data until the first NULL terminator
and all data after it.
Args:
data (bytes): data to decode
encoding (str): The codec to use
strict (bool): If True will raise ValueError in case no NULL is found
... |
def create_authn_query_response(self, subject, session_index=None,
requested_context=None, in_response_to=None,
issuer=None, sign_response=False,
status=None, sign_alg=None, digest_alg=None,
... | A successful <Response> will contain one or more assertions containing
authentication statements.
:return: | Below is the the instruction that describes the task:
### Input:
A successful <Response> will contain one or more assertions containing
authentication statements.
:return:
### Response:
def create_authn_query_response(self, subject, session_index=None,
requested... |
def predict(
self, user_ids, item_ids, item_features=None, user_features=None, num_threads=1
):
"""
Compute the recommendation score for user-item pairs.
For details on how to use feature matrices, see the documentation
on the :class:`lightfm.LightFM` class.
Argumen... | Compute the recommendation score for user-item pairs.
For details on how to use feature matrices, see the documentation
on the :class:`lightfm.LightFM` class.
Arguments
---------
user_ids: integer or np.int32 array of shape [n_pairs,]
single user id or an array co... | Below is the the instruction that describes the task:
### Input:
Compute the recommendation score for user-item pairs.
For details on how to use feature matrices, see the documentation
on the :class:`lightfm.LightFM` class.
Arguments
---------
user_ids: integer or np.int32... |
def decode(decoder, data, length, frame_size, decode_fec, channels=2):
"""Decode an Opus frame
Unlike the `opus_decode` function , this function takes an additional parameter `channels`,
which indicates the number of channels in the frame
"""
pcm_size = frame_size * channels * ctypes.sizeof(ctypes... | Decode an Opus frame
Unlike the `opus_decode` function , this function takes an additional parameter `channels`,
which indicates the number of channels in the frame | Below is the the instruction that describes the task:
### Input:
Decode an Opus frame
Unlike the `opus_decode` function , this function takes an additional parameter `channels`,
which indicates the number of channels in the frame
### Response:
def decode(decoder, data, length, frame_size, decode_fec, chan... |
def log_url (self, url_data):
"""
Put invalid url in blacklist, delete valid url from blacklist.
"""
key = (url_data.parent_url, url_data.cache_url)
key = repr(key)
if key in self.blacklist:
if url_data.valid:
del self.blacklist[key]
... | Put invalid url in blacklist, delete valid url from blacklist. | Below is the the instruction that describes the task:
### Input:
Put invalid url in blacklist, delete valid url from blacklist.
### Response:
def log_url (self, url_data):
"""
Put invalid url in blacklist, delete valid url from blacklist.
"""
key = (url_data.parent_url, url_data.cac... |
def emit(self, event, *args, **kwargs):
"""Use this to send a structured event, with a name and arguments, to
the client.
By default, it uses this namespace's endpoint. You can send messages on
other endpoints with something like:
``self.socket['/other_endpoint'].emit()``.
... | Use this to send a structured event, with a name and arguments, to
the client.
By default, it uses this namespace's endpoint. You can send messages on
other endpoints with something like:
``self.socket['/other_endpoint'].emit()``.
However, it is possible that the ``'/other... | Below is the the instruction that describes the task:
### Input:
Use this to send a structured event, with a name and arguments, to
the client.
By default, it uses this namespace's endpoint. You can send messages on
other endpoints with something like:
``self.socket['/other_end... |
def _ToJSonObj(self, columns_order=None, order_by=()):
"""Returns an object suitable to be converted to JSON.
Args:
columns_order: Optional. A list of all column IDs in the order in which
you want them created in the output table. If specified,
all column IDs mus... | Returns an object suitable to be converted to JSON.
Args:
columns_order: Optional. A list of all column IDs in the order in which
you want them created in the output table. If specified,
all column IDs must be present.
order_by: Optional. Specifies the name of ... | Below is the the instruction that describes the task:
### Input:
Returns an object suitable to be converted to JSON.
Args:
columns_order: Optional. A list of all column IDs in the order in which
you want them created in the output table. If specified,
all column ... |
def create(self, schema="{}", **kwargs):
"""Creates a stream given an optional JSON schema encoded as a python dict. You can also add other properties
of the stream, such as the icon, datatype or description. Create accepts both a string schema and
a dict-encoded schema."""
if isinstance... | Creates a stream given an optional JSON schema encoded as a python dict. You can also add other properties
of the stream, such as the icon, datatype or description. Create accepts both a string schema and
a dict-encoded schema. | Below is the the instruction that describes the task:
### Input:
Creates a stream given an optional JSON schema encoded as a python dict. You can also add other properties
of the stream, such as the icon, datatype or description. Create accepts both a string schema and
a dict-encoded schema.
### Res... |
def add_item(self, host, key, value, clock=None, state=0):
"""
Add a single item into DataContainer
:host: hostname to which item will be linked to
:key: item key as defined in Zabbix
:value: item value
:clock: timestemp as integer. If not provided self.clock()) will be ... | Add a single item into DataContainer
:host: hostname to which item will be linked to
:key: item key as defined in Zabbix
:value: item value
:clock: timestemp as integer. If not provided self.clock()) will be used | Below is the the instruction that describes the task:
### Input:
Add a single item into DataContainer
:host: hostname to which item will be linked to
:key: item key as defined in Zabbix
:value: item value
:clock: timestemp as integer. If not provided self.clock()) will be used
### R... |
def prepareSystem(cls):
"""
Prepares this system for the downloading and lookup of resources. This method should only
be invoked on a worker node. It is idempotent but not thread-safe.
"""
try:
resourceRootDirPath = os.environ[cls.rootDirPathEnvName]
except Ke... | Prepares this system for the downloading and lookup of resources. This method should only
be invoked on a worker node. It is idempotent but not thread-safe. | Below is the the instruction that describes the task:
### Input:
Prepares this system for the downloading and lookup of resources. This method should only
be invoked on a worker node. It is idempotent but not thread-safe.
### Response:
def prepareSystem(cls):
"""
Prepares this system for th... |
def get_thellier_gui_meas_mapping(input_df, output=2):
"""
Get the appropriate mapping for translating measurements in Thellier GUI.
This requires special handling for treat_step_num/measurement/measurement_number.
Parameters
----------
input_df : pandas DataFrame
MagIC records
outp... | Get the appropriate mapping for translating measurements in Thellier GUI.
This requires special handling for treat_step_num/measurement/measurement_number.
Parameters
----------
input_df : pandas DataFrame
MagIC records
output : int
output to this MagIC data model (2 or 3)
Outp... | Below is the the instruction that describes the task:
### Input:
Get the appropriate mapping for translating measurements in Thellier GUI.
This requires special handling for treat_step_num/measurement/measurement_number.
Parameters
----------
input_df : pandas DataFrame
MagIC records
ou... |
def dist01(graph, weight, source=0, target=None):
"""Shortest path in a 0,1 weighted graph
:param graph: directed graph in listlist or listdict format
:param weight: matrix or adjacency dictionary
:param int source: vertex
:param target: exploration stops once distance to target is found
:retur... | Shortest path in a 0,1 weighted graph
:param graph: directed graph in listlist or listdict format
:param weight: matrix or adjacency dictionary
:param int source: vertex
:param target: exploration stops once distance to target is found
:returns: distance table, predecessor table
:complexity: `O... | Below is the the instruction that describes the task:
### Input:
Shortest path in a 0,1 weighted graph
:param graph: directed graph in listlist or listdict format
:param weight: matrix or adjacency dictionary
:param int source: vertex
:param target: exploration stops once distance to target is foun... |
def follow_link(self, link, **kwargs):
"""Click a link.
:param Tag link: Link to click
:param kwargs: Keyword arguments to `Session::send`
"""
try:
href = link['href']
except KeyError:
raise exceptions.RoboError('Link element must have "href" '
... | Click a link.
:param Tag link: Link to click
:param kwargs: Keyword arguments to `Session::send` | Below is the the instruction that describes the task:
### Input:
Click a link.
:param Tag link: Link to click
:param kwargs: Keyword arguments to `Session::send`
### Response:
def follow_link(self, link, **kwargs):
"""Click a link.
:param Tag link: Link to click
:param kwa... |
def _validate_zip(the_zip):
"""Validate zipped data package
"""
datapackage_jsons = [f for f in the_zip.namelist() if f.endswith('datapackage.json')]
if len(datapackage_jsons) != 1:
msg = 'DataPackage must have only one "datapackage.json" (had {n})'
raise exceptions.DataPackageException(... | Validate zipped data package | Below is the the instruction that describes the task:
### Input:
Validate zipped data package
### Response:
def _validate_zip(the_zip):
"""Validate zipped data package
"""
datapackage_jsons = [f for f in the_zip.namelist() if f.endswith('datapackage.json')]
if len(datapackage_jsons) != 1:
m... |
def isHandlerPresent(self, event_name):
"""Check if an event has an handler."""
if event_name not in self.handlers:
raise ValueError('{} is not a valid event'.format(event_name))
return self.handlers[event_name] is not None | Check if an event has an handler. | Below is the the instruction that describes the task:
### Input:
Check if an event has an handler.
### Response:
def isHandlerPresent(self, event_name):
"""Check if an event has an handler."""
if event_name not in self.handlers:
raise ValueError('{} is not a valid event'.format(event_na... |
def get_http_raw(self, url=None, retry_count=3, headers=None,
request_type='GET', form_data=None):
"""
The function for retrieving a raw HTML result via HTTP.
Args:
url (:obj:`str`): The URL to retrieve (required).
retry_count (:obj:`int`): The numbe... | The function for retrieving a raw HTML result via HTTP.
Args:
url (:obj:`str`): The URL to retrieve (required).
retry_count (:obj:`int`): The number of times to retry in case
socket errors, timeouts, connection resets, etc. are
encountered. Defaults to 3.... | Below is the the instruction that describes the task:
### Input:
The function for retrieving a raw HTML result via HTTP.
Args:
url (:obj:`str`): The URL to retrieve (required).
retry_count (:obj:`int`): The number of times to retry in case
socket errors, timeouts, co... |
def do_work(self, actions_queue, returns_queue, control_queue=None): # pragma: no cover
"""Main function of the worker.
* Get checks
* Launch new checks
* Manage finished checks
:param actions_queue: Global Queue Master->Slave
:type actions_queue: Queue.Queue
:p... | Main function of the worker.
* Get checks
* Launch new checks
* Manage finished checks
:param actions_queue: Global Queue Master->Slave
:type actions_queue: Queue.Queue
:param returns_queue: queue managed by manager
:type returns_queue: Queue.Queue
:retur... | Below is the the instruction that describes the task:
### Input:
Main function of the worker.
* Get checks
* Launch new checks
* Manage finished checks
:param actions_queue: Global Queue Master->Slave
:type actions_queue: Queue.Queue
:param returns_queue: queue manag... |
def max_run_length(x: np.ndarray, val: int):
"""Finds the maximum continuous length of the given value in the sequence"""
if x.size == 0:
return 0
else:
y = np.array(x[1:] != x[:-1])
i = np.append(np.where(y), len(x) - 1)
run_lengths = np.diff(np.a... | Finds the maximum continuous length of the given value in the sequence | Below is the the instruction that describes the task:
### Input:
Finds the maximum continuous length of the given value in the sequence
### Response:
def max_run_length(x: np.ndarray, val: int):
"""Finds the maximum continuous length of the given value in the sequence"""
if x.size == 0:
... |
def compute(chart):
""" Computes the behavior. """
factors = []
# Planets in House1 or Conjunct Asc
house1 = chart.getHouse(const.HOUSE1)
planetsHouse1 = chart.objects.getObjectsInHouse(house1)
asc = chart.getAngle(const.ASC)
planetsConjAsc = chart.objects.getObjectsAspecting(asc, ... | Computes the behavior. | Below is the the instruction that describes the task:
### Input:
Computes the behavior.
### Response:
def compute(chart):
""" Computes the behavior. """
factors = []
# Planets in House1 or Conjunct Asc
house1 = chart.getHouse(const.HOUSE1)
planetsHouse1 = chart.objects.getObjectsInHou... |
def get_bitcoin_virtual_transactions(blockchain_opts, first_block_height, last_block_height, tx_filter=None, spv_last_block=None, first_block_hash=None, **hints):
"""
Get the sequence of virtualchain transactions from the blockchain.
Each transaction returned will be a `nulldata` transaction (i.e. the first... | Get the sequence of virtualchain transactions from the blockchain.
Each transaction returned will be a `nulldata` transaction (i.e. the first output script starts with OP_RETURN).
* output values will be in satoshis
* `fee` will be defined, and will be the total amount sent (in satoshis)
* `txindex` wil... | Below is the the instruction that describes the task:
### Input:
Get the sequence of virtualchain transactions from the blockchain.
Each transaction returned will be a `nulldata` transaction (i.e. the first output script starts with OP_RETURN).
* output values will be in satoshis
* `fee` will be defined... |
def load_figure(self, fig, fmt):
"""Set a new figure in the figure canvas."""
self.figcanvas.load_figure(fig, fmt)
self.scale_image()
self.figcanvas.repaint() | Set a new figure in the figure canvas. | Below is the the instruction that describes the task:
### Input:
Set a new figure in the figure canvas.
### Response:
def load_figure(self, fig, fmt):
"""Set a new figure in the figure canvas."""
self.figcanvas.load_figure(fig, fmt)
self.scale_image()
self.figcanvas.repaint() |
def vn_info(call=None, kwargs=None):
'''
Retrieves information for the virtual network.
.. versionadded:: 2016.3.0
name
The name of the virtual network for which to gather information. Can be
used instead of ``vn_id``.
vn_id
The ID of the virtual network for which to gathe... | Retrieves information for the virtual network.
.. versionadded:: 2016.3.0
name
The name of the virtual network for which to gather information. Can be
used instead of ``vn_id``.
vn_id
The ID of the virtual network for which to gather information. Can be
used instead of ``n... | Below is the the instruction that describes the task:
### Input:
Retrieves information for the virtual network.
.. versionadded:: 2016.3.0
name
The name of the virtual network for which to gather information. Can be
used instead of ``vn_id``.
vn_id
The ID of the virtual networ... |
def _init_worker(X, X_shape, X_dtype):
"""Initializer for pool for _mprotate"""
# Using a dictionary is not strictly necessary. You can also
# use global variables.
mprotate_dict["X"] = X
mprotate_dict["X_shape"] = X_shape
mprotate_dict["X_dtype"] = X_dtype | Initializer for pool for _mprotate | Below is the the instruction that describes the task:
### Input:
Initializer for pool for _mprotate
### Response:
def _init_worker(X, X_shape, X_dtype):
"""Initializer for pool for _mprotate"""
# Using a dictionary is not strictly necessary. You can also
# use global variables.
mprotate_dict["X"] =... |
def data_merge(a, b):
"""merges b into a and return merged result
based on http://stackoverflow.com/questions/7204805/python-dictionaries-of-dictionaries-merge
and extended to also merge arrays and to replace the content of keys with the same name
NOTE: tuples and arbitrary objects are not handled as i... | merges b into a and return merged result
based on http://stackoverflow.com/questions/7204805/python-dictionaries-of-dictionaries-merge
and extended to also merge arrays and to replace the content of keys with the same name
NOTE: tuples and arbitrary objects are not handled as it is totally ambiguous what s... | Below is the the instruction that describes the task:
### Input:
merges b into a and return merged result
based on http://stackoverflow.com/questions/7204805/python-dictionaries-of-dictionaries-merge
and extended to also merge arrays and to replace the content of keys with the same name
NOTE: tuples an... |
def _get_lines_in_file(self, filename):
"""
:rtype: list
"""
with codecs.open(filename, encoding='utf-8') as file:
return file.read().splitlines() | :rtype: list | Below is the the instruction that describes the task:
### Input:
:rtype: list
### Response:
def _get_lines_in_file(self, filename):
"""
:rtype: list
"""
with codecs.open(filename, encoding='utf-8') as file:
return file.read().splitlines() |
def _load_x509(certificate):
"""
Loads an ASN.1 object of an x509 certificate into a Certificate object
:param certificate:
An asn1crypto.x509.Certificate object
:return:
A Certificate object
"""
source = certificate.dump()
cf_source = None
try:
cf_source = CF... | Loads an ASN.1 object of an x509 certificate into a Certificate object
:param certificate:
An asn1crypto.x509.Certificate object
:return:
A Certificate object | Below is the the instruction that describes the task:
### Input:
Loads an ASN.1 object of an x509 certificate into a Certificate object
:param certificate:
An asn1crypto.x509.Certificate object
:return:
A Certificate object
### Response:
def _load_x509(certificate):
"""
Loads an A... |
def list_databases(self, instance, limit=None, marker=None):
"""Returns all databases for the specified instance."""
return instance.list_databases(limit=limit, marker=marker) | Returns all databases for the specified instance. | Below is the the instruction that describes the task:
### Input:
Returns all databases for the specified instance.
### Response:
def list_databases(self, instance, limit=None, marker=None):
"""Returns all databases for the specified instance."""
return instance.list_databases(limit=limit, marker=ma... |
def loop(_=None, force=False): # pylint: disable=invalid-name
"""Causes a function to loop indefinitely."""
if not force:
raise AttributeError(
'threads.loop() is DEPRECATED. If you really like this and want to '
'keep it, file an issue at https://github.com/google/openhtf/issues '
'a... | Causes a function to loop indefinitely. | Below is the the instruction that describes the task:
### Input:
Causes a function to loop indefinitely.
### Response:
def loop(_=None, force=False): # pylint: disable=invalid-name
"""Causes a function to loop indefinitely."""
if not force:
raise AttributeError(
'threads.loop() is DEPRECATED. If... |
def _monitor_events(self):
"""Watch for Processing Block events."""
LOG.info("Starting to monitor PB events")
check_counter = 0
while True:
if check_counter == 50:
check_counter = 0
LOG.debug('Checking for PB events...')
published_... | Watch for Processing Block events. | Below is the the instruction that describes the task:
### Input:
Watch for Processing Block events.
### Response:
def _monitor_events(self):
"""Watch for Processing Block events."""
LOG.info("Starting to monitor PB events")
check_counter = 0
while True:
if check_counter ... |
def getLayerIndex(self, layer):
"""
Given a reference to a layer, returns the index of that layer in
self.layers.
"""
for i in range(len(self.layers)):
if layer == self.layers[i]: # shallow cmp
return i
return -1 # not in list | Given a reference to a layer, returns the index of that layer in
self.layers. | Below is the the instruction that describes the task:
### Input:
Given a reference to a layer, returns the index of that layer in
self.layers.
### Response:
def getLayerIndex(self, layer):
"""
Given a reference to a layer, returns the index of that layer in
self.layers.
""" ... |
def Wagner_original(T, Tc, Pc, a, b, c, d):
r'''Calculates vapor pressure using the Wagner equation (3, 6 form).
Requires critical temperature and pressure as well as four coefficients
specific to each chemical.
.. math::
\ln P^{sat}= \ln P_c + \frac{a\tau + b \tau^{1.5} + c\tau^3 + d\tau^6}
... | r'''Calculates vapor pressure using the Wagner equation (3, 6 form).
Requires critical temperature and pressure as well as four coefficients
specific to each chemical.
.. math::
\ln P^{sat}= \ln P_c + \frac{a\tau + b \tau^{1.5} + c\tau^3 + d\tau^6}
{T_r}
\tau = 1 - \frac{T... | Below is the the instruction that describes the task:
### Input:
r'''Calculates vapor pressure using the Wagner equation (3, 6 form).
Requires critical temperature and pressure as well as four coefficients
specific to each chemical.
.. math::
\ln P^{sat}= \ln P_c + \frac{a\tau + b \tau^{1.5} +... |
def ReqOrderInsert(self, pInstrument: str, pDirection: DirectType, pOffset: OffsetType, pPrice: float = 0.0, pVolume: int = 1, pType: OrderType = OrderType.Limit, pCustom: int = 0):
"""委托
:param pInstrument:
:param pDirection:
:param pOffset:
:param pPrice:
:param pVolum... | 委托
:param pInstrument:
:param pDirection:
:param pOffset:
:param pPrice:
:param pVolume:
:param pType:
:param pCustom:
:return: | Below is the the instruction that describes the task:
### Input:
委托
:param pInstrument:
:param pDirection:
:param pOffset:
:param pPrice:
:param pVolume:
:param pType:
:param pCustom:
:return:
### Response:
def ReqOrderInsert(self, pInstrument: str, ... |
def _fixStringValue(s, p):
"""Clean up string value including special characters, etc."""
# pylint: disable=too-many-branches
s = s[1:-1]
rv = ''
esc = False
i = -1
while i < len(s) - 1:
i += 1
ch = s[i]
if ch == '\\' and not esc:
esc = True
c... | Clean up string value including special characters, etc. | Below is the the instruction that describes the task:
### Input:
Clean up string value including special characters, etc.
### Response:
def _fixStringValue(s, p):
"""Clean up string value including special characters, etc."""
# pylint: disable=too-many-branches
s = s[1:-1]
rv = ''
esc = False
... |
def mean_vector(lons, lats):
"""
Returns the resultant vector from a series of longitudes and latitudes
Parameters
----------
lons : array-like
A sequence of longitudes (in radians)
lats : array-like
A sequence of latitudes (in radians)
Returns
-------
mean_vec : tu... | Returns the resultant vector from a series of longitudes and latitudes
Parameters
----------
lons : array-like
A sequence of longitudes (in radians)
lats : array-like
A sequence of latitudes (in radians)
Returns
-------
mean_vec : tuple
(lon, lat) in radians
r_v... | Below is the the instruction that describes the task:
### Input:
Returns the resultant vector from a series of longitudes and latitudes
Parameters
----------
lons : array-like
A sequence of longitudes (in radians)
lats : array-like
A sequence of latitudes (in radians)
Returns
... |
def updates_selection(update_selection):
""" Decorator indicating that the decorated method could change the selection"""
def handle_update(selection, *args, **kwargs):
"""Check for changes in the selection
If the selection is changed by the decorated method, the internal core element lists are... | Decorator indicating that the decorated method could change the selection | Below is the the instruction that describes the task:
### Input:
Decorator indicating that the decorated method could change the selection
### Response:
def updates_selection(update_selection):
""" Decorator indicating that the decorated method could change the selection"""
def handle_update(selection, *ar... |
def evaluate(self, instance, step, extra):
"""Evaluate the current ContainerAttribute.
Args:
obj (LazyStub): a lazy stub of the object being constructed, if
needed.
containers (list of LazyStub): a list of lazy stubs of factories
being evaluated i... | Evaluate the current ContainerAttribute.
Args:
obj (LazyStub): a lazy stub of the object being constructed, if
needed.
containers (list of LazyStub): a list of lazy stubs of factories
being evaluated in a chain, each item being a future field of
... | Below is the the instruction that describes the task:
### Input:
Evaluate the current ContainerAttribute.
Args:
obj (LazyStub): a lazy stub of the object being constructed, if
needed.
containers (list of LazyStub): a list of lazy stubs of factories
be... |
def valid_dict(d, keys=None):
"""
检查是否字典中含有值为None的键(给定键的名称则检查给定的键,如果没有,则检查全部键)
- 如果没有值为None的键,则返回True,反之False
- 如果keys中的键不存在于d中,也返回False
"""
if keys is None:
d_ = d
else:
d_ = itemfilter(lambda item: item[0] in keys, d)
if len(d_) != len(keys):
return Fal... | 检查是否字典中含有值为None的键(给定键的名称则检查给定的键,如果没有,则检查全部键)
- 如果没有值为None的键,则返回True,反之False
- 如果keys中的键不存在于d中,也返回False | Below is the the instruction that describes the task:
### Input:
检查是否字典中含有值为None的键(给定键的名称则检查给定的键,如果没有,则检查全部键)
- 如果没有值为None的键,则返回True,反之False
- 如果keys中的键不存在于d中,也返回False
### Response:
def valid_dict(d, keys=None):
"""
检查是否字典中含有值为None的键(给定键的名称则检查给定的键,如果没有,则检查全部键)
- 如果没有值为None的键,则返回True,反之False
... |
def destroy():
"""Destroy a database."""
if not os.path.exists(ARGS.database):
exit('Error: The database does not exist; you must create it first.')
if ARGS.force:
os.remove(ARGS.database)
elif raw_input('Destroy {0} [y/n]? '.format(ARGS.database)) in ('y', 'Y'):
os.remove(ARGS.d... | Destroy a database. | Below is the the instruction that describes the task:
### Input:
Destroy a database.
### Response:
def destroy():
"""Destroy a database."""
if not os.path.exists(ARGS.database):
exit('Error: The database does not exist; you must create it first.')
if ARGS.force:
os.remove(ARGS.database)... |
def mad(arr, relative=True):
""" Median Absolute Deviation: a "Robust" version of standard deviation.
Indices variabililty of the sample.
https://en.wikipedia.org/wiki/Median_absolute_deviation
"""
with warnings.catch_warnings():
warnings.simplefilter("ignore")
med = np.nanme... | Median Absolute Deviation: a "Robust" version of standard deviation.
Indices variabililty of the sample.
https://en.wikipedia.org/wiki/Median_absolute_deviation | Below is the the instruction that describes the task:
### Input:
Median Absolute Deviation: a "Robust" version of standard deviation.
Indices variabililty of the sample.
https://en.wikipedia.org/wiki/Median_absolute_deviation
### Response:
def mad(arr, relative=True):
""" Median Absolute Deviat... |
def memory_write16(self, addr, data, zone=None):
"""Writes half-words to memory of a target system.
Args:
self (JLink): the ``JLink`` instance
addr (int): start address to write to
data (list): list of half-words to write
zone (str): optional memory zone to acces... | Writes half-words to memory of a target system.
Args:
self (JLink): the ``JLink`` instance
addr (int): start address to write to
data (list): list of half-words to write
zone (str): optional memory zone to access
Returns:
Number of half-words written t... | Below is the the instruction that describes the task:
### Input:
Writes half-words to memory of a target system.
Args:
self (JLink): the ``JLink`` instance
addr (int): start address to write to
data (list): list of half-words to write
zone (str): optional memory zone... |
async def answer_media_group(self, media: typing.Union[MediaGroup, typing.List],
disable_notification: typing.Union[base.Boolean, None] = None,
reply=False) -> typing.List[Message]:
"""
Use this method to send a group of photos or videos ... | Use this method to send a group of photos or videos as an album.
Source: https://core.telegram.org/bots/api#sendmediagroup
:param media: A JSON-serialized array describing photos and videos to be sent
:type media: :obj:`typing.Union[types.MediaGroup, typing.List]`
:param disable_notifi... | Below is the the instruction that describes the task:
### Input:
Use this method to send a group of photos or videos as an album.
Source: https://core.telegram.org/bots/api#sendmediagroup
:param media: A JSON-serialized array describing photos and videos to be sent
:type media: :obj:`typin... |
def tojson(val, indent=None):
'''
Implementation of tojson filter (only present in Jinja 2.9 and later). If
Jinja 2.9 or later is installed, then the upstream version of this filter
will be used.
'''
options = {'ensure_ascii': True}
if indent is not None:
options['indent'] = indent
... | Implementation of tojson filter (only present in Jinja 2.9 and later). If
Jinja 2.9 or later is installed, then the upstream version of this filter
will be used. | Below is the the instruction that describes the task:
### Input:
Implementation of tojson filter (only present in Jinja 2.9 and later). If
Jinja 2.9 or later is installed, then the upstream version of this filter
will be used.
### Response:
def tojson(val, indent=None):
'''
Implementation of tojson... |
def balance(ctx, accounts):
""" Show Account balances
"""
t = PrettyTable(["Account", "Amount"])
t.align = "r"
for a in accounts:
account = Account(a, peerplays_instance=ctx.peerplays)
for b in account.balances:
t.add_row([str(a), str(b)])
click.echo(str(t)) | Show Account balances | Below is the the instruction that describes the task:
### Input:
Show Account balances
### Response:
def balance(ctx, accounts):
""" Show Account balances
"""
t = PrettyTable(["Account", "Amount"])
t.align = "r"
for a in accounts:
account = Account(a, peerplays_instance=ctx.peerplays)
... |
def network_interfaces_list(resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
List all network interfaces within a resource group.
:param resource_group: The resource group name to list network
interfaces within.
CLI Example:
.. code-block:: bash
salt-call azurearm_n... | .. versionadded:: 2019.2.0
List all network interfaces within a resource group.
:param resource_group: The resource group name to list network
interfaces within.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.network_interfaces_list testgroup | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2019.2.0
List all network interfaces within a resource group.
:param resource_group: The resource group name to list network
interfaces within.
CLI Example:
.. code-block:: bash
salt-call azurearm... |
def parse_response(gdb_mi_text):
"""Parse gdb mi text and turn it into a dictionary.
See https://sourceware.org/gdb/onlinedocs/gdb/GDB_002fMI-Stream-Records.html#GDB_002fMI-Stream-Records
for details on types of gdb mi output.
Args:
gdb_mi_text (str): String output from gdb
Returns:
... | Parse gdb mi text and turn it into a dictionary.
See https://sourceware.org/gdb/onlinedocs/gdb/GDB_002fMI-Stream-Records.html#GDB_002fMI-Stream-Records
for details on types of gdb mi output.
Args:
gdb_mi_text (str): String output from gdb
Returns:
dict with the following keys:
... | Below is the the instruction that describes the task:
### Input:
Parse gdb mi text and turn it into a dictionary.
See https://sourceware.org/gdb/onlinedocs/gdb/GDB_002fMI-Stream-Records.html#GDB_002fMI-Stream-Records
for details on types of gdb mi output.
Args:
gdb_mi_text (str): String output... |
def createStyle(self, body, verbose=None):
"""
Creates a new Visual Style using the message body.
Returns the title of the new Visual Style. If the title of the Visual Style already existed in the session, a new one will be automatically generated and returned.
:param body: The... | Creates a new Visual Style using the message body.
Returns the title of the new Visual Style. If the title of the Visual Style already existed in the session, a new one will be automatically generated and returned.
:param body: The details of the new Visual Style to be created.
:param ... | Below is the the instruction that describes the task:
### Input:
Creates a new Visual Style using the message body.
Returns the title of the new Visual Style. If the title of the Visual Style already existed in the session, a new one will be automatically generated and returned.
:param bod... |
def _process_task(self, task, function_execution_info):
"""Execute a task assigned to this worker.
This method deserializes a task from the scheduler, and attempts to
execute the task. If the task succeeds, the outputs are stored in the
local object store. If the task throws an exceptio... | Execute a task assigned to this worker.
This method deserializes a task from the scheduler, and attempts to
execute the task. If the task succeeds, the outputs are stored in the
local object store. If the task throws an exception, RayTaskError
objects are stored in the object store to r... | Below is the the instruction that describes the task:
### Input:
Execute a task assigned to this worker.
This method deserializes a task from the scheduler, and attempts to
execute the task. If the task succeeds, the outputs are stored in the
local object store. If the task throws an except... |
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
set_mysql_engine()
engine = session.create_engine(neutron_config.database.connection)
connection = engine.connect()
context.co... | Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context. | Below is the the instruction that describes the task:
### Input:
Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
### Response:
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to cr... |
def generate_data_for_env_problem(problem_name):
"""Generate data for `EnvProblem`s."""
assert FLAGS.env_problem_max_env_steps > 0, ("--env_problem_max_env_steps "
"should be greater than zero")
assert FLAGS.env_problem_batch_size > 0, ("--env_problem_batch_size shou... | Generate data for `EnvProblem`s. | Below is the the instruction that describes the task:
### Input:
Generate data for `EnvProblem`s.
### Response:
def generate_data_for_env_problem(problem_name):
"""Generate data for `EnvProblem`s."""
assert FLAGS.env_problem_max_env_steps > 0, ("--env_problem_max_env_steps "
... |
def _eval_firstorder(self, rvecs, data, sigma):
"""The first-order Barnes approximation"""
if not self.blocksize:
dist_between_points = self._distance_matrix(rvecs, self.x)
gaussian_weights = self._weight(dist_between_points, sigma=sigma)
return gaussian_weights.dot(d... | The first-order Barnes approximation | Below is the the instruction that describes the task:
### Input:
The first-order Barnes approximation
### Response:
def _eval_firstorder(self, rvecs, data, sigma):
"""The first-order Barnes approximation"""
if not self.blocksize:
dist_between_points = self._distance_matrix(rvecs, self.x... |
def struct_time_to_jd(st):
"""
Return a float number representing the Julian Date for the given
`struct_time`.
NOTE: extra fields `tm_wday`, `tm_yday`, and `tm_isdst` are ignored.
"""
year, month, day = st[:3]
hours, minutes, seconds = st[3:6]
# Convert time of day to fraction of day
... | Return a float number representing the Julian Date for the given
`struct_time`.
NOTE: extra fields `tm_wday`, `tm_yday`, and `tm_isdst` are ignored. | Below is the the instruction that describes the task:
### Input:
Return a float number representing the Julian Date for the given
`struct_time`.
NOTE: extra fields `tm_wday`, `tm_yday`, and `tm_isdst` are ignored.
### Response:
def struct_time_to_jd(st):
"""
Return a float number representing the ... |
def parse(url_or_path, encoding=None, handler_class=DrillHandler):
"""
:param url_or_path: A file-like object, a filesystem path, a URL, or a string containing XML
:rtype: :class:`XmlElement`
"""
handler = handler_class()
parser = expat.ParserCreate(encoding)
parser.buffer_text = 1
parse... | :param url_or_path: A file-like object, a filesystem path, a URL, or a string containing XML
:rtype: :class:`XmlElement` | Below is the the instruction that describes the task:
### Input:
:param url_or_path: A file-like object, a filesystem path, a URL, or a string containing XML
:rtype: :class:`XmlElement`
### Response:
def parse(url_or_path, encoding=None, handler_class=DrillHandler):
"""
:param url_or_path: A file-like ... |
def createCitation(self, multiCite = False):
"""Overwriting the general [citation creator](./ExtendedRecord.html#metaknowledge.ExtendedRecord.createCitation) to deal with scopus weirdness.
Creates a citation string, using the same format as other WOS citations, for the [Record](./Record.html#metaknowle... | Overwriting the general [citation creator](./ExtendedRecord.html#metaknowledge.ExtendedRecord.createCitation) to deal with scopus weirdness.
Creates a citation string, using the same format as other WOS citations, for the [Record](./Record.html#metaknowledge.Record) by reading the relevant special tags (`'year... | Below is the the instruction that describes the task:
### Input:
Overwriting the general [citation creator](./ExtendedRecord.html#metaknowledge.ExtendedRecord.createCitation) to deal with scopus weirdness.
Creates a citation string, using the same format as other WOS citations, for the [Record](./Record.ht... |
def global_matches(self, text):
"""Compute matches when text is a simple name.
Return a list of all keywords, built-in functions and names currently
defined in self.namespace that match.
"""
matches = []
n = len(text)
for word in self.namespace:
if wor... | Compute matches when text is a simple name.
Return a list of all keywords, built-in functions and names currently
defined in self.namespace that match. | Below is the the instruction that describes the task:
### Input:
Compute matches when text is a simple name.
Return a list of all keywords, built-in functions and names currently
defined in self.namespace that match.
### Response:
def global_matches(self, text):
"""Compute matches when text... |
def _format_list(result):
"""Format list responses into a table."""
if not result:
return result
if isinstance(result[0], dict):
return _format_list_objects(result)
table = Table(['value'])
for item in result:
table.add_row([iter_to_table(item)])
return table | Format list responses into a table. | Below is the the instruction that describes the task:
### Input:
Format list responses into a table.
### Response:
def _format_list(result):
"""Format list responses into a table."""
if not result:
return result
if isinstance(result[0], dict):
return _format_list_objects(result)
... |
def Show(self, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Call native `ShowWindow(SW.Show)`.
Return bool, True if succeed otherwise False.
"""
return self.ShowWindow(SW.Show, waitTime) | Call native `ShowWindow(SW.Show)`.
Return bool, True if succeed otherwise False. | Below is the the instruction that describes the task:
### Input:
Call native `ShowWindow(SW.Show)`.
Return bool, True if succeed otherwise False.
### Response:
def Show(self, waitTime: float = OPERATION_WAIT_TIME) -> bool:
"""
Call native `ShowWindow(SW.Show)`.
Return bool, True if ... |
def service_reload(service_name, restart_on_failure=False, **kwargs):
"""Reload a system service, optionally falling back to restart if
reload fails.
The specified service name is managed via the system level init system.
Some init systems (e.g. upstart) require that additional arguments be
provide... | Reload a system service, optionally falling back to restart if
reload fails.
The specified service name is managed via the system level init system.
Some init systems (e.g. upstart) require that additional arguments be
provided in order to directly control service instances whereas other init
syste... | Below is the the instruction that describes the task:
### Input:
Reload a system service, optionally falling back to restart if
reload fails.
The specified service name is managed via the system level init system.
Some init systems (e.g. upstart) require that additional arguments be
provided in ord... |
def accept_EP_PKG(self, inst):
'''
A Package contains packageable elements
'''
for child in many(inst).PE_PE[8000]():
self.accept(child) | A Package contains packageable elements | Below is the the instruction that describes the task:
### Input:
A Package contains packageable elements
### Response:
def accept_EP_PKG(self, inst):
'''
A Package contains packageable elements
'''
for child in many(inst).PE_PE[8000]():
self.accept(child) |
def _parse_value(self): # type: () -> Item
"""
Attempts to parse a value at the current position.
"""
self.mark()
c = self._current
trivia = Trivia()
if c == StringType.SLB.value:
return self._parse_basic_string()
elif c == StringType.SLL.val... | Attempts to parse a value at the current position. | Below is the the instruction that describes the task:
### Input:
Attempts to parse a value at the current position.
### Response:
def _parse_value(self): # type: () -> Item
"""
Attempts to parse a value at the current position.
"""
self.mark()
c = self._current
triv... |
def drp(points, epsilon):
""" Douglas ramer peucker
Based on https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm
Args:
points (:obj:`list` of :obj:`Point`)
epsilon (float): drp threshold
Returns:
:obj:`list` of :obj:`Point`
"""
dmax = 0.0
i... | Douglas ramer peucker
Based on https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm
Args:
points (:obj:`list` of :obj:`Point`)
epsilon (float): drp threshold
Returns:
:obj:`list` of :obj:`Point` | Below is the the instruction that describes the task:
### Input:
Douglas ramer peucker
Based on https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm
Args:
points (:obj:`list` of :obj:`Point`)
epsilon (float): drp threshold
Returns:
:obj:`list` of :obj:`... |
def list_math_substraction_number(a, b):
"""!
@brief Calculates subtraction between list and number.
@details Each element from list 'a' is subtracted by number 'b'.
@param[in] a (list): List of elements that supports mathematical subtraction.
@param[in] b (list): Value that supports math... | !
@brief Calculates subtraction between list and number.
@details Each element from list 'a' is subtracted by number 'b'.
@param[in] a (list): List of elements that supports mathematical subtraction.
@param[in] b (list): Value that supports mathematical subtraction.
@return (list) R... | Below is the the instruction that describes the task:
### Input:
!
@brief Calculates subtraction between list and number.
@details Each element from list 'a' is subtracted by number 'b'.
@param[in] a (list): List of elements that supports mathematical subtraction.
@param[in] b (list): Valu... |
def notChainStr (states, s):
"""XXX I'm not sure this is how it should be done, but I'm going to
try it anyway. Note that for this case, I require only single character
arcs, since I would have to basically invert all accepting states and
non-accepting states of any sub-NFA's.
"""
assert len(s)... | XXX I'm not sure this is how it should be done, but I'm going to
try it anyway. Note that for this case, I require only single character
arcs, since I would have to basically invert all accepting states and
non-accepting states of any sub-NFA's. | Below is the the instruction that describes the task:
### Input:
XXX I'm not sure this is how it should be done, but I'm going to
try it anyway. Note that for this case, I require only single character
arcs, since I would have to basically invert all accepting states and
non-accepting states of any sub... |
def _set_below(self, v, load=False):
"""
Setter method for below, mapped from YANG variable /rbridge_id/threshold_monitor/interface/policy/area/alert/below (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_below is considered as a private
method. Backends l... | Setter method for below, mapped from YANG variable /rbridge_id/threshold_monitor/interface/policy/area/alert/below (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_below is considered as a private
method. Backends looking to populate this variable should
do so... | Below is the the instruction that describes the task:
### Input:
Setter method for below, mapped from YANG variable /rbridge_id/threshold_monitor/interface/policy/area/alert/below (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_below is considered as a private
... |
def value_call(method_name, *args, **kwargs):
"""
Creates an effect that will call value's method with specified name
with the specified arguments and keywords.
@param method_name: the name of method belonging to the value.
@type method_name: str
"""
def value_call(value, context, **_params... | Creates an effect that will call value's method with specified name
with the specified arguments and keywords.
@param method_name: the name of method belonging to the value.
@type method_name: str | Below is the the instruction that describes the task:
### Input:
Creates an effect that will call value's method with specified name
with the specified arguments and keywords.
@param method_name: the name of method belonging to the value.
@type method_name: str
### Response:
def value_call(method_name,... |
def to_volume(mesh,
file_name=None,
max_element=None,
mesher_id=1):
"""
Convert a surface mesh to a 3D volume mesh generated by gmsh.
An easy way to install the gmsh sdk is through the gmsh-sdk
package on pypi, which downloads and sets up gmsh:
pip inst... | Convert a surface mesh to a 3D volume mesh generated by gmsh.
An easy way to install the gmsh sdk is through the gmsh-sdk
package on pypi, which downloads and sets up gmsh:
pip install gmsh-sdk
Algorithm details, although check gmsh docs for more information:
The "Delaunay" algorithm is split ... | Below is the the instruction that describes the task:
### Input:
Convert a surface mesh to a 3D volume mesh generated by gmsh.
An easy way to install the gmsh sdk is through the gmsh-sdk
package on pypi, which downloads and sets up gmsh:
pip install gmsh-sdk
Algorithm details, although check g... |
def filter_pages(pages, pagenum, pagename):
""" Choices pages by pagenum and pagename """
if pagenum:
try:
pages = [list(pages)[pagenum - 1]]
except IndexError:
raise IndexError('Invalid page number: %d' % pagenum)
if pagename:
pages = [page for page in pages... | Choices pages by pagenum and pagename | Below is the the instruction that describes the task:
### Input:
Choices pages by pagenum and pagename
### Response:
def filter_pages(pages, pagenum, pagename):
""" Choices pages by pagenum and pagename """
if pagenum:
try:
pages = [list(pages)[pagenum - 1]]
except IndexError:
... |
def _confirm_exit(self):
"""confirm shutdown on ^C
A second ^C, or answering 'y' within 5s will cause shutdown,
otherwise original SIGINT handler will be restored.
This doesn't work on Windows.
"""
# FIXME: remove this delay when pyzmq dependency is >= 2... | confirm shutdown on ^C
A second ^C, or answering 'y' within 5s will cause shutdown,
otherwise original SIGINT handler will be restored.
This doesn't work on Windows. | Below is the the instruction that describes the task:
### Input:
confirm shutdown on ^C
A second ^C, or answering 'y' within 5s will cause shutdown,
otherwise original SIGINT handler will be restored.
This doesn't work on Windows.
### Response:
def _confirm_exit(self):
... |
def cache_warmup(strategy_name, *args, **kwargs):
"""
Warm up cache.
This task periodically hits charts to warm up the cache.
"""
logger.info('Loading strategy')
class_ = None
for class_ in strategies:
if class_.name == strategy_name:
break
else:
message = f... | Warm up cache.
This task periodically hits charts to warm up the cache. | Below is the the instruction that describes the task:
### Input:
Warm up cache.
This task periodically hits charts to warm up the cache.
### Response:
def cache_warmup(strategy_name, *args, **kwargs):
"""
Warm up cache.
This task periodically hits charts to warm up the cache.
"""
logger.... |
def _remember_avatarness(
self, character, graph, node,
is_avatar=True, branch=None, turn=None,
tick=None
):
"""Use this to record a change in avatarness.
Should be called whenever a node that wasn't an avatar of a
character now is, and whenever a node th... | Use this to record a change in avatarness.
Should be called whenever a node that wasn't an avatar of a
character now is, and whenever a node that was an avatar of a
character now isn't.
``character`` is the one using the node as an avatar,
``graph`` is the character the node is... | Below is the the instruction that describes the task:
### Input:
Use this to record a change in avatarness.
Should be called whenever a node that wasn't an avatar of a
character now is, and whenever a node that was an avatar of a
character now isn't.
``character`` is the one using ... |
def in_casapy (helper, asdm=None, ms=None):
"""This function is run inside the weirdo casapy IPython environment! A
strange set of modules is available, and the
`pwkit.environments.casa.scripting` system sets up a very particular
environment to allow encapsulated scripting.
"""
if asdm is None:... | This function is run inside the weirdo casapy IPython environment! A
strange set of modules is available, and the
`pwkit.environments.casa.scripting` system sets up a very particular
environment to allow encapsulated scripting. | Below is the the instruction that describes the task:
### Input:
This function is run inside the weirdo casapy IPython environment! A
strange set of modules is available, and the
`pwkit.environments.casa.scripting` system sets up a very particular
environment to allow encapsulated scripting.
### Respons... |
def command(self, keycode):
'''
Presses a key.
Generates the actual key press on the device and prints the line in the script.
'''
self.device.press(keycode)
self.printOperation(None, Operation.PRESS, keycode) | Presses a key.
Generates the actual key press on the device and prints the line in the script. | Below is the the instruction that describes the task:
### Input:
Presses a key.
Generates the actual key press on the device and prints the line in the script.
### Response:
def command(self, keycode):
'''
Presses a key.
Generates the actual key press on the device and prints the li... |
def install(self, plugin):
''' Add a plugin to the list of plugins and prepare it for beeing
applied to all routes of this application. A plugin may be a simple
decorator or an object that implements the :class:`Plugin` API.
'''
if hasattr(plugin, 'setup'): plugin.setup(s... | Add a plugin to the list of plugins and prepare it for beeing
applied to all routes of this application. A plugin may be a simple
decorator or an object that implements the :class:`Plugin` API. | Below is the the instruction that describes the task:
### Input:
Add a plugin to the list of plugins and prepare it for beeing
applied to all routes of this application. A plugin may be a simple
decorator or an object that implements the :class:`Plugin` API.
### Response:
def install(self, ... |
def fit(self, X):
"""Fit the model.
Arguments:
X: `np.ndarray` of shape (n, 1).
Returns:
None
"""
if isinstance(X, (pd.Series, pd.DataFrame)):
self.name = X.name
self.constant_value = self._get_constant_value(X)
if self.cons... | Fit the model.
Arguments:
X: `np.ndarray` of shape (n, 1).
Returns:
None | Below is the the instruction that describes the task:
### Input:
Fit the model.
Arguments:
X: `np.ndarray` of shape (n, 1).
Returns:
None
### Response:
def fit(self, X):
"""Fit the model.
Arguments:
X: `np.ndarray` of shape (n, 1).
Ret... |
def newest(self):
""" Gets the newest entry in the view, regardless of sort order """
if self._order_by == 'newest':
return self.first
if self._order_by == 'oldest':
return self.last
return max(self.entries, key=lambda x: (x.date, x.id)) | Gets the newest entry in the view, regardless of sort order | Below is the the instruction that describes the task:
### Input:
Gets the newest entry in the view, regardless of sort order
### Response:
def newest(self):
""" Gets the newest entry in the view, regardless of sort order """
if self._order_by == 'newest':
return self.first
if se... |
def _fill(self):
"""Advance the iterator without returning the old head."""
prev = self._head
super(AutoApplyIterator, self)._fill()
if self._head is not None:
self.on_next(self._head, prev) | Advance the iterator without returning the old head. | Below is the the instruction that describes the task:
### Input:
Advance the iterator without returning the old head.
### Response:
def _fill(self):
"""Advance the iterator without returning the old head."""
prev = self._head
super(AutoApplyIterator, self)._fill()
if self._head is not None:
s... |
def _on_event(self, conv_event):
"""Open conversation tab for new messages & pass events to notifier."""
conv = self._conv_list.get(conv_event.conversation_id)
user = conv.get_user(conv_event.user_id)
show_notification = all((
isinstance(conv_event, hangups.ChatMessageEvent),... | Open conversation tab for new messages & pass events to notifier. | Below is the the instruction that describes the task:
### Input:
Open conversation tab for new messages & pass events to notifier.
### Response:
def _on_event(self, conv_event):
"""Open conversation tab for new messages & pass events to notifier."""
conv = self._conv_list.get(conv_event.conversatio... |
def pdf(self, mu):
"""
PDF for Normal prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- p(mu)
"""
if self.transform is not None:
mu = self.transfor... | PDF for Normal prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- p(mu) | Below is the the instruction that describes the task:
### Input:
PDF for Normal prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- p(mu)
### Response:
def pdf(self, mu):
"""
... |
def get_resource(remote):
"""Query CERN Resources to get user info and groups."""
cached_resource = session.pop('cern_resource', None)
if cached_resource:
return cached_resource
response = remote.get(REMOTE_APP_RESOURCE_API_URL)
dict_response = get_dict_from_response(response)
session['... | Query CERN Resources to get user info and groups. | Below is the the instruction that describes the task:
### Input:
Query CERN Resources to get user info and groups.
### Response:
def get_resource(remote):
"""Query CERN Resources to get user info and groups."""
cached_resource = session.pop('cern_resource', None)
if cached_resource:
return cach... |
def feed_forward_layers(inputs, outputs, connections):
"""
Collect the layers whose members can be evaluated in parallel in a feed-forward network.
:param inputs: list of the network input nodes
:param outputs: list of the output node identifiers
:param connections: list of (input, output) connectio... | Collect the layers whose members can be evaluated in parallel in a feed-forward network.
:param inputs: list of the network input nodes
:param outputs: list of the output node identifiers
:param connections: list of (input, output) connections in the network.
Returns a list of layers, with each layer c... | Below is the the instruction that describes the task:
### Input:
Collect the layers whose members can be evaluated in parallel in a feed-forward network.
:param inputs: list of the network input nodes
:param outputs: list of the output node identifiers
:param connections: list of (input, output) connect... |
def maybe_convert_platform_interval(values):
"""
Try to do platform conversion, with special casing for IntervalArray.
Wrapper around maybe_convert_platform that alters the default return
dtype in certain cases to be compatible with IntervalArray. For example,
empty lists return with integer dtype ... | Try to do platform conversion, with special casing for IntervalArray.
Wrapper around maybe_convert_platform that alters the default return
dtype in certain cases to be compatible with IntervalArray. For example,
empty lists return with integer dtype instead of object dtype, which is
prohibited for Inte... | Below is the the instruction that describes the task:
### Input:
Try to do platform conversion, with special casing for IntervalArray.
Wrapper around maybe_convert_platform that alters the default return
dtype in certain cases to be compatible with IntervalArray. For example,
empty lists return with in... |
def init(self):
"""
To be overridden to initialize the datasets needed by the calculation
"""
oq = self.oqparam
if not oq.risk_imtls:
if self.datastore.parent:
oq.risk_imtls = (
self.datastore.parent['oqparam'].risk_imtls)
i... | To be overridden to initialize the datasets needed by the calculation | Below is the the instruction that describes the task:
### Input:
To be overridden to initialize the datasets needed by the calculation
### Response:
def init(self):
"""
To be overridden to initialize the datasets needed by the calculation
"""
oq = self.oqparam
if not oq.risk... |
def _set_slave_timeout(self, dpid, port, timeout):
"""set the timeout time at some port of some datapath."""
slave = self._get_slave(dpid, port)
if slave:
slave['timeout'] = timeout | set the timeout time at some port of some datapath. | Below is the the instruction that describes the task:
### Input:
set the timeout time at some port of some datapath.
### Response:
def _set_slave_timeout(self, dpid, port, timeout):
"""set the timeout time at some port of some datapath."""
slave = self._get_slave(dpid, port)
if slave:
... |
def replace_variable(self, variable):
"""
Replaces an existing OpenFisca variable in the tax and benefit system by a new one.
The new variable must have the same name than the replaced one.
If no variable with the given name exists in the tax and benefit system, no error will be raised... | Replaces an existing OpenFisca variable in the tax and benefit system by a new one.
The new variable must have the same name than the replaced one.
If no variable with the given name exists in the tax and benefit system, no error will be raised and the new variable will be simply added.
:para... | Below is the the instruction that describes the task:
### Input:
Replaces an existing OpenFisca variable in the tax and benefit system by a new one.
The new variable must have the same name than the replaced one.
If no variable with the given name exists in the tax and benefit system, no error wil... |
def conv_act_layer(from_layer, name, num_filter, kernel=(1,1), pad=(0,0), \
stride=(1,1), act_type="relu", use_batchnorm=False):
"""
wrapper for a small Convolution group
Parameters:
----------
from_layer : mx.symbol
continue on which layer
name : str
base name of the new la... | wrapper for a small Convolution group
Parameters:
----------
from_layer : mx.symbol
continue on which layer
name : str
base name of the new layers
num_filter : int
how many filters to use in Convolution layer
kernel : tuple (int, int)
kernel size (h, w)
pad :... | Below is the the instruction that describes the task:
### Input:
wrapper for a small Convolution group
Parameters:
----------
from_layer : mx.symbol
continue on which layer
name : str
base name of the new layers
num_filter : int
how many filters to use in Convolution lay... |
def can_lookup_objective_prerequisites(self):
"""Tests if this user can perform Objective lookups.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known all methods in this
session will result in a PermissionDenied. This is intended a... | Tests if this user can perform Objective lookups.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known all methods in this
session will result in a PermissionDenied. This is intended as a
hint to an application that may opt not to of... | Below is the the instruction that describes the task:
### Input:
Tests if this user can perform Objective lookups.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known all methods in this
session will result in a PermissionDenied. This i... |
def jiggle_text_file(self): # type: () -> int
"""
Update ver strings in a non-python, ordinary text file in root of package (next to setup.py).
:return:
"""
changed = 0
files_to_update = []
for version_txt in self.file_inventory.text_files:
if os.pat... | Update ver strings in a non-python, ordinary text file in root of package (next to setup.py).
:return: | Below is the the instruction that describes the task:
### Input:
Update ver strings in a non-python, ordinary text file in root of package (next to setup.py).
:return:
### Response:
def jiggle_text_file(self): # type: () -> int
"""
Update ver strings in a non-python, ordinary text file in ... |
def union(self, x, y):
"""Merges part that contain x and part containing y
:returns: False if x, y are already in same part
:complexity: O(inverse_ackerman(n))
"""
repr_x = self.find(x)
repr_y = self.find(y)
if repr_x == repr_y: # already in the same compon... | Merges part that contain x and part containing y
:returns: False if x, y are already in same part
:complexity: O(inverse_ackerman(n)) | Below is the the instruction that describes the task:
### Input:
Merges part that contain x and part containing y
:returns: False if x, y are already in same part
:complexity: O(inverse_ackerman(n))
### Response:
def union(self, x, y):
"""Merges part that contain x and part containing y
... |
def _nelec(self):
""" Particles per unit lorentz factor
"""
pd = self.particle_distribution(self._gam * mec2)
return pd.to(1 / mec2_unit).value | Particles per unit lorentz factor | Below is the the instruction that describes the task:
### Input:
Particles per unit lorentz factor
### Response:
def _nelec(self):
""" Particles per unit lorentz factor
"""
pd = self.particle_distribution(self._gam * mec2)
return pd.to(1 / mec2_unit).value |
def start_plugins(conf, watcher_plugin_class, health_plugin_class,
sleep_time):
"""
Start the working threads:
- Health monitor (the health plugin)
- Config change monitor (the watcher plugin)
"""
# No matter what the chosen plugin to watch for config updates: We get a
# ... | Start the working threads:
- Health monitor (the health plugin)
- Config change monitor (the watcher plugin) | Below is the the instruction that describes the task:
### Input:
Start the working threads:
- Health monitor (the health plugin)
- Config change monitor (the watcher plugin)
### Response:
def start_plugins(conf, watcher_plugin_class, health_plugin_class,
sleep_time):
"""
Start th... |
def add_log(self, x, flag_also_show=False):
"""Delegates to parent form"""
self.parent_form.add_log(x, flag_also_show) | Delegates to parent form | Below is the the instruction that describes the task:
### Input:
Delegates to parent form
### Response:
def add_log(self, x, flag_also_show=False):
"""Delegates to parent form"""
self.parent_form.add_log(x, flag_also_show) |
def err(*output, **kwargs):
"""Writes output to stderr.
:arg wrap: If you set ``wrap=False``, then ``err`` won't textwrap
the output.
"""
output = 'Error: ' + ' '.join([str(o) for o in output])
if kwargs.get('wrap') is not False:
output = '\n'.join(wrap(output, kwargs.get('indent',... | Writes output to stderr.
:arg wrap: If you set ``wrap=False``, then ``err`` won't textwrap
the output. | Below is the the instruction that describes the task:
### Input:
Writes output to stderr.
:arg wrap: If you set ``wrap=False``, then ``err`` won't textwrap
the output.
### Response:
def err(*output, **kwargs):
"""Writes output to stderr.
:arg wrap: If you set ``wrap=False``, then ``err`` won'... |
def get(self, split_id: str) -> Split:
""" load transaction by id """
query = (
self.query
.filter(Split.guid == split_id)
)
return query.one() | load transaction by id | Below is the the instruction that describes the task:
### Input:
load transaction by id
### Response:
def get(self, split_id: str) -> Split:
""" load transaction by id """
query = (
self.query
.filter(Split.guid == split_id)
)
return query.one() |
def part_name(self, basename='/tmp/sitemap.xml', part_number=0):
"""Name (file or URI) for one component sitemap.
Works for both filenames and URIs because manipulates only the end
of the string.
Abstracting this into a function that starts from the basename to get
prefix and s... | Name (file or URI) for one component sitemap.
Works for both filenames and URIs because manipulates only the end
of the string.
Abstracting this into a function that starts from the basename to get
prefix and suffix each time seems a bit wasteful but perhaps not worth
worrying ... | Below is the the instruction that describes the task:
### Input:
Name (file or URI) for one component sitemap.
Works for both filenames and URIs because manipulates only the end
of the string.
Abstracting this into a function that starts from the basename to get
prefix and suffix e... |
def parse_stat(self, buf):
"""
`buf` is a readable file-like object
returns a tuple: (metrics, tags, mode, version)
"""
metrics = []
buf.seek(0)
# Check the version line to make sure we parse the rest of the
# body correctly. Particularly, the Connections... | `buf` is a readable file-like object
returns a tuple: (metrics, tags, mode, version) | Below is the the instruction that describes the task:
### Input:
`buf` is a readable file-like object
returns a tuple: (metrics, tags, mode, version)
### Response:
def parse_stat(self, buf):
"""
`buf` is a readable file-like object
returns a tuple: (metrics, tags, mode, version)
... |
def unix_time(self, end_datetime=None, start_datetime=None):
"""
Get a timestamp between January 1, 1970 and now, unless passed
explicit start_datetime or end_datetime values.
:example 1061306726
"""
start_datetime = self._parse_start_datetime(start_datetime)
end_... | Get a timestamp between January 1, 1970 and now, unless passed
explicit start_datetime or end_datetime values.
:example 1061306726 | Below is the the instruction that describes the task:
### Input:
Get a timestamp between January 1, 1970 and now, unless passed
explicit start_datetime or end_datetime values.
:example 1061306726
### Response:
def unix_time(self, end_datetime=None, start_datetime=None):
"""
Get a ti... |
def parseConfigFile(configFile=None):
"""Returns a configparser.SafeConfigParser instance with configs
read from the config file. Default location of the config file is
at ~/.wakatime.cfg.
"""
# get config file location from ENV
if not configFile:
configFile = getConfigFile()
confi... | Returns a configparser.SafeConfigParser instance with configs
read from the config file. Default location of the config file is
at ~/.wakatime.cfg. | Below is the the instruction that describes the task:
### Input:
Returns a configparser.SafeConfigParser instance with configs
read from the config file. Default location of the config file is
at ~/.wakatime.cfg.
### Response:
def parseConfigFile(configFile=None):
"""Returns a configparser.SafeConfigPa... |
def move_page_bottom(self):
"""
Move the cursor to the last item on the page.
"""
self.nav.page_index = self.content.range[1]
self.nav.cursor_index = 0
self.nav.inverted = True | Move the cursor to the last item on the page. | Below is the the instruction that describes the task:
### Input:
Move the cursor to the last item on the page.
### Response:
def move_page_bottom(self):
"""
Move the cursor to the last item on the page.
"""
self.nav.page_index = self.content.range[1]
self.nav.cursor_index = ... |
def Save(session, filename=None):
"""
save your session to use it later.
Returns the filename of the written file.
If not filename is given, a file named `androguard_session_<DATE>.ag` will
be created in the current working directory.
`<DATE>` is a timestamp with the following format: `%Y-%m-%d... | save your session to use it later.
Returns the filename of the written file.
If not filename is given, a file named `androguard_session_<DATE>.ag` will
be created in the current working directory.
`<DATE>` is a timestamp with the following format: `%Y-%m-%d_%H%M%S`.
This function will overwrite ex... | Below is the the instruction that describes the task:
### Input:
save your session to use it later.
Returns the filename of the written file.
If not filename is given, a file named `androguard_session_<DATE>.ag` will
be created in the current working directory.
`<DATE>` is a timestamp with the foll... |
def localize(self):
"""
Check if this module was saved as a resource. If it was, return a new module descriptor
that points to a local copy of that resource. Should only be called on a worker node. On
the leader, this method returns this resource, i.e. self.
:rtype: toil.resourc... | Check if this module was saved as a resource. If it was, return a new module descriptor
that points to a local copy of that resource. Should only be called on a worker node. On
the leader, this method returns this resource, i.e. self.
:rtype: toil.resource.Resource | Below is the the instruction that describes the task:
### Input:
Check if this module was saved as a resource. If it was, return a new module descriptor
that points to a local copy of that resource. Should only be called on a worker node. On
the leader, this method returns this resource, i.e. self.
... |
def Network_setCookie(self, name, value, **kwargs):
"""
Function path: Network.setCookie
Domain: Network
Method name: setCookie
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'name' (type: string) -> Cookie name.
'value' (type: string) -> Cookie valu... | Function path: Network.setCookie
Domain: Network
Method name: setCookie
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'name' (type: string) -> Cookie name.
'value' (type: string) -> Cookie value.
Optional arguments:
'url' (type: string) -> The ... | Below is the the instruction that describes the task:
### Input:
Function path: Network.setCookie
Domain: Network
Method name: setCookie
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'name' (type: string) -> Cookie name.
'value' (type: string) -> Co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.