code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def getquerydict(self, sep='&', encoding='utf-8', errors='strict'):
"""Split the query component into individual `name=value` pairs
separated by `sep` and return a dictionary of query variables.
The dictionary keys are the unique query variable names and
the values are lists of values fo... | Split the query component into individual `name=value` pairs
separated by `sep` and return a dictionary of query variables.
The dictionary keys are the unique query variable names and
the values are lists of values for each name. | Below is the the instruction that describes the task:
### Input:
Split the query component into individual `name=value` pairs
separated by `sep` and return a dictionary of query variables.
The dictionary keys are the unique query variable names and
the values are lists of values for each nam... |
def move_file(originals, destination):
"""
Move file from original path to destination path.
:type originals: Array of str
:param originals: The original path
:type destination: str
:param destination: The destination path
"""
for original in originals:
if o... | Move file from original path to destination path.
:type originals: Array of str
:param originals: The original path
:type destination: str
:param destination: The destination path | Below is the the instruction that describes the task:
### Input:
Move file from original path to destination path.
:type originals: Array of str
:param originals: The original path
:type destination: str
:param destination: The destination path
### Response:
def move_file(original... |
def activationFunctionASIG(self, x):
"""
Determine the activation of a node based on that nodes net input.
"""
def act(v):
if v < -15.0: return 0.0
elif v > 15.0: return 1.0
else: return 1.0 / (1.0 + Numeric.exp(-v))
return Numeric.array(lis... | Determine the activation of a node based on that nodes net input. | Below is the the instruction that describes the task:
### Input:
Determine the activation of a node based on that nodes net input.
### Response:
def activationFunctionASIG(self, x):
"""
Determine the activation of a node based on that nodes net input.
"""
def act(v):
if ... |
def as_xml(self,parent):
"""Create vcard-tmp XML representation of the field.
:Parameters:
- `parent`: parent node for the element
:Types:
- `parent`: `libxml2.xmlNode`
:return: xml node with the field data.
:returntype: `libxml2.xmlNode`"""
if s... | Create vcard-tmp XML representation of the field.
:Parameters:
- `parent`: parent node for the element
:Types:
- `parent`: `libxml2.xmlNode`
:return: xml node with the field data.
:returntype: `libxml2.xmlNode` | Below is the the instruction that describes the task:
### Input:
Create vcard-tmp XML representation of the field.
:Parameters:
- `parent`: parent node for the element
:Types:
- `parent`: `libxml2.xmlNode`
:return: xml node with the field data.
:returntype: ... |
def refresh(self):
"""
Refresh this model from the server.
Updates attributes with the server-defined values. This is useful where the Model
instance came from a partial response (eg. a list query) and additional details
are required.
Existing attribute values will be o... | Refresh this model from the server.
Updates attributes with the server-defined values. This is useful where the Model
instance came from a partial response (eg. a list query) and additional details
are required.
Existing attribute values will be overwritten. | Below is the the instruction that describes the task:
### Input:
Refresh this model from the server.
Updates attributes with the server-defined values. This is useful where the Model
instance came from a partial response (eg. a list query) and additional details
are required.
Exist... |
def copy_all_a(input_a, *other_inputs, **kwargs):
"""Copy all readings in input a into the output.
All other inputs are skipped so that after this function runs there are no
readings left in any of the input walkers when the function finishes, even
if it generated no output readings.
Returns:
... | Copy all readings in input a into the output.
All other inputs are skipped so that after this function runs there are no
readings left in any of the input walkers when the function finishes, even
if it generated no output readings.
Returns:
list(IOTileReading) | Below is the the instruction that describes the task:
### Input:
Copy all readings in input a into the output.
All other inputs are skipped so that after this function runs there are no
readings left in any of the input walkers when the function finishes, even
if it generated no output readings.
R... |
def active_pixmap(self, value):
"""
Setter for **self.__active_pixmap** attribute.
:param value: Attribute value.
:type value: QPixmap
"""
if value is not None:
assert type(value) is QPixmap, "'{0}' attribute: '{1}' type is not 'QPixmap'!".format(
... | Setter for **self.__active_pixmap** attribute.
:param value: Attribute value.
:type value: QPixmap | Below is the the instruction that describes the task:
### Input:
Setter for **self.__active_pixmap** attribute.
:param value: Attribute value.
:type value: QPixmap
### Response:
def active_pixmap(self, value):
"""
Setter for **self.__active_pixmap** attribute.
:param value... |
async def updateTrigger(self, iden, query):
'''
Change an existing trigger's query
'''
trig = self.cell.triggers.get(iden)
self._trig_auth_check(trig.get('useriden'))
self.cell.triggers.mod(iden, query) | Change an existing trigger's query | Below is the the instruction that describes the task:
### Input:
Change an existing trigger's query
### Response:
async def updateTrigger(self, iden, query):
'''
Change an existing trigger's query
'''
trig = self.cell.triggers.get(iden)
self._trig_auth_check(trig.get('userid... |
def find_executable(self):
'''Find an executable node, which means nodes that has not been completed
and has no input dependency.'''
if 'DAG' in env.config['SOS_DEBUG'] or 'ALL' in env.config['SOS_DEBUG']:
env.log_to_file('DAG', 'find_executable')
for node in self.nodes():
... | Find an executable node, which means nodes that has not been completed
and has no input dependency. | Below is the the instruction that describes the task:
### Input:
Find an executable node, which means nodes that has not been completed
and has no input dependency.
### Response:
def find_executable(self):
'''Find an executable node, which means nodes that has not been completed
and has no ... |
def _build_index(self):
"""Itera todos los datasets, distribucioens y fields indexandolos."""
datasets_index = {}
distributions_index = {}
fields_index = {}
# recorre todos los datasets
for dataset_index, dataset in enumerate(self.datasets):
if "identifier" ... | Itera todos los datasets, distribucioens y fields indexandolos. | Below is the the instruction that describes the task:
### Input:
Itera todos los datasets, distribucioens y fields indexandolos.
### Response:
def _build_index(self):
"""Itera todos los datasets, distribucioens y fields indexandolos."""
datasets_index = {}
distributions_index = {}
... |
def export(self, swf, shape, **export_opts):
""" Exports the specified shape of the SWF to SVG.
@param swf The SWF.
@param shape Which shape to export, either by characterId(int) or as a Tag object.
"""
# If `shape` is given as int, find corresponding shape tag.
if is... | Exports the specified shape of the SWF to SVG.
@param swf The SWF.
@param shape Which shape to export, either by characterId(int) or as a Tag object. | Below is the the instruction that describes the task:
### Input:
Exports the specified shape of the SWF to SVG.
@param swf The SWF.
@param shape Which shape to export, either by characterId(int) or as a Tag object.
### Response:
def export(self, swf, shape, **export_opts):
""" Exports th... |
def get_ht_op(_, data):
"""http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n766.
Positional arguments:
data -- bytearray data to read.
Returns:
Dict.
"""
protection = ('no', 'nonmember', 20, 'non-HT mixed')
sta_chan_width = (20, 'any')
answers = {
... | http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n766.
Positional arguments:
data -- bytearray data to read.
Returns:
Dict. | Below is the the instruction that describes the task:
### Input:
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n766.
Positional arguments:
data -- bytearray data to read.
Returns:
Dict.
### Response:
def get_ht_op(_, data):
"""http://git.kernel.org/cgit/linux/k... |
def model_installed(name):
"""Check if spaCy language model is installed.
From https://github.com/explosion/spaCy/blob/master/spacy/util.py
:param name:
:return:
"""
data_path = util.get_data_path()
if not data_path or not data_path.exists():
raise I... | Check if spaCy language model is installed.
From https://github.com/explosion/spaCy/blob/master/spacy/util.py
:param name:
:return: | Below is the the instruction that describes the task:
### Input:
Check if spaCy language model is installed.
From https://github.com/explosion/spaCy/blob/master/spacy/util.py
:param name:
:return:
### Response:
def model_installed(name):
"""Check if spaCy language model is install... |
def idle_all_workers(self):
'''Set the global mode to :attr:`IDLE` and wait for workers to stop.
This can wait arbitrarily long before returning. The worst
case in "normal" usage involves waiting five minutes for a
"lost" job to expire; a well-behaved but very-long-running job
... | Set the global mode to :attr:`IDLE` and wait for workers to stop.
This can wait arbitrarily long before returning. The worst
case in "normal" usage involves waiting five minutes for a
"lost" job to expire; a well-behaved but very-long-running job
can extend its own lease further, and t... | Below is the the instruction that describes the task:
### Input:
Set the global mode to :attr:`IDLE` and wait for workers to stop.
This can wait arbitrarily long before returning. The worst
case in "normal" usage involves waiting five minutes for a
"lost" job to expire; a well-behaved but ... |
def get_client_kwargs(self):
"""Get kwargs for use with the methods in :mod:`nailgun.client`.
This method returns a dict of attributes that can be unpacked and used
as kwargs via the ``**`` operator. For example::
cfg = ServerConfig.get()
client.get(cfg.url + '/api/v2',... | Get kwargs for use with the methods in :mod:`nailgun.client`.
This method returns a dict of attributes that can be unpacked and used
as kwargs via the ``**`` operator. For example::
cfg = ServerConfig.get()
client.get(cfg.url + '/api/v2', **cfg.get_client_kwargs())
Thi... | Below is the the instruction that describes the task:
### Input:
Get kwargs for use with the methods in :mod:`nailgun.client`.
This method returns a dict of attributes that can be unpacked and used
as kwargs via the ``**`` operator. For example::
cfg = ServerConfig.get()
cl... |
def _tiles_from_bbox(bbox, zoom_level):
"""
* Returns all tiles for the specified bounding box
"""
if isinstance(bbox, dict):
point_min = Point.from_latitude_longitude(latitude=bbox['tl'], longitude=bbox['tr'])
point_max = Point.from_latitude_longitude(latitude=... | * Returns all tiles for the specified bounding box | Below is the the instruction that describes the task:
### Input:
* Returns all tiles for the specified bounding box
### Response:
def _tiles_from_bbox(bbox, zoom_level):
"""
* Returns all tiles for the specified bounding box
"""
if isinstance(bbox, dict):
point_min = P... |
def serialize(self, obj):
"""Serialize an object for sending to the front-end."""
if hasattr(obj, '_jsid'):
return {'immutable': False, 'value': obj._jsid}
else:
obj_json = {'immutable': True}
try:
json.dumps(obj)
obj_json['valu... | Serialize an object for sending to the front-end. | Below is the the instruction that describes the task:
### Input:
Serialize an object for sending to the front-end.
### Response:
def serialize(self, obj):
"""Serialize an object for sending to the front-end."""
if hasattr(obj, '_jsid'):
return {'immutable': False, 'value': obj._jsid}
... |
def delete_unique_identity(db, uuid):
"""Remove a unique identity from the registry.
Function that removes from the registry, the unique identity
that matches with uuid. Data related to this identity will be
also removed.
It checks first whether the unique identity is already on the registry.
... | Remove a unique identity from the registry.
Function that removes from the registry, the unique identity
that matches with uuid. Data related to this identity will be
also removed.
It checks first whether the unique identity is already on the registry.
When it is found, the unique identity is remo... | Below is the the instruction that describes the task:
### Input:
Remove a unique identity from the registry.
Function that removes from the registry, the unique identity
that matches with uuid. Data related to this identity will be
also removed.
It checks first whether the unique identity is alrea... |
def hasAttribute(self, attr: str) -> bool:
"""Return True if this node has ``attr``."""
if attr == 'class':
return bool(self.classList)
return attr in self.attributes | Return True if this node has ``attr``. | Below is the the instruction that describes the task:
### Input:
Return True if this node has ``attr``.
### Response:
def hasAttribute(self, attr: str) -> bool:
"""Return True if this node has ``attr``."""
if attr == 'class':
return bool(self.classList)
return attr in self.attri... |
def sha_hash(self) -> str:
"""
Return uppercase hex sha256 hash from signed raw document
:return:
"""
return hashlib.sha256(self.signed_raw().encode("ascii")).hexdigest().upper() | Return uppercase hex sha256 hash from signed raw document
:return: | Below is the the instruction that describes the task:
### Input:
Return uppercase hex sha256 hash from signed raw document
:return:
### Response:
def sha_hash(self) -> str:
"""
Return uppercase hex sha256 hash from signed raw document
:return:
"""
return hashlib.sh... |
def match_modules(allowed_modules):
"""Creates a matcher that matches a list/set/tuple of allowed modules."""
cleaned_allowed_modules = [
utils.mod_to_mod_name(tmp_mod)
for tmp_mod in allowed_modules
]
cleaned_split_allowed_modules = [
tmp_mod.split(".")
for tmp_mod in cl... | Creates a matcher that matches a list/set/tuple of allowed modules. | Below is the the instruction that describes the task:
### Input:
Creates a matcher that matches a list/set/tuple of allowed modules.
### Response:
def match_modules(allowed_modules):
"""Creates a matcher that matches a list/set/tuple of allowed modules."""
cleaned_allowed_modules = [
utils.mod_to_m... |
def state(self, container_id=None, sudo=None, sync_socket=None):
''' get the state of an OciImage, if it exists. The optional states that
can be returned are created, running, stopped or (not existing).
Equivalent command line example:
singularity oci state <container_ID>
... | get the state of an OciImage, if it exists. The optional states that
can be returned are created, running, stopped or (not existing).
Equivalent command line example:
singularity oci state <container_ID>
Parameters
==========
container_id: the id to g... | Below is the the instruction that describes the task:
### Input:
get the state of an OciImage, if it exists. The optional states that
can be returned are created, running, stopped or (not existing).
Equivalent command line example:
singularity oci state <container_ID>
... |
def check_entitlement(doi):
"""Check whether IP and credentials enable access to content for a doi.
This function uses the entitlement endpoint of the Elsevier API to check
whether an article is available to a given institution. Note that this
feature of the API is itself not available for all institut... | Check whether IP and credentials enable access to content for a doi.
This function uses the entitlement endpoint of the Elsevier API to check
whether an article is available to a given institution. Note that this
feature of the API is itself not available for all institution keys. | Below is the the instruction that describes the task:
### Input:
Check whether IP and credentials enable access to content for a doi.
This function uses the entitlement endpoint of the Elsevier API to check
whether an article is available to a given institution. Note that this
feature of the API is its... |
def allows_simple_recursion(self):
"""Check recursion level and extern status."""
rec_level = self.aggregate.config["recursionlevel"]
if rec_level >= 0 and self.recursion_level >= rec_level:
log.debug(LOG_CHECK, "... no, maximum recursion level reached.")
return False
... | Check recursion level and extern status. | Below is the the instruction that describes the task:
### Input:
Check recursion level and extern status.
### Response:
def allows_simple_recursion(self):
"""Check recursion level and extern status."""
rec_level = self.aggregate.config["recursionlevel"]
if rec_level >= 0 and self.recursion_... |
def post(self, path, query=None, data=None, redirects=True):
"""
POST request wrapper for :func:`request()`
"""
return self.request('POST', path, query, data, redirects) | POST request wrapper for :func:`request()` | Below is the the instruction that describes the task:
### Input:
POST request wrapper for :func:`request()`
### Response:
def post(self, path, query=None, data=None, redirects=True):
"""
POST request wrapper for :func:`request()`
"""
return self.request('POST', path, query, data, re... |
def as_list(data, use_pandas=True, header=True):
"""
Convert an H2O data object into a python-specific object.
WARNING! This will pull all data local!
If Pandas is available (and use_pandas is True), then pandas will be used to parse the
data frame. Otherwise, a list-of-lists populated by characte... | Convert an H2O data object into a python-specific object.
WARNING! This will pull all data local!
If Pandas is available (and use_pandas is True), then pandas will be used to parse the
data frame. Otherwise, a list-of-lists populated by character data will be returned (so
the types of data will all be... | Below is the the instruction that describes the task:
### Input:
Convert an H2O data object into a python-specific object.
WARNING! This will pull all data local!
If Pandas is available (and use_pandas is True), then pandas will be used to parse the
data frame. Otherwise, a list-of-lists populated by ... |
def from_ofxparse(data, institution):
"""Instantiate :py:class:`ofxclient.Account` subclass from ofxparse
module
:param data: an ofxparse account
:type data: An :py:class:`ofxparse.Account` object
:param institution: The parent institution of the account
:type institutio... | Instantiate :py:class:`ofxclient.Account` subclass from ofxparse
module
:param data: an ofxparse account
:type data: An :py:class:`ofxparse.Account` object
:param institution: The parent institution of the account
:type institution: :py:class:`ofxclient.Institution` object | Below is the the instruction that describes the task:
### Input:
Instantiate :py:class:`ofxclient.Account` subclass from ofxparse
module
:param data: an ofxparse account
:type data: An :py:class:`ofxparse.Account` object
:param institution: The parent institution of the account
... |
def get_json(self, uri_path, http_method='GET', query_parameters=None, body=None, headers=None):
"""
Fetches the JSON returned, after making the call and checking for errors.
:param uri_path: Endpoint to be used to make a request.
:param http_method: HTTP method to be used.
:para... | Fetches the JSON returned, after making the call and checking for errors.
:param uri_path: Endpoint to be used to make a request.
:param http_method: HTTP method to be used.
:param query_parameters: Parameters to be added to the request.
:param body: Optional body, if required.
:... | Below is the the instruction that describes the task:
### Input:
Fetches the JSON returned, after making the call and checking for errors.
:param uri_path: Endpoint to be used to make a request.
:param http_method: HTTP method to be used.
:param query_parameters: Parameters to be added to th... |
def _sumSeries(a: float, b: float, steps: int) -> float:
"""
Return value of the the following polynomial.
.. math::
(a * e^(b*steps) - 1) / (e^b - 1)
:param a: multiplier
:param b: exponent multiplier
:param steps: the number of steps
"""
retu... | Return value of the the following polynomial.
.. math::
(a * e^(b*steps) - 1) / (e^b - 1)
:param a: multiplier
:param b: exponent multiplier
:param steps: the number of steps | Below is the the instruction that describes the task:
### Input:
Return value of the the following polynomial.
.. math::
(a * e^(b*steps) - 1) / (e^b - 1)
:param a: multiplier
:param b: exponent multiplier
:param steps: the number of steps
### Response:
def _sumSeries(a:... |
def disable(name, no_block=False, root=None, **kwargs): # pylint: disable=unused-argument
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
contro... | .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is done to avoid a race condition in cases where
the ``salt-minion`` service is r... | Below is the the instruction that describes the task:
### Input:
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is done to avoid a r... |
def hex(self):
"""Return a hexadecimal representation of a BigFloat."""
sign = '-' if self._sign() else ''
e = self._exponent()
if isinstance(e, six.string_types):
return sign + e
m = self._significand()
_, digits, _ = _mpfr_get_str2(
16,
... | Return a hexadecimal representation of a BigFloat. | Below is the the instruction that describes the task:
### Input:
Return a hexadecimal representation of a BigFloat.
### Response:
def hex(self):
"""Return a hexadecimal representation of a BigFloat."""
sign = '-' if self._sign() else ''
e = self._exponent()
if isinstance(e, six.str... |
def estimate_skeleton(indep_test_func, data_matrix, alpha, **kwargs):
"""Estimate a skeleton graph from the statistis information.
Args:
indep_test_func: the function name for a conditional
independency test.
data_matrix: data (as a numpy array).
alpha: the significance leve... | Estimate a skeleton graph from the statistis information.
Args:
indep_test_func: the function name for a conditional
independency test.
data_matrix: data (as a numpy array).
alpha: the significance level.
kwargs:
'max_reach': maximum value of l (see the code)... | Below is the the instruction that describes the task:
### Input:
Estimate a skeleton graph from the statistis information.
Args:
indep_test_func: the function name for a conditional
independency test.
data_matrix: data (as a numpy array).
alpha: the significance level.
... |
def _netcdf2pandas(self, netcdf_data, query_variables, start, end):
"""
Transforms data from netcdf to pandas DataFrame.
Parameters
----------
data: netcdf
Data returned from UNIDATA NCSS query.
query_variables: list
The variables requested.
... | Transforms data from netcdf to pandas DataFrame.
Parameters
----------
data: netcdf
Data returned from UNIDATA NCSS query.
query_variables: list
The variables requested.
start: Timestamp
The start time
end: Timestamp
The en... | Below is the the instruction that describes the task:
### Input:
Transforms data from netcdf to pandas DataFrame.
Parameters
----------
data: netcdf
Data returned from UNIDATA NCSS query.
query_variables: list
The variables requested.
start: Timestamp... |
def binary(self):
"""
return encoded representation
"""
creation_size = len(self.creation)
if creation_size == 1:
return (
b_chr(_TAG_PID_EXT) +
self.node.binary() + self.id + self.serial + self.creation
)
elif creat... | return encoded representation | Below is the the instruction that describes the task:
### Input:
return encoded representation
### Response:
def binary(self):
"""
return encoded representation
"""
creation_size = len(self.creation)
if creation_size == 1:
return (
b_chr(_TAG_PID_... |
def get_pipe(self, object_type):
"""
Returns a generator that maps the input of the pipe to an elasticsearch object.
Will call id_to_object if it cannot serialize the data from json.
"""
for line in sys.stdin:
try:
data = json.loads(line.strip(... | Returns a generator that maps the input of the pipe to an elasticsearch object.
Will call id_to_object if it cannot serialize the data from json. | Below is the the instruction that describes the task:
### Input:
Returns a generator that maps the input of the pipe to an elasticsearch object.
Will call id_to_object if it cannot serialize the data from json.
### Response:
def get_pipe(self, object_type):
"""
Returns a generator t... |
def is_unicode_string(string):
"""
Return ``True`` if the given string is a Unicode string,
that is, of type ``unicode`` in Python 2 or ``str`` in Python 3.
Return ``None`` if ``string`` is ``None``.
:param str string: the string to be checked
:rtype: bool
"""
if string is None:
... | Return ``True`` if the given string is a Unicode string,
that is, of type ``unicode`` in Python 2 or ``str`` in Python 3.
Return ``None`` if ``string`` is ``None``.
:param str string: the string to be checked
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Return ``True`` if the given string is a Unicode string,
that is, of type ``unicode`` in Python 2 or ``str`` in Python 3.
Return ``None`` if ``string`` is ``None``.
:param str string: the string to be checked
:rtype: bool
### Respons... |
def stop(self):
"""
Stops the dependency manager (must be called before clear())
:return: The removed bindings (list) or None
"""
self._context.remove_service_listener(self)
if self.services:
return [
(service, reference)
for r... | Stops the dependency manager (must be called before clear())
:return: The removed bindings (list) or None | Below is the the instruction that describes the task:
### Input:
Stops the dependency manager (must be called before clear())
:return: The removed bindings (list) or None
### Response:
def stop(self):
"""
Stops the dependency manager (must be called before clear())
:return: The re... |
def get_medium_url(self):
"""Returns the medium size image URL."""
if self.is_gif():
return self.get_absolute_url()
return '%s%s-%s.jpg' % (settings.MEDIA_URL, self.get_name(), 'medium') | Returns the medium size image URL. | Below is the the instruction that describes the task:
### Input:
Returns the medium size image URL.
### Response:
def get_medium_url(self):
"""Returns the medium size image URL."""
if self.is_gif():
return self.get_absolute_url()
return '%s%s-%s.jpg' % (settings.MEDIA_URL, self.... |
def columns(self):
"""获取用户专栏.
:return: 用户专栏,返回生成器
:rtype: Column.Iterable
"""
from .column import Column
if self.url is None or self.post_num == 0:
return
soup = BeautifulSoup(self._session.get(self.url + 'posts').text)
column_list = soup.fin... | 获取用户专栏.
:return: 用户专栏,返回生成器
:rtype: Column.Iterable | Below is the the instruction that describes the task:
### Input:
获取用户专栏.
:return: 用户专栏,返回生成器
:rtype: Column.Iterable
### Response:
def columns(self):
"""获取用户专栏.
:return: 用户专栏,返回生成器
:rtype: Column.Iterable
"""
from .column import Column
if self.url ... |
def _format_repo_args(comment=None, component=None, distribution=None,
uploaders_file=None, saltenv='base'):
'''
Format the common arguments for creating or editing a repository.
:param str comment: The description of the repository.
:param str component: The default component to ... | Format the common arguments for creating or editing a repository.
:param str comment: The description of the repository.
:param str component: The default component to use when publishing.
:param str distribution: The default distribution to use when publishing.
:param str uploaders_file: The repositor... | Below is the the instruction that describes the task:
### Input:
Format the common arguments for creating or editing a repository.
:param str comment: The description of the repository.
:param str component: The default component to use when publishing.
:param str distribution: The default distribution... |
def prepare_timestamp_micros(data, schema):
"""Converts datetime.datetime to int timestamp with microseconds"""
if isinstance(data, datetime.datetime):
if data.tzinfo is not None:
delta = (data - epoch)
return int(delta.total_seconds() * MCS_PER_SECOND)
t = int(time.mktim... | Converts datetime.datetime to int timestamp with microseconds | Below is the the instruction that describes the task:
### Input:
Converts datetime.datetime to int timestamp with microseconds
### Response:
def prepare_timestamp_micros(data, schema):
"""Converts datetime.datetime to int timestamp with microseconds"""
if isinstance(data, datetime.datetime):
if dat... |
def load_nii(strPathIn, varSzeThr=5000.0):
"""
Load nii file.
Parameters
----------
strPathIn : str
Path to nii file to load.
varSzeThr : float
If the nii file is larger than this threshold (in MB), the file is
loaded volume-by-volume in order to prevent memory overflow.... | Load nii file.
Parameters
----------
strPathIn : str
Path to nii file to load.
varSzeThr : float
If the nii file is larger than this threshold (in MB), the file is
loaded volume-by-volume in order to prevent memory overflow. Default
threshold is 1000 MB.
Returns
... | Below is the the instruction that describes the task:
### Input:
Load nii file.
Parameters
----------
strPathIn : str
Path to nii file to load.
varSzeThr : float
If the nii file is larger than this threshold (in MB), the file is
loaded volume-by-volume in order to prevent me... |
def load(cls, data):
"""Construct a Constant class from it's dict data.
.. versionadded:: 0.0.2
"""
if len(data) == 1:
for key, value in data.items():
if "__classname__" not in value: # pragma: no cover
raise ValueError
na... | Construct a Constant class from it's dict data.
.. versionadded:: 0.0.2 | Below is the the instruction that describes the task:
### Input:
Construct a Constant class from it's dict data.
.. versionadded:: 0.0.2
### Response:
def load(cls, data):
"""Construct a Constant class from it's dict data.
.. versionadded:: 0.0.2
"""
if len(data) == 1:
... |
def chord_task(*args, **kwargs):
u"""
Override of the default task decorator to specify use of this backend.
"""
given_backend = kwargs.get(u'backend', None)
if not isinstance(given_backend, ChordableDjangoBackend):
kwargs[u'backend'] = ChordableDjangoBackend(kwargs.get('app', current_app))
... | u"""
Override of the default task decorator to specify use of this backend. | Below is the the instruction that describes the task:
### Input:
u"""
Override of the default task decorator to specify use of this backend.
### Response:
def chord_task(*args, **kwargs):
u"""
Override of the default task decorator to specify use of this backend.
"""
given_backend = kwargs.get(... |
def _initialize(self):
"""
Initialize model and layers.
"""
meta = getattr(self, ModelBase._meta_attr)
# read modelfile, convert JSON and load/update model
if self.param_file is not None:
self._load()
LOGGER.debug('model:\n%r', self.model)
# in... | Initialize model and layers. | Below is the the instruction that describes the task:
### Input:
Initialize model and layers.
### Response:
def _initialize(self):
"""
Initialize model and layers.
"""
meta = getattr(self, ModelBase._meta_attr)
# read modelfile, convert JSON and load/update model
if ... |
def nanopub_to_edges(nanopub: dict = {}, rules: List[str] = [], orthologize_targets: list = []):
"""Process nanopub into edges and load into EdgeStore
Args:
nanopub: BEL Nanopub
rules: list of compute rules to process
orthologize_targets: list of species in TAX:<int> format
Returns... | Process nanopub into edges and load into EdgeStore
Args:
nanopub: BEL Nanopub
rules: list of compute rules to process
orthologize_targets: list of species in TAX:<int> format
Returns:
list: of edges
Edge object:
{
"edge": {
"subject": {
... | Below is the the instruction that describes the task:
### Input:
Process nanopub into edges and load into EdgeStore
Args:
nanopub: BEL Nanopub
rules: list of compute rules to process
orthologize_targets: list of species in TAX:<int> format
Returns:
list: of edges
Edge ... |
def normal(nmr_distributions, nmr_samples, mean=0, std=1, ctype='float', seed=None):
"""Draw random samples from the Gaussian distribution.
Args:
nmr_distributions (int): the number of unique continuous_distributions to create
nmr_samples (int): The number of samples to draw
mean (float... | Draw random samples from the Gaussian distribution.
Args:
nmr_distributions (int): the number of unique continuous_distributions to create
nmr_samples (int): The number of samples to draw
mean (float or ndarray): The mean of the distribution
std (float or ndarray): The standard devi... | Below is the the instruction that describes the task:
### Input:
Draw random samples from the Gaussian distribution.
Args:
nmr_distributions (int): the number of unique continuous_distributions to create
nmr_samples (int): The number of samples to draw
mean (float or ndarray): The mean ... |
def qos(self, prefetch_size=0, prefetch_count=0, apply_global=False):
"""Request specific Quality of Service.
This method requests a specific quality of service. The QoS
can be specified for the current channel or for all channels
on the connection. The particular properties and seman... | Request specific Quality of Service.
This method requests a specific quality of service. The QoS
can be specified for the current channel or for all channels
on the connection. The particular properties and semantics of
a qos method always depend on the content class semantics.
... | Below is the the instruction that describes the task:
### Input:
Request specific Quality of Service.
This method requests a specific quality of service. The QoS
can be specified for the current channel or for all channels
on the connection. The particular properties and semantics of
... |
def active_service_location(doc):
"""View for getting active service by location"""
if doc.get('state') != 'deactivated':
for service_id, service in doc.get('services', {}).items():
if service.get('state') != 'deactivated':
service['id'] = service_id
service['... | View for getting active service by location | Below is the the instruction that describes the task:
### Input:
View for getting active service by location
### Response:
def active_service_location(doc):
"""View for getting active service by location"""
if doc.get('state') != 'deactivated':
for service_id, service in doc.get('services', {}).ite... |
def get_edges(data, superints, splits):
"""
Gets edge trimming based on the overlap of sequences at the edges of
alignments and the tuple arg passed in for edge_trimming. Trims as
(R1 left, R1 right, R2 left, R2 right). We also trim off the restriction
site if it present. This modifies superints, an... | Gets edge trimming based on the overlap of sequences at the edges of
alignments and the tuple arg passed in for edge_trimming. Trims as
(R1 left, R1 right, R2 left, R2 right). We also trim off the restriction
site if it present. This modifies superints, and so should be run on an
engine so it doesn't af... | Below is the the instruction that describes the task:
### Input:
Gets edge trimming based on the overlap of sequences at the edges of
alignments and the tuple arg passed in for edge_trimming. Trims as
(R1 left, R1 right, R2 left, R2 right). We also trim off the restriction
site if it present. This modif... |
def open_channel(self):
"""Open a new channel with RabbitMQ by issuing the Channel.Open RPC
command. When RabbitMQ responds that the channel is open, the
on_channel_open callback will be invoked by pika.
"""
_logger.info('Creating a new channel')
self._connection.channel(... | Open a new channel with RabbitMQ by issuing the Channel.Open RPC
command. When RabbitMQ responds that the channel is open, the
on_channel_open callback will be invoked by pika. | Below is the the instruction that describes the task:
### Input:
Open a new channel with RabbitMQ by issuing the Channel.Open RPC
command. When RabbitMQ responds that the channel is open, the
on_channel_open callback will be invoked by pika.
### Response:
def open_channel(self):
"""Open a n... |
def update_nb_metadata(nb_path=None, title=None, summary=None, keywords='fastai', overwrite=True, **kwargs):
"Creates jekyll metadata for given notebook path."
nb = read_nb(nb_path)
data = {'title': title, 'summary': summary, 'keywords': keywords, **kwargs}
data = {k:v for (k,v) in data.items() if v is ... | Creates jekyll metadata for given notebook path. | Below is the the instruction that describes the task:
### Input:
Creates jekyll metadata for given notebook path.
### Response:
def update_nb_metadata(nb_path=None, title=None, summary=None, keywords='fastai', overwrite=True, **kwargs):
"Creates jekyll metadata for given notebook path."
nb = read_nb(nb_pat... |
def course_discovery_search(search_term=None, size=20, from_=0, field_dictionary=None):
"""
Course Discovery activities against the search engine index of course details
"""
# We'll ignore the course-enrollemnt informaiton in field and filter
# dictionary, and use our own logic upon enrollment dates... | Course Discovery activities against the search engine index of course details | Below is the the instruction that describes the task:
### Input:
Course Discovery activities against the search engine index of course details
### Response:
def course_discovery_search(search_term=None, size=20, from_=0, field_dictionary=None):
"""
Course Discovery activities against the search engine inde... |
def add_chain(self, chain, parameters=None, name=None, weights=None, posterior=None, walkers=None,
grid=False, num_eff_data_points=None, num_free_params=None, color=None, linewidth=None,
linestyle=None, kde=None, shade=None, shade_alpha=None, power=None, marker_style=None, marker_siz... | Add a chain to the consumer.
Parameters
----------
chain : str|ndarray|dict
The chain to load. Normally a ``numpy.ndarray``. If a string is found, it
interprets the string as a filename and attempts to load it in. If a ``dict``
is passed in, it assumes the di... | Below is the the instruction that describes the task:
### Input:
Add a chain to the consumer.
Parameters
----------
chain : str|ndarray|dict
The chain to load. Normally a ``numpy.ndarray``. If a string is found, it
interprets the string as a filename and attempts to ... |
def detail(self, *args, **kwargs):
prefix = kwargs.pop("prefix", default_prefix)
# remove dublicates
kwargs["votes"] = list(set(kwargs["votes"]))
""" This is an example how to sort votes prior to using them in the
Object
"""
# # Sort votes
# kwargs["vo... | This is an example how to sort votes prior to using them in the
Object | Below is the the instruction that describes the task:
### Input:
This is an example how to sort votes prior to using them in the
Object
### Response:
def detail(self, *args, **kwargs):
prefix = kwargs.pop("prefix", default_prefix)
# remove dublicates
kwargs["votes"] = list(set(k... |
def policy_factory_from_module(config, module):
"""Create a policy factory that works by config.include()'ing a module.
This function does some trickery with the Pyramid config system. Loosely,
it does config.include(module), and then sucks out information about the
authn policy that was registered. I... | Create a policy factory that works by config.include()'ing a module.
This function does some trickery with the Pyramid config system. Loosely,
it does config.include(module), and then sucks out information about the
authn policy that was registered. It's complicated by pyramid's delayed-
commit system... | Below is the the instruction that describes the task:
### Input:
Create a policy factory that works by config.include()'ing a module.
This function does some trickery with the Pyramid config system. Loosely,
it does config.include(module), and then sucks out information about the
authn policy that was ... |
def crc7(data):
"""
Compute CRC of a whole message.
"""
crc = 0
for c in data:
crc = CRC7_TABLE[crc ^ c]
return crc | Compute CRC of a whole message. | Below is the the instruction that describes the task:
### Input:
Compute CRC of a whole message.
### Response:
def crc7(data):
"""
Compute CRC of a whole message.
"""
crc = 0
for c in data:
crc = CRC7_TABLE[crc ^ c]
return crc |
def set_coords(self, x=0, y=0, z=0, t=0):
"""
set coords of agent in an arbitrary world
"""
self.coords = {}
self.coords['x'] = x
self.coords['y'] = y
self.coords['z'] = z
self.coords['t'] = t | set coords of agent in an arbitrary world | Below is the the instruction that describes the task:
### Input:
set coords of agent in an arbitrary world
### Response:
def set_coords(self, x=0, y=0, z=0, t=0):
"""
set coords of agent in an arbitrary world
"""
self.coords = {}
self.coords['x'] = x
self.coords['y']... |
def interpolate(self, transform, transitions=None, Y=None):
"""Interpolate new data onto a transformation of the graph data
One of either transitions or Y should be provided
Parameters
----------
transform : array-like, shape=[n_samples, n_transform_features]
transiti... | Interpolate new data onto a transformation of the graph data
One of either transitions or Y should be provided
Parameters
----------
transform : array-like, shape=[n_samples, n_transform_features]
transitions : array-like, optional, shape=[n_samples_y, n_samples]
... | Below is the the instruction that describes the task:
### Input:
Interpolate new data onto a transformation of the graph data
One of either transitions or Y should be provided
Parameters
----------
transform : array-like, shape=[n_samples, n_transform_features]
transition... |
async def select_page(self, info: SQLQueryInfo, size=1, page=1) -> Tuple[Tuple[DataRecord, ...], int]:
"""
Select from database
:param info:
:param size: -1 means infinite
:param page:
:param need_count: if True, get count as second return value, otherwise -1
:ret... | Select from database
:param info:
:param size: -1 means infinite
:param page:
:param need_count: if True, get count as second return value, otherwise -1
:return: records. count | Below is the the instruction that describes the task:
### Input:
Select from database
:param info:
:param size: -1 means infinite
:param page:
:param need_count: if True, get count as second return value, otherwise -1
:return: records. count
### Response:
async def select_pa... |
def touched_files(self, parent):
"""
:API: public
"""
try:
return self._scm.changed_files(from_commit=parent,
include_untracked=True,
relative_to=get_buildroot())
except Scm.ScmException as e:
raise self.WorkspaceE... | :API: public | Below is the the instruction that describes the task:
### Input:
:API: public
### Response:
def touched_files(self, parent):
"""
:API: public
"""
try:
return self._scm.changed_files(from_commit=parent,
include_untracked=True,
... |
def get_args(self, state, is_fp=None, sizes=None, stack_base=None):
"""
`is_fp` should be a list of booleans specifying whether each corresponding argument is floating-point -
True for fp and False for int. For a shorthand to assume that all the parameters are int, pass the number of
par... | `is_fp` should be a list of booleans specifying whether each corresponding argument is floating-point -
True for fp and False for int. For a shorthand to assume that all the parameters are int, pass the number of
parameters as an int.
If you've customized this CC, you may omit this parameter en... | Below is the the instruction that describes the task:
### Input:
`is_fp` should be a list of booleans specifying whether each corresponding argument is floating-point -
True for fp and False for int. For a shorthand to assume that all the parameters are int, pass the number of
parameters as an int.
... |
def display_name(name, obj, local):
"""
Get the display name of an object.
Keyword arguments (all required):
* ``name`` -- the name of the object as a string.
* ``obj`` -- the object itself.
* ``local`` -- a boolean value indicating whether the object is in local
scope or owned by an obj... | Get the display name of an object.
Keyword arguments (all required):
* ``name`` -- the name of the object as a string.
* ``obj`` -- the object itself.
* ``local`` -- a boolean value indicating whether the object is in local
scope or owned by an object. | Below is the the instruction that describes the task:
### Input:
Get the display name of an object.
Keyword arguments (all required):
* ``name`` -- the name of the object as a string.
* ``obj`` -- the object itself.
* ``local`` -- a boolean value indicating whether the object is in local
sco... |
def mol_supplier(lines, no_halt, assign_descriptors):
"""Yields molecules generated from CTAB text
Args:
lines (iterable): CTAB text lines
no_halt (boolean):
True: shows warning messages for invalid format and go on.
False: throws an exception for it and stop parsing.
... | Yields molecules generated from CTAB text
Args:
lines (iterable): CTAB text lines
no_halt (boolean):
True: shows warning messages for invalid format and go on.
False: throws an exception for it and stop parsing.
assign_descriptors (boolean):
if True, defa... | Below is the the instruction that describes the task:
### Input:
Yields molecules generated from CTAB text
Args:
lines (iterable): CTAB text lines
no_halt (boolean):
True: shows warning messages for invalid format and go on.
False: throws an exception for it and stop par... |
def V_horiz_ellipsoidal(D, L, a, h, headonly=False):
r'''Calculates volume of a tank with ellipsoidal ends, according to [1]_.
.. math::
V_f = A_fL + \pi a h^2\left(1 - \frac{h}{3R}\right)
.. math::
Af = R^2\cos^{-1}\frac{R-h}{R} - (R-h)\sqrt{2Rh - h^2}
Parameters
----------
D... | r'''Calculates volume of a tank with ellipsoidal ends, according to [1]_.
.. math::
V_f = A_fL + \pi a h^2\left(1 - \frac{h}{3R}\right)
.. math::
Af = R^2\cos^{-1}\frac{R-h}{R} - (R-h)\sqrt{2Rh - h^2}
Parameters
----------
D : float
Diameter of the main cylindrical section... | Below is the the instruction that describes the task:
### Input:
r'''Calculates volume of a tank with ellipsoidal ends, according to [1]_.
.. math::
V_f = A_fL + \pi a h^2\left(1 - \frac{h}{3R}\right)
.. math::
Af = R^2\cos^{-1}\frac{R-h}{R} - (R-h)\sqrt{2Rh - h^2}
Parameters
----... |
def categorical_df_concat(df_list, inplace=False):
"""
Prepare list of pandas DataFrames to be used as input to pd.concat.
Ensure any columns of type 'category' have the same categories across each
dataframe.
Parameters
----------
df_list : list
List of dataframes with same columns.... | Prepare list of pandas DataFrames to be used as input to pd.concat.
Ensure any columns of type 'category' have the same categories across each
dataframe.
Parameters
----------
df_list : list
List of dataframes with same columns.
inplace : bool
True if input list can be modified.... | Below is the the instruction that describes the task:
### Input:
Prepare list of pandas DataFrames to be used as input to pd.concat.
Ensure any columns of type 'category' have the same categories across each
dataframe.
Parameters
----------
df_list : list
List of dataframes with same co... |
def update(self, changed_state_model=None, with_expand=False):
"""Checks if all states are in tree and if tree has states which were deleted
:param changed_state_model: Model that row has to be updated
:param with_expand: The expand flag for the tree
"""
if not self.view_is_regi... | Checks if all states are in tree and if tree has states which were deleted
:param changed_state_model: Model that row has to be updated
:param with_expand: The expand flag for the tree | Below is the the instruction that describes the task:
### Input:
Checks if all states are in tree and if tree has states which were deleted
:param changed_state_model: Model that row has to be updated
:param with_expand: The expand flag for the tree
### Response:
def update(self, changed_state_mod... |
def _refresh_hierarchy_recursive(self, cached_hierarchy, file_hierarchy):
"""Recursively goes through given corresponding hierarchies from cache and filesystem
and adds/refreshes/removes added/changed/removed assistants.
Args:
cached_hierarchy: the respective hierarchy part from cur... | Recursively goes through given corresponding hierarchies from cache and filesystem
and adds/refreshes/removes added/changed/removed assistants.
Args:
cached_hierarchy: the respective hierarchy part from current cache
(for format see Cache class docstring)
... | Below is the the instruction that describes the task:
### Input:
Recursively goes through given corresponding hierarchies from cache and filesystem
and adds/refreshes/removes added/changed/removed assistants.
Args:
cached_hierarchy: the respective hierarchy part from current cache
... |
def _get_adv_trans_stats(self, cmd, return_tdo=False):
"""Utility function to fetch the transfer statistics for the last
advanced transfer. Checking the stats appears to sync the
controller. For details on the advanced transfer please refer
to the documentation at
http://diamondm... | Utility function to fetch the transfer statistics for the last
advanced transfer. Checking the stats appears to sync the
controller. For details on the advanced transfer please refer
to the documentation at
http://diamondman.github.io/Adapt/cable_digilent_adept.html#bulk-requests | Below is the the instruction that describes the task:
### Input:
Utility function to fetch the transfer statistics for the last
advanced transfer. Checking the stats appears to sync the
controller. For details on the advanced transfer please refer
to the documentation at
http://diamo... |
def pending_settings(self):
"""Property to provide reference to bios_pending_settings instance
It is calculated once when the first time it is queried. On refresh,
this property gets reset.
"""
return BIOSPendingSettings(
self._conn, utils.get_subresource_path_by(
... | Property to provide reference to bios_pending_settings instance
It is calculated once when the first time it is queried. On refresh,
this property gets reset. | Below is the the instruction that describes the task:
### Input:
Property to provide reference to bios_pending_settings instance
It is calculated once when the first time it is queried. On refresh,
this property gets reset.
### Response:
def pending_settings(self):
"""Property to provide r... |
def clear(self):
"Remove all items and reset internal structures"
dict.clear(self)
self._key = 0
if hasattr(self._list_view, "wx_obj"):
self._list_view.wx_obj.DeleteAllItems() | Remove all items and reset internal structures | Below is the the instruction that describes the task:
### Input:
Remove all items and reset internal structures
### Response:
def clear(self):
"Remove all items and reset internal structures"
dict.clear(self)
self._key = 0
if hasattr(self._list_view, "wx_obj"):
self... |
def GetMemBalloonMaxMB(self):
'''Undocumented.'''
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetMemBalloonMaxMB(self.handle.value, byref(counter))
if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)
return counter.value | Undocumented. | Below is the the instruction that describes the task:
### Input:
Undocumented.
### Response:
def GetMemBalloonMaxMB(self):
'''Undocumented.'''
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetMemBalloonMaxMB(self.handle.value, byref(counter))
if ret != VMGUESTLIB_ERROR_SUCCESS: rai... |
def unique(list1, list2):
"""
Get unique items in list1 that are not in list2
:return: Unique items only in list 1
"""
set2 = set(list2)
list1_unique = [x for x in tqdm(list1, desc='Unique', total=len(list1)) if x not in set2]
return list1_unique | Get unique items in list1 that are not in list2
:return: Unique items only in list 1 | Below is the the instruction that describes the task:
### Input:
Get unique items in list1 that are not in list2
:return: Unique items only in list 1
### Response:
def unique(list1, list2):
"""
Get unique items in list1 that are not in list2
:return: Unique items only in list 1
"""
set2 = s... |
def get_project_root():
""" Determine location of `tasks.py`."""
try:
tasks_py = sys.modules['tasks']
except KeyError:
return None
else:
return os.path.abspath(os.path.dirname(tasks_py.__file__)) | Determine location of `tasks.py`. | Below is the the instruction that describes the task:
### Input:
Determine location of `tasks.py`.
### Response:
def get_project_root():
""" Determine location of `tasks.py`."""
try:
tasks_py = sys.modules['tasks']
except KeyError:
return None
else:
return os.path.abspath(os... |
def getDevStats(self, dev, devtype = None):
"""Returns I/O stats for block device.
@param dev: Device name
@param devtype: Device type. (Ignored if None.)
@return: Dict of stats.
"""
if devtype is not None:
if self._devClassTree is... | Returns I/O stats for block device.
@param dev: Device name
@param devtype: Device type. (Ignored if None.)
@return: Dict of stats. | Below is the the instruction that describes the task:
### Input:
Returns I/O stats for block device.
@param dev: Device name
@param devtype: Device type. (Ignored if None.)
@return: Dict of stats.
### Response:
def getDevStats(self, dev, devtype = None):
"""Retur... |
def stop(self):
"""
Stop the sensor server (soft stop - signal packet loop to stop)
Warning: Is non blocking (server might still do something after this!)
:rtype: None
"""
self.debug("()")
super(SensorServer, self).stop()
# No new clients
if self.... | Stop the sensor server (soft stop - signal packet loop to stop)
Warning: Is non blocking (server might still do something after this!)
:rtype: None | Below is the the instruction that describes the task:
### Input:
Stop the sensor server (soft stop - signal packet loop to stop)
Warning: Is non blocking (server might still do something after this!)
:rtype: None
### Response:
def stop(self):
"""
Stop the sensor server (soft stop -... |
def requeue(self, message_id, timeout=0, backoff=True):
"""Re-queue a message (indicate failure to process)."""
self.send(nsq.requeue(message_id, timeout))
self.finish_inflight()
self.on_requeue.send(
self,
message_id=message_id,
timeout=timeout,
... | Re-queue a message (indicate failure to process). | Below is the the instruction that describes the task:
### Input:
Re-queue a message (indicate failure to process).
### Response:
def requeue(self, message_id, timeout=0, backoff=True):
"""Re-queue a message (indicate failure to process)."""
self.send(nsq.requeue(message_id, timeout))
self.f... |
def get_codec_info(cls):
"""
Returns information used by the codecs library to configure the
codec for use.
"""
codec = cls()
codec_info = {
'encode': codec.encode,
'decode': codec.decode,
}
# In Python 2, all codecs are made equa... | Returns information used by the codecs library to configure the
codec for use. | Below is the the instruction that describes the task:
### Input:
Returns information used by the codecs library to configure the
codec for use.
### Response:
def get_codec_info(cls):
"""
Returns information used by the codecs library to configure the
codec for use.
"""
... |
def _expand_placeholder_value(value):
"""
Return the SQL string representation of the specified placeholder's
value.
@param value: the value of a placeholder such as a simple element, a
list, or a tuple of one string.
@note: by convention, a tuple of one string in... | Return the SQL string representation of the specified placeholder's
value.
@param value: the value of a placeholder such as a simple element, a
list, or a tuple of one string.
@note: by convention, a tuple of one string indicates that this string
MUST not be quoted as... | Below is the the instruction that describes the task:
### Input:
Return the SQL string representation of the specified placeholder's
value.
@param value: the value of a placeholder such as a simple element, a
list, or a tuple of one string.
@note: by convention, a tuple of on... |
def subCell2DCoords(*args, **kwargs):
'''Same as subCell2DSlices but returning coordinates
Example:
g = subCell2DCoords(arr, shape)
for x, y in g:
plt.plot(x, y)
'''
for _, _, s0, s1 in subCell2DSlices(*args, **kwargs):
yield ((s1.start, s1.start, s1.sto... | Same as subCell2DSlices but returning coordinates
Example:
g = subCell2DCoords(arr, shape)
for x, y in g:
plt.plot(x, y) | Below is the the instruction that describes the task:
### Input:
Same as subCell2DSlices but returning coordinates
Example:
g = subCell2DCoords(arr, shape)
for x, y in g:
plt.plot(x, y)
### Response:
def subCell2DCoords(*args, **kwargs):
'''Same as subCell2DSlices but... |
def add_blacklisted_filepaths(self, filepaths, remove_from_stored=True):
"""
Add `filepaths` to blacklisted filepaths.
If `remove_from_stored` is `True`, any `filepaths` in
`plugin_filepaths` will be automatically removed.
Recommend passing in absolute filepaths but method will ... | Add `filepaths` to blacklisted filepaths.
If `remove_from_stored` is `True`, any `filepaths` in
`plugin_filepaths` will be automatically removed.
Recommend passing in absolute filepaths but method will attempt
to convert to absolute filepaths based on current working directory. | Below is the the instruction that describes the task:
### Input:
Add `filepaths` to blacklisted filepaths.
If `remove_from_stored` is `True`, any `filepaths` in
`plugin_filepaths` will be automatically removed.
Recommend passing in absolute filepaths but method will attempt
to conve... |
def _find_next_ready_node(self):
"""
Finds the next node that is ready to be built.
This is *the* main guts of the DAG walk. We loop through the
list of candidates, looking for something that has no un-built
children (i.e., that is a leaf Node or has dependencies that are
... | Finds the next node that is ready to be built.
This is *the* main guts of the DAG walk. We loop through the
list of candidates, looking for something that has no un-built
children (i.e., that is a leaf Node or has dependencies that are
all leaf Nodes or up-to-date). Candidate Nodes ar... | Below is the the instruction that describes the task:
### Input:
Finds the next node that is ready to be built.
This is *the* main guts of the DAG walk. We loop through the
list of candidates, looking for something that has no un-built
children (i.e., that is a leaf Node or has dependencie... |
def datetime(value,
allow_empty = False,
minimum = None,
maximum = None,
coerce_value = True,
**kwargs):
"""Validate that ``value`` is a valid datetime.
.. caution::
If supplying a string, the string needs to be in an ISO 8601-format to pa... | Validate that ``value`` is a valid datetime.
.. caution::
If supplying a string, the string needs to be in an ISO 8601-format to pass
validation. If it is not in an ISO 8601-format, validation will fail.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :class:`dat... | Below is the the instruction that describes the task:
### Input:
Validate that ``value`` is a valid datetime.
.. caution::
If supplying a string, the string needs to be in an ISO 8601-format to pass
validation. If it is not in an ISO 8601-format, validation will fail.
:param value: The value ... |
def get_random_subreddit(self, nsfw=False):
"""Return a random Subreddit object.
:param nsfw: When true, return a random NSFW Subreddit object. Calling
in this manner will set the 'over18' cookie for the duration of the
PRAW session.
"""
path = 'random'
... | Return a random Subreddit object.
:param nsfw: When true, return a random NSFW Subreddit object. Calling
in this manner will set the 'over18' cookie for the duration of the
PRAW session. | Below is the the instruction that describes the task:
### Input:
Return a random Subreddit object.
:param nsfw: When true, return a random NSFW Subreddit object. Calling
in this manner will set the 'over18' cookie for the duration of the
PRAW session.
### Response:
def get_random_s... |
def _ParseTokenType(self, file_object, file_offset):
"""Parses a token type.
Args:
file_object (dfvfs.FileIO): file-like object.
file_offset (int): offset of the token relative to the start of
the file-like object.
Returns:
int: token type
"""
token_type_map = self._Get... | Parses a token type.
Args:
file_object (dfvfs.FileIO): file-like object.
file_offset (int): offset of the token relative to the start of
the file-like object.
Returns:
int: token type | Below is the the instruction that describes the task:
### Input:
Parses a token type.
Args:
file_object (dfvfs.FileIO): file-like object.
file_offset (int): offset of the token relative to the start of
the file-like object.
Returns:
int: token type
### Response:
def _ParseToke... |
def create_for_wrong_result_type(parser: _BaseParserDeclarationForRegistries, desired_type: Type[T],
obj: PersistedObject, result: T, options: Dict[str, Dict[str, Any]]):
"""
Helper method provided because we actually can't put that in the constructor, it creates a b... | Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests
https://github.com/nose-devs/nose/issues/725
:param parser:
:param desired_type:
:param obj:
:param result:
:param options:
:return: | Below is the the instruction that describes the task:
### Input:
Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests
https://github.com/nose-devs/nose/issues/725
:param parser:
:param desired_type:
:param obj:
:param r... |
def segment(self, eps, min_time):
"""In-place segmentation of segments
Spatio-temporal segmentation of each segment
The number of segments may increse after this step
Returns:
This track
"""
new_segments = []
for segment in self.segments:
... | In-place segmentation of segments
Spatio-temporal segmentation of each segment
The number of segments may increse after this step
Returns:
This track | Below is the the instruction that describes the task:
### Input:
In-place segmentation of segments
Spatio-temporal segmentation of each segment
The number of segments may increse after this step
Returns:
This track
### Response:
def segment(self, eps, min_time):
"""In-... |
def datasets_create_new(self, dataset_new_request, **kwargs): # noqa: E501
"""Create a new dataset # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.datasets_create_new(dataset_new_re... | Create a new dataset # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.datasets_create_new(dataset_new_request, async_req=True)
>>> result = thread.get()
:param async_req bool... | Below is the the instruction that describes the task:
### Input:
Create a new dataset # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.datasets_create_new(dataset_new_request, async_req=T... |
def decompress_messages(self, partitions_offmsgs):
""" Decompress pre-defined compressed fields for each message. """
for pomsg in partitions_offmsgs:
if pomsg['message']:
pomsg['message'] = self.decompress_fun(pomsg['message'])
yield pomsg | Decompress pre-defined compressed fields for each message. | Below is the the instruction that describes the task:
### Input:
Decompress pre-defined compressed fields for each message.
### Response:
def decompress_messages(self, partitions_offmsgs):
""" Decompress pre-defined compressed fields for each message. """
for pomsg in partitions_offmsgs:
... |
def reverse(self):
"""
Reverses the items of this collection "in place" (only two values are
retrieved from Redis at a time).
"""
def reverse_trans(pipe):
if self.writeback:
self._sync_helper(pipe)
n = self.__len__(pipe)
for i ... | Reverses the items of this collection "in place" (only two values are
retrieved from Redis at a time). | Below is the the instruction that describes the task:
### Input:
Reverses the items of this collection "in place" (only two values are
retrieved from Redis at a time).
### Response:
def reverse(self):
"""
Reverses the items of this collection "in place" (only two values are
retrieve... |
def _build_processor(cls, session: AppSession):
'''Create the Processor
Returns:
Processor: An instance of :class:`.processor.BaseProcessor`.
'''
web_processor = cls._build_web_processor(session)
ftp_processor = cls._build_ftp_processor(session)
delegate_proc... | Create the Processor
Returns:
Processor: An instance of :class:`.processor.BaseProcessor`. | Below is the the instruction that describes the task:
### Input:
Create the Processor
Returns:
Processor: An instance of :class:`.processor.BaseProcessor`.
### Response:
def _build_processor(cls, session: AppSession):
'''Create the Processor
Returns:
Processor: An ... |
def create_seq(self, project):
"""Create and return a new sequence
:param project: the project for the sequence
:type deps: :class:`jukeboxcore.djadapter.models.Project`
:returns: The created sequence or None
:rtype: None | :class:`jukeboxcore.djadapter.models.Sequence`
... | Create and return a new sequence
:param project: the project for the sequence
:type deps: :class:`jukeboxcore.djadapter.models.Project`
:returns: The created sequence or None
:rtype: None | :class:`jukeboxcore.djadapter.models.Sequence`
:raises: None | Below is the the instruction that describes the task:
### Input:
Create and return a new sequence
:param project: the project for the sequence
:type deps: :class:`jukeboxcore.djadapter.models.Project`
:returns: The created sequence or None
:rtype: None | :class:`jukeboxcore.djadapte... |
def UnregisterFlowProcessingHandler(self, timeout=None):
"""Unregisters any registered flow processing handler."""
if self.flow_processing_request_handler_thread:
self.flow_processing_request_handler_stop = True
self.flow_processing_request_handler_thread.join(timeout)
if self.flow_processing_... | Unregisters any registered flow processing handler. | Below is the the instruction that describes the task:
### Input:
Unregisters any registered flow processing handler.
### Response:
def UnregisterFlowProcessingHandler(self, timeout=None):
"""Unregisters any registered flow processing handler."""
if self.flow_processing_request_handler_thread:
self.fl... |
def scatter(self, *args, **kwargs):
"""Add a scatter plot."""
cls = _make_class(ScatterVisual,
_default_marker=kwargs.pop('marker', None),
)
return self._add_item(cls, *args, **kwargs) | Add a scatter plot. | Below is the the instruction that describes the task:
### Input:
Add a scatter plot.
### Response:
def scatter(self, *args, **kwargs):
"""Add a scatter plot."""
cls = _make_class(ScatterVisual,
_default_marker=kwargs.pop('marker', None),
)
... |
def _root(path, root):
'''
Relocate an absolute path to a new root directory.
'''
if root:
return os.path.join(root, os.path.relpath(path, os.path.sep))
else:
return path | Relocate an absolute path to a new root directory. | Below is the the instruction that describes the task:
### Input:
Relocate an absolute path to a new root directory.
### Response:
def _root(path, root):
'''
Relocate an absolute path to a new root directory.
'''
if root:
return os.path.join(root, os.path.relpath(path, os.path.sep))
else... |
def get_subparser(self, name):
"""
Convenience method to get a certain subparser
Parameters
----------
name: str
The name of the subparser
Returns
-------
FuncArgParser
The subparsers corresponding to `name`
"""
if... | Convenience method to get a certain subparser
Parameters
----------
name: str
The name of the subparser
Returns
-------
FuncArgParser
The subparsers corresponding to `name` | Below is the the instruction that describes the task:
### Input:
Convenience method to get a certain subparser
Parameters
----------
name: str
The name of the subparser
Returns
-------
FuncArgParser
The subparsers corresponding to `name`
### ... |
def setup(console=False, port=None):
"""Setup integration
Register plug-ins and integrate into the host
Arguments:
console (bool): DEPRECATED
port (int, optional): DEPRECATED
"""
if self._has_been_setup:
teardown()
register_plugins()
register_host()
self._ha... | Setup integration
Register plug-ins and integrate into the host
Arguments:
console (bool): DEPRECATED
port (int, optional): DEPRECATED | Below is the the instruction that describes the task:
### Input:
Setup integration
Register plug-ins and integrate into the host
Arguments:
console (bool): DEPRECATED
port (int, optional): DEPRECATED
### Response:
def setup(console=False, port=None):
"""Setup integration
Register... |
def getWorkflowDir(workflowID, configWorkDir=None):
"""
Returns a path to the directory where worker directories and the cache will be located
for this workflow.
:param str workflowID: Unique identifier for the workflow
:param str configWorkDir: Value passed to the program using... | Returns a path to the directory where worker directories and the cache will be located
for this workflow.
:param str workflowID: Unique identifier for the workflow
:param str configWorkDir: Value passed to the program using the --workDir flag
:return: Path to the workflow directory
... | Below is the the instruction that describes the task:
### Input:
Returns a path to the directory where worker directories and the cache will be located
for this workflow.
:param str workflowID: Unique identifier for the workflow
:param str configWorkDir: Value passed to the program using th... |
def get_table_rate_rule_by_id(cls, table_rate_rule_id, **kwargs):
"""Find TableRateRule
Return single instance of TableRateRule by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_t... | Find TableRateRule
Return single instance of TableRateRule by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_table_rate_rule_by_id(table_rate_rule_id, async=True)
>>> result = thr... | Below is the the instruction that describes the task:
### Input:
Find TableRateRule
Return single instance of TableRateRule by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_table_rat... |
def get_media_detail_output_interface_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface ... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_media_detail_output_interface_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.