code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def check_filter(self, args, kwargs):
"""
Calls all filters in the :attr:`_filters` list and if all of them
return :const:`True` will return :const:`True`. If any of the filters
return :const:`False` will return :const:`True` instead.
This method is equal to the following snippe... | Calls all filters in the :attr:`_filters` list and if all of them
return :const:`True` will return :const:`True`. If any of the filters
return :const:`False` will return :const:`True` instead.
This method is equal to the following snippet:
`all(f(*args, **kwargs) for f in self.filte... | Below is the the instruction that describes the task:
### Input:
Calls all filters in the :attr:`_filters` list and if all of them
return :const:`True` will return :const:`True`. If any of the filters
return :const:`False` will return :const:`True` instead.
This method is equal to the follo... |
def render_tag(self, context, kwargs, nodelist):
'''render content with "active" urls logic'''
# load configuration from passed options
self.load_configuration(**kwargs)
# get request from context
request = context['request']
# get full path from request
self.fu... | render content with "active" urls logic | Below is the the instruction that describes the task:
### Input:
render content with "active" urls logic
### Response:
def render_tag(self, context, kwargs, nodelist):
'''render content with "active" urls logic'''
# load configuration from passed options
self.load_configuration(**kwargs)
... |
def is_callable(val):
"""
Checks whether a variable is a callable, e.g. a function.
Parameters
----------
val
The variable to check.
Returns
-------
bool
True if the variable is a callable. Otherwise False.
"""
# python 3.x with x <= 2 does not support callable... | Checks whether a variable is a callable, e.g. a function.
Parameters
----------
val
The variable to check.
Returns
-------
bool
True if the variable is a callable. Otherwise False. | Below is the the instruction that describes the task:
### Input:
Checks whether a variable is a callable, e.g. a function.
Parameters
----------
val
The variable to check.
Returns
-------
bool
True if the variable is a callable. Otherwise False.
### Response:
def is_callab... |
def _compute_iso_color(self):
""" compute LineVisual color from level index and corresponding level
color
"""
level_color = []
colors = self._lc
for i, index in enumerate(self._li):
level_color.append(np.zeros((index, 4)) + colors[i])
self._cl = np.vst... | compute LineVisual color from level index and corresponding level
color | Below is the the instruction that describes the task:
### Input:
compute LineVisual color from level index and corresponding level
color
### Response:
def _compute_iso_color(self):
""" compute LineVisual color from level index and corresponding level
color
"""
level_color = ... |
def install(self, plugin, name=None, **opts):
"""Install plugin to the application."""
source = plugin
if isinstance(plugin, str):
module, _, attr = plugin.partition(':')
module = import_module(module)
plugin = getattr(module, attr or 'Plugin', None)
... | Install plugin to the application. | Below is the the instruction that describes the task:
### Input:
Install plugin to the application.
### Response:
def install(self, plugin, name=None, **opts):
"""Install plugin to the application."""
source = plugin
if isinstance(plugin, str):
module, _, attr = plugin.partitio... |
def update_done(self, *args, **kwargs):
"""Clear out the previous update"""
kwargs['state'] = 'done'
self.update(*args, **kwargs)
self.rec = None | Clear out the previous update | Below is the the instruction that describes the task:
### Input:
Clear out the previous update
### Response:
def update_done(self, *args, **kwargs):
"""Clear out the previous update"""
kwargs['state'] = 'done'
self.update(*args, **kwargs)
self.rec = None |
def closeGlyphsOverGSUB(gsub, glyphs):
""" Use the FontTools subsetter to perform a closure over the GSUB table
given the initial `glyphs` (set of glyph names, str). Update the set
in-place adding all the glyph names that can be reached via GSUB
substitutions from this initial set.
"""
subsetter... | Use the FontTools subsetter to perform a closure over the GSUB table
given the initial `glyphs` (set of glyph names, str). Update the set
in-place adding all the glyph names that can be reached via GSUB
substitutions from this initial set. | Below is the the instruction that describes the task:
### Input:
Use the FontTools subsetter to perform a closure over the GSUB table
given the initial `glyphs` (set of glyph names, str). Update the set
in-place adding all the glyph names that can be reached via GSUB
substitutions from this initial set.... |
def call(self, service, method, *args, **kwargs):
"""Make a SoftLayer API call.
:param method: the method to call on the service
:param \\*args: (optional) arguments for the remote call
:param id: (optional) id for the resource
:param mask: (optional) object mask
:param ... | Make a SoftLayer API call.
:param method: the method to call on the service
:param \\*args: (optional) arguments for the remote call
:param id: (optional) id for the resource
:param mask: (optional) object mask
:param dict filter: (optional) filter dict
:param dict heade... | Below is the the instruction that describes the task:
### Input:
Make a SoftLayer API call.
:param method: the method to call on the service
:param \\*args: (optional) arguments for the remote call
:param id: (optional) id for the resource
:param mask: (optional) object mask
... |
def includes(self, lo_freq: float) -> bool:
"""Whether `lo_freq` is within the `LoRange`.
Args:
lo_freq: LO frequency to be checked
Returns:
bool: True if lo_freq is included in this range, otherwise False
"""
if self._lb <= lo_freq <= self._ub:
... | Whether `lo_freq` is within the `LoRange`.
Args:
lo_freq: LO frequency to be checked
Returns:
bool: True if lo_freq is included in this range, otherwise False | Below is the the instruction that describes the task:
### Input:
Whether `lo_freq` is within the `LoRange`.
Args:
lo_freq: LO frequency to be checked
Returns:
bool: True if lo_freq is included in this range, otherwise False
### Response:
def includes(self, lo_freq: float) ... |
def _init_settings(self):
""" Init setting """
self._show_whitespaces = False
self._tab_length = 4
self._use_spaces_instead_of_tabs = True
self.setTabStopWidth(self._tab_length *
self.fontMetrics().width(" "))
self._set_whitespaces_flags(self.... | Init setting | Below is the the instruction that describes the task:
### Input:
Init setting
### Response:
def _init_settings(self):
""" Init setting """
self._show_whitespaces = False
self._tab_length = 4
self._use_spaces_instead_of_tabs = True
self.setTabStopWidth(self._tab_length *
... |
def find_path(self, test_function=None, on_targets=False):
"""
General helper method that iterates breadth-first over the referential_domain's
cells and returns a path where the test_function is True
"""
assert self.has_referential_domain(), "need context set"
if not tes... | General helper method that iterates breadth-first over the referential_domain's
cells and returns a path where the test_function is True | Below is the the instruction that describes the task:
### Input:
General helper method that iterates breadth-first over the referential_domain's
cells and returns a path where the test_function is True
### Response:
def find_path(self, test_function=None, on_targets=False):
"""
General help... |
def ttl(self):
"""LeaseTimeToLive retrieves lease information.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
:return:
"""
result = sel... | LeaseTimeToLive retrieves lease information.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
:return: | Below is the the instruction that describes the task:
### Input:
LeaseTimeToLive retrieves lease information.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
... |
def detach_user_policy(policy_name, user_name,
region=None, key=None, keyid=None, profile=None):
'''
Detach a managed policy to a user.
CLI Example:
.. code-block:: bash
salt myminion boto_iam.detach_user_policy mypolicy myuser
'''
conn = _get_conn(region=region, key... | Detach a managed policy to a user.
CLI Example:
.. code-block:: bash
salt myminion boto_iam.detach_user_policy mypolicy myuser | Below is the the instruction that describes the task:
### Input:
Detach a managed policy to a user.
CLI Example:
.. code-block:: bash
salt myminion boto_iam.detach_user_policy mypolicy myuser
### Response:
def detach_user_policy(policy_name, user_name,
region=None, key=None, ke... |
def get_available_networks(self, **kwargs):
"""
Retrieves the list of Ethernet networks, Fibre Channel networks and network sets that are available
to a server profile template along with their respective ports. The scopeUris, serverHardwareTypeUri and
enclosureGroupUri parameters should... | Retrieves the list of Ethernet networks, Fibre Channel networks and network sets that are available
to a server profile template along with their respective ports. The scopeUris, serverHardwareTypeUri and
enclosureGroupUri parameters should be specified to get the available networks for a new server pro... | Below is the the instruction that describes the task:
### Input:
Retrieves the list of Ethernet networks, Fibre Channel networks and network sets that are available
to a server profile template along with their respective ports. The scopeUris, serverHardwareTypeUri and
enclosureGroupUri parameters s... |
def update_product_set(
self,
product_set,
location=None,
product_set_id=None,
update_mask=None,
project_id=None,
retry=None,
timeout=None,
metadata=None,
):
"""
For the documentation see:
:class:`~airflow.contrib.operat... | For the documentation see:
:class:`~airflow.contrib.operators.gcp_vision_operator.CloudVisionProductSetUpdateOperator` | Below is the the instruction that describes the task:
### Input:
For the documentation see:
:class:`~airflow.contrib.operators.gcp_vision_operator.CloudVisionProductSetUpdateOperator`
### Response:
def update_product_set(
self,
product_set,
location=None,
product_set_id=None... |
def updates(self, offset=None):
"""Fetch the messages that a bot can read.
When the `offset` is given it will retrieve all the messages
that are greater or equal to that offset. Take into account
that, due to how the API works, all previous messages will
be removed from the serv... | Fetch the messages that a bot can read.
When the `offset` is given it will retrieve all the messages
that are greater or equal to that offset. Take into account
that, due to how the API works, all previous messages will
be removed from the server.
:param offset: fetch the messa... | Below is the the instruction that describes the task:
### Input:
Fetch the messages that a bot can read.
When the `offset` is given it will retrieve all the messages
that are greater or equal to that offset. Take into account
that, due to how the API works, all previous messages will
... |
def list(self):
"""
Get all current labels
:return: The Logentries API response
:rtype: list of dict
:raises: This will raise a
:class:`ServerException<logentries_api.exceptions.ServerException>`
if there is an error from Logentries
"""
r... | Get all current labels
:return: The Logentries API response
:rtype: list of dict
:raises: This will raise a
:class:`ServerException<logentries_api.exceptions.ServerException>`
if there is an error from Logentries | Below is the the instruction that describes the task:
### Input:
Get all current labels
:return: The Logentries API response
:rtype: list of dict
:raises: This will raise a
:class:`ServerException<logentries_api.exceptions.ServerException>`
if there is an error from... |
def run_sweep(
self,
program: Union[circuits.Circuit, schedules.Schedule],
params: study.Sweepable,
repetitions: int = 1,
) -> List[study.TrialResult]:
"""Runs the supplied Circuit or Schedule, mimicking quantum hardware.
In contrast to run, this allows for sweeping ... | Runs the supplied Circuit or Schedule, mimicking quantum hardware.
In contrast to run, this allows for sweeping over different parameter
values.
Args:
program: The circuit or schedule to simulate.
params: Parameters to run with the program.
repetitions: The ... | Below is the the instruction that describes the task:
### Input:
Runs the supplied Circuit or Schedule, mimicking quantum hardware.
In contrast to run, this allows for sweeping over different parameter
values.
Args:
program: The circuit or schedule to simulate.
para... |
def previous_day(self):
"""Return the HDate for the previous day."""
return HDate(self.gdate + datetime.timedelta(-1), self.diaspora,
self.hebrew) | Return the HDate for the previous day. | Below is the the instruction that describes the task:
### Input:
Return the HDate for the previous day.
### Response:
def previous_day(self):
"""Return the HDate for the previous day."""
return HDate(self.gdate + datetime.timedelta(-1), self.diaspora,
self.hebrew) |
def _construct_node_from_actions(self,
current_node: Tree,
remaining_actions: List[List[str]]) -> List[List[str]]:
"""
Given a current node in the logical form tree, and a list of actions in an action sequence,
this method... | Given a current node in the logical form tree, and a list of actions in an action sequence,
this method fills in the children of the current node from the action sequence, then
returns whatever actions are left.
For example, we could get a node with type ``c``, and an action sequence that begin... | Below is the the instruction that describes the task:
### Input:
Given a current node in the logical form tree, and a list of actions in an action sequence,
this method fills in the children of the current node from the action sequence, then
returns whatever actions are left.
For example, w... |
def SymmetricDifference(self, scriptnames):
'''Takes in a set, list, or tuple scriptnames and returns the symmetric difference (as a list)
of scriptnames and the stored names.'''
scriptnames = set(scriptnames)
myscripts = set(self.scripts.keys())
return list(scriptnames.difference(myscripts).union(myscripts.d... | Takes in a set, list, or tuple scriptnames and returns the symmetric difference (as a list)
of scriptnames and the stored names. | Below is the the instruction that describes the task:
### Input:
Takes in a set, list, or tuple scriptnames and returns the symmetric difference (as a list)
of scriptnames and the stored names.
### Response:
def SymmetricDifference(self, scriptnames):
'''Takes in a set, list, or tuple scriptnames and returns t... |
def update_local_repo(self, force=False):
"""Given a remote path (e.g. github.com/gamechanger/gclib), pull the latest
commits from master to bring the local copy up to date."""
self.ensure_local_repo()
logging.info('Updating local repo {}'.format(self.remote_path))
managed_repo... | Given a remote path (e.g. github.com/gamechanger/gclib), pull the latest
commits from master to bring the local copy up to date. | Below is the the instruction that describes the task:
### Input:
Given a remote path (e.g. github.com/gamechanger/gclib), pull the latest
commits from master to bring the local copy up to date.
### Response:
def update_local_repo(self, force=False):
"""Given a remote path (e.g. github.com/gamechang... |
def _number_negative_start_handler(c, ctx):
"""Handles numeric values that start with a negative sign. Branches to delegate co-routines according to
_NEGATIVE_TABLE.
"""
assert c == _MINUS
assert len(ctx.value) == 0
ctx.set_ion_type(IonType.INT)
ctx.value.append(c)
c, _ = yield
yield... | Handles numeric values that start with a negative sign. Branches to delegate co-routines according to
_NEGATIVE_TABLE. | Below is the the instruction that describes the task:
### Input:
Handles numeric values that start with a negative sign. Branches to delegate co-routines according to
_NEGATIVE_TABLE.
### Response:
def _number_negative_start_handler(c, ctx):
"""Handles numeric values that start with a negative sign. Branch... |
def from_timestamp_pb(cls, stamp):
"""Parse RFC 3339-compliant timestamp, preserving nanoseconds.
Args:
stamp (:class:`~google.protobuf.timestamp_pb2.Timestamp`): timestamp message
Returns:
:class:`DatetimeWithNanoseconds`:
an instance matching the times... | Parse RFC 3339-compliant timestamp, preserving nanoseconds.
Args:
stamp (:class:`~google.protobuf.timestamp_pb2.Timestamp`): timestamp message
Returns:
:class:`DatetimeWithNanoseconds`:
an instance matching the timestamp message | Below is the the instruction that describes the task:
### Input:
Parse RFC 3339-compliant timestamp, preserving nanoseconds.
Args:
stamp (:class:`~google.protobuf.timestamp_pb2.Timestamp`): timestamp message
Returns:
:class:`DatetimeWithNanoseconds`:
an inst... |
def projects_from_metadata(metadata):
"""Extract the project dependencies from a metadata spec."""
projects = []
for data in metadata:
meta = distlib.metadata.Metadata(fileobj=io.StringIO(data))
projects.extend(pypi.just_name(project) for project in meta.run_requires)
return frozenset(ma... | Extract the project dependencies from a metadata spec. | Below is the the instruction that describes the task:
### Input:
Extract the project dependencies from a metadata spec.
### Response:
def projects_from_metadata(metadata):
"""Extract the project dependencies from a metadata spec."""
projects = []
for data in metadata:
meta = distlib.metadata.Me... |
def PathCollection(mode="agg", *args, **kwargs):
"""
mode: string
- "raw" (speed: fastest, size: small, output: ugly, no dash,
no thickness)
- "agg" (speed: medium, size: medium output: nice, some flaws, no dash)
- "agg+" (speed: slow, size: big, output: perfect, no dash)... | mode: string
- "raw" (speed: fastest, size: small, output: ugly, no dash,
no thickness)
- "agg" (speed: medium, size: medium output: nice, some flaws, no dash)
- "agg+" (speed: slow, size: big, output: perfect, no dash) | Below is the the instruction that describes the task:
### Input:
mode: string
- "raw" (speed: fastest, size: small, output: ugly, no dash,
no thickness)
- "agg" (speed: medium, size: medium output: nice, some flaws, no dash)
- "agg+" (speed: slow, size: big, output: perfect, ... |
def get_next_assessment_part_id(self, assessment_part_id=None):
"""This supports the basic simple sequence case. Can be overriden in a record for other cases"""
if assessment_part_id is None:
part_id = self.get_id()
else:
part_id = assessment_part_id
return get_ne... | This supports the basic simple sequence case. Can be overriden in a record for other cases | Below is the the instruction that describes the task:
### Input:
This supports the basic simple sequence case. Can be overriden in a record for other cases
### Response:
def get_next_assessment_part_id(self, assessment_part_id=None):
"""This supports the basic simple sequence case. Can be overriden in a re... |
def gen_challenge(self, state):
"""This function generates a challenge for given state. It selects a
random number and sets that as the challenge key. By default, v_max
is set to the prime, and the number of chunks to challenge is the
number of chunks in the file. (this doesn't guaran... | This function generates a challenge for given state. It selects a
random number and sets that as the challenge key. By default, v_max
is set to the prime, and the number of chunks to challenge is the
number of chunks in the file. (this doesn't guarantee that the whole
file will be che... | Below is the the instruction that describes the task:
### Input:
This function generates a challenge for given state. It selects a
random number and sets that as the challenge key. By default, v_max
is set to the prime, and the number of chunks to challenge is the
number of chunks in the f... |
def _EntriesGenerator(self):
"""Retrieves directory entries.
Since a directory can contain a vast number of entries using
a generator is more memory efficient.
Yields:
FakePathSpec: a path specification.
"""
location = getattr(self.path_spec, 'location', None)
if location is not None... | Retrieves directory entries.
Since a directory can contain a vast number of entries using
a generator is more memory efficient.
Yields:
FakePathSpec: a path specification. | Below is the the instruction that describes the task:
### Input:
Retrieves directory entries.
Since a directory can contain a vast number of entries using
a generator is more memory efficient.
Yields:
FakePathSpec: a path specification.
### Response:
def _EntriesGenerator(self):
"""Retrieve... |
def _exclude_ss_bonded_cysteines(self):
"""
Pre-compute ss bonds to discard cystines for H-adding.
"""
ss_bonds = self.nh_structure.search_ss_bonds()
for cys_pair in ss_bonds:
cys1, cys2 = cys_pair
cys1.resname = 'CYX'
c... | Pre-compute ss bonds to discard cystines for H-adding. | Below is the the instruction that describes the task:
### Input:
Pre-compute ss bonds to discard cystines for H-adding.
### Response:
def _exclude_ss_bonded_cysteines(self):
"""
Pre-compute ss bonds to discard cystines for H-adding.
"""
ss_bonds = self.nh_structure.search_... |
def call_sphinx(out_type, build_dir = "build"):
"""
Call the ``sphinx-build`` for the given output type and the ``make`` when
the target has this possibility.
Parameters
----------
out_type :
A builder name for ``sphinx-build``. See the full list at
`<http://sphinx-doc.org/invocation.html>`_.
bui... | Call the ``sphinx-build`` for the given output type and the ``make`` when
the target has this possibility.
Parameters
----------
out_type :
A builder name for ``sphinx-build``. See the full list at
`<http://sphinx-doc.org/invocation.html>`_.
build_dir :
Directory for storing the output. Defaults ... | Below is the the instruction that describes the task:
### Input:
Call the ``sphinx-build`` for the given output type and the ``make`` when
the target has this possibility.
Parameters
----------
out_type :
A builder name for ``sphinx-build``. See the full list at
`<http://sphinx-doc.org/invocation.h... |
def randomizeSequence(sequence, symbolsPerSequence, numColumns, sparsity, p = 0.25):
"""
Takes a sequence as input and randomizes a percentage p of it by choosing
SDRs at random while preserving the remaining invariant.
@param sequence (array) sequence to be randomized
@param symbolsPerSequence (int) numbe... | Takes a sequence as input and randomizes a percentage p of it by choosing
SDRs at random while preserving the remaining invariant.
@param sequence (array) sequence to be randomized
@param symbolsPerSequence (int) number of symbols per sequence
@param numColumns (int) number of columns in the TM
@param spar... | Below is the the instruction that describes the task:
### Input:
Takes a sequence as input and randomizes a percentage p of it by choosing
SDRs at random while preserving the remaining invariant.
@param sequence (array) sequence to be randomized
@param symbolsPerSequence (int) number of symbols per sequenc... |
def get_results(self, fp=sys.stdout, inline=True, delim=None, fetch=True, qlog=None, arguments=[]):
"""
Fetches the result for the command represented by this object
get_results will retrieve results of the command and write to stdout by default.
Optionally one can write to a filestream... | Fetches the result for the command represented by this object
get_results will retrieve results of the command and write to stdout by default.
Optionally one can write to a filestream specified in `fp`. The `inline` argument
decides whether the result can be returned as a CRLF separated string.... | Below is the the instruction that describes the task:
### Input:
Fetches the result for the command represented by this object
get_results will retrieve results of the command and write to stdout by default.
Optionally one can write to a filestream specified in `fp`. The `inline` argument
d... |
def ssh_sa_ssh_client_key_exchange(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ssh_sa = ET.SubElement(config, "ssh-sa", xmlns="urn:brocade.com:mgmt:brocade-sec-services")
ssh = ET.SubElement(ssh_sa, "ssh")
client = ET.SubElement(ssh, "client"... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def ssh_sa_ssh_client_key_exchange(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ssh_sa = ET.SubElement(config, "ssh-sa", xmlns="urn:brocade.com:mgmt:brocad... |
def _raiseValidationException(standardExcMsg, customExcMsg=None):
"""Raise ValidationException with standardExcMsg, unless customExcMsg is specified."""
if customExcMsg is None:
raise ValidationException(str(standardExcMsg))
else:
raise ValidationException(str(customExcMsg)) | Raise ValidationException with standardExcMsg, unless customExcMsg is specified. | Below is the the instruction that describes the task:
### Input:
Raise ValidationException with standardExcMsg, unless customExcMsg is specified.
### Response:
def _raiseValidationException(standardExcMsg, customExcMsg=None):
"""Raise ValidationException with standardExcMsg, unless customExcMsg is specified.""... |
def setcompress(self, comp_type, value=0, v2=0):
"""Compresses the dataset using a specified compression method.
Args::
comp_type compression type, identified by one of the
SDC.COMP_xxx constants
value,v2 auxiliary value(s) needed by some compression t... | Compresses the dataset using a specified compression method.
Args::
comp_type compression type, identified by one of the
SDC.COMP_xxx constants
value,v2 auxiliary value(s) needed by some compression types
SDC.COMP_SKPHUFF Skipping-Hu... | Below is the the instruction that describes the task:
### Input:
Compresses the dataset using a specified compression method.
Args::
comp_type compression type, identified by one of the
SDC.COMP_xxx constants
value,v2 auxiliary value(s) needed by some comp... |
def write(self, data, offset=0, write_through=False, unbuffered=False,
wait=True, send=True):
"""
Writes data to an opened file.
Supports out of band send function, call this function with send=False
to return a tuple of (SMBWriteRequest, receive_func) instead of
s... | Writes data to an opened file.
Supports out of band send function, call this function with send=False
to return a tuple of (SMBWriteRequest, receive_func) instead of
sending the the request and waiting for the response. The receive_func
can be used to get the response from the server by... | Below is the the instruction that describes the task:
### Input:
Writes data to an opened file.
Supports out of band send function, call this function with send=False
to return a tuple of (SMBWriteRequest, receive_func) instead of
sending the the request and waiting for the response. The re... |
def policy_set_definitions(self):
"""Instance depends on the API version:
* 2017-06-01-preview: :class:`PolicySetDefinitionsOperations<azure.mgmt.resource.policy.v2017_06_01_preview.operations.PolicySetDefinitionsOperations>`
* 2018-03-01: :class:`PolicySetDefinitionsOperations<azure.mgmt... | Instance depends on the API version:
* 2017-06-01-preview: :class:`PolicySetDefinitionsOperations<azure.mgmt.resource.policy.v2017_06_01_preview.operations.PolicySetDefinitionsOperations>`
* 2018-03-01: :class:`PolicySetDefinitionsOperations<azure.mgmt.resource.policy.v2018_03_01.operations.Polic... | Below is the the instruction that describes the task:
### Input:
Instance depends on the API version:
* 2017-06-01-preview: :class:`PolicySetDefinitionsOperations<azure.mgmt.resource.policy.v2017_06_01_preview.operations.PolicySetDefinitionsOperations>`
* 2018-03-01: :class:`PolicySetDefiniti... |
def run(self, *args, **kwargs) -> Callable:
"""Return wrapped function.
Haskell: runReader :: Reader r a -> r -> a
This is the inverse of unit and returns the wrapped function.
"""
return self.fn(*args, **kwargs) if args or kwargs else self.fn | Return wrapped function.
Haskell: runReader :: Reader r a -> r -> a
This is the inverse of unit and returns the wrapped function. | Below is the the instruction that describes the task:
### Input:
Return wrapped function.
Haskell: runReader :: Reader r a -> r -> a
This is the inverse of unit and returns the wrapped function.
### Response:
def run(self, *args, **kwargs) -> Callable:
"""Return wrapped function.
... |
def permissions_for(self, member):
"""Handles permission resolution for the current :class:`Member`.
This function takes into consideration the following cases:
- Guild owner
- Guild roles
- Channel overrides
- Member overrides
Parameters
----------
... | Handles permission resolution for the current :class:`Member`.
This function takes into consideration the following cases:
- Guild owner
- Guild roles
- Channel overrides
- Member overrides
Parameters
----------
member: :class:`Member`
The m... | Below is the the instruction that describes the task:
### Input:
Handles permission resolution for the current :class:`Member`.
This function takes into consideration the following cases:
- Guild owner
- Guild roles
- Channel overrides
- Member overrides
Parameters... |
def leave_transaction_management(using=None):
"""
Leaves transaction management for a running thread. A dirty flag is carried
over to the surrounding block, as a commit will commit all changes, even
those from outside. (Commits are on connection level.)
"""
if using is None:
for using in... | Leaves transaction management for a running thread. A dirty flag is carried
over to the surrounding block, as a commit will commit all changes, even
those from outside. (Commits are on connection level.) | Below is the the instruction that describes the task:
### Input:
Leaves transaction management for a running thread. A dirty flag is carried
over to the surrounding block, as a commit will commit all changes, even
those from outside. (Commits are on connection level.)
### Response:
def leave_transaction_ma... |
def serialize_training_step(features, model_fn, batch_dim, num_splits):
"""Break the training batch into multiple microbatches.
Returns two structures:
grads - a list of Tensors corresponding to the gradients on
graph.trainable_variables. These are summed across all microbatches
outputs - a dictionary ... | Break the training batch into multiple microbatches.
Returns two structures:
grads - a list of Tensors corresponding to the gradients on
graph.trainable_variables. These are summed across all microbatches
outputs - a dictionary of Tensors corresponding to the output dictionary of
model_fn. Each va... | Below is the the instruction that describes the task:
### Input:
Break the training batch into multiple microbatches.
Returns two structures:
grads - a list of Tensors corresponding to the gradients on
graph.trainable_variables. These are summed across all microbatches
outputs - a dictionary of Tenso... |
def update_cache(album_cache, image_cache, app, client_id, ttl, album_whitelist, image_whitelist):
"""Update cache items with expired TTLs.
:param dict album_cache: Cache of Imgur albums to update. Keys are Imgur IDs, values are Album instances.
:param dict image_cache: Cache of Imgur images to update. Key... | Update cache items with expired TTLs.
:param dict album_cache: Cache of Imgur albums to update. Keys are Imgur IDs, values are Album instances.
:param dict image_cache: Cache of Imgur images to update. Keys are Imgur IDs, values are Image instances.
:param sphinx.application.Sphinx app: Sphinx application ... | Below is the the instruction that describes the task:
### Input:
Update cache items with expired TTLs.
:param dict album_cache: Cache of Imgur albums to update. Keys are Imgur IDs, values are Album instances.
:param dict image_cache: Cache of Imgur images to update. Keys are Imgur IDs, values are Image ins... |
def update_status(table_name="swdata", date_column="date"):
"""
Set the status endpoint on ScraperWiki to the latest entry e.g.
'Latest entry: 2013-10-01'
"""
status_text = 'Latest entry: {}'.format(
_get_most_recent_record(table_name, date_column))
L.info(status_text)
scraperwiki.s... | Set the status endpoint on ScraperWiki to the latest entry e.g.
'Latest entry: 2013-10-01' | Below is the the instruction that describes the task:
### Input:
Set the status endpoint on ScraperWiki to the latest entry e.g.
'Latest entry: 2013-10-01'
### Response:
def update_status(table_name="swdata", date_column="date"):
"""
Set the status endpoint on ScraperWiki to the latest entry e.g.
'... |
def get_input_list_from_task(task, placeholder_dict):
"""
Purpose: Parse a Task object to extract the files to be staged as the output.
Details: The extracted data is then converted into the appropriate RP directive depending on whether the data
is to be copied/downloaded.
:arguments:
:tas... | Purpose: Parse a Task object to extract the files to be staged as the output.
Details: The extracted data is then converted into the appropriate RP directive depending on whether the data
is to be copied/downloaded.
:arguments:
:task: EnTK Task object
:placeholder_dict: dictionary holding ... | Below is the the instruction that describes the task:
### Input:
Purpose: Parse a Task object to extract the files to be staged as the output.
Details: The extracted data is then converted into the appropriate RP directive depending on whether the data
is to be copied/downloaded.
:arguments:
:... |
def dt_dt(sdat, tstart=None, tend=None):
"""Derivative of temperature.
Compute dT/dt as a function of time using an explicit Euler scheme.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
tstart (float): time at which the computation should start. Use the
... | Derivative of temperature.
Compute dT/dt as a function of time using an explicit Euler scheme.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
tstart (float): time at which the computation should start. Use the
beginning of the time series data if set to... | Below is the the instruction that describes the task:
### Input:
Derivative of temperature.
Compute dT/dt as a function of time using an explicit Euler scheme.
Args:
sdat (:class:`~stagpy.stagyydata.StagyyData`): a StagyyData instance.
tstart (float): time at which the computation should s... |
def punchcard(self, branch='master', limit=None, days=None, by=None, normalize=None, ignore_globs=None, include_globs=None):
"""
Returns a pandas DataFrame containing all of the data for a punchcard.
* day_of_week
* hour_of_day
* author / committer
* lines
*... | Returns a pandas DataFrame containing all of the data for a punchcard.
* day_of_week
* hour_of_day
* author / committer
* lines
* insertions
* deletions
* net
:param branch: the branch to return commits for
:param limit: (optional, default... | Below is the the instruction that describes the task:
### Input:
Returns a pandas DataFrame containing all of the data for a punchcard.
* day_of_week
* hour_of_day
* author / committer
* lines
* insertions
* deletions
* net
:param branch: the ... |
def get_agents(self, addr=True, agent_cls=None, as_coro=False):
"""Get agents from the managed environment.
This is a managing function for the
:py:meth:`~creamas.environment.Environment.get_agents`. Returned
agent list excludes the environment's manager agent (this agent) by
de... | Get agents from the managed environment.
This is a managing function for the
:py:meth:`~creamas.environment.Environment.get_agents`. Returned
agent list excludes the environment's manager agent (this agent) by
design. | Below is the the instruction that describes the task:
### Input:
Get agents from the managed environment.
This is a managing function for the
:py:meth:`~creamas.environment.Environment.get_agents`. Returned
agent list excludes the environment's manager agent (this agent) by
design.
... |
def LikelihoodFunction(Template, Data, PSD, detRespP, detGCDelay=0):
""" LikelihoodFunction - function to calculate the likelihood of livePoint,
given Data.
Template - (N_fd) complex array containing Fourier domain trial signal.
Data - (N_fd) complex array containing Fourier domain GW data.... | LikelihoodFunction - function to calculate the likelihood of livePoint,
given Data.
Template - (N_fd) complex array containing Fourier domain trial signal.
Data - (N_fd) complex array containing Fourier domain GW data.
PSD - Noise power spectral density for a gravitational wave detector... | Below is the the instruction that describes the task:
### Input:
LikelihoodFunction - function to calculate the likelihood of livePoint,
given Data.
Template - (N_fd) complex array containing Fourier domain trial signal.
Data - (N_fd) complex array containing Fourier domain GW data.
... |
def query_context(self, regions, file_factory=PythonFile):
"""
Return which set of test contexts intersect a set of code regions.
Parameters
----------
regions: A sequence of Intervals
file_factory: Callable (optional, default PythonFile)
A callable that ta... | Return which set of test contexts intersect a set of code regions.
Parameters
----------
regions: A sequence of Intervals
file_factory: Callable (optional, default PythonFile)
A callable that takes a filename and
returns a PythonFile object.
Returns
... | Below is the the instruction that describes the task:
### Input:
Return which set of test contexts intersect a set of code regions.
Parameters
----------
regions: A sequence of Intervals
file_factory: Callable (optional, default PythonFile)
A callable that takes a file... |
def track_execution(cmd, project, experiment, **kwargs):
"""Guard the execution of the given command.
The given command (`cmd`) will be executed inside a database context.
As soon as you leave the context we will commit the transaction.
Any necessary modifications to the database can be identified insi... | Guard the execution of the given command.
The given command (`cmd`) will be executed inside a database context.
As soon as you leave the context we will commit the transaction.
Any necessary modifications to the database can be identified inside
the context with the RunInfo object.
Args:
c... | Below is the the instruction that describes the task:
### Input:
Guard the execution of the given command.
The given command (`cmd`) will be executed inside a database context.
As soon as you leave the context we will commit the transaction.
Any necessary modifications to the database can be identified... |
def format_python2_stmts(python_stmts, show_tokens=False, showast=False,
showgrammar=False, compile_mode='exec'):
"""
formats python2 statements
"""
parser_debug = {'rules': False, 'transition': False,
'reduce': showgrammar,
'errorstack':... | formats python2 statements | Below is the the instruction that describes the task:
### Input:
formats python2 statements
### Response:
def format_python2_stmts(python_stmts, show_tokens=False, showast=False,
showgrammar=False, compile_mode='exec'):
"""
formats python2 statements
"""
parser_debug = {'r... |
def get_job_details(job_id,
deployment_name,
token_manager=None,
app_url=defaults.APP_URL):
"""
return job details for a specific job id
"""
jobs = get_jobs(deployment_name,
token_manager=token_manager,
... | return job details for a specific job id | Below is the the instruction that describes the task:
### Input:
return job details for a specific job id
### Response:
def get_job_details(job_id,
deployment_name,
token_manager=None,
app_url=defaults.APP_URL):
"""
return job details for a specif... |
def mtabstr2doestr(st1):
"""mtabstr2doestr"""
seperator = '$ =============='
alist = st1.split(seperator)
#this removes all the tabs that excel
#puts after the seperator and before the next line
for num in range(0, len(alist)):
alist[num] = alist[num].lstrip()
st2 = ''
for num i... | mtabstr2doestr | Below is the the instruction that describes the task:
### Input:
mtabstr2doestr
### Response:
def mtabstr2doestr(st1):
"""mtabstr2doestr"""
seperator = '$ =============='
alist = st1.split(seperator)
#this removes all the tabs that excel
#puts after the seperator and before the next line
f... |
def poke_publication_state(publication_id, cursor):
"""Invoked to poke at the publication to update and acquire its current
state. This is used to persist the publication to archive.
"""
cursor.execute("""\
SELECT "state", "state_messages", "is_pre_publication", "publisher"
FROM publications
WHERE id = ... | Invoked to poke at the publication to update and acquire its current
state. This is used to persist the publication to archive. | Below is the the instruction that describes the task:
### Input:
Invoked to poke at the publication to update and acquire its current
state. This is used to persist the publication to archive.
### Response:
def poke_publication_state(publication_id, cursor):
"""Invoked to poke at the publication to update ... |
def handle_offchain_secretreveal(
initiator_state: InitiatorTransferState,
state_change: ReceiveSecretReveal,
channel_state: NettingChannelState,
pseudo_random_generator: random.Random,
) -> TransitionResult[InitiatorTransferState]:
""" Once the next hop proves it knows the secret, t... | Once the next hop proves it knows the secret, the initiator can unlock
the mediated transfer.
This will validate the secret, and if valid a new balance proof is sent to
the next hop with the current lock removed from the merkle tree and the
transferred amount updated. | Below is the the instruction that describes the task:
### Input:
Once the next hop proves it knows the secret, the initiator can unlock
the mediated transfer.
This will validate the secret, and if valid a new balance proof is sent to
the next hop with the current lock removed from the merkle tree and t... |
def register_shortcut(self, qaction_or_qshortcut, context, name,
add_sc_to_tip=False):
"""
Register QAction or QShortcut to Spyder main application.
if add_sc_to_tip is True, the shortcut is added to the
action's tooltip
"""
self.main.register_s... | Register QAction or QShortcut to Spyder main application.
if add_sc_to_tip is True, the shortcut is added to the
action's tooltip | Below is the the instruction that describes the task:
### Input:
Register QAction or QShortcut to Spyder main application.
if add_sc_to_tip is True, the shortcut is added to the
action's tooltip
### Response:
def register_shortcut(self, qaction_or_qshortcut, context, name,
... |
def addDependency(self, item):
"""
Creates a dependency for this item to the next item. This item will
be treated as the source, the other as the target.
:param item | <QGanttWidgetItem>
"""
if item in self._dependencies:
return
... | Creates a dependency for this item to the next item. This item will
be treated as the source, the other as the target.
:param item | <QGanttWidgetItem> | Below is the the instruction that describes the task:
### Input:
Creates a dependency for this item to the next item. This item will
be treated as the source, the other as the target.
:param item | <QGanttWidgetItem>
### Response:
def addDependency(self, item):
"""
... |
def validate_required(self, value):
''' Validates the given value agains this field's 'required' property
'''
if self.required and (value is None or value==''):
raise MissingFieldError(self.name) | Validates the given value agains this field's 'required' property | Below is the the instruction that describes the task:
### Input:
Validates the given value agains this field's 'required' property
### Response:
def validate_required(self, value):
''' Validates the given value agains this field's 'required' property
'''
if self.required and (value is None ... |
def compareAaReads(read1, read2, gapChars='-', offsets=None):
"""
Compare two amino acid sequences.
@param read1: A C{Read} instance or an instance of one of its subclasses.
@param read2: A C{Read} instance or an instance of one of its subclasses.
@param gapChars: An object supporting __contains__ ... | Compare two amino acid sequences.
@param read1: A C{Read} instance or an instance of one of its subclasses.
@param read2: A C{Read} instance or an instance of one of its subclasses.
@param gapChars: An object supporting __contains__ with characters that
should be considered to be gaps.
@param o... | Below is the the instruction that describes the task:
### Input:
Compare two amino acid sequences.
@param read1: A C{Read} instance or an instance of one of its subclasses.
@param read2: A C{Read} instance or an instance of one of its subclasses.
@param gapChars: An object supporting __contains__ with ... |
async def sort(self, name, start=None, num=None, by=None, get=None,
desc=False, alpha=False, store=None, groups=False):
"""
Sort and return the list, set or sorted set at ``name``.
``start`` and ``num`` allow for paging through the sorted data
``by`` allows using an extern... | Sort and return the list, set or sorted set at ``name``.
``start`` and ``num`` allow for paging through the sorted data
``by`` allows using an external key to weight and sort the items.
Use an "*" to indicate where in the key the item value is located
``get`` allows for returning ... | Below is the the instruction that describes the task:
### Input:
Sort and return the list, set or sorted set at ``name``.
``start`` and ``num`` allow for paging through the sorted data
``by`` allows using an external key to weight and sort the items.
Use an "*" to indicate where in the... |
def _pad(string, size):
"""
'Pad' a string with leading zeroes to fit the given size, truncating
if necessary.
"""
strlen = len(string)
if strlen == size:
return string
if strlen < size:
return _padding[0:size-strlen] + string
return string[-size:] | 'Pad' a string with leading zeroes to fit the given size, truncating
if necessary. | Below is the the instruction that describes the task:
### Input:
'Pad' a string with leading zeroes to fit the given size, truncating
if necessary.
### Response:
def _pad(string, size):
"""
'Pad' a string with leading zeroes to fit the given size, truncating
if necessary.
"""
strlen = len(s... |
def difference_update(self, *others):
r"""Remove all elements contained the others from this multiset.
>>> ms = Multiset('aab')
>>> ms.difference_update('abc')
>>> sorted(ms)
['a']
You can also use the ``-=`` operator for the same effect. However, the operator version
... | r"""Remove all elements contained the others from this multiset.
>>> ms = Multiset('aab')
>>> ms.difference_update('abc')
>>> sorted(ms)
['a']
You can also use the ``-=`` operator for the same effect. However, the operator version
will only accept a set as other operato... | Below is the the instruction that describes the task:
### Input:
r"""Remove all elements contained the others from this multiset.
>>> ms = Multiset('aab')
>>> ms.difference_update('abc')
>>> sorted(ms)
['a']
You can also use the ``-=`` operator for the same effect. However,... |
def load_path_with_default(self, path, default_constructor):
'''
Same as `load_path(path)', except uses default_constructor on import
errors, or if loaded a auto-generated namespace package (e.g. bare
directory).
'''
try:
imported_obj = self.load_path(path)
... | Same as `load_path(path)', except uses default_constructor on import
errors, or if loaded a auto-generated namespace package (e.g. bare
directory). | Below is the the instruction that describes the task:
### Input:
Same as `load_path(path)', except uses default_constructor on import
errors, or if loaded a auto-generated namespace package (e.g. bare
directory).
### Response:
def load_path_with_default(self, path, default_constructor):
'''... |
def _water(cls, T, P):
"""Get properties of pure water, Table4 pag 8"""
water = IAPWS95(P=P, T=T)
prop = {}
prop["g"] = water.h-T*water.s
prop["gt"] = -water.s
prop["gp"] = 1./water.rho
prop["gtt"] = -water.cp/T
prop["gtp"] = water.betas*water.cp/T
... | Get properties of pure water, Table4 pag 8 | Below is the the instruction that describes the task:
### Input:
Get properties of pure water, Table4 pag 8
### Response:
def _water(cls, T, P):
"""Get properties of pure water, Table4 pag 8"""
water = IAPWS95(P=P, T=T)
prop = {}
prop["g"] = water.h-T*water.s
prop["gt"] = -w... |
def network_create(auth=None, **kwargs):
'''
Create a network
name
Name of the network being created
shared : False
If ``True``, set the network as shared
admin_state_up : True
If ``True``, Set the network administrative state to "up"
external : False
Control ... | Create a network
name
Name of the network being created
shared : False
If ``True``, set the network as shared
admin_state_up : True
If ``True``, Set the network administrative state to "up"
external : False
Control whether or not this network is externally accessible
... | Below is the the instruction that describes the task:
### Input:
Create a network
name
Name of the network being created
shared : False
If ``True``, set the network as shared
admin_state_up : True
If ``True``, Set the network administrative state to "up"
external : False
... |
def from_str(cls, string):
"""
Creates a literal from a string
Parameters
----------
string : str
If the string starts with '!', it's interpreted as a negated variable
Returns
-------
caspo.core.literal.Literal
Created object inst... | Creates a literal from a string
Parameters
----------
string : str
If the string starts with '!', it's interpreted as a negated variable
Returns
-------
caspo.core.literal.Literal
Created object instance | Below is the the instruction that describes the task:
### Input:
Creates a literal from a string
Parameters
----------
string : str
If the string starts with '!', it's interpreted as a negated variable
Returns
-------
caspo.core.literal.Literal
... |
def get_context(self, language):
""" Get the context(description) of this task """
context = self.gettext(language, self._context) if self._context else ""
vals = self._hook_manager.call_hook('task_context', course=self.get_course(), task=self, default=context)
return ParsableText(vals[0... | Get the context(description) of this task | Below is the the instruction that describes the task:
### Input:
Get the context(description) of this task
### Response:
def get_context(self, language):
""" Get the context(description) of this task """
context = self.gettext(language, self._context) if self._context else ""
vals = self._h... |
def _build_regular_workflow(json_spec):
"""
Precondition: json_spec must be validated
"""
workflow_id = dxpy.api.workflow_new(json_spec)["id"]
dxpy.api.workflow_close(workflow_id)
return workflow_id | Precondition: json_spec must be validated | Below is the the instruction that describes the task:
### Input:
Precondition: json_spec must be validated
### Response:
def _build_regular_workflow(json_spec):
"""
Precondition: json_spec must be validated
"""
workflow_id = dxpy.api.workflow_new(json_spec)["id"]
dxpy.api.workflow_close(workflo... |
def _remove_white_background(image):
"""Remove white background in the preview image."""
from PIL import ImageMath, Image
if image.mode == "RGBA":
bands = image.split()
a = bands[3]
rgb = [
ImageMath.eval(
'convert('
'float(x + a - 255) * 2... | Remove white background in the preview image. | Below is the the instruction that describes the task:
### Input:
Remove white background in the preview image.
### Response:
def _remove_white_background(image):
"""Remove white background in the preview image."""
from PIL import ImageMath, Image
if image.mode == "RGBA":
bands = image.split()
... |
def xywh_from_points(points):
"""
Constructs an dict representing a rectangle with keys x, y, w, h
"""
xys = [[int(p) for p in pair.split(',')] for pair in points.split(' ')]
minx = sys.maxsize
miny = sys.maxsize
maxx = 0
maxy = 0
for xy in xys:
if xy[0] < minx:
m... | Constructs an dict representing a rectangle with keys x, y, w, h | Below is the the instruction that describes the task:
### Input:
Constructs an dict representing a rectangle with keys x, y, w, h
### Response:
def xywh_from_points(points):
"""
Constructs an dict representing a rectangle with keys x, y, w, h
"""
xys = [[int(p) for p in pair.split(',')] for pair in... |
def fitLine(points, c="orange", lw=1):
"""
Fits a line through points.
Extra info is stored in ``actor.info['slope']``, ``actor.info['center']``, ``actor.info['variances']``.
.. hint:: |fitline| |fitline.py|_
"""
data = np.array(points)
datamean = data.mean(axis=0)
uu, dd, vv = np.lina... | Fits a line through points.
Extra info is stored in ``actor.info['slope']``, ``actor.info['center']``, ``actor.info['variances']``.
.. hint:: |fitline| |fitline.py|_ | Below is the the instruction that describes the task:
### Input:
Fits a line through points.
Extra info is stored in ``actor.info['slope']``, ``actor.info['center']``, ``actor.info['variances']``.
.. hint:: |fitline| |fitline.py|_
### Response:
def fitLine(points, c="orange", lw=1):
"""
Fits a li... |
def get_tokens(self):
"""Returns a generator of the tokens."""
if self._filename:
with open(self._filename) as ifile:
self._data = ifile.read()
with QasmParser(self._filename) as qasm_p:
return qasm_p.get_tokens() | Returns a generator of the tokens. | Below is the the instruction that describes the task:
### Input:
Returns a generator of the tokens.
### Response:
def get_tokens(self):
"""Returns a generator of the tokens."""
if self._filename:
with open(self._filename) as ifile:
self._data = ifile.read()
with... |
def to_blob(self, repo):
""":return: Blob using the information of this index entry"""
return Blob(repo, self.binsha, self.mode, self.path) | :return: Blob using the information of this index entry | Below is the the instruction that describes the task:
### Input:
:return: Blob using the information of this index entry
### Response:
def to_blob(self, repo):
""":return: Blob using the information of this index entry"""
return Blob(repo, self.binsha, self.mode, self.path) |
def itemFromIndex(self, index):
""" Gets the item given the model index
"""
sourceIndex = self.mapToSource(index)
return self.sourceModel().itemFromIndex(sourceIndex) | Gets the item given the model index | Below is the the instruction that describes the task:
### Input:
Gets the item given the model index
### Response:
def itemFromIndex(self, index):
""" Gets the item given the model index
"""
sourceIndex = self.mapToSource(index)
return self.sourceModel().itemFromIndex(sourceIndex) |
def parse_variables(args):
"""
Parse variables as passed on the command line.
Returns
-------
dict
Mapping variable name to the value.
"""
if args is None:
return {}
def parse_variable(string):
tokens = string.split('=')
name = tokens[0]
value =... | Parse variables as passed on the command line.
Returns
-------
dict
Mapping variable name to the value. | Below is the the instruction that describes the task:
### Input:
Parse variables as passed on the command line.
Returns
-------
dict
Mapping variable name to the value.
### Response:
def parse_variables(args):
"""
Parse variables as passed on the command line.
Returns
-------
... |
def send(*args, **kwargs):
""" Make sure that we have an instance of the GraphiteClient.
Then send the metrics to the graphite server.
User consumable method.
"""
if not _module_instance:
raise GraphiteSendException(
"Must call graphitesend.init() before sending")
_module_in... | Make sure that we have an instance of the GraphiteClient.
Then send the metrics to the graphite server.
User consumable method. | Below is the the instruction that describes the task:
### Input:
Make sure that we have an instance of the GraphiteClient.
Then send the metrics to the graphite server.
User consumable method.
### Response:
def send(*args, **kwargs):
""" Make sure that we have an instance of the GraphiteClient.
The... |
def _submit(
self,
metric_name,
message,
send_histograms_buckets=True,
send_monotonic_counter=False,
custom_tags=None,
hostname=None,
):
"""
For each metric in the message, report it as a gauge with all labels as tags
except if a labels... | For each metric in the message, report it as a gauge with all labels as tags
except if a labels dict is passed, in which case keys are label names we'll extract
and corresponding values are tag names we'll use (eg: {'node': 'node'}).
Histograms generate a set of values instead of a unique metri... | Below is the the instruction that describes the task:
### Input:
For each metric in the message, report it as a gauge with all labels as tags
except if a labels dict is passed, in which case keys are label names we'll extract
and corresponding values are tag names we'll use (eg: {'node': 'node'}).
... |
def download(cls, root, check=None):
"""Download and unzip an online archive (.zip, .gz, or .tgz).
Arguments:
root (str): Folder to download data to.
check (str or None): Folder whose existence indicates
that the dataset has already been downloaded, or
... | Download and unzip an online archive (.zip, .gz, or .tgz).
Arguments:
root (str): Folder to download data to.
check (str or None): Folder whose existence indicates
that the dataset has already been downloaded, or
None to check the existence of root/{cls.n... | Below is the the instruction that describes the task:
### Input:
Download and unzip an online archive (.zip, .gz, or .tgz).
Arguments:
root (str): Folder to download data to.
check (str or None): Folder whose existence indicates
that the dataset has already been down... |
def __search(self, obj, item, parent="root", parents_ids=frozenset({})):
"""The main search method"""
if self.__skip_this(item, parent):
return
elif isinstance(obj, strings) and isinstance(item, strings):
self.__search_str(obj, item, parent)
elif isinstance(obj... | The main search method | Below is the the instruction that describes the task:
### Input:
The main search method
### Response:
def __search(self, obj, item, parent="root", parents_ids=frozenset({})):
"""The main search method"""
if self.__skip_this(item, parent):
return
elif isinstance(obj, strings) a... |
def gather_bootstrap_script(bootstrap=None):
'''
Download the salt-bootstrap script, and return its location
bootstrap
URL of alternate bootstrap script
CLI Example:
.. code-block:: bash
salt '*' config.gather_bootstrap_script
'''
if not HAS_CLOUD:
return False, '... | Download the salt-bootstrap script, and return its location
bootstrap
URL of alternate bootstrap script
CLI Example:
.. code-block:: bash
salt '*' config.gather_bootstrap_script | Below is the the instruction that describes the task:
### Input:
Download the salt-bootstrap script, and return its location
bootstrap
URL of alternate bootstrap script
CLI Example:
.. code-block:: bash
salt '*' config.gather_bootstrap_script
### Response:
def gather_bootstrap_scrip... |
def get_all_quiz_submissions(self, quiz_id, course_id, include=None):
"""
Get all quiz submissions.
Get a list of all submissions for this quiz. Users who can view or manage
grades for a course will have submissions from multiple users returned. A
user who can only submit ... | Get all quiz submissions.
Get a list of all submissions for this quiz. Users who can view or manage
grades for a course will have submissions from multiple users returned. A
user who can only submit will have only their own submissions returned. When
a user has an in-progress submi... | Below is the the instruction that describes the task:
### Input:
Get all quiz submissions.
Get a list of all submissions for this quiz. Users who can view or manage
grades for a course will have submissions from multiple users returned. A
user who can only submit will have only their ow... |
def modify_snapshot(snapshot_id=None,
description=None,
userdata=None,
cleanup=None,
config="root"):
'''
Modify attributes of an existing snapshot.
config
Configuration name. (Default: root)
snapshot_id
ID ... | Modify attributes of an existing snapshot.
config
Configuration name. (Default: root)
snapshot_id
ID of the snapshot to be modified.
cleanup
Change the cleanup method of the snapshot. (str)
description
Change the description of the snapshot. (str)
userdata
... | Below is the the instruction that describes the task:
### Input:
Modify attributes of an existing snapshot.
config
Configuration name. (Default: root)
snapshot_id
ID of the snapshot to be modified.
cleanup
Change the cleanup method of the snapshot. (str)
description
... |
def iterate(self, shuffle=True):
'''Iterate over batches in the dataset.
This method generates ``iteration_size`` batches from the dataset and
then returns.
Parameters
----------
shuffle : bool, optional
Shuffle the batches in this dataset if the iteration r... | Iterate over batches in the dataset.
This method generates ``iteration_size`` batches from the dataset and
then returns.
Parameters
----------
shuffle : bool, optional
Shuffle the batches in this dataset if the iteration reaches the end
of the batch list... | Below is the the instruction that describes the task:
### Input:
Iterate over batches in the dataset.
This method generates ``iteration_size`` batches from the dataset and
then returns.
Parameters
----------
shuffle : bool, optional
Shuffle the batches in this d... |
def track_from_url(url, timeout=DEFAULT_ASYNC_TIMEOUT):
"""
Create a track object from a public http URL.
NOTE: Does not create the detailed analysis for the Track. Call
Track.get_analysis() for that.
Args:
url: A string giving the URL to read from. This must be on a public machine accessi... | Create a track object from a public http URL.
NOTE: Does not create the detailed analysis for the Track. Call
Track.get_analysis() for that.
Args:
url: A string giving the URL to read from. This must be on a public machine accessible by HTTP.
Example:
>>> t = track.track_from_url("htt... | Below is the the instruction that describes the task:
### Input:
Create a track object from a public http URL.
NOTE: Does not create the detailed analysis for the Track. Call
Track.get_analysis() for that.
Args:
url: A string giving the URL to read from. This must be on a public machine access... |
def read_identity(self, identity_id, query_membership=None, properties=None):
"""ReadIdentity.
:param str identity_id:
:param str query_membership:
:param str properties:
:rtype: :class:`<Identity> <azure.devops.v5_0.identity.models.Identity>`
"""
route_values = {... | ReadIdentity.
:param str identity_id:
:param str query_membership:
:param str properties:
:rtype: :class:`<Identity> <azure.devops.v5_0.identity.models.Identity>` | Below is the the instruction that describes the task:
### Input:
ReadIdentity.
:param str identity_id:
:param str query_membership:
:param str properties:
:rtype: :class:`<Identity> <azure.devops.v5_0.identity.models.Identity>`
### Response:
def read_identity(self, identity_id, quer... |
def fold_text_stream(self, prefix, postfix="", hidden_stream=None, **kwargs):
"""
:param str prefix: always visible
:param str postfix: always visible, right after.
:param io.TextIOBase|io.StringIO hidden_stream: sys.stdout by default.
If this is sys.stdout, it will replace t... | :param str prefix: always visible
:param str postfix: always visible, right after.
:param io.TextIOBase|io.StringIO hidden_stream: sys.stdout by default.
If this is sys.stdout, it will replace that stream,
and collect the data during the context (in the `with` block). | Below is the the instruction that describes the task:
### Input:
:param str prefix: always visible
:param str postfix: always visible, right after.
:param io.TextIOBase|io.StringIO hidden_stream: sys.stdout by default.
If this is sys.stdout, it will replace that stream,
and c... |
def hue(self, hue):
""" Set the group hue.
:param hue: Hue in decimal percent (0.0-1.0).
"""
if hue < 0 or hue > 1:
raise ValueError("Hue must be a percentage "
"represented as decimal 0-1.0")
self._hue = hue
cmd = self.command_se... | Set the group hue.
:param hue: Hue in decimal percent (0.0-1.0). | Below is the the instruction that describes the task:
### Input:
Set the group hue.
:param hue: Hue in decimal percent (0.0-1.0).
### Response:
def hue(self, hue):
""" Set the group hue.
:param hue: Hue in decimal percent (0.0-1.0).
"""
if hue < 0 or hue > 1:
r... |
def getRetinas(self, retina_name=None):
"""Information about retinas
Args:
retina_name, str: The retina name (optional) (optional)
Returns: Array[Retina]
"""
resourcePath = '/retinas'
method = 'GET'
queryParams = {}
headerParams = {'Accep... | Information about retinas
Args:
retina_name, str: The retina name (optional) (optional)
Returns: Array[Retina] | Below is the the instruction that describes the task:
### Input:
Information about retinas
Args:
retina_name, str: The retina name (optional) (optional)
Returns: Array[Retina]
### Response:
def getRetinas(self, retina_name=None):
"""Information about retinas
Args:
... |
async def jsk_repeat(self, ctx: commands.Context, times: int, *, command_string: str):
"""
Runs a command multiple times in a row.
This acts like the command was invoked several times manually, so it obeys cooldowns.
"""
with self.submit(ctx): # allow repeats to be cancelled
... | Runs a command multiple times in a row.
This acts like the command was invoked several times manually, so it obeys cooldowns. | Below is the the instruction that describes the task:
### Input:
Runs a command multiple times in a row.
This acts like the command was invoked several times manually, so it obeys cooldowns.
### Response:
async def jsk_repeat(self, ctx: commands.Context, times: int, *, command_string: str):
"""
... |
def _update_response_location_header(self, resource):
"""
Adds a new or replaces an existing Location header to the response
headers pointing to the URL of the given resource.
"""
location = resource_to_url(resource, request=self.request)
loc_hdr = ('Location', location)
... | Adds a new or replaces an existing Location header to the response
headers pointing to the URL of the given resource. | Below is the the instruction that describes the task:
### Input:
Adds a new or replaces an existing Location header to the response
headers pointing to the URL of the given resource.
### Response:
def _update_response_location_header(self, resource):
"""
Adds a new or replaces an existing L... |
def make_room_alias(chain_id: ChainID, *suffixes: str) -> str:
"""Given a chain_id and any number of suffixes (global room names, pair of addresses),
compose and return the canonical room name for raiden network
network name from raiden_contracts.constants.ID_TO_NETWORKNAME is used for name, if available,
... | Given a chain_id and any number of suffixes (global room names, pair of addresses),
compose and return the canonical room name for raiden network
network name from raiden_contracts.constants.ID_TO_NETWORKNAME is used for name, if available,
else numeric id
Params:
chain_id: numeric blockchain i... | Below is the the instruction that describes the task:
### Input:
Given a chain_id and any number of suffixes (global room names, pair of addresses),
compose and return the canonical room name for raiden network
network name from raiden_contracts.constants.ID_TO_NETWORKNAME is used for name, if available,
... |
def request(self, method, params=None):
"""Send a JSON RPC request to the client.
Args:
method (str): The method name of the message to send
params (any): The payload of the message
Returns:
Future that will resolve once a response has been received
... | Send a JSON RPC request to the client.
Args:
method (str): The method name of the message to send
params (any): The payload of the message
Returns:
Future that will resolve once a response has been received | Below is the the instruction that describes the task:
### Input:
Send a JSON RPC request to the client.
Args:
method (str): The method name of the message to send
params (any): The payload of the message
Returns:
Future that will resolve once a response has been... |
def normalize_query_parameters(query_string):
"""
normalize_query_parameters(query_string) -> dict
Converts a query string into a dictionary mapping parameter names to a
list of the sorted values. This ensurses that the query string follows
% encoding rules according to RFC 3986 and checks for dup... | normalize_query_parameters(query_string) -> dict
Converts a query string into a dictionary mapping parameter names to a
list of the sorted values. This ensurses that the query string follows
% encoding rules according to RFC 3986 and checks for duplicate keys.
A ValueError exception is raised if a pe... | Below is the the instruction that describes the task:
### Input:
normalize_query_parameters(query_string) -> dict
Converts a query string into a dictionary mapping parameter names to a
list of the sorted values. This ensurses that the query string follows
% encoding rules according to RFC 3986 and che... |
def find_urls(self, site, frametype, gpsstart, gpsend,
match=None, on_gaps='warn'):
"""Find all files of the given type in the [start, end) GPS interval.
"""
span = Segment(gpsstart, gpsend)
cache = [e for e in self._read_ffl_cache(site, frametype) if
e... | Find all files of the given type in the [start, end) GPS interval. | Below is the the instruction that describes the task:
### Input:
Find all files of the given type in the [start, end) GPS interval.
### Response:
def find_urls(self, site, frametype, gpsstart, gpsend,
match=None, on_gaps='warn'):
"""Find all files of the given type in the [start, end) GPS... |
def enrich_backend(url, clean, backend_name, backend_params, cfg_section_name,
ocean_index=None,
ocean_index_enrich=None,
db_projects_map=None, json_projects_map=None,
db_sortinghat=None,
no_incremental=False, only_identities... | Enrich Ocean index | Below is the the instruction that describes the task:
### Input:
Enrich Ocean index
### Response:
def enrich_backend(url, clean, backend_name, backend_params, cfg_section_name,
ocean_index=None,
ocean_index_enrich=None,
db_projects_map=None, json_projects_ma... |
def transform(self, flip_x, flip_y, swap_xy):
"""Transform view of the image.
.. note::
Transforming the image is generally faster than rotating,
if rotating in 90 degree increments. Also see :meth:`rotate`.
Parameters
----------
flipx, flipy : bool
... | Transform view of the image.
.. note::
Transforming the image is generally faster than rotating,
if rotating in 90 degree increments. Also see :meth:`rotate`.
Parameters
----------
flipx, flipy : bool
If `True`, flip the image in the X and Y axes, r... | Below is the the instruction that describes the task:
### Input:
Transform view of the image.
.. note::
Transforming the image is generally faster than rotating,
if rotating in 90 degree increments. Also see :meth:`rotate`.
Parameters
----------
flipx, flip... |
def create_vm(client, name, compute_resource, datastore, disksize, nics,
memory, num_cpus, guest_id, host=None):
"""Create a virtual machine using the specified values.
:param name: The name of the VM to create.
:type name: str
:param compute_resource: The name of a ComputeResource in whi... | Create a virtual machine using the specified values.
:param name: The name of the VM to create.
:type name: str
:param compute_resource: The name of a ComputeResource in which to \
create the VM.
:type compute_resource: str
:param datastore: The name of the datastore on which to create ... | Below is the the instruction that describes the task:
### Input:
Create a virtual machine using the specified values.
:param name: The name of the VM to create.
:type name: str
:param compute_resource: The name of a ComputeResource in which to \
create the VM.
:type compute_resource: st... |
def visualize_learning_result(self, state_key):
'''
Visualize learning result.
'''
x, y = state_key
map_arr = copy.deepcopy(self.__map_arr)
goal_point_tuple = np.where(map_arr == self.__end_point_label)
goal_x, goal_y = goal_point_tuple
map_arr[y][x] = "@"... | Visualize learning result. | Below is the the instruction that describes the task:
### Input:
Visualize learning result.
### Response:
def visualize_learning_result(self, state_key):
'''
Visualize learning result.
'''
x, y = state_key
map_arr = copy.deepcopy(self.__map_arr)
goal_point_tuple = np... |
def _retrieve_value(self, entity, default=None):
"""Internal helper to retrieve the value for this Property from an entity.
This returns None if no value is set, or the default argument if
given. For a repeated Property this returns a list if a value is
set, otherwise None. No additional transformati... | Internal helper to retrieve the value for this Property from an entity.
This returns None if no value is set, or the default argument if
given. For a repeated Property this returns a list if a value is
set, otherwise None. No additional transformations are applied. | Below is the the instruction that describes the task:
### Input:
Internal helper to retrieve the value for this Property from an entity.
This returns None if no value is set, or the default argument if
given. For a repeated Property this returns a list if a value is
set, otherwise None. No additional... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.