code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def output_flair_stats(self):
"""Display statistics (number of users) for each unique flair item."""
css_counter = Counter()
text_counter = Counter()
for flair in self.current_flair():
if flair['flair_css_class']:
css_counter[flair['flair_css_class']] += 1
... | Display statistics (number of users) for each unique flair item. | Below is the the instruction that describes the task:
### Input:
Display statistics (number of users) for each unique flair item.
### Response:
def output_flair_stats(self):
"""Display statistics (number of users) for each unique flair item."""
css_counter = Counter()
text_counter = Counter... |
def include_codemirror(self):
"""Include resources in pages"""
contents = []
# base
js = self._get_tag('codemirror.js', 'script')
css = self._get_tag('codemirror.css', 'stylesheet')
if js and css:
contents.append(js)
contents.append(css)
# ... | Include resources in pages | Below is the the instruction that describes the task:
### Input:
Include resources in pages
### Response:
def include_codemirror(self):
"""Include resources in pages"""
contents = []
# base
js = self._get_tag('codemirror.js', 'script')
css = self._get_tag('codemirror.css', '... |
def heartbeat_tick(self, rate=2):
"""Send heartbeat packets, if necessary, and fail if none have been
received recently. This should be called frequently, on the order of
once per second.
:keyword rate: Ignored
"""
if not self.heartbeat:
return
# tr... | Send heartbeat packets, if necessary, and fail if none have been
received recently. This should be called frequently, on the order of
once per second.
:keyword rate: Ignored | Below is the the instruction that describes the task:
### Input:
Send heartbeat packets, if necessary, and fail if none have been
received recently. This should be called frequently, on the order of
once per second.
:keyword rate: Ignored
### Response:
def heartbeat_tick(self, rate=2):
... |
def build_mv_grid_district(self, poly_id, subst_id, grid_district_geo_data,
station_geo_data):
"""Initiates single MV grid_district including station and grid
Parameters
----------
poly_id: int
ID of grid_district according to database table. Also use... | Initiates single MV grid_district including station and grid
Parameters
----------
poly_id: int
ID of grid_district according to database table. Also used as ID for created grid #TODO: check type
subst_id: int
ID of station according to database table #TODO: chec... | Below is the the instruction that describes the task:
### Input:
Initiates single MV grid_district including station and grid
Parameters
----------
poly_id: int
ID of grid_district according to database table. Also used as ID for created grid #TODO: check type
subst_id: ... |
def jtag_disable(self):
"""
Disables JTAG output on the controller. JTAG operations executed
immediately after this function will return useless data or fail.
Usage:
>>> from proteusisc import getAttachedControllers, bitarray
>>> c = getAttachedControllers()[0]
... | Disables JTAG output on the controller. JTAG operations executed
immediately after this function will return useless data or fail.
Usage:
>>> from proteusisc import getAttachedControllers, bitarray
>>> c = getAttachedControllers()[0]
>>> c.jtag_enable()
>... | Below is the the instruction that describes the task:
### Input:
Disables JTAG output on the controller. JTAG operations executed
immediately after this function will return useless data or fail.
Usage:
>>> from proteusisc import getAttachedControllers, bitarray
>>> c = getA... |
def readlines(self, hint=-1):
"""Read lines until EOF, and return them as a list.
If *hint* is specified, then stop reading lines as soon as the total
size of all lines exceeds *hint*.
"""
self._check_readable()
lines = []
chunks = []
bytes_read = 0
... | Read lines until EOF, and return them as a list.
If *hint* is specified, then stop reading lines as soon as the total
size of all lines exceeds *hint*. | Below is the the instruction that describes the task:
### Input:
Read lines until EOF, and return them as a list.
If *hint* is specified, then stop reading lines as soon as the total
size of all lines exceeds *hint*.
### Response:
def readlines(self, hint=-1):
"""Read lines until EOF, and ... |
def initialize(module_name=None):
"""
Build the giotto settings object. This function gets called
at the very begining of every request cycle.
"""
import giotto
from giotto.utils import random_string, switchout_keyvalue
from django.conf import settings
setattr(giotto, '_config', GiottoS... | Build the giotto settings object. This function gets called
at the very begining of every request cycle. | Below is the the instruction that describes the task:
### Input:
Build the giotto settings object. This function gets called
at the very begining of every request cycle.
### Response:
def initialize(module_name=None):
"""
Build the giotto settings object. This function gets called
at the very begin... |
def complete(self):
"""is the game over?"""
if None not in [v for v in self.squares]:
return True
if self.winner() is not None:
return True
return False | is the game over? | Below is the the instruction that describes the task:
### Input:
is the game over?
### Response:
def complete(self):
"""is the game over?"""
if None not in [v for v in self.squares]:
return True
if self.winner() is not None:
return True
return False |
def bend_rounded_Crane(Di, angle, rc=None, bend_diameters=None):
r'''Calculates the loss coefficient for any rounded bend in a pipe
according to the Crane TP 410M [1]_ method. This method effectively uses
an interpolation from tabulated values in [1]_ for friction factor
multipliers vs. curvature radius... | r'''Calculates the loss coefficient for any rounded bend in a pipe
according to the Crane TP 410M [1]_ method. This method effectively uses
an interpolation from tabulated values in [1]_ for friction factor
multipliers vs. curvature radius.
.. figure:: fittings/bend_rounded.png
:scale: 30 %
... | Below is the the instruction that describes the task:
### Input:
r'''Calculates the loss coefficient for any rounded bend in a pipe
according to the Crane TP 410M [1]_ method. This method effectively uses
an interpolation from tabulated values in [1]_ for friction factor
multipliers vs. curvature radius... |
def post(self):
'''
:ref:`Authenticate <rest_tornado-auth>` against Salt's eauth system
.. http:post:: /login
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:reqheader Content-Type: |req_ct|
:form eauth: the eauth backend c... | :ref:`Authenticate <rest_tornado-auth>` against Salt's eauth system
.. http:post:: /login
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:reqheader Content-Type: |req_ct|
:form eauth: the eauth backend configured for the user
:... | Below is the the instruction that describes the task:
### Input:
:ref:`Authenticate <rest_tornado-auth>` against Salt's eauth system
.. http:post:: /login
:reqheader X-Auth-Token: |req_token|
:reqheader Accept: |req_accept|
:reqheader Content-Type: |req_ct|
... |
def poll(self):
"""Poll from the buffer
It is a non-blocking operation, and when the buffer is empty, it raises Queue.Empty exception
"""
try:
# non-blocking
ret = self._buffer.get(block=False)
if self._producer_callback is not None:
self._producer_callback()
return ret
... | Poll from the buffer
It is a non-blocking operation, and when the buffer is empty, it raises Queue.Empty exception | Below is the the instruction that describes the task:
### Input:
Poll from the buffer
It is a non-blocking operation, and when the buffer is empty, it raises Queue.Empty exception
### Response:
def poll(self):
"""Poll from the buffer
It is a non-blocking operation, and when the buffer is empty, it ra... |
def call(self, method, *args, **params):
"""Calls a method on the server."""
transaction_id = params.get("transaction_id")
if not transaction_id:
self.transaction_id += 1
transaction_id = self.transaction_id
obj = params.get("obj")
args = [method, tran... | Calls a method on the server. | Below is the the instruction that describes the task:
### Input:
Calls a method on the server.
### Response:
def call(self, method, *args, **params):
"""Calls a method on the server."""
transaction_id = params.get("transaction_id")
if not transaction_id:
self.transaction_id +=... |
def simple_response_str(command, status, status_text, content=""):
""" Creates an OSP response XML string.
Arguments:
command (str): OSP Command to respond to.
status (int): Status of the response.
status_text (str): Status text of the response.
content (str): Text part of the r... | Creates an OSP response XML string.
Arguments:
command (str): OSP Command to respond to.
status (int): Status of the response.
status_text (str): Status text of the response.
content (str): Text part of the response XML element.
Return:
String of response in xml format. | Below is the the instruction that describes the task:
### Input:
Creates an OSP response XML string.
Arguments:
command (str): OSP Command to respond to.
status (int): Status of the response.
status_text (str): Status text of the response.
content (str): Text part of the respons... |
def data(self):
"""This is the data object serialized to the js layer"""
content = {
'form_data': self.form_data,
'token': self.token,
'viz_name': self.viz_type,
'filter_select_enabled': self.datasource.filter_select_enabled,
}
return conte... | This is the data object serialized to the js layer | Below is the the instruction that describes the task:
### Input:
This is the data object serialized to the js layer
### Response:
def data(self):
"""This is the data object serialized to the js layer"""
content = {
'form_data': self.form_data,
'token': self.token,
... |
def save(self):
"""
Save profile settings into user profile directory
"""
config = self.profiledir + '/config'
if not isdir(self.profiledir):
makedirs(self.profiledir)
cp = SafeConfigParser()
cp.add_section('ssh')
cp.set('ssh', 'private_key',... | Save profile settings into user profile directory | Below is the the instruction that describes the task:
### Input:
Save profile settings into user profile directory
### Response:
def save(self):
"""
Save profile settings into user profile directory
"""
config = self.profiledir + '/config'
if not isdir(self.profiledir):
... |
def _find_workflows(mcs, attrs):
"""Finds all occurrences of a workflow in the attributes definitions.
Returns:
dict(str => StateField): maps an attribute name to a StateField
describing the related Workflow.
"""
workflows = {}
for attribute, value in... | Finds all occurrences of a workflow in the attributes definitions.
Returns:
dict(str => StateField): maps an attribute name to a StateField
describing the related Workflow. | Below is the the instruction that describes the task:
### Input:
Finds all occurrences of a workflow in the attributes definitions.
Returns:
dict(str => StateField): maps an attribute name to a StateField
describing the related Workflow.
### Response:
def _find_workflows(mcs, a... |
def update(self, pbar, width):
'Updates the progress bar and its subcomponents'
left, marker, right = (format_updatable(i, pbar) for i in
(self.left, self.marker, self.right))
width -= len(left) + len(right)
# Marker must *always* have length of 1
... | Updates the progress bar and its subcomponents | Below is the the instruction that describes the task:
### Input:
Updates the progress bar and its subcomponents
### Response:
def update(self, pbar, width):
'Updates the progress bar and its subcomponents'
left, marker, right = (format_updatable(i, pbar) for i in
(se... |
def circos_radius(n_nodes, node_r):
"""
Automatically computes the origin-to-node centre radius of the Circos plot
using the triangle equality sine rule.
a / sin(A) = b / sin(B) = c / sin(C)
:param n_nodes: the number of nodes in the plot.
:type n_nodes: int
:param node_r: the radius of ea... | Automatically computes the origin-to-node centre radius of the Circos plot
using the triangle equality sine rule.
a / sin(A) = b / sin(B) = c / sin(C)
:param n_nodes: the number of nodes in the plot.
:type n_nodes: int
:param node_r: the radius of each node.
:type node_r: float
:returns: O... | Below is the the instruction that describes the task:
### Input:
Automatically computes the origin-to-node centre radius of the Circos plot
using the triangle equality sine rule.
a / sin(A) = b / sin(B) = c / sin(C)
:param n_nodes: the number of nodes in the plot.
:type n_nodes: int
:param nod... |
def external2internal(xe, bounds):
""" Convert a series of external variables to internal variables"""
xi = np.empty_like(xe)
for i, (v, bound) in enumerate(zip(xe, bounds)):
a = bound[0] # minimum
b = bound[1] # maximum
if a == None and b == None: # No constraints
... | Convert a series of external variables to internal variables | Below is the the instruction that describes the task:
### Input:
Convert a series of external variables to internal variables
### Response:
def external2internal(xe, bounds):
""" Convert a series of external variables to internal variables"""
xi = np.empty_like(xe)
for i, (v, bound) in enumerate(zip(... |
def _reverse_indexer(self):
"""
Compute the inverse of a categorical, returning
a dict of categories -> indexers.
*This is an internal function*
Returns
-------
dict of categories -> indexers
Example
-------
In [1]: c = pd.Categorical(li... | Compute the inverse of a categorical, returning
a dict of categories -> indexers.
*This is an internal function*
Returns
-------
dict of categories -> indexers
Example
-------
In [1]: c = pd.Categorical(list('aabca'))
In [2]: c
Out[2]:
... | Below is the the instruction that describes the task:
### Input:
Compute the inverse of a categorical, returning
a dict of categories -> indexers.
*This is an internal function*
Returns
-------
dict of categories -> indexers
Example
-------
In [1]: ... |
def _mutual_info_score(reference_indices, estimated_indices, contingency=None):
"""Compute the mutual information between two sequence labelings.
Parameters
----------
reference_indices : np.ndarray
Array of reference indices
estimated_indices : np.ndarray
Array of estimated indices... | Compute the mutual information between two sequence labelings.
Parameters
----------
reference_indices : np.ndarray
Array of reference indices
estimated_indices : np.ndarray
Array of estimated indices
contingency : np.ndarray
Pre-computed contingency matrix. If None, one wi... | Below is the the instruction that describes the task:
### Input:
Compute the mutual information between two sequence labelings.
Parameters
----------
reference_indices : np.ndarray
Array of reference indices
estimated_indices : np.ndarray
Array of estimated indices
contingency :... |
def merge_close(events, min_interval, merge_to_longer=False):
"""Merge events that are separated by a less than a minimum interval.
Parameters
----------
events : list of dict
events with 'start' and 'end' times, from one or several channels.
**Events must be sorted by their start time.... | Merge events that are separated by a less than a minimum interval.
Parameters
----------
events : list of dict
events with 'start' and 'end' times, from one or several channels.
**Events must be sorted by their start time.**
min_interval : float
minimum delay between consecutive... | Below is the the instruction that describes the task:
### Input:
Merge events that are separated by a less than a minimum interval.
Parameters
----------
events : list of dict
events with 'start' and 'end' times, from one or several channels.
**Events must be sorted by their start time.... |
def evaluate(self, dataset, metric='auto', **kwargs):
"""
Evaluate the model by making predictions of target values and comparing
these to actual values.
Parameters
----------
dataset : SFrame
An SFrame having the same feature columns as provided when creatin... | Evaluate the model by making predictions of target values and comparing
these to actual values.
Parameters
----------
dataset : SFrame
An SFrame having the same feature columns as provided when creating
the model.
metric : str, optional
Name ... | Below is the the instruction that describes the task:
### Input:
Evaluate the model by making predictions of target values and comparing
these to actual values.
Parameters
----------
dataset : SFrame
An SFrame having the same feature columns as provided when creating
... |
def plot_weights(self, h, **kwargs):
""" Plot the weights from the aggregating algorithm
Parameters
----------
h : int
How many steps to run the aggregating algorithm on
Returns
----------
- A plot of the weights for each model constituent o... | Plot the weights from the aggregating algorithm
Parameters
----------
h : int
How many steps to run the aggregating algorithm on
Returns
----------
- A plot of the weights for each model constituent over time | Below is the the instruction that describes the task:
### Input:
Plot the weights from the aggregating algorithm
Parameters
----------
h : int
How many steps to run the aggregating algorithm on
Returns
----------
- A plot of the weights for each... |
def polynomial_norm(coeffs):
r"""Computes :math:`L_2` norm of polynomial on :math:`\left[0, 1\right]`.
We have
.. math::
\left\langle f, f \right\rangle = \sum_{i, j}
\int_0^1 c_i c_j x^{i + j} \, dx = \sum_{i, j}
\frac{c_i c_j}{i + j + 1} = \sum_{i} \frac{c_i^2}{2 i + 1}
... | r"""Computes :math:`L_2` norm of polynomial on :math:`\left[0, 1\right]`.
We have
.. math::
\left\langle f, f \right\rangle = \sum_{i, j}
\int_0^1 c_i c_j x^{i + j} \, dx = \sum_{i, j}
\frac{c_i c_j}{i + j + 1} = \sum_{i} \frac{c_i^2}{2 i + 1}
+ 2 \sum_{j > i} \frac{c_... | Below is the the instruction that describes the task:
### Input:
r"""Computes :math:`L_2` norm of polynomial on :math:`\left[0, 1\right]`.
We have
.. math::
\left\langle f, f \right\rangle = \sum_{i, j}
\int_0^1 c_i c_j x^{i + j} \, dx = \sum_{i, j}
\frac{c_i c_j}{i + j + 1} ... |
def _validate_output_data(
self, original_res, serialized_res, formatted_res, request):
""" Override to not validate doc output. """
if self._is_doc_request(request):
return
else:
return super(DocumentedResource, self)._validate_output_data(
origin... | Override to not validate doc output. | Below is the the instruction that describes the task:
### Input:
Override to not validate doc output.
### Response:
def _validate_output_data(
self, original_res, serialized_res, formatted_res, request):
""" Override to not validate doc output. """
if self._is_doc_request(request):
... |
def format(self, response_data):
"""
Make Flask `Response` object, with data returned as a generator for the CSV content
The CSV is built from JSON-like object (Python `dict` or list of `dicts`)
"""
if "items" in response_data:
list_response_data = response_data["ite... | Make Flask `Response` object, with data returned as a generator for the CSV content
The CSV is built from JSON-like object (Python `dict` or list of `dicts`) | Below is the the instruction that describes the task:
### Input:
Make Flask `Response` object, with data returned as a generator for the CSV content
The CSV is built from JSON-like object (Python `dict` or list of `dicts`)
### Response:
def format(self, response_data):
"""
Make Flask `Respo... |
def plot_points(points_arcsec, array, units, kpc_per_arcsec, pointsize, zoom_offset_arcsec):
"""Plot a set of points over the array of data on the figure.
Parameters
-----------
positions : [[]]
Lists of (y,x) coordinates on the image which are plotted as colored dots, to highlight specific pix... | Plot a set of points over the array of data on the figure.
Parameters
-----------
positions : [[]]
Lists of (y,x) coordinates on the image which are plotted as colored dots, to highlight specific pixels.
array : data.array.scaled_array.ScaledArray
The 2D array of data which is plotted.
... | Below is the the instruction that describes the task:
### Input:
Plot a set of points over the array of data on the figure.
Parameters
-----------
positions : [[]]
Lists of (y,x) coordinates on the image which are plotted as colored dots, to highlight specific pixels.
array : data.array.sca... |
def add(self, index, var):
"""Add a minibatch of images to the monitor.
Args:
index (int): Index.
var (:obj:`~nnabla.Variable`, :obj:`~nnabla.NdArray`, or :obj:`~numpy.ndarray`):
A minibatch of images with ``(N, ..., C, H, W)`` format.
If C == 2, ... | Add a minibatch of images to the monitor.
Args:
index (int): Index.
var (:obj:`~nnabla.Variable`, :obj:`~nnabla.NdArray`, or :obj:`~numpy.ndarray`):
A minibatch of images with ``(N, ..., C, H, W)`` format.
If C == 2, blue channel is appended with ones. If... | Below is the the instruction that describes the task:
### Input:
Add a minibatch of images to the monitor.
Args:
index (int): Index.
var (:obj:`~nnabla.Variable`, :obj:`~nnabla.NdArray`, or :obj:`~numpy.ndarray`):
A minibatch of images with ``(N, ..., C, H, W)`` form... |
def __get_button(self, account_id, button_type, **kwargs):
"""Call documentation: `/subscription_plan/get_button
<https://www.wepay.com/developer/reference/subscription_plan#get_button>`_,
plus extra keyword parameters:
:keyword str access_token: will be used instead of instance... | Call documentation: `/subscription_plan/get_button
<https://www.wepay.com/developer/reference/subscription_plan#get_button>`_,
plus extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_mode=True`` will set `aut... | Below is the the instruction that describes the task:
### Input:
Call documentation: `/subscription_plan/get_button
<https://www.wepay.com/developer/reference/subscription_plan#get_button>`_,
plus extra keyword parameters:
:keyword str access_token: will be used instead of instance'... |
def update_query_parameters(url, query_parameters):
"""
Return url with updated query parameters.
Arguments:
url (str): Original url whose query parameters need to be updated.
query_parameters (dict): A dictionary containing query parameters to be added to course selection url.
Returns... | Return url with updated query parameters.
Arguments:
url (str): Original url whose query parameters need to be updated.
query_parameters (dict): A dictionary containing query parameters to be added to course selection url.
Returns:
(slug): slug identifier for the identity provider that... | Below is the the instruction that describes the task:
### Input:
Return url with updated query parameters.
Arguments:
url (str): Original url whose query parameters need to be updated.
query_parameters (dict): A dictionary containing query parameters to be added to course selection url.
Re... |
def get_tasks(self):
"""
Return tasks as list of (name, function) tuples.
"""
def predicate(item):
return (inspect.isfunction(item) and
item.__name__ not in self._helper_names)
return inspect.getmembers(self._tasks, predicate) | Return tasks as list of (name, function) tuples. | Below is the the instruction that describes the task:
### Input:
Return tasks as list of (name, function) tuples.
### Response:
def get_tasks(self):
"""
Return tasks as list of (name, function) tuples.
"""
def predicate(item):
return (inspect.isfunction(item) and
... |
def _delay(self, ms):
"""Implement default delay mechanism.
"""
if ms:
self.Delay(ms)
else:
if self.default_delay:
self.Delay(self.default_delay) | Implement default delay mechanism. | Below is the the instruction that describes the task:
### Input:
Implement default delay mechanism.
### Response:
def _delay(self, ms):
"""Implement default delay mechanism.
"""
if ms:
self.Delay(ms)
else:
if self.default_delay:
self.Delay(sel... |
def plot(self,bins=10,facecolor='0.5',plot_cols=None,
filename="ensemble.pdf",func_dict = None,
**kwargs):
"""plot ensemble histograms to multipage pdf
Parameters
----------
bins : int
number of bins
facecolor : str
... | plot ensemble histograms to multipage pdf
Parameters
----------
bins : int
number of bins
facecolor : str
color
plot_cols : list of str
subset of ensemble columns to plot. If None, all are plotted.
Default is None
filename... | Below is the the instruction that describes the task:
### Input:
plot ensemble histograms to multipage pdf
Parameters
----------
bins : int
number of bins
facecolor : str
color
plot_cols : list of str
subset of ensemble columns to plot. I... |
def update_image_location(self, timeline_json):
"""Update the image location."""
if not timeline_json:
return False
# If we get a list of objects back (likely)
# then we just want the first one as it should be the "newest"
if isinstance(timeline_json, (tuple, list)):... | Update the image location. | Below is the the instruction that describes the task:
### Input:
Update the image location.
### Response:
def update_image_location(self, timeline_json):
"""Update the image location."""
if not timeline_json:
return False
# If we get a list of objects back (likely)
# th... |
def ggpht_s1600_extender(pipeline_index,
finder_image_urls,
extender_image_urls=[],
*args, **kwargs):
"""
Example:
http://lh4.ggpht.com/-fFi-qJRuxeY/UjwHSOTHGOI/AAAAAAAArgE/SWTMT-hXzB4/s640/Celeber-ru-Emma-Watson-Net-A-Porter-The-Edi... | Example:
http://lh4.ggpht.com/-fFi-qJRuxeY/UjwHSOTHGOI/AAAAAAAArgE/SWTMT-hXzB4/s640/Celeber-ru-Emma-Watson-Net-A-Porter-The-Edit-Magazine-Photoshoot-2013-01.jpg
to
http://lh4.ggpht.com/-fFi-qJRuxeY/UjwHSOTHGOI/AAAAAAAArgE/SWTMT-hXzB4/s1600/Celeber-ru-Emma-Watson-Net-A-Porter-The-Edit-Magazine-Photoshoot-201... | Below is the the instruction that describes the task:
### Input:
Example:
http://lh4.ggpht.com/-fFi-qJRuxeY/UjwHSOTHGOI/AAAAAAAArgE/SWTMT-hXzB4/s640/Celeber-ru-Emma-Watson-Net-A-Porter-The-Edit-Magazine-Photoshoot-2013-01.jpg
to
http://lh4.ggpht.com/-fFi-qJRuxeY/UjwHSOTHGOI/AAAAAAAArgE/SWTMT-hXzB4/s1600... |
def get_tag(self, tag_name, **kwargs):
"""get a tag by name
Args:
tag_name (string): name of tag to get
Returns:
dictionary of the response
"""
return self._get_object_by_name(self._TAG_ENDPOINT_SUFFIX,
tag_name,
... | get a tag by name
Args:
tag_name (string): name of tag to get
Returns:
dictionary of the response | Below is the the instruction that describes the task:
### Input:
get a tag by name
Args:
tag_name (string): name of tag to get
Returns:
dictionary of the response
### Response:
def get_tag(self, tag_name, **kwargs):
"""get a tag by name
Args:
t... |
def from_email(self, value):
"""The email address of the sender
:param value: The email address of the sender
:type value: From, str, tuple
"""
if isinstance(value, str):
value = From(value, None)
if isinstance(value, tuple):
value = From(value[0]... | The email address of the sender
:param value: The email address of the sender
:type value: From, str, tuple | Below is the the instruction that describes the task:
### Input:
The email address of the sender
:param value: The email address of the sender
:type value: From, str, tuple
### Response:
def from_email(self, value):
"""The email address of the sender
:param value: The email addres... |
def Add(self, other):
"""Returns a copy of this set with a new element added."""
new_descriptors = []
for desc in self.descriptors + other.descriptors:
if desc not in new_descriptors:
new_descriptors.append(desc)
return TypeDescriptorSet(*new_descriptors) | Returns a copy of this set with a new element added. | Below is the the instruction that describes the task:
### Input:
Returns a copy of this set with a new element added.
### Response:
def Add(self, other):
"""Returns a copy of this set with a new element added."""
new_descriptors = []
for desc in self.descriptors + other.descriptors:
if desc not i... |
def choose_tasks(self, stream_id, values):
"""Choose tasks for a given stream_id and values and Returns a list of target tasks"""
if stream_id not in self.targets:
return []
ret = []
for target in self.targets[stream_id]:
ret.extend(target.choose_tasks(values))
return ret | Choose tasks for a given stream_id and values and Returns a list of target tasks | Below is the the instruction that describes the task:
### Input:
Choose tasks for a given stream_id and values and Returns a list of target tasks
### Response:
def choose_tasks(self, stream_id, values):
"""Choose tasks for a given stream_id and values and Returns a list of target tasks"""
if stream_id not ... |
def _average_called_depth(in_file):
"""Retrieve the average depth of called reads in the provided VCF.
"""
import cyvcf2
depths = []
for rec in cyvcf2.VCF(str(in_file)):
d = rec.INFO.get("DP")
if d is not None:
depths.append(int(d))
if len(depths) > 0:
return ... | Retrieve the average depth of called reads in the provided VCF. | Below is the the instruction that describes the task:
### Input:
Retrieve the average depth of called reads in the provided VCF.
### Response:
def _average_called_depth(in_file):
"""Retrieve the average depth of called reads in the provided VCF.
"""
import cyvcf2
depths = []
for rec in cyvcf2.V... |
def find_files(path, filter="*.md"):
""" Finds files with an (optional) given extension in a given path. """
if os.path.isfile(path):
return [path]
if os.path.isdir(path):
matches = []
for root, dirnames, filenames in os.walk(path):
for filena... | Finds files with an (optional) given extension in a given path. | Below is the the instruction that describes the task:
### Input:
Finds files with an (optional) given extension in a given path.
### Response:
def find_files(path, filter="*.md"):
""" Finds files with an (optional) given extension in a given path. """
if os.path.isfile(path):
return [pa... |
def upload_dict(s3_conn, s3_prefix, data_to_sync):
"""Syncs a dictionary to an S3 bucket, serializing each value in the
dictionary as a JSON file with the key as its name.
Args:
s3_conn: (boto.s3.connection) an s3 connection
s3_prefix: (str) the destination prefix
data_to_sync: (dic... | Syncs a dictionary to an S3 bucket, serializing each value in the
dictionary as a JSON file with the key as its name.
Args:
s3_conn: (boto.s3.connection) an s3 connection
s3_prefix: (str) the destination prefix
data_to_sync: (dict) | Below is the the instruction that describes the task:
### Input:
Syncs a dictionary to an S3 bucket, serializing each value in the
dictionary as a JSON file with the key as its name.
Args:
s3_conn: (boto.s3.connection) an s3 connection
s3_prefix: (str) the destination prefix
data_to... |
def _create_base_string(method, base, params):
"""
Returns base string for HMAC-SHA1 signature as specified in:
http://oauth.net/core/1.0a/#rfc.section.9.1.3.
"""
normalized_qs = _normalize_params(params)
return _join_by_ampersand(method, base, normalized_qs) | Returns base string for HMAC-SHA1 signature as specified in:
http://oauth.net/core/1.0a/#rfc.section.9.1.3. | Below is the the instruction that describes the task:
### Input:
Returns base string for HMAC-SHA1 signature as specified in:
http://oauth.net/core/1.0a/#rfc.section.9.1.3.
### Response:
def _create_base_string(method, base, params):
"""
Returns base string for HMAC-SHA1 signature as specified in:
... |
def get_preprocessing_queue(preprocessing_list):
"""Get preprocessing queue from a list of dictionaries
>>> l = [{'RemoveDuplicateTime': None},
{'ScaleAndShift': [{'center': True}]}
]
>>> get_preprocessing_queue(l)
[RemoveDuplicateTime, ScaleAndShift
- center: True
- ... | Get preprocessing queue from a list of dictionaries
>>> l = [{'RemoveDuplicateTime': None},
{'ScaleAndShift': [{'center': True}]}
]
>>> get_preprocessing_queue(l)
[RemoveDuplicateTime, ScaleAndShift
- center: True
- max_width: 1
- max_height: 1
] | Below is the the instruction that describes the task:
### Input:
Get preprocessing queue from a list of dictionaries
>>> l = [{'RemoveDuplicateTime': None},
{'ScaleAndShift': [{'center': True}]}
]
>>> get_preprocessing_queue(l)
[RemoveDuplicateTime, ScaleAndShift
- center:... |
def add_chain(self, group_name, component_map):
"""
Adds the component chain to ``group_name`` in the fast5.
These are added as attributes to the group.
:param group_name: The group name you wish to add chaining data to,
e.g. ``Test_000``
:param component_map: The se... | Adds the component chain to ``group_name`` in the fast5.
These are added as attributes to the group.
:param group_name: The group name you wish to add chaining data to,
e.g. ``Test_000``
:param component_map: The set of components and corresponding
group names or group p... | Below is the the instruction that describes the task:
### Input:
Adds the component chain to ``group_name`` in the fast5.
These are added as attributes to the group.
:param group_name: The group name you wish to add chaining data to,
e.g. ``Test_000``
:param component_map: The s... |
def alarm_disable(self):
"""
disable the alarm
"""
log.debug("alarm => disable...")
params = {"enabled": False}
self._app_exec("com.lametric.clock", "clock.alarm", params=params) | disable the alarm | Below is the the instruction that describes the task:
### Input:
disable the alarm
### Response:
def alarm_disable(self):
"""
disable the alarm
"""
log.debug("alarm => disable...")
params = {"enabled": False}
self._app_exec("com.lametric.clock", "clock.alarm", params... |
def length(self):
"""
The total discretized length of every entity.
Returns
--------
length: float, summed length of every entity
"""
length = float(sum(i.length(self.vertices)
for i in self.entities))
return length | The total discretized length of every entity.
Returns
--------
length: float, summed length of every entity | Below is the the instruction that describes the task:
### Input:
The total discretized length of every entity.
Returns
--------
length: float, summed length of every entity
### Response:
def length(self):
"""
The total discretized length of every entity.
Returns
... |
def log_metrics(metrics, summ_writer, log_prefix, step, history=None):
"""Log metrics to summary writer and history."""
rjust_len = max([len(name) for name in metrics])
for name, value in six.iteritems(metrics):
step_log(step, "%s %s | % .8f" % (
log_prefix.ljust(5), name.rjust(rjust_len), value))
... | Log metrics to summary writer and history. | Below is the the instruction that describes the task:
### Input:
Log metrics to summary writer and history.
### Response:
def log_metrics(metrics, summ_writer, log_prefix, step, history=None):
"""Log metrics to summary writer and history."""
rjust_len = max([len(name) for name in metrics])
for name, value in... |
def encrypt(self, value, precision=None, r_value=None):
"""Encode and Paillier encrypt a real number *value*.
Args:
value: an int or float to be encrypted.
If int, it must satisfy abs(*value*) < :attr:`n`/3.
If float, it must satisfy abs(*value* / *precision*) <<
... | Encode and Paillier encrypt a real number *value*.
Args:
value: an int or float to be encrypted.
If int, it must satisfy abs(*value*) < :attr:`n`/3.
If float, it must satisfy abs(*value* / *precision*) <<
:attr:`n`/3
(i.e. if a float is near the limit t... | Below is the the instruction that describes the task:
### Input:
Encode and Paillier encrypt a real number *value*.
Args:
value: an int or float to be encrypted.
If int, it must satisfy abs(*value*) < :attr:`n`/3.
If float, it must satisfy abs(*value* / *precision*) <<
... |
def export(self, nidm_version, export_dir):
"""
Create prov graph.
"""
# Contrast Map entity
atts = (
(PROV['type'], NIDM_CONTRAST_MAP),
(NIDM_CONTRAST_NAME, self.name))
if not self.isderfrommap:
atts = atts + (
(NIDM_I... | Create prov graph. | Below is the the instruction that describes the task:
### Input:
Create prov graph.
### Response:
def export(self, nidm_version, export_dir):
"""
Create prov graph.
"""
# Contrast Map entity
atts = (
(PROV['type'], NIDM_CONTRAST_MAP),
(NIDM_CONTRAST_N... |
def _insert_file(cursor, file, media_type):
"""Upsert the ``file`` and ``media_type`` into the files table.
Returns the ``fileid`` and ``sha1`` of the upserted file.
"""
resource_hash = _get_file_sha1(file)
cursor.execute("SELECT fileid FROM files WHERE sha1 = %s",
(resource_hash... | Upsert the ``file`` and ``media_type`` into the files table.
Returns the ``fileid`` and ``sha1`` of the upserted file. | Below is the the instruction that describes the task:
### Input:
Upsert the ``file`` and ``media_type`` into the files table.
Returns the ``fileid`` and ``sha1`` of the upserted file.
### Response:
def _insert_file(cursor, file, media_type):
"""Upsert the ``file`` and ``media_type`` into the files table.
... |
def mchirp_compression(m1, m2, fmin, fmax, min_seglen=0.02, df_multiple=None):
"""Return the frequencies needed to compress a waveform with the given
chirp mass. This is based on the estimate in rough_time_estimate.
Parameters
----------
m1: float
mass of first component object in solar mas... | Return the frequencies needed to compress a waveform with the given
chirp mass. This is based on the estimate in rough_time_estimate.
Parameters
----------
m1: float
mass of first component object in solar masses
m2: float
mass of second component object in solar masses
fmin : f... | Below is the the instruction that describes the task:
### Input:
Return the frequencies needed to compress a waveform with the given
chirp mass. This is based on the estimate in rough_time_estimate.
Parameters
----------
m1: float
mass of first component object in solar masses
m2: float... |
def separator_width(self, value):
"""
Setter for **self.__separator_width** attribute.
:param value: Attribute value.
:type value: int
"""
if value is not None:
assert type(value) is int, "'{0}' attribute: '{1}' type is not 'int'!".format("separator_width", ... | Setter for **self.__separator_width** attribute.
:param value: Attribute value.
:type value: int | Below is the the instruction that describes the task:
### Input:
Setter for **self.__separator_width** attribute.
:param value: Attribute value.
:type value: int
### Response:
def separator_width(self, value):
"""
Setter for **self.__separator_width** attribute.
:param val... |
def get_py_file_if_possible(pyc_name):
"""Try to retrieve a X.py file for a given X.py[c] file."""
if pyc_name.endswith(('.py', '.so', '.pyd')):
return pyc_name
assert pyc_name.endswith('.pyc')
non_compiled_file = pyc_name[:-1]
if os.path.exists(non_compiled_file):
return non_compile... | Try to retrieve a X.py file for a given X.py[c] file. | Below is the the instruction that describes the task:
### Input:
Try to retrieve a X.py file for a given X.py[c] file.
### Response:
def get_py_file_if_possible(pyc_name):
"""Try to retrieve a X.py file for a given X.py[c] file."""
if pyc_name.endswith(('.py', '.so', '.pyd')):
return pyc_name
a... |
def move_to(self, xpos, ypos):
"""
Move cursor to specified position
"""
self.stream.write(self.move(ypos, xpos)) | Move cursor to specified position | Below is the the instruction that describes the task:
### Input:
Move cursor to specified position
### Response:
def move_to(self, xpos, ypos):
"""
Move cursor to specified position
"""
self.stream.write(self.move(ypos, xpos)) |
def is_permitted(self, permission_s):
"""
:param permission_s: a collection of 1..N permissions
:type permission_s: List of authz_abcs.Permission object(s) or String(s)
:returns: a List of tuple(s), containing the authz_abcs.Permission and a
Boolean indicating whether ... | :param permission_s: a collection of 1..N permissions
:type permission_s: List of authz_abcs.Permission object(s) or String(s)
:returns: a List of tuple(s), containing the authz_abcs.Permission and a
Boolean indicating whether the permission is granted | Below is the the instruction that describes the task:
### Input:
:param permission_s: a collection of 1..N permissions
:type permission_s: List of authz_abcs.Permission object(s) or String(s)
:returns: a List of tuple(s), containing the authz_abcs.Permission and a
Boolean indicati... |
def get_version(self) -> str:
"""
Open the file referenced in this object, and scrape the version.
:return:
The version as a string, an empty string if there is no match
to the magic_line, or any file exception messages encountered.
"""
try:
... | Open the file referenced in this object, and scrape the version.
:return:
The version as a string, an empty string if there is no match
to the magic_line, or any file exception messages encountered. | Below is the the instruction that describes the task:
### Input:
Open the file referenced in this object, and scrape the version.
:return:
The version as a string, an empty string if there is no match
to the magic_line, or any file exception messages encountered.
### Response:
def ... |
def list_member_groups(self, member_id):
''' a method to retrieve a list of meetup groups member belongs to
:param member_id: integer with meetup member id
:return: dictionary with list of group details in [json]
group_details = self.objects.group_profile.schema
'''
... | a method to retrieve a list of meetup groups member belongs to
:param member_id: integer with meetup member id
:return: dictionary with list of group details in [json]
group_details = self.objects.group_profile.schema | Below is the the instruction that describes the task:
### Input:
a method to retrieve a list of meetup groups member belongs to
:param member_id: integer with meetup member id
:return: dictionary with list of group details in [json]
group_details = self.objects.group_profile.schema
##... |
def collection(self):
"""Return the redis-collection instance."""
if not self.include_collections:
return None
ctx = stack.top
if ctx is not None:
if not hasattr(ctx, 'redislite_collection'):
ctx.redislite_collection = Collection(redis=self.connect... | Return the redis-collection instance. | Below is the the instruction that describes the task:
### Input:
Return the redis-collection instance.
### Response:
def collection(self):
"""Return the redis-collection instance."""
if not self.include_collections:
return None
ctx = stack.top
if ctx is not None:
... |
def get_calls(self, job_name):
'''
Reads file by given name and returns CallEdge array
'''
config = self.file_index.get_by_name(job_name).yaml
calls = self.get_calls_from_dict(config, from_name=job_name)
return calls | Reads file by given name and returns CallEdge array | Below is the the instruction that describes the task:
### Input:
Reads file by given name and returns CallEdge array
### Response:
def get_calls(self, job_name):
'''
Reads file by given name and returns CallEdge array
'''
config = self.file_index.get_by_name(job_name).yaml
... |
def generate_init(self, dst, out_format, vms_to_include, filters=None):
"""
Generate an init file which represents this env and can
be used with the images created by self.export_vms
Args:
dst (str): path and name of the new init file
out_format (plugins.output.Ou... | Generate an init file which represents this env and can
be used with the images created by self.export_vms
Args:
dst (str): path and name of the new init file
out_format (plugins.output.OutFormatPlugin):
formatter for the output (the default is yaml)
f... | Below is the the instruction that describes the task:
### Input:
Generate an init file which represents this env and can
be used with the images created by self.export_vms
Args:
dst (str): path and name of the new init file
out_format (plugins.output.OutFormatPlugin):
... |
def put(self, pid, record, key):
"""Handle the file rename through the PUT deposit file.
Permission required: `update_permission_factory`.
:param pid: Pid object (from url).
:param record: Record object resolved from the pid.
:param key: Unique identifier for the file in the de... | Handle the file rename through the PUT deposit file.
Permission required: `update_permission_factory`.
:param pid: Pid object (from url).
:param record: Record object resolved from the pid.
:param key: Unique identifier for the file in the deposit. | Below is the the instruction that describes the task:
### Input:
Handle the file rename through the PUT deposit file.
Permission required: `update_permission_factory`.
:param pid: Pid object (from url).
:param record: Record object resolved from the pid.
:param key: Unique identifi... |
def query_handler(cls, identifier, role=None):
'''
Lookup the handler for the giving idetifier (descriptor_type) and role.
In case it was not found return the default.
Logic goes as follows:
- First try to find exact match for identifier and role,
- Try to find match f... | Lookup the handler for the giving idetifier (descriptor_type) and role.
In case it was not found return the default.
Logic goes as follows:
- First try to find exact match for identifier and role,
- Try to find match for identifier and role=None,
- Return default handler. | Below is the the instruction that describes the task:
### Input:
Lookup the handler for the giving idetifier (descriptor_type) and role.
In case it was not found return the default.
Logic goes as follows:
- First try to find exact match for identifier and role,
- Try to find match... |
def _inherited_panel(panel, base_panels_from_pillar, ret):
'''Return a panel with properties from parents.'''
base_panels = []
for base_panel_from_pillar in base_panels_from_pillar:
base_panel = __salt__['pillar.get'](base_panel_from_pillar)
if base_panel:
base_panels.append(base... | Return a panel with properties from parents. | Below is the the instruction that describes the task:
### Input:
Return a panel with properties from parents.
### Response:
def _inherited_panel(panel, base_panels_from_pillar, ret):
'''Return a panel with properties from parents.'''
base_panels = []
for base_panel_from_pillar in base_panels_from_pilla... |
def addOption(classobj, name, default, dtype=str, doc=None):
"""Adds a renderer option named 'name', with the given default value.
'dtype' must be a callable to convert a string to an option.
'doc' is a doc string.
Options will be initialized from config file here.
"""
# ... | Adds a renderer option named 'name', with the given default value.
'dtype' must be a callable to convert a string to an option.
'doc' is a doc string.
Options will be initialized from config file here. | Below is the the instruction that describes the task:
### Input:
Adds a renderer option named 'name', with the given default value.
'dtype' must be a callable to convert a string to an option.
'doc' is a doc string.
Options will be initialized from config file here.
### Response:
def addOpt... |
def set_public_transport_route(self, public_transport_route):
"""
Set the public transport route.
:param public_transport_route: TransportRoute
"""
self._query_params += str(QueryParam.ROUTE_ID) + str(public_transport_route) | Set the public transport route.
:param public_transport_route: TransportRoute | Below is the the instruction that describes the task:
### Input:
Set the public transport route.
:param public_transport_route: TransportRoute
### Response:
def set_public_transport_route(self, public_transport_route):
"""
Set the public transport route.
:param public_transport_rout... |
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done t... | .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned... | 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 which modify installed packages from the
``salt-minion`` daemon's control group. This is done t... |
def __json(self):
"""
Using the exclude lists, convert fields to a string.
"""
if self.exclude_list is None:
self.exclude_list = []
fields = {}
for key, item in vars(self).items():
if hasattr(self, '_sa_instance_state'):
# ... | Using the exclude lists, convert fields to a string. | Below is the the instruction that describes the task:
### Input:
Using the exclude lists, convert fields to a string.
### Response:
def __json(self):
"""
Using the exclude lists, convert fields to a string.
"""
if self.exclude_list is None:
self.exclude_list = []
... |
def increment_failed_logins(self):
""" Increment failed logins counter"""
if not self.failed_logins:
self.failed_logins = 1
elif not self.failed_login_limit_reached():
self.failed_logins += 1
else:
self.reset_login_counter()
self.lock_accou... | Increment failed logins counter | Below is the the instruction that describes the task:
### Input:
Increment failed logins counter
### Response:
def increment_failed_logins(self):
""" Increment failed logins counter"""
if not self.failed_logins:
self.failed_logins = 1
elif not self.failed_login_limit_reached():
... |
def set_prompt(self, prompt=None):
"""
Defines a pattern that is waited for when calling the expect_prompt()
method.
If the set_prompt() method is not called, or if it is called with the
prompt argument set to None, a default prompt is used that should
work with many devi... | Defines a pattern that is waited for when calling the expect_prompt()
method.
If the set_prompt() method is not called, or if it is called with the
prompt argument set to None, a default prompt is used that should
work with many devices running Unix, IOS, IOS-XR, or Junos and others.
... | Below is the the instruction that describes the task:
### Input:
Defines a pattern that is waited for when calling the expect_prompt()
method.
If the set_prompt() method is not called, or if it is called with the
prompt argument set to None, a default prompt is used that should
work ... |
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`"""
n=pa... | 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: ... |
async def invite(self, room_id: str, user_id: str, check_cache: bool = False
) -> Optional[dict]:
"""
Invite a user to participate in a particular room. See also: `API reference`_
Args:
room_id: The room identifier (not alias) to which to invite the user.
... | Invite a user to participate in a particular room. See also: `API reference`_
Args:
room_id: The room identifier (not alias) to which to invite the user.
user_id: The fully qualified user ID of the invitee.
check_cache: Whether or not to check the state cache before inviting... | Below is the the instruction that describes the task:
### Input:
Invite a user to participate in a particular room. See also: `API reference`_
Args:
room_id: The room identifier (not alias) to which to invite the user.
user_id: The fully qualified user ID of the invitee.
... |
def aggregate(self, func, *columns):
"""
Execute an aggregate function against the database
:param func: The aggregate function
:type func: str
:param columns: The columns to execute the fnction for
:type columns: tuple
:return: The aggregate result
:rt... | Execute an aggregate function against the database
:param func: The aggregate function
:type func: str
:param columns: The columns to execute the fnction for
:type columns: tuple
:return: The aggregate result
:rtype: mixed | Below is the the instruction that describes the task:
### Input:
Execute an aggregate function against the database
:param func: The aggregate function
:type func: str
:param columns: The columns to execute the fnction for
:type columns: tuple
:return: The aggregate result... |
def download_SRA(self, email, directory='./', **kwargs):
"""Download RAW data as SRA file.
The files will be downloaded to the sample directory created ad hoc
or the directory specified by the parameter. The sample has to come
from sequencing eg. mRNA-seq, CLIP etc.
An importan... | Download RAW data as SRA file.
The files will be downloaded to the sample directory created ad hoc
or the directory specified by the parameter. The sample has to come
from sequencing eg. mRNA-seq, CLIP etc.
An important parameter is a filetype. By default an SRA
is accessed by ... | Below is the the instruction that describes the task:
### Input:
Download RAW data as SRA file.
The files will be downloaded to the sample directory created ad hoc
or the directory specified by the parameter. The sample has to come
from sequencing eg. mRNA-seq, CLIP etc.
An importa... |
def rm(self, name):
"""
Remove a data analog called 'name'.
The 'name' can contain a path specifier.
Warning: see
http://stackoverflow.com/questions/5844672/delete-an-element-from-a-dictionary
deleting from the snode_current changes diction... | Remove a data analog called 'name'.
The 'name' can contain a path specifier.
Warning: see
http://stackoverflow.com/questions/5844672/delete-an-element-from-a-dictionary
deleting from the snode_current changes dictionary contents for any other
agents th... | Below is the the instruction that describes the task:
### Input:
Remove a data analog called 'name'.
The 'name' can contain a path specifier.
Warning: see
http://stackoverflow.com/questions/5844672/delete-an-element-from-a-dictionary
deleting from the snode_cu... |
def save_data(self, trigger_id, **data):
"""
let's save the data
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_id: int
:type data: dict
:return: the status of the sav... | let's save the data
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_id: int
:type data: dict
:return: the status of the save statement
:rtype: boolean | Below is the the instruction that describes the task:
### Input:
let's save the data
:param trigger_id: trigger ID from which to save data
:param data: the data to check to be used and save
:type trigger_id: int
:type data: dict
:return: the status of the... |
def _create_variable(orig_v, step, variables):
"""Create a new output variable, potentially over-writing existing or creating new.
"""
# get current variable, and convert to be the output of our process step
try:
v = _get_variable(orig_v["id"], variables)
except ValueError:
v = copy.... | Create a new output variable, potentially over-writing existing or creating new. | Below is the the instruction that describes the task:
### Input:
Create a new output variable, potentially over-writing existing or creating new.
### Response:
def _create_variable(orig_v, step, variables):
"""Create a new output variable, potentially over-writing existing or creating new.
"""
# get cu... |
def _get_refreshed_check_result(self, check_id):
"""
Given the ``check_id``, return the dict of Trusted Advisor check
results. This handles refreshing the Trusted Advisor check, if desired,
according to ``self.refresh_mode`` and ``self.refresh_timeout``.
:param check_id: the Tru... | Given the ``check_id``, return the dict of Trusted Advisor check
results. This handles refreshing the Trusted Advisor check, if desired,
according to ``self.refresh_mode`` and ``self.refresh_timeout``.
:param check_id: the Trusted Advisor check ID
:type check_id: str
:returns: d... | Below is the the instruction that describes the task:
### Input:
Given the ``check_id``, return the dict of Trusted Advisor check
results. This handles refreshing the Trusted Advisor check, if desired,
according to ``self.refresh_mode`` and ``self.refresh_timeout``.
:param check_id: the Tru... |
def html_format(data, out, opts=None, **kwargs):
'''
Return the formatted string as HTML.
'''
ansi_escaped_string = string_format(data, out, opts, **kwargs)
return ansi_escaped_string.replace(' ', ' ').replace('\n', '<br />') | Return the formatted string as HTML. | Below is the the instruction that describes the task:
### Input:
Return the formatted string as HTML.
### Response:
def html_format(data, out, opts=None, **kwargs):
'''
Return the formatted string as HTML.
'''
ansi_escaped_string = string_format(data, out, opts, **kwargs)
return ansi_escaped_st... |
def tokenize(text, regexps=TOKENIZERRULES):
"""Tokenizes a string and returns a list of tokens
:param text: The text to tokenise
:type text: string
:param regexps: Regular expressions to use as tokeniser rules in tokenisation (default=_pynlpl.textprocessors.TOKENIZERRULES_)
:type regexps: Tuple/li... | Tokenizes a string and returns a list of tokens
:param text: The text to tokenise
:type text: string
:param regexps: Regular expressions to use as tokeniser rules in tokenisation (default=_pynlpl.textprocessors.TOKENIZERRULES_)
:type regexps: Tuple/list of regular expressions to use in tokenisation
... | Below is the the instruction that describes the task:
### Input:
Tokenizes a string and returns a list of tokens
:param text: The text to tokenise
:type text: string
:param regexps: Regular expressions to use as tokeniser rules in tokenisation (default=_pynlpl.textprocessors.TOKENIZERRULES_)
:type ... |
def certify_set(
value, certifier=None, min_len=None, max_len=None, include_collections=False,
required=True,
):
"""
Certifier for a set.
:param set value:
The set to be certified.
:param func certifier:
A function to be called on each value in the list to check that it is valid... | Certifier for a set.
:param set value:
The set to be certified.
:param func certifier:
A function to be called on each value in the list to check that it is valid.
:param int min_len:
The minimum acceptable length for the list. If None, the minimum length is not checked.
:param ... | Below is the the instruction that describes the task:
### Input:
Certifier for a set.
:param set value:
The set to be certified.
:param func certifier:
A function to be called on each value in the list to check that it is valid.
:param int min_len:
The minimum acceptable length ... |
def destroy(self, force=False):
"""
Like shutdown(), but also removes all accounts, hosts, etc., and
does not restart the queue. In other words, the queue can no longer
be used after calling this method.
:type force: bool
:param force: Whether to wait until all jobs wer... | Like shutdown(), but also removes all accounts, hosts, etc., and
does not restart the queue. In other words, the queue can no longer
be used after calling this method.
:type force: bool
:param force: Whether to wait until all jobs were processed. | Below is the the instruction that describes the task:
### Input:
Like shutdown(), but also removes all accounts, hosts, etc., and
does not restart the queue. In other words, the queue can no longer
be used after calling this method.
:type force: bool
:param force: Whether to wait u... |
def _roc(y_true, y_score, ax=None):
"""
Plot ROC curve for binary classification.
Parameters
----------
y_true : array-like, shape = [n_samples]
Correct target values (ground truth).
y_score : array-like, shape = [n_samples]
Target scores (estimator predictions).
ax: matplot... | Plot ROC curve for binary classification.
Parameters
----------
y_true : array-like, shape = [n_samples]
Correct target values (ground truth).
y_score : array-like, shape = [n_samples]
Target scores (estimator predictions).
ax: matplotlib Axes
Axes object to draw the plot on... | Below is the the instruction that describes the task:
### Input:
Plot ROC curve for binary classification.
Parameters
----------
y_true : array-like, shape = [n_samples]
Correct target values (ground truth).
y_score : array-like, shape = [n_samples]
Target scores (estimator predicti... |
def execute(self):
"""
Stops the cluster if it's running.
"""
cluster_name = self.params.cluster
creator = make_creator(self.params.config,
storage_path=self.params.storage)
try:
cluster = creator.load_cluster(cluster_name)
... | Stops the cluster if it's running. | Below is the the instruction that describes the task:
### Input:
Stops the cluster if it's running.
### Response:
def execute(self):
"""
Stops the cluster if it's running.
"""
cluster_name = self.params.cluster
creator = make_creator(self.params.config,
... |
def get_ini_config(config=os.path.join(os.path.expanduser('~'), '.zdeskcfg'),
default_section=None, section=None):
"""This is a convenience function for getting the zdesk configuration
from an ini file without the need to decorate and call your own function.
Handy when using zdesk and zdeskcfg from ... | This is a convenience function for getting the zdesk configuration
from an ini file without the need to decorate and call your own function.
Handy when using zdesk and zdeskcfg from the interactive prompt. | Below is the the instruction that describes the task:
### Input:
This is a convenience function for getting the zdesk configuration
from an ini file without the need to decorate and call your own function.
Handy when using zdesk and zdeskcfg from the interactive prompt.
### Response:
def get_ini_config(con... |
def __can_attempt(self, namespace: str, add_attempt=True) -> bool:
"""
Checks if a namespace is rate limited or not with including/excluding the current call
:param namespace: Rate limiting namespace
:type namespace: str
:param add_attempt: Boolean value indicating if the curre... | Checks if a namespace is rate limited or not with including/excluding the current call
:param namespace: Rate limiting namespace
:type namespace: str
:param add_attempt: Boolean value indicating if the current call should be considered as an attempt or not
:type add_attempt: bool
... | Below is the the instruction that describes the task:
### Input:
Checks if a namespace is rate limited or not with including/excluding the current call
:param namespace: Rate limiting namespace
:type namespace: str
:param add_attempt: Boolean value indicating if the current call should be ... |
def load_module(self, name):
"""Load a namespace module as if coming from an empty file.
"""
_verbose_message('namespace module loaded with path {!r}', self.path)
# Adjusting code from LoaderBasics
if name in sys.modules:
mod = sys.modules[name]
self.exec... | Load a namespace module as if coming from an empty file. | Below is the the instruction that describes the task:
### Input:
Load a namespace module as if coming from an empty file.
### Response:
def load_module(self, name):
"""Load a namespace module as if coming from an empty file.
"""
_verbose_message('namespace module loaded with path {!r}', sel... |
def add_arguments(self):
"""
Add specific command line arguments for this command
"""
# Call our parent to add the default arguments
ApiCli.add_arguments(self)
# Command specific arguments
self.parser.add_argument('-f', '--format', dest='format', action='stor... | Add specific command line arguments for this command | Below is the the instruction that describes the task:
### Input:
Add specific command line arguments for this command
### Response:
def add_arguments(self):
"""
Add specific command line arguments for this command
"""
# Call our parent to add the default arguments
ApiCli... |
def serv(args):
"""Serve a rueckenwind application"""
if not args.no_debug:
tornado.autoreload.start()
extra = []
if sys.stdout.isatty():
# set terminal title
sys.stdout.write('\x1b]2;rw: {}\x07'.format(' '.join(sys.argv[2:])))
if args.cfg:
extra.append(os.path.abs... | Serve a rueckenwind application | Below is the the instruction that describes the task:
### Input:
Serve a rueckenwind application
### Response:
def serv(args):
"""Serve a rueckenwind application"""
if not args.no_debug:
tornado.autoreload.start()
extra = []
if sys.stdout.isatty():
# set terminal title
sys... |
def matchImpObjStrs(fdefs,imp_obj_strs,cdefs):
'''returns imp_funcs, a dictionary with filepath keys that contains
lists of function definition nodes that were imported using
from __ import __ style syntax. also returns imp_classes, which
is the same for class definition nodes.'''
imp_funcs=dict(... | returns imp_funcs, a dictionary with filepath keys that contains
lists of function definition nodes that were imported using
from __ import __ style syntax. also returns imp_classes, which
is the same for class definition nodes. | Below is the the instruction that describes the task:
### Input:
returns imp_funcs, a dictionary with filepath keys that contains
lists of function definition nodes that were imported using
from __ import __ style syntax. also returns imp_classes, which
is the same for class definition nodes.
### Res... |
def _check_subresource(self, subresource: str):
"""Check if specific_resources parameter is valid.
:param str resource: subresource to check.
"""
warnings.warn(
"subresource in URL is deprecated." " Use _include mecanism instead.",
DeprecationWarning,
)
... | Check if specific_resources parameter is valid.
:param str resource: subresource to check. | Below is the the instruction that describes the task:
### Input:
Check if specific_resources parameter is valid.
:param str resource: subresource to check.
### Response:
def _check_subresource(self, subresource: str):
"""Check if specific_resources parameter is valid.
:param str resource:... |
def cmd_sync(self, low):
'''
Execute a salt-ssh call synchronously.
.. versionadded:: 2015.5.0
WARNING: Eauth is **NOT** respected
.. code-block:: python
client.cmd_sync({
'tgt': 'silver',
'fun': 'test.ping',
'arg': ... | Execute a salt-ssh call synchronously.
.. versionadded:: 2015.5.0
WARNING: Eauth is **NOT** respected
.. code-block:: python
client.cmd_sync({
'tgt': 'silver',
'fun': 'test.ping',
'arg': (),
'tgt_type'='glob',
... | Below is the the instruction that describes the task:
### Input:
Execute a salt-ssh call synchronously.
.. versionadded:: 2015.5.0
WARNING: Eauth is **NOT** respected
.. code-block:: python
client.cmd_sync({
'tgt': 'silver',
'fun': 'test.ping',... |
def verifications(self):
"""
Access the verifications
:returns: twilio.rest.preview.acc_security.service.verification.VerificationList
:rtype: twilio.rest.preview.acc_security.service.verification.VerificationList
"""
if self._verifications is None:
self._ver... | Access the verifications
:returns: twilio.rest.preview.acc_security.service.verification.VerificationList
:rtype: twilio.rest.preview.acc_security.service.verification.VerificationList | Below is the the instruction that describes the task:
### Input:
Access the verifications
:returns: twilio.rest.preview.acc_security.service.verification.VerificationList
:rtype: twilio.rest.preview.acc_security.service.verification.VerificationList
### Response:
def verifications(self):
"... |
def usergroup_get(name=None, usrgrpids=None, userids=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see ... | .. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
.. __: https://www.zabbix.com/documentation/2.4/manual/api/refere... | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2016.3.0
Retrieve user groups according to the given parameters
.. note::
This function accepts all usergroup_get properties: keyword argument
names differ depending on your zabbix version, see here__.
... |
def slice(self, start_time, end_time, strict=False):
'''
Slice every annotation contained in the annotation array using
`Annotation.slice`
and return as a new AnnotationArray
See `Annotation.slice` for details about slicing. This function does
not modify the annotations ... | Slice every annotation contained in the annotation array using
`Annotation.slice`
and return as a new AnnotationArray
See `Annotation.slice` for details about slicing. This function does
not modify the annotations in the original annotation array.
Parameters
----------
... | Below is the the instruction that describes the task:
### Input:
Slice every annotation contained in the annotation array using
`Annotation.slice`
and return as a new AnnotationArray
See `Annotation.slice` for details about slicing. This function does
not modify the annotations in t... |
def get_selected_python_frame(cls):
'''Try to obtain the Frame for the python code in the selected frame,
or None'''
frame = cls.get_selected_frame()
while frame:
if frame.is_evalframeex():
return frame
frame = frame.older()
# Not found:
... | Try to obtain the Frame for the python code in the selected frame,
or None | Below is the the instruction that describes the task:
### Input:
Try to obtain the Frame for the python code in the selected frame,
or None
### Response:
def get_selected_python_frame(cls):
'''Try to obtain the Frame for the python code in the selected frame,
or None'''
frame = cls.... |
def _filter_hovered_items(self, items, event):
"""Filters out items that cannot be hovered
:param list items: Sorted list of items beneath the cursor
:param Gtk.Event event: Motion event
:return: filtered items
:rtype: list
"""
items = self._filter_library_state(... | Filters out items that cannot be hovered
:param list items: Sorted list of items beneath the cursor
:param Gtk.Event event: Motion event
:return: filtered items
:rtype: list | Below is the the instruction that describes the task:
### Input:
Filters out items that cannot be hovered
:param list items: Sorted list of items beneath the cursor
:param Gtk.Event event: Motion event
:return: filtered items
:rtype: list
### Response:
def _filter_hovered_items(sel... |
def as_cache_key(self, ireq):
"""Given a requirement, return its cache key.
This behavior is a little weird in order to allow backwards
compatibility with cache files. For a requirement without extras, this
will return, for example::
("ipython", "2.1.0")
For a requ... | Given a requirement, return its cache key.
This behavior is a little weird in order to allow backwards
compatibility with cache files. For a requirement without extras, this
will return, for example::
("ipython", "2.1.0")
For a requirement with extras, the extras will be c... | Below is the the instruction that describes the task:
### Input:
Given a requirement, return its cache key.
This behavior is a little weird in order to allow backwards
compatibility with cache files. For a requirement without extras, this
will return, for example::
("ipython", ... |
def active_url(context, urls, css=None):
"""
Highlight menu item based on url tag.
Returns a css class if ``request.path`` is in given ``url``.
:param url:
Django url to be reversed.
:param css:
Css class to be returned for highlighting. Return active if none set.
"""... | Highlight menu item based on url tag.
Returns a css class if ``request.path`` is in given ``url``.
:param url:
Django url to be reversed.
:param css:
Css class to be returned for highlighting. Return active if none set. | Below is the the instruction that describes the task:
### Input:
Highlight menu item based on url tag.
Returns a css class if ``request.path`` is in given ``url``.
:param url:
Django url to be reversed.
:param css:
Css class to be returned for highlighting. Return active if no... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.