code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def master(master=None, connected=True):
'''
.. versionadded:: 2015.5.0
Fire an event if the minion gets disconnected from its master. This
function is meant to be run via a scheduled job from the minion. If
master_ip is an FQDN/Hostname, is must be resolvable to a valid IPv4
address.
CLI ... | .. versionadded:: 2015.5.0
Fire an event if the minion gets disconnected from its master. This
function is meant to be run via a scheduled job from the minion. If
master_ip is an FQDN/Hostname, is must be resolvable to a valid IPv4
address.
CLI Example:
.. code-block:: bash
salt '*' ... | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2015.5.0
Fire an event if the minion gets disconnected from its master. This
function is meant to be run via a scheduled job from the minion. If
master_ip is an FQDN/Hostname, is must be resolvable to a valid IPv4
ad... |
def _parse_videoname(cls, videoname):
""" parse videoname and return video info dict
video info contains:
- title, the name of video
- sub_title, the sub_title of video
- resolution,
- source,
-
- season, defaults to 0
- episode, defaults to 0
... | parse videoname and return video info dict
video info contains:
- title, the name of video
- sub_title, the sub_title of video
- resolution,
- source,
-
- season, defaults to 0
- episode, defaults to 0 | Below is the the instruction that describes the task:
### Input:
parse videoname and return video info dict
video info contains:
- title, the name of video
- sub_title, the sub_title of video
- resolution,
- source,
-
- season, defaults to 0
- episode,... |
def run(self):
"""Import the controller and run it.
This mimics the processing done by :func:`helper.start`
when a controller is run in the foreground. A new instance
of ``self.controller`` is created and run until a keyboard
interrupt occurs or the controller stops on its own ... | Import the controller and run it.
This mimics the processing done by :func:`helper.start`
when a controller is run in the foreground. A new instance
of ``self.controller`` is created and run until a keyboard
interrupt occurs or the controller stops on its own accord. | Below is the the instruction that describes the task:
### Input:
Import the controller and run it.
This mimics the processing done by :func:`helper.start`
when a controller is run in the foreground. A new instance
of ``self.controller`` is created and run until a keyboard
interrupt... |
def _welch_anova(self, dv=None, between=None, export_filename=None):
"""Return one-way Welch ANOVA."""
aov = welch_anova(data=self, dv=dv, between=between,
export_filename=export_filename)
return aov | Return one-way Welch ANOVA. | Below is the the instruction that describes the task:
### Input:
Return one-way Welch ANOVA.
### Response:
def _welch_anova(self, dv=None, between=None, export_filename=None):
"""Return one-way Welch ANOVA."""
aov = welch_anova(data=self, dv=dv, between=between,
export_filename=export... |
def handle_stage_changed(self, model):
'''
handle a stage change in the data model
:param model: the data model that was changed
'''
stages = model.get_stages()
if self.dataman:
self.dataman.set('stages', stages) | handle a stage change in the data model
:param model: the data model that was changed | Below is the the instruction that describes the task:
### Input:
handle a stage change in the data model
:param model: the data model that was changed
### Response:
def handle_stage_changed(self, model):
'''
handle a stage change in the data model
:param model: the data model that... |
def get_Generic_itemtype(sq, simplify=True):
"""Retrieves the item type from a PEP 484 generic or subclass of such.
sq must be a typing.Tuple or (subclass of) typing.Iterable or typing.Container.
Consequently this also works with typing.List, typing.Set and typing.Dict.
Note that for typing.Dict and map... | Retrieves the item type from a PEP 484 generic or subclass of such.
sq must be a typing.Tuple or (subclass of) typing.Iterable or typing.Container.
Consequently this also works with typing.List, typing.Set and typing.Dict.
Note that for typing.Dict and mapping types in general, the key type is regarded as i... | Below is the the instruction that describes the task:
### Input:
Retrieves the item type from a PEP 484 generic or subclass of such.
sq must be a typing.Tuple or (subclass of) typing.Iterable or typing.Container.
Consequently this also works with typing.List, typing.Set and typing.Dict.
Note that for ty... |
def describe_target_groups(names=None,
target_group_arns=None,
load_balancer_arn=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
Describes... | Describes the specified target groups or all of your target groups. By default,
all target groups are described. Alternatively, you can specify one of the
following to filter the results: the ARN of the load balancer, the names of
one or more target groups, or the ARNs of one or more target groups.
Ret... | Below is the the instruction that describes the task:
### Input:
Describes the specified target groups or all of your target groups. By default,
all target groups are described. Alternatively, you can specify one of the
following to filter the results: the ARN of the load balancer, the names of
one or m... |
def get_min_vertex_distance( coor, guess ):
"""Can miss the minimum, but is enough for our purposes."""
# Sort by x.
ix = nm.argsort( coor[:,0] )
scoor = coor[ix]
mvd = 1e16
# Get mvd in chunks potentially smaller than guess.
n_coor = coor.shape[0]
print n_coor
i0 = i1 = 0... | Can miss the minimum, but is enough for our purposes. | Below is the the instruction that describes the task:
### Input:
Can miss the minimum, but is enough for our purposes.
### Response:
def get_min_vertex_distance( coor, guess ):
"""Can miss the minimum, but is enough for our purposes."""
# Sort by x.
ix = nm.argsort( coor[:,0] )
scoor = coor[ix]
... |
def search(self, **kwargs):
"""
Method to search equipments based on extends search.
:param search: Dict containing QuerySets to find equipments.
:param include: Array containing fields to include on response.
:param exclude: Array containing fields to exclude on response.
... | Method to search equipments based on extends search.
:param search: Dict containing QuerySets to find equipments.
:param include: Array containing fields to include on response.
:param exclude: Array containing fields to exclude on response.
:param fields: Array containing fields to ov... | Below is the the instruction that describes the task:
### Input:
Method to search equipments based on extends search.
:param search: Dict containing QuerySets to find equipments.
:param include: Array containing fields to include on response.
:param exclude: Array containing fields to exclu... |
def _parse_param(key, val):
""" Parse the query param looking for sparse fields params
Ensure the `val` or what will become the sparse fields
is always an array. If the query param is not a sparse
fields query param then return None.
:param key:
the query parameter key in the request (left... | Parse the query param looking for sparse fields params
Ensure the `val` or what will become the sparse fields
is always an array. If the query param is not a sparse
fields query param then return None.
:param key:
the query parameter key in the request (left of =)
:param val:
the q... | Below is the the instruction that describes the task:
### Input:
Parse the query param looking for sparse fields params
Ensure the `val` or what will become the sparse fields
is always an array. If the query param is not a sparse
fields query param then return None.
:param key:
the query p... |
def read_function(data, window, ij, g_args):
"""Takes an array, and sets any value above the mean to the max, the rest to 0"""
output = (data[0] > numpy.mean(data[0])).astype(data[0].dtype) * data[0].max()
return output | Takes an array, and sets any value above the mean to the max, the rest to 0 | Below is the the instruction that describes the task:
### Input:
Takes an array, and sets any value above the mean to the max, the rest to 0
### Response:
def read_function(data, window, ij, g_args):
"""Takes an array, and sets any value above the mean to the max, the rest to 0"""
output = (data[0] > numpy... |
def json_response(obj):
"""
returns a json response from a json serializable python object
"""
return Response(
response=json.dumps(
obj, indent=4, cls=AirflowJsonEncoder),
status=200,
mimetype="application/json") | returns a json response from a json serializable python object | Below is the the instruction that describes the task:
### Input:
returns a json response from a json serializable python object
### Response:
def json_response(obj):
"""
returns a json response from a json serializable python object
"""
return Response(
response=json.dumps(
obj,... |
def _group_batches_shared(xs, caller_batch_fn, prep_data_fn):
"""Shared functionality for grouping by batches for variant calling and joint calling.
"""
singles = []
batch_groups = collections.defaultdict(list)
for args in xs:
data = utils.to_single_data(args)
caller, batch = caller_... | Shared functionality for grouping by batches for variant calling and joint calling. | Below is the the instruction that describes the task:
### Input:
Shared functionality for grouping by batches for variant calling and joint calling.
### Response:
def _group_batches_shared(xs, caller_batch_fn, prep_data_fn):
"""Shared functionality for grouping by batches for variant calling and joint calling.... |
async def on_raw_cap(self, message):
""" Handle CAP message. """
target, subcommand = message.params[:2]
params = message.params[2:]
# Call handler.
attr = 'on_raw_cap_' + pydle.protocol.identifierify(subcommand)
if hasattr(self, attr):
await getattr(self, at... | Handle CAP message. | Below is the the instruction that describes the task:
### Input:
Handle CAP message.
### Response:
async def on_raw_cap(self, message):
""" Handle CAP message. """
target, subcommand = message.params[:2]
params = message.params[2:]
# Call handler.
attr = 'on_raw_cap_' + pyd... |
def is_authenticated(user):
"""Return whether or not a User is authenticated.
Function provides compatibility following deprecation of method call to
`is_authenticated()` in Django 2.0.
This is *only* required to support Django < v1.10 (i.e. v1.9 and earlier),
as `is_authenticated` was introduced ... | Return whether or not a User is authenticated.
Function provides compatibility following deprecation of method call to
`is_authenticated()` in Django 2.0.
This is *only* required to support Django < v1.10 (i.e. v1.9 and earlier),
as `is_authenticated` was introduced as a property in v1.10.s | Below is the the instruction that describes the task:
### Input:
Return whether or not a User is authenticated.
Function provides compatibility following deprecation of method call to
`is_authenticated()` in Django 2.0.
This is *only* required to support Django < v1.10 (i.e. v1.9 and earlier),
as ... |
def buildNavigation(self):
"""
Chooses the appropriate layout navigation component based on user prefs
"""
if self.buildSpec['navigation'] == constants.TABBED:
navigation = Tabbar(self, self.buildSpec, self.configs)
else:
navigation = Sidebar(self, ... | Chooses the appropriate layout navigation component based on user prefs | Below is the the instruction that describes the task:
### Input:
Chooses the appropriate layout navigation component based on user prefs
### Response:
def buildNavigation(self):
"""
Chooses the appropriate layout navigation component based on user prefs
"""
if self.buildSpec['na... |
def _fill_function(func, globals, defaults, dict, module, closure_values):
""" Fills in the rest of function data into the skeleton function object
that were created via _make_skel_func().
"""
func.__globals__.update(globals)
func.__defaults__ = defaults
func.__dict__ = dict
func.__modul... | Fills in the rest of function data into the skeleton function object
that were created via _make_skel_func(). | Below is the the instruction that describes the task:
### Input:
Fills in the rest of function data into the skeleton function object
that were created via _make_skel_func().
### Response:
def _fill_function(func, globals, defaults, dict, module, closure_values):
""" Fills in the rest of function data ... |
def form_lines_valid(self, form):
"""Handle a valid LineFormSet."""
handled = 0
for inner_form in form:
if not inner_form.cleaned_data.get(formsets.DELETION_FIELD_NAME):
handled += 1
self.handle_inner_form(inner_form)
self.log_and_notify_lines... | Handle a valid LineFormSet. | Below is the the instruction that describes the task:
### Input:
Handle a valid LineFormSet.
### Response:
def form_lines_valid(self, form):
"""Handle a valid LineFormSet."""
handled = 0
for inner_form in form:
if not inner_form.cleaned_data.get(formsets.DELETION_FIELD_NAME):
... |
def submesh(mesh,
faces_sequence,
only_watertight=False,
append=False):
"""
Return a subset of a mesh.
Parameters
----------
mesh : Trimesh
Source mesh to take geometry from
faces_sequence : sequence (p,) int
Indexes of mesh.faces
only_wate... | Return a subset of a mesh.
Parameters
----------
mesh : Trimesh
Source mesh to take geometry from
faces_sequence : sequence (p,) int
Indexes of mesh.faces
only_watertight : bool
Only return submeshes which are watertight.
append : bool
Return a single mesh which h... | Below is the the instruction that describes the task:
### Input:
Return a subset of a mesh.
Parameters
----------
mesh : Trimesh
Source mesh to take geometry from
faces_sequence : sequence (p,) int
Indexes of mesh.faces
only_watertight : bool
Only return submeshes which a... |
def set_row_height(self, row, tab, height):
"""Sets row height"""
try:
old_height = self.row_heights.pop((row, tab))
except KeyError:
old_height = None
if height is not None:
self.row_heights[(row, tab)] = float(height) | Sets row height | Below is the the instruction that describes the task:
### Input:
Sets row height
### Response:
def set_row_height(self, row, tab, height):
"""Sets row height"""
try:
old_height = self.row_heights.pop((row, tab))
except KeyError:
old_height = None
if height... |
def set_stable_spot_instance_settings(self, maximum_bid_price_percentage=None,
timeout_for_request=None,
allow_fallback=True):
"""
Purchase options for stable spot instances.
`maximum_bid_price_percentage`: Maxi... | Purchase options for stable spot instances.
`maximum_bid_price_percentage`: Maximum value to bid for stable node spot
instances, expressed as a percentage of the base price
(applies to both master and slave nodes).
`timeout_for_request`: Timeout for a stable node spot instance ... | Below is the the instruction that describes the task:
### Input:
Purchase options for stable spot instances.
`maximum_bid_price_percentage`: Maximum value to bid for stable node spot
instances, expressed as a percentage of the base price
(applies to both master and slave nodes).
... |
def map_data(self):
"""
provides a mapping from the CSV file to the
aikif data structures.
"""
with open(self.src_file, "r") as f:
for line in f:
cols = line.split(',')
print(cols) | provides a mapping from the CSV file to the
aikif data structures. | Below is the the instruction that describes the task:
### Input:
provides a mapping from the CSV file to the
aikif data structures.
### Response:
def map_data(self):
"""
provides a mapping from the CSV file to the
aikif data structures.
"""
with open(self.src_file,... |
def allocate_objects(self, eps = 0.01, noise_size = 1):
"""!
@brief Allocates object segments.
@param[in] eps (double): Tolerance level that define maximal difference between phases of oscillators in one segment.
@param[in] noise_size (uint): Threshold that defines noise - ... | !
@brief Allocates object segments.
@param[in] eps (double): Tolerance level that define maximal difference between phases of oscillators in one segment.
@param[in] noise_size (uint): Threshold that defines noise - segments size (in pixels) that is less then the threshold is conside... | Below is the the instruction that describes the task:
### Input:
!
@brief Allocates object segments.
@param[in] eps (double): Tolerance level that define maximal difference between phases of oscillators in one segment.
@param[in] noise_size (uint): Threshold that defines noise -... |
def init(config, workdir=None, logfile=None, loglevel=logging.INFO, **kwargs):
"""
Initialize the Lago environment
Args:
config(str): Path to LagoInitFile
workdir(str): Path to initalize the workdir, defaults to "$PWD/.lago"
**kwargs(dict): Pass arguments to :func:`~lago.cmd.do_init... | Initialize the Lago environment
Args:
config(str): Path to LagoInitFile
workdir(str): Path to initalize the workdir, defaults to "$PWD/.lago"
**kwargs(dict): Pass arguments to :func:`~lago.cmd.do_init`
logfile(str): A path to setup a log file.
loglevel(int): :mod:`logging` l... | Below is the the instruction that describes the task:
### Input:
Initialize the Lago environment
Args:
config(str): Path to LagoInitFile
workdir(str): Path to initalize the workdir, defaults to "$PWD/.lago"
**kwargs(dict): Pass arguments to :func:`~lago.cmd.do_init`
logfile(str)... |
def getDatetimeAxis():
"""
use datetime as x-axis
"""
dataSet = 'nyc_taxi'
filePath = './data/' + dataSet + '.csv'
data = pd.read_csv(filePath, header=0, skiprows=[1, 2],
names=['datetime', 'value', 'timeofday', 'dayofweek'])
xaxisDate = pd.to_datetime(data['datetime'])
return xaxi... | use datetime as x-axis | Below is the the instruction that describes the task:
### Input:
use datetime as x-axis
### Response:
def getDatetimeAxis():
"""
use datetime as x-axis
"""
dataSet = 'nyc_taxi'
filePath = './data/' + dataSet + '.csv'
data = pd.read_csv(filePath, header=0, skiprows=[1, 2],
names=['d... |
def getSpec(cls):
"""
Return the Spec for ApicalTMSequenceRegion.
"""
spec = {
"description": ApicalTMSequenceRegion.__doc__,
"singleNodeOnly": True,
"inputs": {
"activeColumns": {
"description": ("An array of 0's and 1's representing the active "
... | Return the Spec for ApicalTMSequenceRegion. | Below is the the instruction that describes the task:
### Input:
Return the Spec for ApicalTMSequenceRegion.
### Response:
def getSpec(cls):
"""
Return the Spec for ApicalTMSequenceRegion.
"""
spec = {
"description": ApicalTMSequenceRegion.__doc__,
"singleNodeOnly": True,
"inputs... |
def _map_input(self, input_stream):
"""
Iterate over input and call the mapper for each item.
If the job has a parser defined, the return values from the parser will
be passed as arguments to the mapper.
If the input is coded output from a previous run,
the arguments wil... | Iterate over input and call the mapper for each item.
If the job has a parser defined, the return values from the parser will
be passed as arguments to the mapper.
If the input is coded output from a previous run,
the arguments will be splitted in key and value. | Below is the the instruction that describes the task:
### Input:
Iterate over input and call the mapper for each item.
If the job has a parser defined, the return values from the parser will
be passed as arguments to the mapper.
If the input is coded output from a previous run,
the ... |
def get_dev_details(ip_address):
"""Takes string input of IP address to issue RESTUL call to HP IMC
:param ip_address: string object of dotted decimal notation of IPv4 address
:return: dictionary of device details
>>> get_dev_details('10.101.0.1')
{'symbolLevel': '2', 'typeName': 'Cisco 2811', 'loc... | Takes string input of IP address to issue RESTUL call to HP IMC
:param ip_address: string object of dotted decimal notation of IPv4 address
:return: dictionary of device details
>>> get_dev_details('10.101.0.1')
{'symbolLevel': '2', 'typeName': 'Cisco 2811', 'location': 'changed this too', 'status': '1... | Below is the the instruction that describes the task:
### Input:
Takes string input of IP address to issue RESTUL call to HP IMC
:param ip_address: string object of dotted decimal notation of IPv4 address
:return: dictionary of device details
>>> get_dev_details('10.101.0.1')
{'symbolLevel': '2', '... |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extracting dictionary of coefficients specific to required
#... | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values. | Below is the the instruction that describes the task:
### Input:
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
### Response:
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :m... |
def colors_like(color, arr, colormap=DEFAULT_COLORMAP):
'''
Given an array of size NxM (usually Nx3), we accept color in the following ways:
- A string color name. The accepted names are roughly what's in X11's rgb.txt
- An explicit rgb triple, in (3, ), (3, 1), or (1, 3) shape
- A list of values (N... | Given an array of size NxM (usually Nx3), we accept color in the following ways:
- A string color name. The accepted names are roughly what's in X11's rgb.txt
- An explicit rgb triple, in (3, ), (3, 1), or (1, 3) shape
- A list of values (N, ), (N, 1), or (1, N) that are put through a colormap to get per ve... | Below is the the instruction that describes the task:
### Input:
Given an array of size NxM (usually Nx3), we accept color in the following ways:
- A string color name. The accepted names are roughly what's in X11's rgb.txt
- An explicit rgb triple, in (3, ), (3, 1), or (1, 3) shape
- A list of values (... |
def sources(self):
"""
Get the sources for a given experience_id, which is tied to a specific language
:param experience_id: int; video content id
:return: sources dict
"""
api_url = self.sources_api_url.format(experience_id=self.experience_id)
res = self.get(api_... | Get the sources for a given experience_id, which is tied to a specific language
:param experience_id: int; video content id
:return: sources dict | Below is the the instruction that describes the task:
### Input:
Get the sources for a given experience_id, which is tied to a specific language
:param experience_id: int; video content id
:return: sources dict
### Response:
def sources(self):
"""
Get the sources for a given experie... |
def drop_column(self, name):
"""Drop the column ``name``.
::
table.drop_column('created_at')
"""
if self.db.engine.dialect.name == 'sqlite':
raise RuntimeError("SQLite does not support dropping columns.")
name = normalize_column_name(name)
with sel... | Drop the column ``name``.
::
table.drop_column('created_at') | Below is the the instruction that describes the task:
### Input:
Drop the column ``name``.
::
table.drop_column('created_at')
### Response:
def drop_column(self, name):
"""Drop the column ``name``.
::
table.drop_column('created_at')
"""
if self.db.eng... |
def get_random_edge(self):
"""This function should be run when there are no leaves, but there are still unscored nodes. It will introduce
a probabilistic element to the algorithm, where some edges are disregarded randomly to eventually get a score
for the network. This means that the score can b... | This function should be run when there are no leaves, but there are still unscored nodes. It will introduce
a probabilistic element to the algorithm, where some edges are disregarded randomly to eventually get a score
for the network. This means that the score can be averaged over many runs for a given ... | Below is the the instruction that describes the task:
### Input:
This function should be run when there are no leaves, but there are still unscored nodes. It will introduce
a probabilistic element to the algorithm, where some edges are disregarded randomly to eventually get a score
for the network. ... |
def setup_experiment(debug=True, verbose=False, app=None):
"""Check the app and, if it's compatible with Wallace, freeze its state."""
print_header()
# Verify that the package is usable.
log("Verifying that directory is compatible with Wallace...")
if not verify_package(verbose=verbose):
ra... | Check the app and, if it's compatible with Wallace, freeze its state. | Below is the the instruction that describes the task:
### Input:
Check the app and, if it's compatible with Wallace, freeze its state.
### Response:
def setup_experiment(debug=True, verbose=False, app=None):
"""Check the app and, if it's compatible with Wallace, freeze its state."""
print_header()
# V... |
def copy(self):
"""
Return a new :class:`~pywbem.CIMClassName` object that is a copy
of this CIM class path.
Objects of this class have no mutable types in any attributes, so
modifications of the original object will not affect the returned copy,
and vice versa.
... | Return a new :class:`~pywbem.CIMClassName` object that is a copy
of this CIM class path.
Objects of this class have no mutable types in any attributes, so
modifications of the original object will not affect the returned copy,
and vice versa.
Note that the Python functions :fun... | Below is the the instruction that describes the task:
### Input:
Return a new :class:`~pywbem.CIMClassName` object that is a copy
of this CIM class path.
Objects of this class have no mutable types in any attributes, so
modifications of the original object will not affect the returned copy,... |
def extract_signature(docstring):
"""Extract the signature from a docstring.
:sig: (str) -> Optional[str]
:param docstring: Docstring to extract the signature from.
:return: Extracted signature, or ``None`` if there's no signature.
"""
root = publish_doctree(docstring, settings_overrides={"repo... | Extract the signature from a docstring.
:sig: (str) -> Optional[str]
:param docstring: Docstring to extract the signature from.
:return: Extracted signature, or ``None`` if there's no signature. | Below is the the instruction that describes the task:
### Input:
Extract the signature from a docstring.
:sig: (str) -> Optional[str]
:param docstring: Docstring to extract the signature from.
:return: Extracted signature, or ``None`` if there's no signature.
### Response:
def extract_signature(docstr... |
def search_directory(self, **kwargs):
"""
SearchAccount is deprecated, using SearchDirectory
:param query: Query string - should be an LDAP-style filter
string (RFC 2254)
:param limit: The maximum number of accounts to return
(0 is default and means all)
:param o... | SearchAccount is deprecated, using SearchDirectory
:param query: Query string - should be an LDAP-style filter
string (RFC 2254)
:param limit: The maximum number of accounts to return
(0 is default and means all)
:param offset: The starting offset (0, 25, etc)
:param dom... | Below is the the instruction that describes the task:
### Input:
SearchAccount is deprecated, using SearchDirectory
:param query: Query string - should be an LDAP-style filter
string (RFC 2254)
:param limit: The maximum number of accounts to return
(0 is default and means all)
... |
def add_tag(self, tag):
""" add a tag to the tag list """
if tag not in self._tags:
self._tags[tag] = dict() | add a tag to the tag list | Below is the the instruction that describes the task:
### Input:
add a tag to the tag list
### Response:
def add_tag(self, tag):
""" add a tag to the tag list """
if tag not in self._tags:
self._tags[tag] = dict() |
def dependency_items(self):
"""
Generates all containers' dependencies, i.e. an iterator on tuples in the format
``(container_name, used_containers)``, whereas the used containers are a set, and can be empty.
:return: Container dependencies.
:rtype: collections.Iterable
... | Generates all containers' dependencies, i.e. an iterator on tuples in the format
``(container_name, used_containers)``, whereas the used containers are a set, and can be empty.
:return: Container dependencies.
:rtype: collections.Iterable | Below is the the instruction that describes the task:
### Input:
Generates all containers' dependencies, i.e. an iterator on tuples in the format
``(container_name, used_containers)``, whereas the used containers are a set, and can be empty.
:return: Container dependencies.
:rtype: collecti... |
def slugify(text, sep='-'):
"""A simple slug generator."""
text = stringify(text)
if text is None:
return None
text = text.replace(sep, WS)
text = normalize(text, ascii=True)
if text is None:
return None
return text.replace(WS, sep) | A simple slug generator. | Below is the the instruction that describes the task:
### Input:
A simple slug generator.
### Response:
def slugify(text, sep='-'):
"""A simple slug generator."""
text = stringify(text)
if text is None:
return None
text = text.replace(sep, WS)
text = normalize(text, ascii=True)
if t... |
def get_sub_comp_info(source_info, comp):
"""Build and return information about a sub-component for a particular selection
"""
sub_comps = source_info.get('components', None)
if sub_comps is None:
return source_info.copy()
moving = source_info.get('moving', False)
... | Build and return information about a sub-component for a particular selection | Below is the the instruction that describes the task:
### Input:
Build and return information about a sub-component for a particular selection
### Response:
def get_sub_comp_info(source_info, comp):
"""Build and return information about a sub-component for a particular selection
"""
sub_com... |
def set_sum_w2(self, w, ix, iy=0, iz=0):
"""
Sets the true number of entries in the bin weighted by w^2
"""
if self.GetSumw2N() == 0:
raise RuntimeError(
"Attempting to access Sumw2 in histogram "
"where weights were not stored")
xl = s... | Sets the true number of entries in the bin weighted by w^2 | Below is the the instruction that describes the task:
### Input:
Sets the true number of entries in the bin weighted by w^2
### Response:
def set_sum_w2(self, w, ix, iy=0, iz=0):
"""
Sets the true number of entries in the bin weighted by w^2
"""
if self.GetSumw2N() == 0:
... |
def create_prefetch(self, addresses):
"""Create futures needed before starting the process of reading the
address's value from the merkle tree.
Args:
addresses (list of str): addresses in the txn's inputs that
aren't in any base context (or any in the chain).
... | Create futures needed before starting the process of reading the
address's value from the merkle tree.
Args:
addresses (list of str): addresses in the txn's inputs that
aren't in any base context (or any in the chain). | Below is the the instruction that describes the task:
### Input:
Create futures needed before starting the process of reading the
address's value from the merkle tree.
Args:
addresses (list of str): addresses in the txn's inputs that
aren't in any base context (or any in... |
def OxmlElement(nsptag_str, nsmap=None):
"""
Return a 'loose' lxml element having the tag specified by *nsptag_str*.
*nsptag_str* must contain the standard namespace prefix, e.g. 'a:tbl'.
The resulting element is an instance of the custom element class for this
tag name if one is defined.
"""
... | Return a 'loose' lxml element having the tag specified by *nsptag_str*.
*nsptag_str* must contain the standard namespace prefix, e.g. 'a:tbl'.
The resulting element is an instance of the custom element class for this
tag name if one is defined. | Below is the the instruction that describes the task:
### Input:
Return a 'loose' lxml element having the tag specified by *nsptag_str*.
*nsptag_str* must contain the standard namespace prefix, e.g. 'a:tbl'.
The resulting element is an instance of the custom element class for this
tag name if one is def... |
def withdict(parser, token):
"""
Take a complete context dict as extra layer.
"""
bits = token.split_contents()
if len(bits) != 2:
raise TemplateSyntaxError("{% withdict %} expects one argument")
nodelist = parser.parse(('endwithdict',))
parser.delete_first_token()
return WithD... | Take a complete context dict as extra layer. | Below is the the instruction that describes the task:
### Input:
Take a complete context dict as extra layer.
### Response:
def withdict(parser, token):
"""
Take a complete context dict as extra layer.
"""
bits = token.split_contents()
if len(bits) != 2:
raise TemplateSyntaxError("{% wi... |
def set_argsx(self, arguments, *args):
"""
Setup the command line arguments, the first item must be an (absolute) filename
to run. Variadic function, must be NULL terminated.
"""
return lib.zproc_set_argsx(self._as_parameter_, arguments, *args) | Setup the command line arguments, the first item must be an (absolute) filename
to run. Variadic function, must be NULL terminated. | Below is the the instruction that describes the task:
### Input:
Setup the command line arguments, the first item must be an (absolute) filename
to run. Variadic function, must be NULL terminated.
### Response:
def set_argsx(self, arguments, *args):
"""
Setup the command line arguments, the first i... |
def _parse_request_arguments(self, request):
"""Parses comma separated request arguments
Args:
request: A request that should contain 'inference_address', 'model_name',
'model_version', 'model_signature'.
Returns:
A tuple of lists for model parameters
"""
inference_addresses = ... | Parses comma separated request arguments
Args:
request: A request that should contain 'inference_address', 'model_name',
'model_version', 'model_signature'.
Returns:
A tuple of lists for model parameters | Below is the the instruction that describes the task:
### Input:
Parses comma separated request arguments
Args:
request: A request that should contain 'inference_address', 'model_name',
'model_version', 'model_signature'.
Returns:
A tuple of lists for model parameters
### Response:
de... |
def _shortcut_open(
uri,
mode,
ignore_ext=False,
buffering=-1,
encoding=None,
errors=None,
):
"""Try to open the URI using the standard library io.open function.
This can be much faster than the alternative of opening in binary mode and
then decoding.... | Try to open the URI using the standard library io.open function.
This can be much faster than the alternative of opening in binary mode and
then decoding.
This is only possible under the following conditions:
1. Opening a local file
2. Ignore extension is set to True
If it is not pos... | Below is the the instruction that describes the task:
### Input:
Try to open the URI using the standard library io.open function.
This can be much faster than the alternative of opening in binary mode and
then decoding.
This is only possible under the following conditions:
1. Opening a local ... |
def random(pages=1):
'''
Get a list of random Wikipedia article titles.
.. note:: Random only gets articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages.
Keyword arguments:
* pages - the number of random pages returned (max of 10)
'''
#http://en.wikipedia.org/w/api.ph... | Get a list of random Wikipedia article titles.
.. note:: Random only gets articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages.
Keyword arguments:
* pages - the number of random pages returned (max of 10) | Below is the the instruction that describes the task:
### Input:
Get a list of random Wikipedia article titles.
.. note:: Random only gets articles from namespace 0, meaning no Category, User talk, or other meta-Wikipedia pages.
Keyword arguments:
* pages - the number of random pages returned (max of 10)
#... |
def _parse(self):
"""
Checks if the CPE Name is valid.
:returns: None
:exception: ValueError - bad-formed CPE Name
"""
# Check prefix and initial bracket of WFN
if self._str[0:5] != CPE2_3_WFN.CPE_PREFIX:
errmsg = "Bad-formed CPE Name: WFN prefix not... | Checks if the CPE Name is valid.
:returns: None
:exception: ValueError - bad-formed CPE Name | Below is the the instruction that describes the task:
### Input:
Checks if the CPE Name is valid.
:returns: None
:exception: ValueError - bad-formed CPE Name
### Response:
def _parse(self):
"""
Checks if the CPE Name is valid.
:returns: None
:exception: ValueError ... |
def mint_sub(client_salt, sector_id="", subject_type="public",
uid='', user_salt=''):
"""
Mint a new sub (subject identifier)
:param authn_event: Authentication event information
:param client_salt: client specific salt - used in pairwise
:param sector_id: Possible sector identifier
... | Mint a new sub (subject identifier)
:param authn_event: Authentication event information
:param client_salt: client specific salt - used in pairwise
:param sector_id: Possible sector identifier
:param subject_type: 'public'/'pairwise'
:return: Subject identifier | Below is the the instruction that describes the task:
### Input:
Mint a new sub (subject identifier)
:param authn_event: Authentication event information
:param client_salt: client specific salt - used in pairwise
:param sector_id: Possible sector identifier
:param subject_type: 'public'/'pairwise'... |
def get_num_shards(num_samples: int, samples_per_shard: int, min_num_shards: int) -> int:
"""
Returns the number of shards.
:param num_samples: Number of training data samples.
:param samples_per_shard: Samples per shard.
:param min_num_shards: Minimum number of shards.
:return: Number of shard... | Returns the number of shards.
:param num_samples: Number of training data samples.
:param samples_per_shard: Samples per shard.
:param min_num_shards: Minimum number of shards.
:return: Number of shards. | Below is the the instruction that describes the task:
### Input:
Returns the number of shards.
:param num_samples: Number of training data samples.
:param samples_per_shard: Samples per shard.
:param min_num_shards: Minimum number of shards.
:return: Number of shards.
### Response:
def get_num_sha... |
def invalid_config_error_message(action, key, val):
"""Returns a better error message when invalid configuration option
is provided."""
if action in ('store_true', 'store_false'):
return ("{0} is not a valid value for {1} option, "
"please specify a boolean value like yes/no, "
... | Returns a better error message when invalid configuration option
is provided. | Below is the the instruction that describes the task:
### Input:
Returns a better error message when invalid configuration option
is provided.
### Response:
def invalid_config_error_message(action, key, val):
"""Returns a better error message when invalid configuration option
is provided."""
if act... |
def independent_data(self):
"""
Read-only Property
:return: Data belonging to each independent variable as a dict with
variable names as key, data as value.
:rtype: collections.OrderedDict
"""
return OrderedDict((var, self.data[var]) for var in self.mode... | Read-only Property
:return: Data belonging to each independent variable as a dict with
variable names as key, data as value.
:rtype: collections.OrderedDict | Below is the the instruction that describes the task:
### Input:
Read-only Property
:return: Data belonging to each independent variable as a dict with
variable names as key, data as value.
:rtype: collections.OrderedDict
### Response:
def independent_data(self):
"""
... |
def OnSecondaryCheckbox(self, event):
"""Top Checkbox event handler"""
self.attrs["top"] = event.IsChecked()
self.attrs["right"] = event.IsChecked()
post_command_event(self, self.DrawChartMsg) | Top Checkbox event handler | Below is the the instruction that describes the task:
### Input:
Top Checkbox event handler
### Response:
def OnSecondaryCheckbox(self, event):
"""Top Checkbox event handler"""
self.attrs["top"] = event.IsChecked()
self.attrs["right"] = event.IsChecked()
post_command_event(self, s... |
def write(self, path=None):
"""
Write all of the HostsEntry instances back to the hosts file
:param path: override the write path
:return: Dictionary containing counts
"""
written_count = 0
comments_written = 0
blanks_written = 0
ipv4_entries_writt... | Write all of the HostsEntry instances back to the hosts file
:param path: override the write path
:return: Dictionary containing counts | Below is the the instruction that describes the task:
### Input:
Write all of the HostsEntry instances back to the hosts file
:param path: override the write path
:return: Dictionary containing counts
### Response:
def write(self, path=None):
"""
Write all of the HostsEntry instance... |
def clear_data(self, queues=None, edge=None, edge_type=None):
"""Clears data from all queues.
If none of the parameters are given then every queue's data is
cleared.
Parameters
----------
queues : int or an iterable of int (optional)
The edge index (or an it... | Clears data from all queues.
If none of the parameters are given then every queue's data is
cleared.
Parameters
----------
queues : int or an iterable of int (optional)
The edge index (or an iterable of edge indices) identifying
the :class:`QueueServer(s... | Below is the the instruction that describes the task:
### Input:
Clears data from all queues.
If none of the parameters are given then every queue's data is
cleared.
Parameters
----------
queues : int or an iterable of int (optional)
The edge index (or an iterab... |
def sanity(request, sysmeta_pyxb):
"""Check that sysmeta_pyxb is suitable for creating a new object and matches the
uploaded sciobj bytes."""
_does_not_contain_replica_sections(sysmeta_pyxb)
_is_not_archived(sysmeta_pyxb)
_obsoleted_by_not_specified(sysmeta_pyxb)
if 'HTTP_VENDOR_GMN_REMOTE_URL' ... | Check that sysmeta_pyxb is suitable for creating a new object and matches the
uploaded sciobj bytes. | Below is the the instruction that describes the task:
### Input:
Check that sysmeta_pyxb is suitable for creating a new object and matches the
uploaded sciobj bytes.
### Response:
def sanity(request, sysmeta_pyxb):
"""Check that sysmeta_pyxb is suitable for creating a new object and matches the
uploade... |
def _prt_qualifiers(associations, prt=sys.stdout):
"""Print Qualifiers found in the annotations.
QUALIFIERS:
1,462 colocalizes_with
1,454 contributes_to
1,157 not
13 not colocalizes_with (TBD: CHK - Seen in gene2go, but not gafs)
... | Print Qualifiers found in the annotations.
QUALIFIERS:
1,462 colocalizes_with
1,454 contributes_to
1,157 not
13 not colocalizes_with (TBD: CHK - Seen in gene2go, but not gafs)
4 not contributes_to (TBD: CHK - Seen in... | Below is the the instruction that describes the task:
### Input:
Print Qualifiers found in the annotations.
QUALIFIERS:
1,462 colocalizes_with
1,454 contributes_to
1,157 not
13 not colocalizes_with (TBD: CHK - Seen in gene2go, but not g... |
def _compute_site_scaling(self, C, vs30):
"""
Returns the site scaling term as a simple coefficient
"""
site_term = np.zeros(len(vs30), dtype=float)
# For soil sites add on the site coefficient
site_term[vs30 < 760.0] = C["e"]
return site_term | Returns the site scaling term as a simple coefficient | Below is the the instruction that describes the task:
### Input:
Returns the site scaling term as a simple coefficient
### Response:
def _compute_site_scaling(self, C, vs30):
"""
Returns the site scaling term as a simple coefficient
"""
site_term = np.zeros(len(vs30), dtype=float)
... |
def sort(self):
"""
Sort the fragments in the list.
:raises ValueError: if there is a fragment which violates
the list constraints
"""
if self.is_guaranteed_sorted:
self.log(u"Already sorted, returning")
return
self.log... | Sort the fragments in the list.
:raises ValueError: if there is a fragment which violates
the list constraints | Below is the the instruction that describes the task:
### Input:
Sort the fragments in the list.
:raises ValueError: if there is a fragment which violates
the list constraints
### Response:
def sort(self):
"""
Sort the fragments in the list.
:raises Val... |
def import_field(field_classpath):
"""
Imports a field by its dotted class path, prepending "django.db.models"
to raw class names and raising an exception if the import fails.
"""
if '.' in field_classpath:
fully_qualified = field_classpath
else:
fully_qualified = "django.db.mode... | Imports a field by its dotted class path, prepending "django.db.models"
to raw class names and raising an exception if the import fails. | Below is the the instruction that describes the task:
### Input:
Imports a field by its dotted class path, prepending "django.db.models"
to raw class names and raising an exception if the import fails.
### Response:
def import_field(field_classpath):
"""
Imports a field by its dotted class path, prepen... |
def columns(x, rho, proxop):
"""Applies a proximal operator to the columns of a matrix"""
xnext = np.zeros_like(x)
for ix in range(x.shape[1]):
xnext[:, ix] = proxop(x[:, ix], rho)
return xnext | Applies a proximal operator to the columns of a matrix | Below is the the instruction that describes the task:
### Input:
Applies a proximal operator to the columns of a matrix
### Response:
def columns(x, rho, proxop):
"""Applies a proximal operator to the columns of a matrix"""
xnext = np.zeros_like(x)
for ix in range(x.shape[1]):
xnext[:, ix] = ... |
def read(self):
"""Iterate over all JSON input (Generator)"""
for line in self.io.read():
with self.parse_line(line) as j:
yield j | Iterate over all JSON input (Generator) | Below is the the instruction that describes the task:
### Input:
Iterate over all JSON input (Generator)
### Response:
def read(self):
"""Iterate over all JSON input (Generator)"""
for line in self.io.read():
with self.parse_line(line) as j:
yield j |
def check_hash(path, checksum, hash_type='md5'):
"""Validate a file using a cryptographic checksum.
:param str checksum: Value of the checksum used to validate the file.
:param str hash_type: Hash algorithm used to generate `checksum`.
Can be any hash alrgorithm supported by :mod:`hashlib`,
... | Validate a file using a cryptographic checksum.
:param str checksum: Value of the checksum used to validate the file.
:param str hash_type: Hash algorithm used to generate `checksum`.
Can be any hash alrgorithm supported by :mod:`hashlib`,
such as md5, sha1, sha256, sha512, etc.
:raises Che... | Below is the the instruction that describes the task:
### Input:
Validate a file using a cryptographic checksum.
:param str checksum: Value of the checksum used to validate the file.
:param str hash_type: Hash algorithm used to generate `checksum`.
Can be any hash alrgorithm supported by :mod:`hash... |
def get_consensus_module(module_name):
"""Returns a consensus module by name.
Args:
module_name (str): The name of the module to load.
Returns:
module: The consensus module.
Raises:
UnknownConsensusModuleError: Raised if the given module_name does
... | Returns a consensus module by name.
Args:
module_name (str): The name of the module to load.
Returns:
module: The consensus module.
Raises:
UnknownConsensusModuleError: Raised if the given module_name does
not correspond to a consensus imple... | Below is the the instruction that describes the task:
### Input:
Returns a consensus module by name.
Args:
module_name (str): The name of the module to load.
Returns:
module: The consensus module.
Raises:
UnknownConsensusModuleError: Raised if the given... |
def get_current_and_head_revision(
database_url: str,
alembic_config_filename: str,
alembic_base_dir: str = None,
version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> Tuple[str, str]:
"""
Returns a tuple of ``(current_revision, head_revision)``; see
:func:`get_current_revis... | Returns a tuple of ``(current_revision, head_revision)``; see
:func:`get_current_revision` and :func:`get_head_revision_from_alembic`.
Arguments:
database_url: SQLAlchemy URL for the database
alembic_config_filename: config filename
alembic_base_dir: directory to start in, so relative p... | Below is the the instruction that describes the task:
### Input:
Returns a tuple of ``(current_revision, head_revision)``; see
:func:`get_current_revision` and :func:`get_head_revision_from_alembic`.
Arguments:
database_url: SQLAlchemy URL for the database
alembic_config_filename: config fi... |
def assert_valid(sysmeta_pyxb, pid):
"""Validate file at {sciobj_path} against schema selected via formatId and raise
InvalidRequest if invalid.
Validation is only performed when:
- SciMeta validation is enabled
- and Object size is below size limit for validation
- and formatId designates obj... | Validate file at {sciobj_path} against schema selected via formatId and raise
InvalidRequest if invalid.
Validation is only performed when:
- SciMeta validation is enabled
- and Object size is below size limit for validation
- and formatId designates object as a Science Metadata object which is re... | Below is the the instruction that describes the task:
### Input:
Validate file at {sciobj_path} against schema selected via formatId and raise
InvalidRequest if invalid.
Validation is only performed when:
- SciMeta validation is enabled
- and Object size is below size limit for validation
- an... |
def get_node_label(self, model):
"""
Defines how labels are constructed from models.
Default - uses verbose name, lines breaks where sensible
"""
if model.is_proxy:
label = "(P) %s" % (model.name.title())
else:
label = "%s" % (model.name.title())
... | Defines how labels are constructed from models.
Default - uses verbose name, lines breaks where sensible | Below is the the instruction that describes the task:
### Input:
Defines how labels are constructed from models.
Default - uses verbose name, lines breaks where sensible
### Response:
def get_node_label(self, model):
"""
Defines how labels are constructed from models.
Default - uses... |
def a_unexpected_prompt(ctx):
"""Provide message when received humphost prompt."""
prompt = ctx.ctrl.match.group(0)
ctx.msg = "Received the jump host prompt: '{}'".format(prompt)
ctx.device.connected = False
ctx.finished = True
raise ConnectionError("Unable to connect to the device.", ctx.ctrl.h... | Provide message when received humphost prompt. | Below is the the instruction that describes the task:
### Input:
Provide message when received humphost prompt.
### Response:
def a_unexpected_prompt(ctx):
"""Provide message when received humphost prompt."""
prompt = ctx.ctrl.match.group(0)
ctx.msg = "Received the jump host prompt: '{}'".format(prompt... |
def _generateAlias(self):
"""Return an unused auth level alias"""
for i in range(1000):
alias = 'cust%d' % (i, )
if alias not in self.auth_level_aliases:
return alias
raise RuntimeError('Could not find an unused alias (tried 1000!)') | Return an unused auth level alias | Below is the the instruction that describes the task:
### Input:
Return an unused auth level alias
### Response:
def _generateAlias(self):
"""Return an unused auth level alias"""
for i in range(1000):
alias = 'cust%d' % (i, )
if alias not in self.auth_level_aliases:
... |
def cumulative_min(self):
"""
Return the cumulative minimum value of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
minimum value of all the elements preceding and including it. The
SArray is expected to be of numeric type (int,... | Return the cumulative minimum value of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
minimum value of all the elements preceding and including it. The
SArray is expected to be of numeric type (int, float).
Returns
-------
... | Below is the the instruction that describes the task:
### Input:
Return the cumulative minimum value of the elements in the SArray.
Returns an SArray where each element in the output corresponds to the
minimum value of all the elements preceding and including it. The
SArray is expected to b... |
def on_commit(self, changes):
"""Method that gets called when a model is changed. This serves
to do the actual index writing.
"""
if _get_config(self)['enable_indexing'] is False:
return None
for wh in self.whoosheers:
if not wh.auto_update:
... | Method that gets called when a model is changed. This serves
to do the actual index writing. | Below is the the instruction that describes the task:
### Input:
Method that gets called when a model is changed. This serves
to do the actual index writing.
### Response:
def on_commit(self, changes):
"""Method that gets called when a model is changed. This serves
to do the actual index wr... |
def generate_parameters(self, parameter_id):
"""Returns a dict of trial (hyper-)parameters, as a serializable object.
Parameters
----------
parameter_id : int
Returns
-------
config : dict
"""
if not self.population:
raise Runtime... | Returns a dict of trial (hyper-)parameters, as a serializable object.
Parameters
----------
parameter_id : int
Returns
-------
config : dict | Below is the the instruction that describes the task:
### Input:
Returns a dict of trial (hyper-)parameters, as a serializable object.
Parameters
----------
parameter_id : int
Returns
-------
config : dict
### Response:
def generate_parameters(self, parameter_i... |
def lookup_facade(name, version):
"""
Given a facade name and version, attempt to pull that facade out
of the correct client<version>.py file.
"""
for _version in range(int(version), 0, -1):
try:
facade = getattr(CLIENTS[str(_version)], name)
return facade
ex... | Given a facade name and version, attempt to pull that facade out
of the correct client<version>.py file. | Below is the the instruction that describes the task:
### Input:
Given a facade name and version, attempt to pull that facade out
of the correct client<version>.py file.
### Response:
def lookup_facade(name, version):
"""
Given a facade name and version, attempt to pull that facade out
of the corre... |
def merge_record_data(self, changes, orig_record=None):
"""This method merges PATCH requests with the db record to ensure no
data is lost. In addition, it is also a hook for other fields to
be overwritten, to ensure immutable fields aren't changed by a
request."""
curren... | This method merges PATCH requests with the db record to ensure no
data is lost. In addition, it is also a hook for other fields to
be overwritten, to ensure immutable fields aren't changed by a
request. | Below is the the instruction that describes the task:
### Input:
This method merges PATCH requests with the db record to ensure no
data is lost. In addition, it is also a hook for other fields to
be overwritten, to ensure immutable fields aren't changed by a
request.
### Response:
... |
def _string_like(self, patterns):
"""
Wildcard fuzzy matching function equivalent to the SQL LIKE directive. Use
% as a multiple-character wildcard or _ (underscore) as a single-character
wildcard.
Use re_search or rlike for regex-based matching.
Parameters
----------
pattern : str or ... | Wildcard fuzzy matching function equivalent to the SQL LIKE directive. Use
% as a multiple-character wildcard or _ (underscore) as a single-character
wildcard.
Use re_search or rlike for regex-based matching.
Parameters
----------
pattern : str or List[str]
A pattern or list of pattern... | Below is the the instruction that describes the task:
### Input:
Wildcard fuzzy matching function equivalent to the SQL LIKE directive. Use
% as a multiple-character wildcard or _ (underscore) as a single-character
wildcard.
Use re_search or rlike for regex-based matching.
Parameters
---------... |
def update_file(self, file_id, upload_id):
"""
Send PUT request to /files/{file_id} to update the file contents to upload_id and sets a label.
:param file_id: str uuid of file
:param upload_id: str uuid of the upload where all the file chunks where uploaded
:param label: str shor... | Send PUT request to /files/{file_id} to update the file contents to upload_id and sets a label.
:param file_id: str uuid of file
:param upload_id: str uuid of the upload where all the file chunks where uploaded
:param label: str short display label for the file
:return: requests.Response... | Below is the the instruction that describes the task:
### Input:
Send PUT request to /files/{file_id} to update the file contents to upload_id and sets a label.
:param file_id: str uuid of file
:param upload_id: str uuid of the upload where all the file chunks where uploaded
:param label: st... |
def fix_e125(self, result):
"""Fix indentation undistinguish from the next logical line."""
num_indent_spaces = int(result['info'].split()[1])
line_index = result['line'] - 1
target = self.source[line_index]
spaces_to_add = num_indent_spaces - len(_get_indentation(target))
... | Fix indentation undistinguish from the next logical line. | Below is the the instruction that describes the task:
### Input:
Fix indentation undistinguish from the next logical line.
### Response:
def fix_e125(self, result):
"""Fix indentation undistinguish from the next logical line."""
num_indent_spaces = int(result['info'].split()[1])
line_index ... |
def global_iterator(self):
"""
Return global iterator sympy expression
"""
global_iterator = sympy.Integer(0)
total_length = sympy.Integer(1)
for var_name, start, end, incr in reversed(self._loop_stack):
loop_var = symbol_pos_int(var_name)
length =... | Return global iterator sympy expression | Below is the the instruction that describes the task:
### Input:
Return global iterator sympy expression
### Response:
def global_iterator(self):
"""
Return global iterator sympy expression
"""
global_iterator = sympy.Integer(0)
total_length = sympy.Integer(1)
for va... |
def getImportPeople(self):
"""
Return an L{ImportPeopleWidget} which is a child of this fragment and
which will add people to C{self.organizer}.
"""
fragment = ImportPeopleWidget(self.organizer)
fragment.setFragmentParent(self)
return fragment | Return an L{ImportPeopleWidget} which is a child of this fragment and
which will add people to C{self.organizer}. | Below is the the instruction that describes the task:
### Input:
Return an L{ImportPeopleWidget} which is a child of this fragment and
which will add people to C{self.organizer}.
### Response:
def getImportPeople(self):
"""
Return an L{ImportPeopleWidget} which is a child of this fragment a... |
def render(self, treewalker, encoding=None):
"""Serializes the stream from the treewalker into a string
:arg treewalker: the treewalker to serialize
:arg encoding: the string encoding to use
:returns: the serialized tree
Example:
>>> from html5lib import parse, getTr... | Serializes the stream from the treewalker into a string
:arg treewalker: the treewalker to serialize
:arg encoding: the string encoding to use
:returns: the serialized tree
Example:
>>> from html5lib import parse, getTreeWalker
>>> from html5lib.serializer import HTM... | Below is the the instruction that describes the task:
### Input:
Serializes the stream from the treewalker into a string
:arg treewalker: the treewalker to serialize
:arg encoding: the string encoding to use
:returns: the serialized tree
Example:
>>> from html5lib import... |
def make_relative (self, other):
"""Return a new path that is the equivalent of this one relative to the path
*other*. Unlike :meth:`relative_to`, this will not throw an error if *self* is
not a sub-path of *other*; instead, it will use ``..`` to build a relative
path. This can result in... | Return a new path that is the equivalent of this one relative to the path
*other*. Unlike :meth:`relative_to`, this will not throw an error if *self* is
not a sub-path of *other*; instead, it will use ``..`` to build a relative
path. This can result in invalid relative paths if *other* contains ... | Below is the the instruction that describes the task:
### Input:
Return a new path that is the equivalent of this one relative to the path
*other*. Unlike :meth:`relative_to`, this will not throw an error if *self* is
not a sub-path of *other*; instead, it will use ``..`` to build a relative
... |
def extract_from_image(self, image):
"""
Extract the image pixels within the polygon.
This function will zero-pad the image if the polygon is partially/fully outside of
the image.
Parameters
----------
image : (H,W) ndarray or (H,W,C) ndarray
The ima... | Extract the image pixels within the polygon.
This function will zero-pad the image if the polygon is partially/fully outside of
the image.
Parameters
----------
image : (H,W) ndarray or (H,W,C) ndarray
The image from which to extract the pixels within the polygon.
... | Below is the the instruction that describes the task:
### Input:
Extract the image pixels within the polygon.
This function will zero-pad the image if the polygon is partially/fully outside of
the image.
Parameters
----------
image : (H,W) ndarray or (H,W,C) ndarray
... |
def as_list(value):
"""clever string spliting:
.. code-block:: python
>>> print(as_list('value'))
['value']
>>> print(as_list('v1 v2'))
['v1', 'v2']
>>> print(as_list(None))
[]
>>> print(as_list(['v1']))
['v1']
"""
if isinstance(value, (l... | clever string spliting:
.. code-block:: python
>>> print(as_list('value'))
['value']
>>> print(as_list('v1 v2'))
['v1', 'v2']
>>> print(as_list(None))
[]
>>> print(as_list(['v1']))
['v1'] | Below is the the instruction that describes the task:
### Input:
clever string spliting:
.. code-block:: python
>>> print(as_list('value'))
['value']
>>> print(as_list('v1 v2'))
['v1', 'v2']
>>> print(as_list(None))
[]
>>> print(as_list(['v1']))
... |
def _Rforce(self,R,z,phi=0.,t=0.):
"""
NAME:
Rforce
PURPOSE:
evaluate radial force K_R (R,z)
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
K_R (R,z)
... | NAME:
Rforce
PURPOSE:
evaluate radial force K_R (R,z)
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
K_R (R,z)
HISTORY:
2010-04-16 - Written - Bovy (N... | Below is the the instruction that describes the task:
### Input:
NAME:
Rforce
PURPOSE:
evaluate radial force K_R (R,z)
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
... |
def required(self, fn):
"""Request decorator. Forces authentication."""
@functools.wraps(fn)
def decorated(*args, **kwargs):
if (not self._check_auth()
# Don't try to force authentication if the request is part
# of the authentication process - otherwise... | Request decorator. Forces authentication. | Below is the the instruction that describes the task:
### Input:
Request decorator. Forces authentication.
### Response:
def required(self, fn):
"""Request decorator. Forces authentication."""
@functools.wraps(fn)
def decorated(*args, **kwargs):
if (not self._check_auth()
... |
def DocFileSuite(*paths, **kw):
"""A unittest suite for one or more doctest files.
The path to each doctest file is given as a string; the
interpretation of that string depends on the keyword argument
"module_relative".
A number of options may be provided as keyword arguments:
module_relative... | A unittest suite for one or more doctest files.
The path to each doctest file is given as a string; the
interpretation of that string depends on the keyword argument
"module_relative".
A number of options may be provided as keyword arguments:
module_relative
If "module_relative" is True, th... | Below is the the instruction that describes the task:
### Input:
A unittest suite for one or more doctest files.
The path to each doctest file is given as a string; the
interpretation of that string depends on the keyword argument
"module_relative".
A number of options may be provided as keyword a... |
def parse_skip_comment(self):
"""Parse a definition comment for noqa skips."""
skipped_error_codes = ''
if self.current.kind == tk.COMMENT:
if 'noqa: ' in self.current.value:
skipped_error_codes = ''.join(
self.current.value.split('noqa: ')[1:])
... | Parse a definition comment for noqa skips. | Below is the the instruction that describes the task:
### Input:
Parse a definition comment for noqa skips.
### Response:
def parse_skip_comment(self):
"""Parse a definition comment for noqa skips."""
skipped_error_codes = ''
if self.current.kind == tk.COMMENT:
if 'noqa: ' in se... |
def up(self, role, root_priority, root_times):
""" A port is started in the state of LISTEN. """
self.port_priority = root_priority
self.port_times = root_times
state = (PORT_STATE_LISTEN if self.config_enable
else PORT_STATE_DISABLE)
self._change_role(role)
... | A port is started in the state of LISTEN. | Below is the the instruction that describes the task:
### Input:
A port is started in the state of LISTEN.
### Response:
def up(self, role, root_priority, root_times):
""" A port is started in the state of LISTEN. """
self.port_priority = root_priority
self.port_times = root_times
... |
def set_joystick(self, x, y, n):
"""
Receives joystick values from the SnakeBoard
x,y Coordinates
n Robot number to give it to
"""
self.robots[n].set_joystick(x, y) | Receives joystick values from the SnakeBoard
x,y Coordinates
n Robot number to give it to | Below is the the instruction that describes the task:
### Input:
Receives joystick values from the SnakeBoard
x,y Coordinates
n Robot number to give it to
### Response:
def set_joystick(self, x, y, n):
"""
Receives joystick values from the SnakeB... |
def add_station(self, lv_station):
"""Adds a LV station to _station and grid graph if not already existing"""
if not isinstance(lv_station, LVStationDing0):
raise Exception('Given LV station is not a LVStationDing0 object.')
if self._station is None:
self._station = lv_st... | Adds a LV station to _station and grid graph if not already existing | Below is the the instruction that describes the task:
### Input:
Adds a LV station to _station and grid graph if not already existing
### Response:
def add_station(self, lv_station):
"""Adds a LV station to _station and grid graph if not already existing"""
if not isinstance(lv_station, LVStationDi... |
def get_queryset(self):
'''
Parameters are already validated in the QuerySetPermission
'''
model_type = self.request.GET.get("type")
pk = self.request.GET.get("id")
content_type_model = ContentType.objects.get(model=model_type.lower())
Model = content_type_model.m... | Parameters are already validated in the QuerySetPermission | Below is the the instruction that describes the task:
### Input:
Parameters are already validated in the QuerySetPermission
### Response:
def get_queryset(self):
'''
Parameters are already validated in the QuerySetPermission
'''
model_type = self.request.GET.get("type")
pk =... |
def getColRowWithinChannel(self, ra, dec, ch, wantZeroOffset=False,
allowIllegalReturnValues=True):
"""Returns (col, row) given a (ra, dec) coordinate and channel number.
"""
# How close is a given ra/dec to the origin of a KeplerModule?
x, y = self.default... | Returns (col, row) given a (ra, dec) coordinate and channel number. | Below is the the instruction that describes the task:
### Input:
Returns (col, row) given a (ra, dec) coordinate and channel number.
### Response:
def getColRowWithinChannel(self, ra, dec, ch, wantZeroOffset=False,
allowIllegalReturnValues=True):
"""Returns (col, row) given a... |
def to_text(path):
"""Wraps Tesseract OCR.
Parameters
----------
path : str
path of electronic invoice in JPG or PNG format
Returns
-------
extracted_str : str
returns extracted text from image in JPG or PNG format
"""
import subprocess
from distutils import sp... | Wraps Tesseract OCR.
Parameters
----------
path : str
path of electronic invoice in JPG or PNG format
Returns
-------
extracted_str : str
returns extracted text from image in JPG or PNG format | Below is the the instruction that describes the task:
### Input:
Wraps Tesseract OCR.
Parameters
----------
path : str
path of electronic invoice in JPG or PNG format
Returns
-------
extracted_str : str
returns extracted text from image in JPG or PNG format
### Response:
d... |
def cells(self) -> Generator[Tuple[int, int], None, None]:
"""Generate cells in span."""
yield from itertools.product(
range(self.row_start, self.row_end),
range(self.column_start, self.column_end)
) | Generate cells in span. | Below is the the instruction that describes the task:
### Input:
Generate cells in span.
### Response:
def cells(self) -> Generator[Tuple[int, int], None, None]:
"""Generate cells in span."""
yield from itertools.product(
range(self.row_start, self.row_end),
range(self.colum... |
def contract(self, jobs, result):
"""
Perform a contract on a number of jobs and block until a result is
retrieved for each job.
"""
for j in jobs:
WorkerPool.put(self, j)
r = []
for i in xrange(len(jobs)):
r.append(result.get())
... | Perform a contract on a number of jobs and block until a result is
retrieved for each job. | Below is the the instruction that describes the task:
### Input:
Perform a contract on a number of jobs and block until a result is
retrieved for each job.
### Response:
def contract(self, jobs, result):
"""
Perform a contract on a number of jobs and block until a result is
retrieve... |
def get_authservers(self, domainid, page=None):
"""Get Authentication servers"""
opts = {}
if page:
opts['page'] = page
return self.api_call(
ENDPOINTS['authservers']['list'],
dict(domainid=domainid), **opts) | Get Authentication servers | Below is the the instruction that describes the task:
### Input:
Get Authentication servers
### Response:
def get_authservers(self, domainid, page=None):
"""Get Authentication servers"""
opts = {}
if page:
opts['page'] = page
return self.api_call(
ENDPOINTS['... |
def create_ref(self, ref, sha):
"""Create a reference in this repository.
:param str ref: (required), fully qualified name of the reference,
e.g. ``refs/heads/master``. If it doesn't start with ``refs`` and
contain at least two slashes, GitHub's API will reject it.
:para... | Create a reference in this repository.
:param str ref: (required), fully qualified name of the reference,
e.g. ``refs/heads/master``. If it doesn't start with ``refs`` and
contain at least two slashes, GitHub's API will reject it.
:param str sha: (required), SHA1 value to set th... | Below is the the instruction that describes the task:
### Input:
Create a reference in this repository.
:param str ref: (required), fully qualified name of the reference,
e.g. ``refs/heads/master``. If it doesn't start with ``refs`` and
contain at least two slashes, GitHub's API wil... |
def ping():
'''
Is the marathon api responding?
'''
try:
response = salt.utils.http.query(
"{0}/ping".format(CONFIG[CONFIG_BASE_URL]),
decode_type='plain',
decode=True,
)
log.debug(
'marathon.info returned successfully: %s',
... | Is the marathon api responding? | Below is the the instruction that describes the task:
### Input:
Is the marathon api responding?
### Response:
def ping():
'''
Is the marathon api responding?
'''
try:
response = salt.utils.http.query(
"{0}/ping".format(CONFIG[CONFIG_BASE_URL]),
decode_type='plain',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.