code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def area_field(key='area'):
"""Provides a select box for country selection"""
area_list = list(subdivisions)
title_map = []
for item in area_list:
title_map.append({'value': item.code, 'name': item.name})
widget = {
'key': key,
'type': 'uiselect',
'titleMap': title_... | Provides a select box for country selection | Below is the the instruction that describes the task:
### Input:
Provides a select box for country selection
### Response:
def area_field(key='area'):
"""Provides a select box for country selection"""
area_list = list(subdivisions)
title_map = []
for item in area_list:
title_map.append({'v... |
def extract_flags_from_text(self, text):
"""
Extract the flags from the given text and return a :class:`set` of flag values. See
:class:`~taxi.timesheet.lines.Entry` for a list of existing flags.
"""
flags = set()
reversed_flags_repr = {v: k for k, v in self.flags_repr.it... | Extract the flags from the given text and return a :class:`set` of flag values. See
:class:`~taxi.timesheet.lines.Entry` for a list of existing flags. | Below is the the instruction that describes the task:
### Input:
Extract the flags from the given text and return a :class:`set` of flag values. See
:class:`~taxi.timesheet.lines.Entry` for a list of existing flags.
### Response:
def extract_flags_from_text(self, text):
"""
Extract the flag... |
def make_variant(cls, converters, re_opts=None, compiled=False, strict=True):
"""
Creates a type converter for a number of type converter alternatives.
The first matching type converter is used.
REQUIRES: type_converter.pattern attribute
:param converters: List of type converte... | Creates a type converter for a number of type converter alternatives.
The first matching type converter is used.
REQUIRES: type_converter.pattern attribute
:param converters: List of type converters as alternatives.
:param re_opts: Regular expression options zu use (=default_re_opts).... | Below is the the instruction that describes the task:
### Input:
Creates a type converter for a number of type converter alternatives.
The first matching type converter is used.
REQUIRES: type_converter.pattern attribute
:param converters: List of type converters as alternatives.
:... |
def set(container, azure_secret_access_key):
"""Set/update the access key for the specified Azure storage container."""
click.secho(dtool_config.utils.set_azure_secret_access_key(
CONFIG_PATH,
container,
azure_secret_access_key
)) | Set/update the access key for the specified Azure storage container. | Below is the the instruction that describes the task:
### Input:
Set/update the access key for the specified Azure storage container.
### Response:
def set(container, azure_secret_access_key):
"""Set/update the access key for the specified Azure storage container."""
click.secho(dtool_config.utils.set_azur... |
def tar_and_upload_dir(session, bucket, s3_key_prefix, script,
directory=None, dependencies=None, kms_key=None):
"""Package source files and upload a compress tar file to S3. The S3 location will be
``s3://<bucket>/s3_key_prefix/sourcedir.tar.gz``.
If directory is an S3 URI, an Uploa... | Package source files and upload a compress tar file to S3. The S3 location will be
``s3://<bucket>/s3_key_prefix/sourcedir.tar.gz``.
If directory is an S3 URI, an UploadedCode object will be returned, but nothing will be
uploaded to S3 (this allow reuse of code already in S3).
If directory is None, th... | Below is the the instruction that describes the task:
### Input:
Package source files and upload a compress tar file to S3. The S3 location will be
``s3://<bucket>/s3_key_prefix/sourcedir.tar.gz``.
If directory is an S3 URI, an UploadedCode object will be returned, but nothing will be
uploaded to S3 (t... |
def strings_to_list_string(strings):
'''Takes a list of strings presumably containing words and phrases,
and returns a "list" form of those strings, like:
>>> strings_to_list_string(('cats', 'dogs'))
>>> 'cats and dogs'
or
>>> strings_to_list_string(('pizza', 'pop', 'chips'))
... | Takes a list of strings presumably containing words and phrases,
and returns a "list" form of those strings, like:
>>> strings_to_list_string(('cats', 'dogs'))
>>> 'cats and dogs'
or
>>> strings_to_list_string(('pizza', 'pop', 'chips'))
>>> 'pizza, pop, and chips'
Ra... | Below is the the instruction that describes the task:
### Input:
Takes a list of strings presumably containing words and phrases,
and returns a "list" form of those strings, like:
>>> strings_to_list_string(('cats', 'dogs'))
>>> 'cats and dogs'
or
>>> strings_to_list_string(('p... |
def report(self, format=ReportFormat.printout, output_path=None):
"""
Returns a report of this class.
:param format: The format of the report.
:param output_path: The path to the file the report is written to.
If None, then the report is not written to a file.
:return... | Returns a report of this class.
:param format: The format of the report.
:param output_path: The path to the file the report is written to.
If None, then the report is not written to a file.
:returns: The descendants of the account. | Below is the the instruction that describes the task:
### Input:
Returns a report of this class.
:param format: The format of the report.
:param output_path: The path to the file the report is written to.
If None, then the report is not written to a file.
:returns: The descendant... |
def retrieve(self, request, _id):
"""
Returns the document containing the given _id or 404
"""
_id = deserialize(_id)
retrieved = self.collection.find_one({'_id': _id})
if retrieved:
return Response(serialize(retrieved))
else:
return Respo... | Returns the document containing the given _id or 404 | Below is the the instruction that describes the task:
### Input:
Returns the document containing the given _id or 404
### Response:
def retrieve(self, request, _id):
"""
Returns the document containing the given _id or 404
"""
_id = deserialize(_id)
retrieved = self.collect... |
def _parse_mtllibs(self):
"""Load mtl files"""
for mtllib in self.meta.mtllibs:
try:
materials = self.material_parser_cls(
os.path.join(self.path, mtllib),
encoding=self.encoding,
strict=self.strict).materials
... | Load mtl files | Below is the the instruction that describes the task:
### Input:
Load mtl files
### Response:
def _parse_mtllibs(self):
"""Load mtl files"""
for mtllib in self.meta.mtllibs:
try:
materials = self.material_parser_cls(
os.path.join(self.path, mtllib),
... |
def init_app(self, app, conf_key=None):
"""
:type app: flask.Flask
:parm str conf_key: Key of flask config.
"""
conf_key = conf_key or self.conf_key or 'PYMEMCACHE'
self.conf_key = conf_key
conf = app.config[conf_key]
if not isinstance(conf, dict):
... | :type app: flask.Flask
:parm str conf_key: Key of flask config. | Below is the the instruction that describes the task:
### Input:
:type app: flask.Flask
:parm str conf_key: Key of flask config.
### Response:
def init_app(self, app, conf_key=None):
"""
:type app: flask.Flask
:parm str conf_key: Key of flask config.
"""
conf_key = c... |
def cache_train(self):
"""
Loads the data for this classifier from a cache file
:return: whether or not we were successful
:rtype: bool
"""
filename = self.get_cache_location()
if not os.path.exists(filename):
return False
categories = pickl... | Loads the data for this classifier from a cache file
:return: whether or not we were successful
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Loads the data for this classifier from a cache file
:return: whether or not we were successful
:rtype: bool
### Response:
def cache_train(self):
"""
Loads the data for this classifier from a cache file
:retu... |
def print_tree(self, maxresults=100, maxdepth=None):
"""Walk the object tree, pretty-printing each branch."""
self.ignore_caller()
for depth, refid, rep in self.walk(maxresults, maxdepth):
print(("%9d" % refid), (" " * depth * 2), rep) | Walk the object tree, pretty-printing each branch. | Below is the the instruction that describes the task:
### Input:
Walk the object tree, pretty-printing each branch.
### Response:
def print_tree(self, maxresults=100, maxdepth=None):
"""Walk the object tree, pretty-printing each branch."""
self.ignore_caller()
for depth, refid, rep in self.... |
def get_transports():
"""
get all known transports from Ariane Server
:return:
"""
LOGGER.debug("TransportService.get_transports")
params = SessionService.complete_transactional_req(None)
if params is None:
if MappingService.driver_type != DriverFactor... | get all known transports from Ariane Server
:return: | Below is the the instruction that describes the task:
### Input:
get all known transports from Ariane Server
:return:
### Response:
def get_transports():
"""
get all known transports from Ariane Server
:return:
"""
LOGGER.debug("TransportService.get_transports")
... |
def batch_augment(x, func, device='/CPU:0'):
"""
Apply dataset augmentation to a batch of exmaples.
:param x: Tensor representing a batch of examples.
:param func: Callable implementing dataset augmentation, operating on
a single image.
:param device: String specifying which device to use.
"""
with tf... | Apply dataset augmentation to a batch of exmaples.
:param x: Tensor representing a batch of examples.
:param func: Callable implementing dataset augmentation, operating on
a single image.
:param device: String specifying which device to use. | Below is the the instruction that describes the task:
### Input:
Apply dataset augmentation to a batch of exmaples.
:param x: Tensor representing a batch of examples.
:param func: Callable implementing dataset augmentation, operating on
a single image.
:param device: String specifying which device to use.... |
def add_headers(vcf_obj, nr_cases=None, sv=False):
"""Add loqus specific information to a VCF header
Args:
vcf_obj(cyvcf2.VCF)
"""
vcf_obj.add_info_to_header(
{
'ID':"Obs",
'Number': '1',
'Type': 'Integer',
'Description': "The number of o... | Add loqus specific information to a VCF header
Args:
vcf_obj(cyvcf2.VCF) | Below is the the instruction that describes the task:
### Input:
Add loqus specific information to a VCF header
Args:
vcf_obj(cyvcf2.VCF)
### Response:
def add_headers(vcf_obj, nr_cases=None, sv=False):
"""Add loqus specific information to a VCF header
Args:
vcf_obj(cyvcf2.VCF)
""... |
def hexblock_byte(cls, data, address = None,
bits = None,
separator = ' ',
width = 16):
... | Dump a block of hexadecimal BYTEs from binary data.
@type data: str
@param data: Binary data.
@type address: str
@param address: Memory address where the data was read from.
@type bits: int
@param bits:
(Optional) Number of bits of the target architectur... | Below is the the instruction that describes the task:
### Input:
Dump a block of hexadecimal BYTEs from binary data.
@type data: str
@param data: Binary data.
@type address: str
@param address: Memory address where the data was read from.
@type bits: int
@param ... |
def login(self, username=None, password=None):
""" Before doing any remote operation, the user has to login to the GMQL serivice.
This can be done in the two following ways:
* Guest mode: the user has no credentials and uses the system only as a temporary guest
* Authenticated m... | Before doing any remote operation, the user has to login to the GMQL serivice.
This can be done in the two following ways:
* Guest mode: the user has no credentials and uses the system only as a temporary guest
* Authenticated mode: the users has credentials and a stable remote account
... | Below is the the instruction that describes the task:
### Input:
Before doing any remote operation, the user has to login to the GMQL serivice.
This can be done in the two following ways:
* Guest mode: the user has no credentials and uses the system only as a temporary guest
* Authe... |
def from_array(array):
"""
Deserialize a new KeyboardButton from a given dictionary.
:return: new KeyboardButton instance.
:rtype: KeyboardButton
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, paramet... | Deserialize a new KeyboardButton from a given dictionary.
:return: new KeyboardButton instance.
:rtype: KeyboardButton | Below is the the instruction that describes the task:
### Input:
Deserialize a new KeyboardButton from a given dictionary.
:return: new KeyboardButton instance.
:rtype: KeyboardButton
### Response:
def from_array(array):
"""
Deserialize a new KeyboardButton from a given dictionary.... |
def order(self, order=None):
"""
If order is given, modify the URL correspondingly, return the current
order otherwise.
"""
if order is None:
return int(self.url.order)
self.url.order = str(order) | If order is given, modify the URL correspondingly, return the current
order otherwise. | Below is the the instruction that describes the task:
### Input:
If order is given, modify the URL correspondingly, return the current
order otherwise.
### Response:
def order(self, order=None):
"""
If order is given, modify the URL correspondingly, return the current
order otherwis... |
def focusOutEvent( self, event ):
"""
Overloads the focus out event to cancel editing when the widget loses
focus.
:param event | <QFocusEvent>
"""
super(XNavigationEdit, self).focusOutEvent(event)
self.cancelEdit() | Overloads the focus out event to cancel editing when the widget loses
focus.
:param event | <QFocusEvent> | Below is the the instruction that describes the task:
### Input:
Overloads the focus out event to cancel editing when the widget loses
focus.
:param event | <QFocusEvent>
### Response:
def focusOutEvent( self, event ):
"""
Overloads the focus out event to cancel editin... |
def _get_distribution_indexes(catalog, dataset_identifier, dataset_title,
distribution_identifier, distribution_title,
logger=None):
"""Devuelve el índice de una distribución en su dataset en función de su
título, junto con el índice de su dataset padr... | Devuelve el índice de una distribución en su dataset en función de su
título, junto con el índice de su dataset padre en el catálogo, en
función de su identificador | Below is the the instruction that describes the task:
### Input:
Devuelve el índice de una distribución en su dataset en función de su
título, junto con el índice de su dataset padre en el catálogo, en
función de su identificador
### Response:
def _get_distribution_indexes(catalog, dataset_identifier, data... |
def children(self, node_parent):
"""!
@brief Returns list of children of node.
@param[in] node_parent (node): Node whose children are required.
@return (list) Children of node. If node haven't got any child then None is returned.
"""
... | !
@brief Returns list of children of node.
@param[in] node_parent (node): Node whose children are required.
@return (list) Children of node. If node haven't got any child then None is returned. | Below is the the instruction that describes the task:
### Input:
!
@brief Returns list of children of node.
@param[in] node_parent (node): Node whose children are required.
@return (list) Children of node. If node haven't got any child then None is returned.
### Respo... |
def _normalize_lang_attrs(self, text, strip):
"""Remove embedded bracketed attributes.
This (potentially) bitwise-ands bracketed attributes together and adds
to the end.
This is applied to a single alternative at a time -- not to a
parenthesized list.
It removes all embe... | Remove embedded bracketed attributes.
This (potentially) bitwise-ands bracketed attributes together and adds
to the end.
This is applied to a single alternative at a time -- not to a
parenthesized list.
It removes all embedded bracketed attributes, logically-ands them
to... | Below is the the instruction that describes the task:
### Input:
Remove embedded bracketed attributes.
This (potentially) bitwise-ands bracketed attributes together and adds
to the end.
This is applied to a single alternative at a time -- not to a
parenthesized list.
It remo... |
def add_data_flow_to_state(from_port, to_port):
"""Interface method between Gaphas and RAFCON core for adding data flows
The method checks the types of the given ports and their relation. From this the necessary parameters for the
add_dat_flow method of the RAFCON core are determined. Also the parent state... | Interface method between Gaphas and RAFCON core for adding data flows
The method checks the types of the given ports and their relation. From this the necessary parameters for the
add_dat_flow method of the RAFCON core are determined. Also the parent state is derived from the ports.
:param from_port: Port... | Below is the the instruction that describes the task:
### Input:
Interface method between Gaphas and RAFCON core for adding data flows
The method checks the types of the given ports and their relation. From this the necessary parameters for the
add_dat_flow method of the RAFCON core are determined. Also th... |
def _worker_handler(future, worker, pipe, timeout):
"""Worker lifecycle manager.
Waits for the worker to be perform its task,
collects result, runs the callback and cleans up the process.
"""
result = _get_result(future, pipe, timeout)
if isinstance(result, BaseException):
if isinstan... | Worker lifecycle manager.
Waits for the worker to be perform its task,
collects result, runs the callback and cleans up the process. | Below is the the instruction that describes the task:
### Input:
Worker lifecycle manager.
Waits for the worker to be perform its task,
collects result, runs the callback and cleans up the process.
### Response:
def _worker_handler(future, worker, pipe, timeout):
"""Worker lifecycle manager.
Wait... |
def get_authorize_url(self, state=None):
""" Gets the URL to use to authorize this app
"""
payload = {'client_id': self.client_id,
'response_type': 'code',
'redirect_uri': self.redirect_uri,
'scope': self.scope}
urlparams = urllib... | Gets the URL to use to authorize this app | Below is the the instruction that describes the task:
### Input:
Gets the URL to use to authorize this app
### Response:
def get_authorize_url(self, state=None):
""" Gets the URL to use to authorize this app
"""
payload = {'client_id': self.client_id,
'response_type': 'co... |
def zones(self):
"""
:class:`list` of :class:`stravalib.model.ActivityZone` objects for this activity.
"""
if self._zones is None:
self.assert_bind_client()
self._zones = self.bind_client.get_activity_zones(self.id)
return self._zones | :class:`list` of :class:`stravalib.model.ActivityZone` objects for this activity. | Below is the the instruction that describes the task:
### Input:
:class:`list` of :class:`stravalib.model.ActivityZone` objects for this activity.
### Response:
def zones(self):
"""
:class:`list` of :class:`stravalib.model.ActivityZone` objects for this activity.
"""
if self._zones ... |
def _createFromLocal(self, data, schema):
"""
Create an RDD for DataFrame from a list or pandas.DataFrame, returns
the RDD and schema.
"""
# make sure data could consumed multiple times
if not isinstance(data, list):
data = list(data)
if schema is Non... | Create an RDD for DataFrame from a list or pandas.DataFrame, returns
the RDD and schema. | Below is the the instruction that describes the task:
### Input:
Create an RDD for DataFrame from a list or pandas.DataFrame, returns
the RDD and schema.
### Response:
def _createFromLocal(self, data, schema):
"""
Create an RDD for DataFrame from a list or pandas.DataFrame, returns
... |
def ReportConfiguration(self, file):
"""
:param file: Destination for report details
:return: None
"""
global encodingpar
print >> file, BuildReportLine("FAM FILE", self.fam_details)
print >> file, BuildReportLine("IMPUTE_ARCHIVES", "%s:%s" % (str(self.chroms[0]),... | :param file: Destination for report details
:return: None | Below is the the instruction that describes the task:
### Input:
:param file: Destination for report details
:return: None
### Response:
def ReportConfiguration(self, file):
"""
:param file: Destination for report details
:return: None
"""
global encodingpar
... |
def get(self, key, default=None):
'''
get - Gets an attribute by key with the chance to provide a default value
@param key <str> - The key to query
@param default <Anything> Default None - The value to return if key is not found
@return - The value of ... | get - Gets an attribute by key with the chance to provide a default value
@param key <str> - The key to query
@param default <Anything> Default None - The value to return if key is not found
@return - The value of attribute at #key, or #default if not present. | Below is the the instruction that describes the task:
### Input:
get - Gets an attribute by key with the chance to provide a default value
@param key <str> - The key to query
@param default <Anything> Default None - The value to return if key is not found
@return - Th... |
def delete_reference_image(
self,
location,
product_id,
reference_image_id,
project_id=None,
retry=None,
timeout=None,
metadata=None,
):
"""
For the documentation see:
:py:class:`~airflow.contrib.operators.gcp_vision_operator.Cl... | For the documentation see:
:py:class:`~airflow.contrib.operators.gcp_vision_operator.CloudVisionReferenceImageCreateOperator` | Below is the the instruction that describes the task:
### Input:
For the documentation see:
:py:class:`~airflow.contrib.operators.gcp_vision_operator.CloudVisionReferenceImageCreateOperator`
### Response:
def delete_reference_image(
self,
location,
product_id,
reference_imag... |
def percolate_declares(program: Program) -> Program:
"""
Move all the DECLARE statements to the top of the program. Return a fresh obejct.
:param program: Perhaps jumbled program.
:return: Program with DECLAREs all at the top and otherwise the same sorted contents.
"""
declare_program = Program... | Move all the DECLARE statements to the top of the program. Return a fresh obejct.
:param program: Perhaps jumbled program.
:return: Program with DECLAREs all at the top and otherwise the same sorted contents. | Below is the the instruction that describes the task:
### Input:
Move all the DECLARE statements to the top of the program. Return a fresh obejct.
:param program: Perhaps jumbled program.
:return: Program with DECLAREs all at the top and otherwise the same sorted contents.
### Response:
def percolate_decl... |
def _rolling_window(a, window, axis=-1):
"""
Make an ndarray with a rolling window along axis.
Parameters
----------
a : array_like
Array to add rolling window to
axis: int
axis position along which rolling window will be applied.
window : int
Size of rolling window
... | Make an ndarray with a rolling window along axis.
Parameters
----------
a : array_like
Array to add rolling window to
axis: int
axis position along which rolling window will be applied.
window : int
Size of rolling window
Returns
-------
Array that is a view of ... | Below is the the instruction that describes the task:
### Input:
Make an ndarray with a rolling window along axis.
Parameters
----------
a : array_like
Array to add rolling window to
axis: int
axis position along which rolling window will be applied.
window : int
Size of... |
def intersect(self, range_):
self.solver.intersection_broad_tests_count += 1
"""Remove variants whose version fall outside of the given range."""
if range_.is_any():
return self
if self.solver.optimised:
if range_ in self.been_intersected_with:
r... | Remove variants whose version fall outside of the given range. | Below is the the instruction that describes the task:
### Input:
Remove variants whose version fall outside of the given range.
### Response:
def intersect(self, range_):
self.solver.intersection_broad_tests_count += 1
"""Remove variants whose version fall outside of the given range."""
if... |
def insert(self, context):
"""
Add Vagrant box to the calling user.
:param resort.engine.execution.Context context:
Current execution context.
"""
self.write([
"box",
"add",
"--name", context.resolve(self.__name),
self.__path(context)
]) | Add Vagrant box to the calling user.
:param resort.engine.execution.Context context:
Current execution context. | Below is the the instruction that describes the task:
### Input:
Add Vagrant box to the calling user.
:param resort.engine.execution.Context context:
Current execution context.
### Response:
def insert(self, context):
"""
Add Vagrant box to the calling user.
:param resort.engine.execution.Cont... |
def show_channel(self, channel, owner):
'''List the channels for owner
If owner is none, the currently logged in user is used
'''
url = '%s/channels/%s/%s' % (self.domain, owner, channel)
res = self.session.get(url)
self._check_response(res, [200])
return res.jso... | List the channels for owner
If owner is none, the currently logged in user is used | Below is the the instruction that describes the task:
### Input:
List the channels for owner
If owner is none, the currently logged in user is used
### Response:
def show_channel(self, channel, owner):
'''List the channels for owner
If owner is none, the currently logged in user is used
... |
def hparams_to_batching_scheme(hparams,
drop_long_sequences=False,
shard_multiplier=1,
length_multiplier=1):
"""Wrapper around _batching_scheme with hparams."""
return batching_scheme(
batch_size=hparams.batch_size,
... | Wrapper around _batching_scheme with hparams. | Below is the the instruction that describes the task:
### Input:
Wrapper around _batching_scheme with hparams.
### Response:
def hparams_to_batching_scheme(hparams,
drop_long_sequences=False,
shard_multiplier=1,
length_mul... |
def delayed_unpacking(self, container, fun, *args, **kwargs):
"""Should be used when unpacking mutable values.
This allows circular references resolution by pausing serialization."""
try:
self._delayed += 1
blob = self._begin()
try:
fun(*args, ... | Should be used when unpacking mutable values.
This allows circular references resolution by pausing serialization. | Below is the the instruction that describes the task:
### Input:
Should be used when unpacking mutable values.
This allows circular references resolution by pausing serialization.
### Response:
def delayed_unpacking(self, container, fun, *args, **kwargs):
"""Should be used when unpacking mutable va... |
def _compute_initial_out_degree(self):
"""The number of operations which use each tensor as input.
Returns:
a {string, int} mapping tensor name to the number of operations which use
it as input, or one plus that quantity if the tensor is final.
"""
out_degree = collections.defaultdict(int)
... | The number of operations which use each tensor as input.
Returns:
a {string, int} mapping tensor name to the number of operations which use
it as input, or one plus that quantity if the tensor is final. | Below is the the instruction that describes the task:
### Input:
The number of operations which use each tensor as input.
Returns:
a {string, int} mapping tensor name to the number of operations which use
it as input, or one plus that quantity if the tensor is final.
### Response:
def _compute_ini... |
def copy(self):
'''
:return: a copy of the container
'''
dup = super(Container, self).copy()
dup._fields = [field.copy() for field in self._fields]
dup._fields_dict = {field.get_name(): field for field in dup._fields if field.get_name() is not None}
dup._container... | :return: a copy of the container | Below is the the instruction that describes the task:
### Input:
:return: a copy of the container
### Response:
def copy(self):
'''
:return: a copy of the container
'''
dup = super(Container, self).copy()
dup._fields = [field.copy() for field in self._fields]
dup._fi... |
def decrypt(self, message):
"""
Decrypt a PGPMessage using this key.
:param message: An encrypted :py:obj:`PGPMessage`
:raises: :py:exc:`~errors.PGPError` if the key is not private, or protected but not unlocked.
:raises: :py:exc:`~errors.PGPDecryptionError` if decryption fails ... | Decrypt a PGPMessage using this key.
:param message: An encrypted :py:obj:`PGPMessage`
:raises: :py:exc:`~errors.PGPError` if the key is not private, or protected but not unlocked.
:raises: :py:exc:`~errors.PGPDecryptionError` if decryption fails for any other reason.
:returns: A new :p... | Below is the the instruction that describes the task:
### Input:
Decrypt a PGPMessage using this key.
:param message: An encrypted :py:obj:`PGPMessage`
:raises: :py:exc:`~errors.PGPError` if the key is not private, or protected but not unlocked.
:raises: :py:exc:`~errors.PGPDecryptionError`... |
def document_delete(index, doc_type, id, hosts=None, profile=None):
'''
Delete a document from an index
index
Index name where the document resides
doc_type
Type of the document
id
Document identifier
CLI example::
salt myminion elasticsearch.document_delete te... | Delete a document from an index
index
Index name where the document resides
doc_type
Type of the document
id
Document identifier
CLI example::
salt myminion elasticsearch.document_delete testindex doctype1 AUx-384m0Bug_8U80wQZ | Below is the the instruction that describes the task:
### Input:
Delete a document from an index
index
Index name where the document resides
doc_type
Type of the document
id
Document identifier
CLI example::
salt myminion elasticsearch.document_delete testindex doc... |
def likelihood2(args):
"""
%prog likelihood2 100_20.json
Plot the likelihood surface and marginal distributions.
"""
from matplotlib import gridspec
p = OptionParser(likelihood2.__doc__)
opts, args, iopts = p.set_image_options(args, figsize="10x5",
style="wh... | %prog likelihood2 100_20.json
Plot the likelihood surface and marginal distributions. | Below is the the instruction that describes the task:
### Input:
%prog likelihood2 100_20.json
Plot the likelihood surface and marginal distributions.
### Response:
def likelihood2(args):
"""
%prog likelihood2 100_20.json
Plot the likelihood surface and marginal distributions.
"""
from ma... |
def settings(cls):
"""
Find the settings for the current class inside the platforms
configuration.
"""
from bernard.platforms.management import get_platform_settings
for platform in get_platform_settings():
candidate = import_class(platform['class'])
... | Find the settings for the current class inside the platforms
configuration. | Below is the the instruction that describes the task:
### Input:
Find the settings for the current class inside the platforms
configuration.
### Response:
def settings(cls):
"""
Find the settings for the current class inside the platforms
configuration.
"""
from ber... |
def block_widths(self):
"""Gets the widths of the blocks.
Note: This works with the property structure `_widths_cache` to avoid
having to recompute these values each time they are needed.
"""
if self._widths_cache is None:
# The first column will have the correct... | Gets the widths of the blocks.
Note: This works with the property structure `_widths_cache` to avoid
having to recompute these values each time they are needed. | Below is the the instruction that describes the task:
### Input:
Gets the widths of the blocks.
Note: This works with the property structure `_widths_cache` to avoid
having to recompute these values each time they are needed.
### Response:
def block_widths(self):
"""Gets the widths of ... |
def patch(self, item, byte_order=BYTEORDER):
""" Returns a memory :class:`Patch` for the given *item* that shall be
patched in the `data source`.
:param item: item to patch.
:param byte_order: encoding :class:`Byteorder` for the item.
:type byte_order: :class:`Byteorder`, :class... | Returns a memory :class:`Patch` for the given *item* that shall be
patched in the `data source`.
:param item: item to patch.
:param byte_order: encoding :class:`Byteorder` for the item.
:type byte_order: :class:`Byteorder`, :class:`str` | Below is the the instruction that describes the task:
### Input:
Returns a memory :class:`Patch` for the given *item* that shall be
patched in the `data source`.
:param item: item to patch.
:param byte_order: encoding :class:`Byteorder` for the item.
:type byte_order: :class:`Byteor... |
def mset(self, *args, **kwargs):
"""
Sets key/values based on a mapping. Mapping can be supplied as a single
dictionary argument or as kwargs.
"""
mapping = kwargs
if args:
if len(args) != 1 or not isinstance(args[0], dict):
raise RedisError('M... | Sets key/values based on a mapping. Mapping can be supplied as a single
dictionary argument or as kwargs. | Below is the the instruction that describes the task:
### Input:
Sets key/values based on a mapping. Mapping can be supplied as a single
dictionary argument or as kwargs.
### Response:
def mset(self, *args, **kwargs):
"""
Sets key/values based on a mapping. Mapping can be supplied as a sing... |
def qdict_get_list(qdict, k):
"""
get list from QueryDict and remove blank date from list.
"""
pks = qdict.getlist(k)
return [e for e in pks if e] | get list from QueryDict and remove blank date from list. | Below is the the instruction that describes the task:
### Input:
get list from QueryDict and remove blank date from list.
### Response:
def qdict_get_list(qdict, k):
"""
get list from QueryDict and remove blank date from list.
"""
pks = qdict.getlist(k)
return [e for e in pks if e] |
def collect_params(self, select=None):
"""Returns a :py:class:`ParameterDict` containing this :py:class:`Block` and all of its
children's Parameters(default), also can returns the select :py:class:`ParameterDict`
which match some given regular expressions.
For example, collect the speci... | Returns a :py:class:`ParameterDict` containing this :py:class:`Block` and all of its
children's Parameters(default), also can returns the select :py:class:`ParameterDict`
which match some given regular expressions.
For example, collect the specified parameters in ['conv1_weight', 'conv1_bias', ... | Below is the the instruction that describes the task:
### Input:
Returns a :py:class:`ParameterDict` containing this :py:class:`Block` and all of its
children's Parameters(default), also can returns the select :py:class:`ParameterDict`
which match some given regular expressions.
For example... |
def return_page(page):
"""Return a rendered template."""
try:
hit_id = request.args['hit_id']
assignment_id = request.args['assignment_id']
worker_id = request.args['worker_id']
mode = request.args['mode']
return render_template(
page,
hit_id=hit_i... | Return a rendered template. | Below is the the instruction that describes the task:
### Input:
Return a rendered template.
### Response:
def return_page(page):
"""Return a rendered template."""
try:
hit_id = request.args['hit_id']
assignment_id = request.args['assignment_id']
worker_id = request.args['worker_id'... |
async def _async_register(self): # pragma: no cover
""" Register the agent in the XMPP server from a coroutine. """
metadata = aioxmpp.make_security_layer(None, no_verify=not self.verify_security)
query = ibr.Query(self.jid.localpart, self.password)
_, stream, features = await aioxmpp.n... | Register the agent in the XMPP server from a coroutine. | Below is the the instruction that describes the task:
### Input:
Register the agent in the XMPP server from a coroutine.
### Response:
async def _async_register(self): # pragma: no cover
""" Register the agent in the XMPP server from a coroutine. """
metadata = aioxmpp.make_security_layer(None, no... |
def import_rsa_key(pem_data):
"""
Extract an RSA key from a PEM-encoded X.509 certificate
:param pem_data: RSA key encoded in standard form
:return: rsa.RSAPublicKey instance
"""
if not pem_data.startswith(PREFIX):
pem_data = bytes('{}\n{}\n{}'.format(PREFIX, pem_data, POSTFIX),
... | Extract an RSA key from a PEM-encoded X.509 certificate
:param pem_data: RSA key encoded in standard form
:return: rsa.RSAPublicKey instance | Below is the the instruction that describes the task:
### Input:
Extract an RSA key from a PEM-encoded X.509 certificate
:param pem_data: RSA key encoded in standard form
:return: rsa.RSAPublicKey instance
### Response:
def import_rsa_key(pem_data):
"""
Extract an RSA key from a PEM-encoded X.509 ... |
def find_connection(self):
'''find an antenna tracker connection if possible'''
if self.connection is not None:
return self.connection
for m in self.mpstate.mav_master:
if 'HEARTBEAT' in m.messages:
if m.messages['HEARTBEAT'].type == mavutil.mavlink.MAV_TY... | find an antenna tracker connection if possible | Below is the the instruction that describes the task:
### Input:
find an antenna tracker connection if possible
### Response:
def find_connection(self):
'''find an antenna tracker connection if possible'''
if self.connection is not None:
return self.connection
for m in self.mpst... |
def filter(self, data, collection, **kwargs):
"""Filter given collection."""
if not data or self.filters is None:
return None, collection
filters = {}
for f in self.filters:
if f.name not in data:
continue
ops, collection = f.filter(co... | Filter given collection. | Below is the the instruction that describes the task:
### Input:
Filter given collection.
### Response:
def filter(self, data, collection, **kwargs):
"""Filter given collection."""
if not data or self.filters is None:
return None, collection
filters = {}
for f in self.f... |
def clear_items_sequential(self):
"""Clears the items sequential flag.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.reso... | Clears the items sequential flag.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.* | Below is the the instruction that describes the task:
### Input:
Clears the items sequential flag.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
### Response:
def clear_items_sequent... |
def _compute_symbolic_link_mapping(
directory: str, extensions: Iterable[str]
) -> Dict[str, str]:
"""
Given a shared analysis directory, produce a mapping from actual source files
to files contained within this directory. Only includes files which have
one of the provided extensions.
... | Given a shared analysis directory, produce a mapping from actual source files
to files contained within this directory. Only includes files which have
one of the provided extensions.
Watchman watches actual source files, so when a change is detected to a
file, this mapping can be used t... | Below is the the instruction that describes the task:
### Input:
Given a shared analysis directory, produce a mapping from actual source files
to files contained within this directory. Only includes files which have
one of the provided extensions.
Watchman watches actual source files, so wh... |
def report_usage_to_host(host_ip, vmid):
#base value
cpu_usage = 0.0
os_mem_usage = 0.0
task_mem_usage = 0.0
io_usage = 0.0
cpu_usage = get_cpu_usage()
os_mem_usage = get_os_mem_usage()
task_mem_usage = get_task_mem_usage()
io_usage = get_io_usage()
usage = str(vmid.strip())+' | '+str(cpu_usage)+' | '+str... | cmd = '/bin/ssh -n -q -o StrictHostKeyChecking=no root@host_ip \"/bin/nohup /bin/python /var/lib/virtdc/vmonere/host/vmonere_listener.py '+usage+' &\"'
cmd = cmd.replace("host_ip",str(host_ip).strip()) | Below is the the instruction that describes the task:
### Input:
cmd = '/bin/ssh -n -q -o StrictHostKeyChecking=no root@host_ip \"/bin/nohup /bin/python /var/lib/virtdc/vmonere/host/vmonere_listener.py '+usage+' &\"'
cmd = cmd.replace("host_ip",str(host_ip).strip())
### Response:
def report_usage_to_host(host_ip,... |
def gen_front_term(self, x, dmp_num):
"""Generates the front term on the forcing term.
For rhythmic DMPs it's non-diminishing, so this
function is just a placeholder to return 1.
x float: the current value of the canonical system
dmp_num int: the index of the current dmp
... | Generates the front term on the forcing term.
For rhythmic DMPs it's non-diminishing, so this
function is just a placeholder to return 1.
x float: the current value of the canonical system
dmp_num int: the index of the current dmp | Below is the the instruction that describes the task:
### Input:
Generates the front term on the forcing term.
For rhythmic DMPs it's non-diminishing, so this
function is just a placeholder to return 1.
x float: the current value of the canonical system
dmp_num int: the index of th... |
def reindex_model_on_save(sender, document, **kwargs):
'''(Re/Un)Index Mongo document on post_save'''
if current_app.config.get('AUTO_INDEX'):
reindex.delay(document) | (Re/Un)Index Mongo document on post_save | Below is the the instruction that describes the task:
### Input:
(Re/Un)Index Mongo document on post_save
### Response:
def reindex_model_on_save(sender, document, **kwargs):
'''(Re/Un)Index Mongo document on post_save'''
if current_app.config.get('AUTO_INDEX'):
reindex.delay(document) |
def interleave(infile_1, infile_2, outfile, suffix1=None, suffix2=None):
'''Makes interleaved file from two sequence files. If used, will append suffix1 onto end
of every sequence name in infile_1, unless it already ends with suffix1. Similar for sufffix2.'''
seq_reader_1 = sequences.file_reader(infile_1)
... | Makes interleaved file from two sequence files. If used, will append suffix1 onto end
of every sequence name in infile_1, unless it already ends with suffix1. Similar for sufffix2. | Below is the the instruction that describes the task:
### Input:
Makes interleaved file from two sequence files. If used, will append suffix1 onto end
of every sequence name in infile_1, unless it already ends with suffix1. Similar for sufffix2.
### Response:
def interleave(infile_1, infile_2, outfile, suffix1... |
def _update_zone(self, zone, status=None):
"""
Updates a zones status.
:param zone: zone number
:type zone: int
:param status: zone status
:type status: int
:raises: IndexError
"""
if not zone in self._zones:
raise IndexError('Zone do... | Updates a zones status.
:param zone: zone number
:type zone: int
:param status: zone status
:type status: int
:raises: IndexError | Below is the the instruction that describes the task:
### Input:
Updates a zones status.
:param zone: zone number
:type zone: int
:param status: zone status
:type status: int
:raises: IndexError
### Response:
def _update_zone(self, zone, status=None):
"""
U... |
def fix_config(self, options):
"""
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict
"""
options = super(ROC... | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict
### Response:
def fi... |
def _get_png_size(version, scale, quiet_zone=4):
"""See: QRCode.get_png_size
This function was abstracted away from QRCode to allow for the output of
QR codes during the build process, i.e. for debugging. It works
just the same except you must specify the code's version. This is needed
to calculate... | See: QRCode.get_png_size
This function was abstracted away from QRCode to allow for the output of
QR codes during the build process, i.e. for debugging. It works
just the same except you must specify the code's version. This is needed
to calculate the PNG's size. | Below is the the instruction that describes the task:
### Input:
See: QRCode.get_png_size
This function was abstracted away from QRCode to allow for the output of
QR codes during the build process, i.e. for debugging. It works
just the same except you must specify the code's version. This is needed
... |
def BetaPrime(alpha, beta, tag=None):
"""
A BetaPrime random variate
Parameters
----------
alpha : scalar
The first shape parameter
beta : scalar
The second shape parameter
"""
assert (
alpha > 0 and beta > 0
), 'BetaPrime "alpha" and "beta" paramete... | A BetaPrime random variate
Parameters
----------
alpha : scalar
The first shape parameter
beta : scalar
The second shape parameter | Below is the the instruction that describes the task:
### Input:
A BetaPrime random variate
Parameters
----------
alpha : scalar
The first shape parameter
beta : scalar
The second shape parameter
### Response:
def BetaPrime(alpha, beta, tag=None):
"""
A BetaPrime random... |
def get_real_percent(self):
"""get_real_percent()
Returns the unmodified percentage of the score based on a 0-point scale."""
if not (self.votes and self.score):
return 0
return 100 * (self.get_real_rating() / self.field.range) | get_real_percent()
Returns the unmodified percentage of the score based on a 0-point scale. | Below is the the instruction that describes the task:
### Input:
get_real_percent()
Returns the unmodified percentage of the score based on a 0-point scale.
### Response:
def get_real_percent(self):
"""get_real_percent()
Returns the unmodified percentage of the score based... |
def remove_values(self, keys):
"""Remove values from data"""
data = self.model.get_data()
for key in sorted(keys, reverse=True):
data.pop(key)
self.set_data(data) | Remove values from data | Below is the the instruction that describes the task:
### Input:
Remove values from data
### Response:
def remove_values(self, keys):
"""Remove values from data"""
data = self.model.get_data()
for key in sorted(keys, reverse=True):
data.pop(key)
self.set_data(da... |
def edit_team_push_restrictions(self, *teams):
"""
:calls: `POST /repos/:owner/:repo/branches/:branch/protection/restrictions <https://developer.github.com/v3/repos/branches>`_
:teams: list of strings
"""
assert all(isinstance(element, (str, unicode)) or isinstance(element, (str,... | :calls: `POST /repos/:owner/:repo/branches/:branch/protection/restrictions <https://developer.github.com/v3/repos/branches>`_
:teams: list of strings | Below is the the instruction that describes the task:
### Input:
:calls: `POST /repos/:owner/:repo/branches/:branch/protection/restrictions <https://developer.github.com/v3/repos/branches>`_
:teams: list of strings
### Response:
def edit_team_push_restrictions(self, *teams):
"""
:calls: `PO... |
def get_params(self):
"""Manually pull params defined in config from OnShape and return a python representation of the params.
Quantities are converted to pint quantities, Bools are converted to python bools and Enums are converted
to strings. Note that Enum names are autogenerated by OnShape an... | Manually pull params defined in config from OnShape and return a python representation of the params.
Quantities are converted to pint quantities, Bools are converted to python bools and Enums are converted
to strings. Note that Enum names are autogenerated by OnShape and do not match the name on the On... | Below is the the instruction that describes the task:
### Input:
Manually pull params defined in config from OnShape and return a python representation of the params.
Quantities are converted to pint quantities, Bools are converted to python bools and Enums are converted
to strings. Note that Enum n... |
def set_camera(self, camera_id):
"""
Set the camera view to the specified camera ID.
"""
self.viewer.cam.fixedcamid = camera_id
self.viewer.cam.type = const.CAMERA_FIXED | Set the camera view to the specified camera ID. | Below is the the instruction that describes the task:
### Input:
Set the camera view to the specified camera ID.
### Response:
def set_camera(self, camera_id):
"""
Set the camera view to the specified camera ID.
"""
self.viewer.cam.fixedcamid = camera_id
self.viewer.cam.type... |
def get_feature(vector, feature):
"""Get a feature vector.
This returns a list of ints, equal in length to the vector input,
representing presence/absence/neutrality with respect to a particular
phonetic feature.
Parameters
----------
vector : list
A tuple or list of ints r... | Get a feature vector.
This returns a list of ints, equal in length to the vector input,
representing presence/absence/neutrality with respect to a particular
phonetic feature.
Parameters
----------
vector : list
A tuple or list of ints representing the phonetic features of a ph... | Below is the the instruction that describes the task:
### Input:
Get a feature vector.
This returns a list of ints, equal in length to the vector input,
representing presence/absence/neutrality with respect to a particular
phonetic feature.
Parameters
----------
vector : list
... |
def caltrack_usage_per_day_predict(
model_type,
model_params,
prediction_index,
temperature_data,
degree_day_method="daily",
with_disaggregated=False,
with_design_matrix=False,
):
""" CalTRACK predict method.
Given a model type, parameters, hourly temperatures, a
:any:`pandas.Da... | CalTRACK predict method.
Given a model type, parameters, hourly temperatures, a
:any:`pandas.DatetimeIndex` index over which to predict meter usage,
return model predictions as totals for the period (so billing period totals,
daily totals, etc.). Optionally include the computed design matrix or
dis... | Below is the the instruction that describes the task:
### Input:
CalTRACK predict method.
Given a model type, parameters, hourly temperatures, a
:any:`pandas.DatetimeIndex` index over which to predict meter usage,
return model predictions as totals for the period (so billing period totals,
daily to... |
def ResetConsoleColor() -> bool:
"""
Reset to the default text color on console window.
Return bool, True if succeed otherwise False.
"""
if sys.stdout:
sys.stdout.flush()
bool(ctypes.windll.kernel32.SetConsoleTextAttribute(_ConsoleOutputHandle, _DefaultConsoleColor)) | Reset to the default text color on console window.
Return bool, True if succeed otherwise False. | Below is the the instruction that describes the task:
### Input:
Reset to the default text color on console window.
Return bool, True if succeed otherwise False.
### Response:
def ResetConsoleColor() -> bool:
"""
Reset to the default text color on console window.
Return bool, True if succeed otherw... |
def resume(self):
"""Sends Play Directive to resume playback at the paused offset"""
directive = self._play_directive('REPLACE_ALL')
directive['audioItem'] = self._audio_item()
self._response['directives'].append(directive)
return self | Sends Play Directive to resume playback at the paused offset | Below is the the instruction that describes the task:
### Input:
Sends Play Directive to resume playback at the paused offset
### Response:
def resume(self):
"""Sends Play Directive to resume playback at the paused offset"""
directive = self._play_directive('REPLACE_ALL')
directive['audioIt... |
def find_ruuvitags(bt_device=''):
"""
Find all RuuviTags. Function will print the mac and the state of the sensors when found.
Function will execute as long as it is stopped. Stop ecexution with Crtl+C.
Returns:
dict: MAC and state of found sensors
"""
log.i... | Find all RuuviTags. Function will print the mac and the state of the sensors when found.
Function will execute as long as it is stopped. Stop ecexution with Crtl+C.
Returns:
dict: MAC and state of found sensors | Below is the the instruction that describes the task:
### Input:
Find all RuuviTags. Function will print the mac and the state of the sensors when found.
Function will execute as long as it is stopped. Stop ecexution with Crtl+C.
Returns:
dict: MAC and state of found sensors
### Respons... |
def optional_data_connections(self):
'''Finds all data connections in which one or more components are not
required.
If all the components involved in a connection are required, that
connection is also required. If one or more are not required, that
connection is optional.
... | Finds all data connections in which one or more components are not
required.
If all the components involved in a connection are required, that
connection is also required. If one or more are not required, that
connection is optional.
Example:
>>> s = RtsProfile(xml_spec... | Below is the the instruction that describes the task:
### Input:
Finds all data connections in which one or more components are not
required.
If all the components involved in a connection are required, that
connection is also required. If one or more are not required, that
connecti... |
def gather(self, *futures: Union[asyncio.Future, asyncio.coroutine]):
"""Gather list of futures/coros and return single Task ready to schedule.
:Example:
Prepare all futures to execution
.. code-block:: python
>>> async def do_something():
... return 'some... | Gather list of futures/coros and return single Task ready to schedule.
:Example:
Prepare all futures to execution
.. code-block:: python
>>> async def do_something():
... return 'something'
...
>>> async def do_something_else():
... | Below is the the instruction that describes the task:
### Input:
Gather list of futures/coros and return single Task ready to schedule.
:Example:
Prepare all futures to execution
.. code-block:: python
>>> async def do_something():
... return 'something'
... |
def redirect_stdout(self, enabled=True, log_level=logging.INFO):
"""
Redirect sys.stdout to file-like object.
"""
if enabled:
if self.__stdout_wrapper:
self.__stdout_wrapper.update_log_level(log_level=log_level)
else:
self.__stdout_... | Redirect sys.stdout to file-like object. | Below is the the instruction that describes the task:
### Input:
Redirect sys.stdout to file-like object.
### Response:
def redirect_stdout(self, enabled=True, log_level=logging.INFO):
"""
Redirect sys.stdout to file-like object.
"""
if enabled:
if self.__stdout_wrapper:... |
def import_upload(self, nvrea, ftype='rpm', rpm_name='', desc=None, htype='md5', lic=None, group=None, vendor=None, req=None):
"""
import the completed upload into pulp
`ftype` - the type of the upload
`rpm_name` - the name of the uploaded rpm
`desc` - description of the rpm
... | import the completed upload into pulp
`ftype` - the type of the upload
`rpm_name` - the name of the uploaded rpm
`desc` - description of the rpm
`htype` - checksum type
`lic` - license used in the packaged software
`group` - package group
`vendor` - software vendo... | Below is the the instruction that describes the task:
### Input:
import the completed upload into pulp
`ftype` - the type of the upload
`rpm_name` - the name of the uploaded rpm
`desc` - description of the rpm
`htype` - checksum type
`lic` - license used in the packaged softw... |
def nom_diam_pipe(self):
"""The nominal diameter of the LFOM pipe"""
ID = pc.diam_circle(self.area_pipe_min)
return pipe.ND_SDR_available(ID, self.sdr) | The nominal diameter of the LFOM pipe | Below is the the instruction that describes the task:
### Input:
The nominal diameter of the LFOM pipe
### Response:
def nom_diam_pipe(self):
"""The nominal diameter of the LFOM pipe"""
ID = pc.diam_circle(self.area_pipe_min)
return pipe.ND_SDR_available(ID, self.sdr) |
def academic_degree(self) -> str:
"""Get a random academic degree.
:return: Degree.
:Example:
Bachelor.
"""
degrees = self._data['academic_degree']
return self.random.choice(degrees) | Get a random academic degree.
:return: Degree.
:Example:
Bachelor. | Below is the the instruction that describes the task:
### Input:
Get a random academic degree.
:return: Degree.
:Example:
Bachelor.
### Response:
def academic_degree(self) -> str:
"""Get a random academic degree.
:return: Degree.
:Example:
Bachelo... |
def parse(self, data, lexer=None, *args, **kwargs):
"""Parse the input JSON data string into a python data structure.
Args:
data: An input data string
lexer: An optional ply.lex instance that overrides the default lexer.
Returns:
A python dict or list representing ... | Parse the input JSON data string into a python data structure.
Args:
data: An input data string
lexer: An optional ply.lex instance that overrides the default lexer.
Returns:
A python dict or list representing the input JSON data. | Below is the the instruction that describes the task:
### Input:
Parse the input JSON data string into a python data structure.
Args:
data: An input data string
lexer: An optional ply.lex instance that overrides the default lexer.
Returns:
A python dict or list represe... |
def _load_file(path):
"""
Loads a file from the local filesystem
"""
if not os.path.exists(path):
parser.error("{} was not found!".format(path))
if USING_PYTHON2:
mode = "r"
else:
mode = "rb"
try:
f = open(path, mode)
return f
except IOError as ex:... | Loads a file from the local filesystem | Below is the the instruction that describes the task:
### Input:
Loads a file from the local filesystem
### Response:
def _load_file(path):
"""
Loads a file from the local filesystem
"""
if not os.path.exists(path):
parser.error("{} was not found!".format(path))
if USING_PYTHON2:
... |
def date_range(start, end, length, time_unit='us'):
"""
Computes a date range given a start date, end date and the number
of samples.
"""
step = (1./compute_density(start, end, length, time_unit))
if pd and isinstance(start, pd.Timestamp):
start = start.to_datetime64()
step = np.time... | Computes a date range given a start date, end date and the number
of samples. | Below is the the instruction that describes the task:
### Input:
Computes a date range given a start date, end date and the number
of samples.
### Response:
def date_range(start, end, length, time_unit='us'):
"""
Computes a date range given a start date, end date and the number
of samples.
"""
... |
def cee_map_remap_lossless_priority_lossless_remapped_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
cee_map = ET.SubElement(config, "cee-map", xmlns="urn:brocade.com:mgmt:brocade-cee-map")
name_key = ET.SubElement(cee_map, "name")
name... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def cee_map_remap_lossless_priority_lossless_remapped_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
cee_map = ET.SubElement(config, "cee-map", xmln... |
def json(self, align_threshold: float = 0.0) -> Dict:
"""
Returns a dictionary suitable for json.dumps() representing all
the information in the class. It is initialized with any keys
present in the corresponding `TranslatorInput` object's pass_through_dict.
Keys from here that a... | Returns a dictionary suitable for json.dumps() representing all
the information in the class. It is initialized with any keys
present in the corresponding `TranslatorInput` object's pass_through_dict.
Keys from here that are not overwritten by Sockeye will thus be passed
through to the o... | Below is the the instruction that describes the task:
### Input:
Returns a dictionary suitable for json.dumps() representing all
the information in the class. It is initialized with any keys
present in the corresponding `TranslatorInput` object's pass_through_dict.
Keys from here that are no... |
def _check_ubridge_version(self, env=None):
"""
Checks if the ubridge executable version
"""
try:
output = yield from subprocess_check_output(self._path, "-v", cwd=self._working_dir, env=env)
match = re.search("ubridge version ([0-9a-z\.]+)", output)
i... | Checks if the ubridge executable version | Below is the the instruction that describes the task:
### Input:
Checks if the ubridge executable version
### Response:
def _check_ubridge_version(self, env=None):
"""
Checks if the ubridge executable version
"""
try:
output = yield from subprocess_check_output(self._pat... |
def and_(*fs):
"""Creates a function that returns true for given arguments
iff every given function evalutes to true for those arguments.
:param fs: Functions to combine
:return: Short-circuiting function performing logical conjunction
on results of ``fs`` applied to its arguments
"""... | Creates a function that returns true for given arguments
iff every given function evalutes to true for those arguments.
:param fs: Functions to combine
:return: Short-circuiting function performing logical conjunction
on results of ``fs`` applied to its arguments | Below is the the instruction that describes the task:
### Input:
Creates a function that returns true for given arguments
iff every given function evalutes to true for those arguments.
:param fs: Functions to combine
:return: Short-circuiting function performing logical conjunction
on res... |
def ports(self):
'''The list of all ports belonging to this component.'''
with self._mutex:
if not self._ports:
self._ports = [ports.parse_port(port, self) \
for port in self._obj.get_ports()]
return self._ports | The list of all ports belonging to this component. | Below is the the instruction that describes the task:
### Input:
The list of all ports belonging to this component.
### Response:
def ports(self):
'''The list of all ports belonging to this component.'''
with self._mutex:
if not self._ports:
self._ports = [ports.parse_po... |
def _serialize_model_helper(self, model, field_dict=None):
"""
A recursive function for serializing a model
into a json ready format.
"""
field_dict = field_dict or self.dot_field_list_to_dict()
if model is None:
return None
if isinstance(model, Query... | A recursive function for serializing a model
into a json ready format. | Below is the the instruction that describes the task:
### Input:
A recursive function for serializing a model
into a json ready format.
### Response:
def _serialize_model_helper(self, model, field_dict=None):
"""
A recursive function for serializing a model
into a json ready format.... |
def _kl_bernoulli_bernoulli(a, b, name=None):
"""Calculate the batched KL divergence KL(a || b) with a and b Bernoulli.
Args:
a: instance of a Bernoulli distribution object.
b: instance of a Bernoulli distribution object.
name: (optional) Name to use for created operations.
default is "kl_bernoul... | Calculate the batched KL divergence KL(a || b) with a and b Bernoulli.
Args:
a: instance of a Bernoulli distribution object.
b: instance of a Bernoulli distribution object.
name: (optional) Name to use for created operations.
default is "kl_bernoulli_bernoulli".
Returns:
Batchwise KL(a || b) | Below is the the instruction that describes the task:
### Input:
Calculate the batched KL divergence KL(a || b) with a and b Bernoulli.
Args:
a: instance of a Bernoulli distribution object.
b: instance of a Bernoulli distribution object.
name: (optional) Name to use for created operations.
defa... |
def write_csv(filename, data, delimiter=CSV_DELIMITER):
""" Write image data to CSV file
:param filename: name of CSV file to write data to
:type filename: str
:param data: image data to write to CSV file
:type data: numpy array
:param delimiter: delimiter used in CSV file. Default is ``;``
... | Write image data to CSV file
:param filename: name of CSV file to write data to
:type filename: str
:param data: image data to write to CSV file
:type data: numpy array
:param delimiter: delimiter used in CSV file. Default is ``;``
:type delimiter: str | Below is the the instruction that describes the task:
### Input:
Write image data to CSV file
:param filename: name of CSV file to write data to
:type filename: str
:param data: image data to write to CSV file
:type data: numpy array
:param delimiter: delimiter used in CSV file. Default is ``;`... |
def colorize(txt, fg=None, bg=None):
"""
Print escape codes to set the terminal color.
fg and bg are indices into the color palette for the foreground and
background colors.
"""
setting = ''
setting += _SET_FG.format(fg) if fg else ''
setting += _SET_BG.format(bg) if bg else ''
ret... | Print escape codes to set the terminal color.
fg and bg are indices into the color palette for the foreground and
background colors. | Below is the the instruction that describes the task:
### Input:
Print escape codes to set the terminal color.
fg and bg are indices into the color palette for the foreground and
background colors.
### Response:
def colorize(txt, fg=None, bg=None):
"""
Print escape codes to set the terminal color.... |
def sources_remove(source_uri, ruby=None, runas=None, gem_bin=None):
'''
Remove a gem source.
:param source_uri: string
The source URI to remove.
:param gem_bin: string : None
Full path to ``gem`` binary to use.
:param ruby: string : None
If RVM or rbenv are installed, the r... | Remove a gem source.
:param source_uri: string
The source URI to remove.
:param gem_bin: string : None
Full path to ``gem`` binary to use.
:param ruby: string : None
If RVM or rbenv are installed, the ruby version and gemset to use.
Ignored if ``gem_bin`` is specified.
:... | Below is the the instruction that describes the task:
### Input:
Remove a gem source.
:param source_uri: string
The source URI to remove.
:param gem_bin: string : None
Full path to ``gem`` binary to use.
:param ruby: string : None
If RVM or rbenv are installed, the ruby version ... |
def find_vlans(
self,
number,
name,
iexact,
environment,
net_type,
network,
ip_version,
subnet,
acl,
pagination):
"""
Find vlans by all search parameters
:param nu... | Find vlans by all search parameters
:param number: Filter by vlan number column
:param name: Filter by vlan name column
:param iexact: Filter by name will be exact?
:param environment: Filter by environment ID related
:param net_type: Filter by network_type ID related
:p... | Below is the the instruction that describes the task:
### Input:
Find vlans by all search parameters
:param number: Filter by vlan number column
:param name: Filter by vlan name column
:param iexact: Filter by name will be exact?
:param environment: Filter by environment ID related
... |
def get_pool(cls) -> Pool:
"""
Yields:
existing db connection pool
"""
if len(cls._connection_params) < 5:
raise ConnectionError('Please call SQLStore.connect before calling this method')
if not cls._pool:
cls._pool = yield from create_pool(**c... | Yields:
existing db connection pool | Below is the the instruction that describes the task:
### Input:
Yields:
existing db connection pool
### Response:
def get_pool(cls) -> Pool:
"""
Yields:
existing db connection pool
"""
if len(cls._connection_params) < 5:
raise ConnectionError('Pl... |
def add_child(self, child):
'''Add child to ``Node`` object
Args:
``child`` (``Node``): The child ``Node`` to be added
'''
if not isinstance(child, Node):
raise TypeError("child must be a Node")
self.children.append(child); child.parent = self | Add child to ``Node`` object
Args:
``child`` (``Node``): The child ``Node`` to be added | Below is the the instruction that describes the task:
### Input:
Add child to ``Node`` object
Args:
``child`` (``Node``): The child ``Node`` to be added
### Response:
def add_child(self, child):
'''Add child to ``Node`` object
Args:
``child`` (``Node``): The child ... |
def list_alarms(self, limit=None, marker=None, return_next=False):
"""
Returns a list of all the alarms created on this entity.
"""
return self._alarm_manager.list(limit=limit, marker=marker,
return_next=return_next) | Returns a list of all the alarms created on this entity. | Below is the the instruction that describes the task:
### Input:
Returns a list of all the alarms created on this entity.
### Response:
def list_alarms(self, limit=None, marker=None, return_next=False):
"""
Returns a list of all the alarms created on this entity.
"""
return self._al... |
def summary(args):
"""
%prog summary old.new.chain old.fasta new.fasta
Provide stats of the chain file.
"""
from jcvi.formats.fasta import summary as fsummary
from jcvi.utils.cbook import percentage, human_size
p = OptionParser(summary.__doc__)
opts, args = p.parse_args(args)
if l... | %prog summary old.new.chain old.fasta new.fasta
Provide stats of the chain file. | Below is the the instruction that describes the task:
### Input:
%prog summary old.new.chain old.fasta new.fasta
Provide stats of the chain file.
### Response:
def summary(args):
"""
%prog summary old.new.chain old.fasta new.fasta
Provide stats of the chain file.
"""
from jcvi.formats.fas... |
def _generate_move(
cls, char, width=None, fill_char=None,
bounce=False, reverse=True, back_char=None):
""" Yields strings that simulate movement of a character from left
to right. For use with `BarSet.from_char`.
Arguments:
char : Charac... | Yields strings that simulate movement of a character from left
to right. For use with `BarSet.from_char`.
Arguments:
char : Character to move across the progress bar.
width : Width for the progress bar.
Default: cl... | Below is the the instruction that describes the task:
### Input:
Yields strings that simulate movement of a character from left
to right. For use with `BarSet.from_char`.
Arguments:
char : Character to move across the progress bar.
width : Wi... |
def is_npvalue(u, dtype):
'''
is_npvalue(u, dtype) yields True if u is a member of the given dtype according to numpy. The
dtype may be specified as a string (see numpy_type) or a type. Note that dtype may be None,
'any', or np.generic, but this will always return True if so.
Note that is_npval... | is_npvalue(u, dtype) yields True if u is a member of the given dtype according to numpy. The
dtype may be specified as a string (see numpy_type) or a type. Note that dtype may be None,
'any', or np.generic, but this will always return True if so.
Note that is_npvalue(1, 'int') will yield True, while is... | Below is the the instruction that describes the task:
### Input:
is_npvalue(u, dtype) yields True if u is a member of the given dtype according to numpy. The
dtype may be specified as a string (see numpy_type) or a type. Note that dtype may be None,
'any', or np.generic, but this will always return True... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.