code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _set_listener(instance, obs):
"""Add listeners to a HasProperties instance"""
if obs.names is everything:
names = list(instance._props)
else:
names = obs.names
for name in names:
if name not in instance._listeners:
instance._listeners[name] = {typ: [] for typ in L... | Add listeners to a HasProperties instance | Below is the the instruction that describes the task:
### Input:
Add listeners to a HasProperties instance
### Response:
def _set_listener(instance, obs):
"""Add listeners to a HasProperties instance"""
if obs.names is everything:
names = list(instance._props)
else:
names = obs.names
... |
def get_any_nt_unit_rule(g):
"""Returns a non-terminal unit rule from 'g', or None if there is none."""
for rule in g.rules:
if len(rule.rhs) == 1 and isinstance(rule.rhs[0], NT):
return rule
return None | Returns a non-terminal unit rule from 'g', or None if there is none. | Below is the the instruction that describes the task:
### Input:
Returns a non-terminal unit rule from 'g', or None if there is none.
### Response:
def get_any_nt_unit_rule(g):
"""Returns a non-terminal unit rule from 'g', or None if there is none."""
for rule in g.rules:
if len(rule.rhs) == 1 and ... |
def area(self):
r"""The area of the current curved polygon.
This assumes, but does not check, that the current curved polygon
is valid (i.e. it is bounded by the edges).
This computes the area via Green's theorem. Using the vector field
:math:`\mathbf{F} = \left[-y, x\right]^T`... | r"""The area of the current curved polygon.
This assumes, but does not check, that the current curved polygon
is valid (i.e. it is bounded by the edges).
This computes the area via Green's theorem. Using the vector field
:math:`\mathbf{F} = \left[-y, x\right]^T`, since
:math:`\... | Below is the the instruction that describes the task:
### Input:
r"""The area of the current curved polygon.
This assumes, but does not check, that the current curved polygon
is valid (i.e. it is bounded by the edges).
This computes the area via Green's theorem. Using the vector field
... |
def get_single_generation(self, table, db='default'):
"""Creates a random generation value for a single table name"""
key = self.keygen.gen_table_key(table, db)
val = self.cache_backend.get(key, None, db)
#if local.get('in_test', None): print force_bytes(val).ljust(32), key
if va... | Creates a random generation value for a single table name | Below is the the instruction that describes the task:
### Input:
Creates a random generation value for a single table name
### Response:
def get_single_generation(self, table, db='default'):
"""Creates a random generation value for a single table name"""
key = self.keygen.gen_table_key(table, db)
... |
def _crop_box(self, size):
"""
Helper that calculates the crop box for the offset within the image.
:param size: The width and height of the image composition.
:type size: tuple
:returns: The bounding box of the image, given ``size``.
:rtype: tuple
"""
(l... | Helper that calculates the crop box for the offset within the image.
:param size: The width and height of the image composition.
:type size: tuple
:returns: The bounding box of the image, given ``size``.
:rtype: tuple | Below is the the instruction that describes the task:
### Input:
Helper that calculates the crop box for the offset within the image.
:param size: The width and height of the image composition.
:type size: tuple
:returns: The bounding box of the image, given ``size``.
:rtype: tuple
... |
def _extractText(self, format):
"""_extractText(self, format) -> PyObject *"""
val = _fitz.TextPage__extractText(self, format)
if format != 2:
return val
import base64, json
class b64encode(json.JSONEncoder):
def default(self,s):
if not f... | _extractText(self, format) -> PyObject * | Below is the the instruction that describes the task:
### Input:
_extractText(self, format) -> PyObject *
### Response:
def _extractText(self, format):
"""_extractText(self, format) -> PyObject *"""
val = _fitz.TextPage__extractText(self, format)
if format != 2:
return val
... |
def disable(self):
"""
Disable the Cloud.
:returns: A list of mist.clients' updated clouds.
"""
payload = {
"new_state": "0"
}
data = json.dumps(payload)
req = self.request(self.mist_client.uri+'/clouds/'+self.id, data=data)
req.post(... | Disable the Cloud.
:returns: A list of mist.clients' updated clouds. | Below is the the instruction that describes the task:
### Input:
Disable the Cloud.
:returns: A list of mist.clients' updated clouds.
### Response:
def disable(self):
"""
Disable the Cloud.
:returns: A list of mist.clients' updated clouds.
"""
payload = {
... |
def fulltext_item(self, itemkey, **kwargs):
""" Get full-text content for an item"""
query_string = "/{t}/{u}/items/{itemkey}/fulltext".format(
t=self.library_type, u=self.library_id, itemkey=itemkey
)
return self._build_query(query_string) | Get full-text content for an item | Below is the the instruction that describes the task:
### Input:
Get full-text content for an item
### Response:
def fulltext_item(self, itemkey, **kwargs):
""" Get full-text content for an item"""
query_string = "/{t}/{u}/items/{itemkey}/fulltext".format(
t=self.library_type, u=self.li... |
def _get_gae_credentials():
"""Gets Google App Engine App Identity credentials and project ID."""
# While this library is normally bundled with app_engine, there are
# some cases where it's not available, so we tolerate ImportError.
try:
import google.auth.app_engine as app_engine
except Imp... | Gets Google App Engine App Identity credentials and project ID. | Below is the the instruction that describes the task:
### Input:
Gets Google App Engine App Identity credentials and project ID.
### Response:
def _get_gae_credentials():
"""Gets Google App Engine App Identity credentials and project ID."""
# While this library is normally bundled with app_engine, there ar... |
def assertit(self):
"""Assert the fact within CLIPS."""
data = clips.data.DataObject(self._env)
data.value = list(self._multifield)
if lib.EnvPutFactSlot(
self._env, self._fact, ffi.NULL, data.byref) != 1:
raise CLIPSError(self._env)
super(ImpliedFac... | Assert the fact within CLIPS. | Below is the the instruction that describes the task:
### Input:
Assert the fact within CLIPS.
### Response:
def assertit(self):
"""Assert the fact within CLIPS."""
data = clips.data.DataObject(self._env)
data.value = list(self._multifield)
if lib.EnvPutFactSlot(
se... |
def subscribe(self, subscriber: 'Subscriber',
prepend: bool = False) -> SubscriptionDisposable:
""" Subscribing the given subscriber.
:param subscriber: subscriber to add
:param prepend: For internal use - usually the subscribers will be
added at the end of a list.... | Subscribing the given subscriber.
:param subscriber: subscriber to add
:param prepend: For internal use - usually the subscribers will be
added at the end of a list. When prepend is True, it will be added
in front of the list. This will habe an effect in the order the
... | Below is the the instruction that describes the task:
### Input:
Subscribing the given subscriber.
:param subscriber: subscriber to add
:param prepend: For internal use - usually the subscribers will be
added at the end of a list. When prepend is True, it will be added
in fr... |
def mergemessage(self, message):
""" parse OueueMessage in Model vars """
if isinstance(message, QueueMessage):
""" merge queue message vars """
for key, value in vars(message).items():
if not value is None:
setattr(self, key, value)
... | parse OueueMessage in Model vars | Below is the the instruction that describes the task:
### Input:
parse OueueMessage in Model vars
### Response:
def mergemessage(self, message):
""" parse OueueMessage in Model vars """
if isinstance(message, QueueMessage):
""" merge queue message vars """
for key, value in ... |
def veas2tas(eas, h):
""" Equivalent airspeed to true airspeed """
rho = vdensity(h)
tas = eas * np.sqrt(rho0 / rho)
return tas | Equivalent airspeed to true airspeed | Below is the the instruction that describes the task:
### Input:
Equivalent airspeed to true airspeed
### Response:
def veas2tas(eas, h):
""" Equivalent airspeed to true airspeed """
rho = vdensity(h)
tas = eas * np.sqrt(rho0 / rho)
return tas |
def connect_all(self):
"""[Re-]connects all signals and slots.
If already in "connected" state, ignores the call.
"""
if self.__connected:
return # assert not self.__connected, "connect_all() already in \"connected\" state"
with self.__lock:
for ... | [Re-]connects all signals and slots.
If already in "connected" state, ignores the call. | Below is the the instruction that describes the task:
### Input:
[Re-]connects all signals and slots.
If already in "connected" state, ignores the call.
### Response:
def connect_all(self):
"""[Re-]connects all signals and slots.
If already in "connected" state, ignores the call.
... |
def _WaitForStartup(self, deadline):
"""Waits for the emulator to start.
Args:
deadline: deadline in seconds
Returns:
True if the emulator responds within the deadline, False otherwise.
"""
start = time.time()
sleep = 0.05
def Elapsed():
return time.time() - start
w... | Waits for the emulator to start.
Args:
deadline: deadline in seconds
Returns:
True if the emulator responds within the deadline, False otherwise. | Below is the the instruction that describes the task:
### Input:
Waits for the emulator to start.
Args:
deadline: deadline in seconds
Returns:
True if the emulator responds within the deadline, False otherwise.
### Response:
def _WaitForStartup(self, deadline):
"""Waits for the emulator t... |
def _next_iter_line(self, row_num):
"""
Wrapper around iterating through `self.data` (CSV source).
When a CSV error is raised, we check for specific
error messages that allow us to customize the
error message displayed to the user.
Parameters
----------
... | Wrapper around iterating through `self.data` (CSV source).
When a CSV error is raised, we check for specific
error messages that allow us to customize the
error message displayed to the user.
Parameters
----------
row_num : The row number of the line being parsed. | Below is the the instruction that describes the task:
### Input:
Wrapper around iterating through `self.data` (CSV source).
When a CSV error is raised, we check for specific
error messages that allow us to customize the
error message displayed to the user.
Parameters
------... |
def delete(self, force_drop=False, *args, **kwargs):
"""
Deletes this row. Drops the tenant's schema if the attribute
auto_drop_schema set to True.
"""
self._drop_schema(force_drop)
super().delete(*args, **kwargs) | Deletes this row. Drops the tenant's schema if the attribute
auto_drop_schema set to True. | Below is the the instruction that describes the task:
### Input:
Deletes this row. Drops the tenant's schema if the attribute
auto_drop_schema set to True.
### Response:
def delete(self, force_drop=False, *args, **kwargs):
"""
Deletes this row. Drops the tenant's schema if the attribute
... |
def _preprocess_params(cls, kwargs):
"""Returns a preprocessed dictionary of parameters.
Use this to filter the kwargs passed to `new`, `create`,
`build` methods.
Args:
**kwargs: a dictionary of parameters
"""
# kwargs.pop('csrf_token', None)
for att... | Returns a preprocessed dictionary of parameters.
Use this to filter the kwargs passed to `new`, `create`,
`build` methods.
Args:
**kwargs: a dictionary of parameters | Below is the the instruction that describes the task:
### Input:
Returns a preprocessed dictionary of parameters.
Use this to filter the kwargs passed to `new`, `create`,
`build` methods.
Args:
**kwargs: a dictionary of parameters
### Response:
def _preprocess_params(cls, kwar... |
def compile_state_action_constraints(self,
state: Sequence[tf.Tensor],
action: Sequence[tf.Tensor]) -> List[TensorFluent]:
'''Compiles the state-action constraints given current `state` and `action` fluents.
Args:
state (Sequence[tf.Tensor]): The current state fluent... | Compiles the state-action constraints given current `state` and `action` fluents.
Args:
state (Sequence[tf.Tensor]): The current state fluents.
action (Sequence[tf.Tensor]): The action fluents.
Returns:
A list of :obj:`rddl2tf.fluent.TensorFluent`. | Below is the the instruction that describes the task:
### Input:
Compiles the state-action constraints given current `state` and `action` fluents.
Args:
state (Sequence[tf.Tensor]): The current state fluents.
action (Sequence[tf.Tensor]): The action fluents.
Returns:
... |
def week_schedule(index, on_time=None, off_time=None, off_days=None):
""" Return boolean time series following given week schedule.
Parameters
----------
index : pandas.DatetimeIndex
Datetime index
on_time : str or datetime.time
Daily opening time. Default: '09:00'
off_time : st... | Return boolean time series following given week schedule.
Parameters
----------
index : pandas.DatetimeIndex
Datetime index
on_time : str or datetime.time
Daily opening time. Default: '09:00'
off_time : str or datetime.time
Daily closing time. Default: '17:00'
off_days :... | Below is the the instruction that describes the task:
### Input:
Return boolean time series following given week schedule.
Parameters
----------
index : pandas.DatetimeIndex
Datetime index
on_time : str or datetime.time
Daily opening time. Default: '09:00'
off_time : str or date... |
def delete(cont, path=None, profile=None):
'''
Delete a container, or delete an object from a container.
CLI Example to delete a container::
salt myminion swift.delete mycontainer
CLI Example to delete an object from a container::
salt myminion swift.delete mycontainer remoteobject
... | Delete a container, or delete an object from a container.
CLI Example to delete a container::
salt myminion swift.delete mycontainer
CLI Example to delete an object from a container::
salt myminion swift.delete mycontainer remoteobject | Below is the the instruction that describes the task:
### Input:
Delete a container, or delete an object from a container.
CLI Example to delete a container::
salt myminion swift.delete mycontainer
CLI Example to delete an object from a container::
salt myminion swift.delete mycontainer ... |
def learn(self, bottomUpInput):
"""
Parameters:
--------------------------------------------
input: Current bottom-up input
retval: ?
"""
self.lrnIterationIdx = self.lrnIterationIdx + 1
self.iterationIdx = self.iterationIdx + 1
if self.verbosity >= 3:
print "\n===... | Parameters:
--------------------------------------------
input: Current bottom-up input
retval: ? | Below is the the instruction that describes the task:
### Input:
Parameters:
--------------------------------------------
input: Current bottom-up input
retval: ?
### Response:
def learn(self, bottomUpInput):
"""
Parameters:
--------------------------------------------
inpu... |
def exist_edge(self, graph, orig, dest, idx, branch, turn, tick, extant):
"""Declare whether or not this edge exists."""
if (branch, turn, tick) in self._btts:
raise TimeError
self._btts.add((branch, turn, tick))
graph, orig, dest = map(self.pack, (graph, orig, dest))
... | Declare whether or not this edge exists. | Below is the the instruction that describes the task:
### Input:
Declare whether or not this edge exists.
### Response:
def exist_edge(self, graph, orig, dest, idx, branch, turn, tick, extant):
"""Declare whether or not this edge exists."""
if (branch, turn, tick) in self._btts:
raise T... |
def _url_for(endpoint: str, **values) -> Union[str, None]:
"""
The same as flask's url_for, except this also supports building external
urls for hosts that are different from app.config.SERVER_NAME. One case
where this is especially useful is for single page apps, where the frontend
is not hosted by... | The same as flask's url_for, except this also supports building external
urls for hosts that are different from app.config.SERVER_NAME. One case
where this is especially useful is for single page apps, where the frontend
is not hosted by the same server as the backend, but the backend still needs
to gen... | Below is the the instruction that describes the task:
### Input:
The same as flask's url_for, except this also supports building external
urls for hosts that are different from app.config.SERVER_NAME. One case
where this is especially useful is for single page apps, where the frontend
is not hosted by t... |
def sleep(self, seconds):
"""Services all futures while waiting
Args:
seconds (float): Time to wait
"""
until = time.time() + seconds
try:
while True:
self._service_futures([], until)
except TimeoutError:
return | Services all futures while waiting
Args:
seconds (float): Time to wait | Below is the the instruction that describes the task:
### Input:
Services all futures while waiting
Args:
seconds (float): Time to wait
### Response:
def sleep(self, seconds):
"""Services all futures while waiting
Args:
seconds (float): Time to wait
"""
... |
def read_struct_field(self, struct_name, field_name, x, y, p=0):
"""Read the value out of a struct maintained by SARK.
This method is particularly useful for reading fields from the ``sv``
struct which, for example, holds information about system status. See
``sark.h`` for details.
... | Read the value out of a struct maintained by SARK.
This method is particularly useful for reading fields from the ``sv``
struct which, for example, holds information about system status. See
``sark.h`` for details.
Parameters
----------
struct_name : string
... | Below is the the instruction that describes the task:
### Input:
Read the value out of a struct maintained by SARK.
This method is particularly useful for reading fields from the ``sv``
struct which, for example, holds information about system status. See
``sark.h`` for details.
Pa... |
def validate(self, data, schema):
'''Perform a data validation against a given schema.
:param data: an object to validate
:param schema: a Voluptous schema to validate against
'''
try:
return schema(data)
except MultipleInvalid as ie:
errors = []
... | Perform a data validation against a given schema.
:param data: an object to validate
:param schema: a Voluptous schema to validate against | Below is the the instruction that describes the task:
### Input:
Perform a data validation against a given schema.
:param data: an object to validate
:param schema: a Voluptous schema to validate against
### Response:
def validate(self, data, schema):
'''Perform a data validation against a... |
def getArrays(self, attr=None, specfiles=None, sort=False, reverse=False,
selector=None, defaultValue=None):
"""Return a condensed array of data selected from :class:`Fi` instances
from ``self.container`` for fast and convenient data processing.
:param attr: list of :class:`Fi... | Return a condensed array of data selected from :class:`Fi` instances
from ``self.container`` for fast and convenient data processing.
:param attr: list of :class:`Fi` item attributes that should be added
to the returned array. The attributes "id" and "specfile" are always
includ... | Below is the the instruction that describes the task:
### Input:
Return a condensed array of data selected from :class:`Fi` instances
from ``self.container`` for fast and convenient data processing.
:param attr: list of :class:`Fi` item attributes that should be added
to the returned ar... |
def delete_product_by_id(cls, product_id, **kwargs):
"""Delete Product
Delete an instance of Product by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_product_by_id(product_id,... | Delete Product
Delete an instance of Product by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_product_by_id(product_id, async=True)
>>> result = thread.get()
:param a... | Below is the the instruction that describes the task:
### Input:
Delete Product
Delete an instance of Product by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_product_by_id(produc... |
def init_widget(self):
""" Initialize the underlying widget.
"""
super(AndroidSwipeRefreshLayout, self).init_widget()
d = self.declaration
w = self.widget
if not d.enabled:
self.set_enabled(d.enabled)
if d.indicator_background_color:
self.... | Initialize the underlying widget. | Below is the the instruction that describes the task:
### Input:
Initialize the underlying widget.
### Response:
def init_widget(self):
""" Initialize the underlying widget.
"""
super(AndroidSwipeRefreshLayout, self).init_widget()
d = self.declaration
w = self.widget
... |
def gfposc(target, inframe, abcorr, obsrvr, crdsys, coord, relate, refval,
adjust, step, nintvals, cnfine, result=None):
"""
Determine time intervals for which a coordinate of an
observer-target position vector satisfies a numerical constraint.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/... | Determine time intervals for which a coordinate of an
observer-target position vector satisfies a numerical constraint.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfposc_c.html
:param target: Name of the target body.
:type target: str
:param inframe: Name of the reference frame for co... | Below is the the instruction that describes the task:
### Input:
Determine time intervals for which a coordinate of an
observer-target position vector satisfies a numerical constraint.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfposc_c.html
:param target: Name of the target body.
:ty... |
def normalLines(actor, ratio=1, c=(0.6, 0.6, 0.6), alpha=0.8):
"""
Build an ``vtkActor`` made of the normals at vertices shown as lines.
"""
maskPts = vtk.vtkMaskPoints()
maskPts.SetOnRatio(ratio)
maskPts.RandomModeOff()
actor = actor.computeNormals()
src = actor.polydata()
maskPts.S... | Build an ``vtkActor`` made of the normals at vertices shown as lines. | Below is the the instruction that describes the task:
### Input:
Build an ``vtkActor`` made of the normals at vertices shown as lines.
### Response:
def normalLines(actor, ratio=1, c=(0.6, 0.6, 0.6), alpha=0.8):
"""
Build an ``vtkActor`` made of the normals at vertices shown as lines.
"""
maskPts =... |
def execute(self, code, silent=False,
user_variables=None, user_expressions=None, allow_stdin=None):
"""Execute code in the kernel.
Parameters
----------
code : str
A string of Python code.
silent : bool, optional (default False)
If set, ... | Execute code in the kernel.
Parameters
----------
code : str
A string of Python code.
silent : bool, optional (default False)
If set, the kernel will execute the code as quietly possible.
user_variables : list, optional
A list of variable na... | Below is the the instruction that describes the task:
### Input:
Execute code in the kernel.
Parameters
----------
code : str
A string of Python code.
silent : bool, optional (default False)
If set, the kernel will execute the code as quietly possible.
... |
def _load(self, url):
"""
Load from remote, but check local file content to identify duplicate content. If local file is found with
same hash then it is used with metadata from remote object to avoid fetching full content.
:param url:
:return:
"""
self._logger.de... | Load from remote, but check local file content to identify duplicate content. If local file is found with
same hash then it is used with metadata from remote object to avoid fetching full content.
:param url:
:return: | Below is the the instruction that describes the task:
### Input:
Load from remote, but check local file content to identify duplicate content. If local file is found with
same hash then it is used with metadata from remote object to avoid fetching full content.
:param url:
:return:
### Resp... |
def _sort_by_indep(self, func='get_value', i=None, iunit=None, unit=None,
uncover=None, trail=None, linebreak=None,
sort_by_indep=None):
"""
must be called before (or within) _do_linebreak
"""
if sort_by_indep is None:
# TODO: a... | must be called before (or within) _do_linebreak | Below is the the instruction that describes the task:
### Input:
must be called before (or within) _do_linebreak
### Response:
def _sort_by_indep(self, func='get_value', i=None, iunit=None, unit=None,
uncover=None, trail=None, linebreak=None,
sort_by_indep=None):
... |
def get_bounds(self):
"""
Get the parameters of bounding box of the UI element.
Returns:
:obj:`list` <:obj:`float`>: 4-list (top, right, bottom, left) coordinates related to the edge of screen in
NormalizedCoordinate system
"""
size = self.get_size()
... | Get the parameters of bounding box of the UI element.
Returns:
:obj:`list` <:obj:`float`>: 4-list (top, right, bottom, left) coordinates related to the edge of screen in
NormalizedCoordinate system | Below is the the instruction that describes the task:
### Input:
Get the parameters of bounding box of the UI element.
Returns:
:obj:`list` <:obj:`float`>: 4-list (top, right, bottom, left) coordinates related to the edge of screen in
NormalizedCoordinate system
### Response:
def g... |
def host_stanzas(self, config_access):
"""
returns a list of host definitions
"""
defn_lines = self.resolve_defn(config_access)
for val_dict in self.variable_iter(config_access.get_variables()):
subst = list(self.apply_substitutions(defn_lines, val_dict))
... | returns a list of host definitions | Below is the the instruction that describes the task:
### Input:
returns a list of host definitions
### Response:
def host_stanzas(self, config_access):
"""
returns a list of host definitions
"""
defn_lines = self.resolve_defn(config_access)
for val_dict in self.variable_ite... |
def send_mail(recipient, sender, subject="", content="", smtp_host="127.0.0.1", smtp_port=25):
"""
Lightweight mail functionality. Sends an mail from *sender* to *recipient* with *subject* and
*content*. *smtp_host* and *smtp_port* are forwarded to the ``smtplib.SMTP`` constructor. *True*
is returned on... | Lightweight mail functionality. Sends an mail from *sender* to *recipient* with *subject* and
*content*. *smtp_host* and *smtp_port* are forwarded to the ``smtplib.SMTP`` constructor. *True*
is returned on success, *False* otherwise. | Below is the the instruction that describes the task:
### Input:
Lightweight mail functionality. Sends an mail from *sender* to *recipient* with *subject* and
*content*. *smtp_host* and *smtp_port* are forwarded to the ``smtplib.SMTP`` constructor. *True*
is returned on success, *False* otherwise.
### Respo... |
def mod_watch(name, sfun=None, **kwargs):
'''
The docker_container watcher, called to invoke the watch command.
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function sho... | The docker_container watcher, called to invoke the watch command.
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the state being triggered. | Below is the the instruction that describes the task:
### Input:
The docker_container watcher, called to invoke the watch command.
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for th... |
def get_tasks(self,
identifier=None,
task_id=None,
task_type=None,
params=None,
config=None,
verbose=None,
request_kwargs=None):
"""Get tasks from the Archive.org catalog. ``internetarch... | Get tasks from the Archive.org catalog. ``internetarchive`` must be configured
with your logged-in-* cookies to use this function. If no arguments are provided,
all queued tasks for the user will be returned.
:type identifier: str
:param identifier: (optional) The Archive.org identifier... | Below is the the instruction that describes the task:
### Input:
Get tasks from the Archive.org catalog. ``internetarchive`` must be configured
with your logged-in-* cookies to use this function. If no arguments are provided,
all queued tasks for the user will be returned.
:type identifier:... |
def _find_sources(im, target, sources, polarity):
"""Get the subset of source nodes with paths to the target.
Given a target, a list of sources, and a path polarity, perform a
breadth-first search upstream from the target to determine whether any of
the queried sources have paths to the target with the... | Get the subset of source nodes with paths to the target.
Given a target, a list of sources, and a path polarity, perform a
breadth-first search upstream from the target to determine whether any of
the queried sources have paths to the target with the appropriate polarity.
For efficiency, does not retur... | Below is the the instruction that describes the task:
### Input:
Get the subset of source nodes with paths to the target.
Given a target, a list of sources, and a path polarity, perform a
breadth-first search upstream from the target to determine whether any of
the queried sources have paths to the tar... |
def print(self):
"""Print self."""
print(
'{dim}Identifier:{none} {cyan}{identifier}{none}\n'
'{dim}Name:{none} {name}\n'
'{dim}Description:{none}\n{description}'.format(
dim=Style.DIM,
cyan=Fore.CYAN,
none=Style.RESET_A... | Print self. | Below is the the instruction that describes the task:
### Input:
Print self.
### Response:
def print(self):
"""Print self."""
print(
'{dim}Identifier:{none} {cyan}{identifier}{none}\n'
'{dim}Name:{none} {name}\n'
'{dim}Description:{none}\n{description}'.format(
... |
def _append_to_data_parts(self, data, start, end):
'''
Intelligently appends data to self.string_parts.
For use by self._format.
'''
try:
while data[start] == ' ':
start += 1
if start == end:
end = len(data[start:])
... | Intelligently appends data to self.string_parts.
For use by self._format. | Below is the the instruction that describes the task:
### Input:
Intelligently appends data to self.string_parts.
For use by self._format.
### Response:
def _append_to_data_parts(self, data, start, end):
'''
Intelligently appends data to self.string_parts.
For use by self._format.
... |
def dispose_qualification_type(self, qualification_id):
"""Remove a qualification type we created"""
return self._is_ok(
self.mturk.delete_qualification_type(QualificationTypeId=qualification_id)
) | Remove a qualification type we created | Below is the the instruction that describes the task:
### Input:
Remove a qualification type we created
### Response:
def dispose_qualification_type(self, qualification_id):
"""Remove a qualification type we created"""
return self._is_ok(
self.mturk.delete_qualification_type(Qualificati... |
def before_app_websocket(self, func: Callable) -> Callable:
"""Add a before request websocket to the App.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.before_websocket`. It applies to all requests to the
app this blueprint is registered o... | Add a before request websocket to the App.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.before_websocket`. It applies to all requests to the
app this blueprint is registered on. An example usage,
.. code-block:: python
bluep... | Below is the the instruction that describes the task:
### Input:
Add a before request websocket to the App.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.before_websocket`. It applies to all requests to the
app this blueprint is registered on.... |
def factory(fileobject, jfs, parentpath): # fileobject from lxml.objectify
'Class method to get the correct file class instatiated'
if hasattr(fileobject, 'currentRevision'): # a normal file
return JFSFile(fileobject, jfs, parentpath)
elif str(fileobject.latestRevision.state) == Prot... | Class method to get the correct file class instatiated | Below is the the instruction that describes the task:
### Input:
Class method to get the correct file class instatiated
### Response:
def factory(fileobject, jfs, parentpath): # fileobject from lxml.objectify
'Class method to get the correct file class instatiated'
if hasattr(fileobject, 'currentRe... |
def _normalize_url(graph: BELGraph, keyword: str) -> Optional[str]: # FIXME move to utilities and unit test
"""Normalize a URL for the BEL graph."""
if keyword == BEL_DEFAULT_NAMESPACE and BEL_DEFAULT_NAMESPACE not in graph.namespace_url:
return BEL_DEFAULT_NAMESPACE_URL
return graph.namespace_url... | Normalize a URL for the BEL graph. | Below is the the instruction that describes the task:
### Input:
Normalize a URL for the BEL graph.
### Response:
def _normalize_url(graph: BELGraph, keyword: str) -> Optional[str]: # FIXME move to utilities and unit test
"""Normalize a URL for the BEL graph."""
if keyword == BEL_DEFAULT_NAMESPACE and BEL... |
def from_global_moment_and_saxis(cls, global_moment, saxis):
"""
Convenience method to initialize Magmom from a given global
magnetic moment, i.e. magnetic moment with saxis=(0,0,1), and
provided saxis.
Method is useful if you do not know the components of your
m... | Convenience method to initialize Magmom from a given global
magnetic moment, i.e. magnetic moment with saxis=(0,0,1), and
provided saxis.
Method is useful if you do not know the components of your
magnetic moment in frame of your desired saxis.
:param global_mom... | Below is the the instruction that describes the task:
### Input:
Convenience method to initialize Magmom from a given global
magnetic moment, i.e. magnetic moment with saxis=(0,0,1), and
provided saxis.
Method is useful if you do not know the components of your
magnetic mome... |
def to_date(self):
"""
construct datetime.date instance represented calendar date of BusinessDate instance
:return datetime.date:
"""
y, m, d = self.to_ymd()
return date(y, m, d) | construct datetime.date instance represented calendar date of BusinessDate instance
:return datetime.date: | Below is the the instruction that describes the task:
### Input:
construct datetime.date instance represented calendar date of BusinessDate instance
:return datetime.date:
### Response:
def to_date(self):
"""
construct datetime.date instance represented calendar date of BusinessDate instan... |
def handle(self, handler):
""" register a handler (add a callback function) """
with self._hlock:
self._handler_list.append(handler)
return self | register a handler (add a callback function) | Below is the the instruction that describes the task:
### Input:
register a handler (add a callback function)
### Response:
def handle(self, handler):
""" register a handler (add a callback function) """
with self._hlock:
self._handler_list.append(handler)
return self |
def get_float_value(self, section, option, default=0.0):
"""Get the float value of an option, if it exists."""
try:
return self.parser.getfloat(section, option)
except NoOptionError:
return float(default) | Get the float value of an option, if it exists. | Below is the the instruction that describes the task:
### Input:
Get the float value of an option, if it exists.
### Response:
def get_float_value(self, section, option, default=0.0):
"""Get the float value of an option, if it exists."""
try:
return self.parser.getfloat(section, option)... |
def db_en010(self, value=None):
""" Corresponds to IDD Field `db_en010`
mean coincident dry-bulb temperature to
Enthalpy corresponding to 1.0% annual cumulative frequency of occurrence
Args:
value (float): value for IDD Field `db_en010`
Unit: C
... | Corresponds to IDD Field `db_en010`
mean coincident dry-bulb temperature to
Enthalpy corresponding to 1.0% annual cumulative frequency of occurrence
Args:
value (float): value for IDD Field `db_en010`
Unit: C
if `value` is None it will not be checked ... | Below is the the instruction that describes the task:
### Input:
Corresponds to IDD Field `db_en010`
mean coincident dry-bulb temperature to
Enthalpy corresponding to 1.0% annual cumulative frequency of occurrence
Args:
value (float): value for IDD Field `db_en010`
... |
def do_gdbserver(self):
"""! @brief Handle 'gdbserver' subcommand."""
self._process_commands(self._args.commands)
gdbs = []
try:
# Build dict of session options.
sessionOptions = convert_session_options(self._args.options)
sessionOptions.update({
... | ! @brief Handle 'gdbserver' subcommand. | Below is the the instruction that describes the task:
### Input:
! @brief Handle 'gdbserver' subcommand.
### Response:
def do_gdbserver(self):
"""! @brief Handle 'gdbserver' subcommand."""
self._process_commands(self._args.commands)
gdbs = []
try:
# Build dict of sessio... |
def make(parser):
"""provison Manila Share with HA"""
s = parser.add_subparsers(
title='commands',
metavar='COMMAND',
help='description',
)
def install_f(args):
install(args)
install_parser = install_subparser(s)
install_parser.set_defaults(func=install_f) | provison Manila Share with HA | Below is the the instruction that describes the task:
### Input:
provison Manila Share with HA
### Response:
def make(parser):
"""provison Manila Share with HA"""
s = parser.add_subparsers(
title='commands',
metavar='COMMAND',
help='description',
)
def install_f(args):
... |
def add_var_condor_cmd(self, command):
"""
Add a condor command to the submit file that allows variable (macro)
arguments to be passes to the executable.
"""
if command not in self.__var_cmds:
self.__var_cmds.append(command)
macro = self.__bad_macro_chars.sub( r'', command )
... | Add a condor command to the submit file that allows variable (macro)
arguments to be passes to the executable. | Below is the the instruction that describes the task:
### Input:
Add a condor command to the submit file that allows variable (macro)
arguments to be passes to the executable.
### Response:
def add_var_condor_cmd(self, command):
"""
Add a condor command to the submit file that allows variable (macro)
... |
def parse(self, name, description):
"""
Parse option name.
:param name: option's name
:param description: option's description
Parsing acceptable names:
* -f: shortname
* --force: longname
* -f, --force: shortname and longname
* ... | Parse option name.
:param name: option's name
:param description: option's description
Parsing acceptable names:
* -f: shortname
* --force: longname
* -f, --force: shortname and longname
* -o <output>: shortname and a required value
... | Below is the the instruction that describes the task:
### Input:
Parse option name.
:param name: option's name
:param description: option's description
Parsing acceptable names:
* -f: shortname
* --force: longname
* -f, --force: shortname and longname
... |
def validate_number_attribute(self,
attribute: str,
value_type: Union[Type[int], Type[float]] = int,
minimum: Optional[Union[int, float]] = None,
maximum: Optional[Union[int, float]] =... | Validates that the attribute contains a numeric value within boundaries if specified | Below is the the instruction that describes the task:
### Input:
Validates that the attribute contains a numeric value within boundaries if specified
### Response:
def validate_number_attribute(self,
attribute: str,
value_type: Union[Type[int], Ty... |
def end(self, *args):
"""
End a nested log.
"""
if self._is_verbose:
# verbose log has no end method
return self
if not args:
self._indent -= 1
return self
self.writeln('end', *args)
self._indent -= 1
retur... | End a nested log. | Below is the the instruction that describes the task:
### Input:
End a nested log.
### Response:
def end(self, *args):
"""
End a nested log.
"""
if self._is_verbose:
# verbose log has no end method
return self
if not args:
self._indent -... |
def create_new_code(cls,**kwargs):
'''
Creates a new Voucher with a unique voucherId
'''
prefix = kwargs.pop('prefix','')
new = False
while not new:
# Standard is a ten-letter random string of uppercase letters
random_string = ''.join(random.choic... | Creates a new Voucher with a unique voucherId | Below is the the instruction that describes the task:
### Input:
Creates a new Voucher with a unique voucherId
### Response:
def create_new_code(cls,**kwargs):
'''
Creates a new Voucher with a unique voucherId
'''
prefix = kwargs.pop('prefix','')
new = False
while n... |
def sync(self, folders):
"""Syncs a list of folders to their assicated buckets.
folders: A list of 2-tuples in the form (folder, bucket)
"""
if not folders:
raise ValueError("No folders to sync given")
for folder in folders:
self.sync_folder(*fold... | Syncs a list of folders to their assicated buckets.
folders: A list of 2-tuples in the form (folder, bucket) | Below is the the instruction that describes the task:
### Input:
Syncs a list of folders to their assicated buckets.
folders: A list of 2-tuples in the form (folder, bucket)
### Response:
def sync(self, folders):
"""Syncs a list of folders to their assicated buckets.
folde... |
def configure(self, kubernetes_host, kubernetes_ca_cert='', token_reviewer_jwt='', pem_keys=None,
mount_point=DEFAULT_MOUNT_POINT):
"""Configure the connection parameters for Kubernetes.
This path honors the distinction between the create and update capabilities inside ACL policies.
... | Configure the connection parameters for Kubernetes.
This path honors the distinction between the create and update capabilities inside ACL policies.
Supported methods:
POST: /auth/{mount_point}/config. Produces: 204 (empty body)
:param kubernetes_host: Host must be a host string, ... | Below is the the instruction that describes the task:
### Input:
Configure the connection parameters for Kubernetes.
This path honors the distinction between the create and update capabilities inside ACL policies.
Supported methods:
POST: /auth/{mount_point}/config. Produces: 204 (empt... |
def _compare_expected(expected, output, sess, onnx, decimal=5, onnx_shape=None, **kwargs):
"""
Compares the expected output against the runtime outputs.
This is specific to *onnxruntime* due to variable *sess*
of type *onnxruntime.InferenceSession*.
"""
tested = 0
if isinstance(expected, lis... | Compares the expected output against the runtime outputs.
This is specific to *onnxruntime* due to variable *sess*
of type *onnxruntime.InferenceSession*. | Below is the the instruction that describes the task:
### Input:
Compares the expected output against the runtime outputs.
This is specific to *onnxruntime* due to variable *sess*
of type *onnxruntime.InferenceSession*.
### Response:
def _compare_expected(expected, output, sess, onnx, decimal=5, onnx_shape... |
def _imm_delattr(self, name):
'''
A persistent immutable's delattr allows the object's value-caches to be invalidated, otherwise
raises an exception.
'''
if _imm_is_persist(self):
values = _imm_value_data(self)
if name in values:
dd = object.__getattribute__(self, '__dict... | A persistent immutable's delattr allows the object's value-caches to be invalidated, otherwise
raises an exception. | Below is the the instruction that describes the task:
### Input:
A persistent immutable's delattr allows the object's value-caches to be invalidated, otherwise
raises an exception.
### Response:
def _imm_delattr(self, name):
'''
A persistent immutable's delattr allows the object's value-caches to be in... |
def get_scores(self, corpus):
'''
Parameters
----------
corpus
Returns
-------
float, pd.Series
float: point on x-axis at even characteristicness
pd.Series: term -> value between 0 and 1, sorted by score in a descending manner
Background scores from corpus
'''
term_ranks = self.term_ranker(corp... | Parameters
----------
corpus
Returns
-------
float, pd.Series
float: point on x-axis at even characteristicness
pd.Series: term -> value between 0 and 1, sorted by score in a descending manner
Background scores from corpus | Below is the the instruction that describes the task:
### Input:
Parameters
----------
corpus
Returns
-------
float, pd.Series
float: point on x-axis at even characteristicness
pd.Series: term -> value between 0 and 1, sorted by score in a descending manner
Background scores from corpus
### Respons... |
def parse_parameter(self, node):
"""
Parses <Parameter>
@param node: Node containing the <Parameter> element
@type node: xml.etree.Element
@raise ParseError: Raised when the parameter does not have a name.
@raise ParseError: Raised when the parameter does not have a
... | Parses <Parameter>
@param node: Node containing the <Parameter> element
@type node: xml.etree.Element
@raise ParseError: Raised when the parameter does not have a name.
@raise ParseError: Raised when the parameter does not have a
dimension. | Below is the the instruction that describes the task:
### Input:
Parses <Parameter>
@param node: Node containing the <Parameter> element
@type node: xml.etree.Element
@raise ParseError: Raised when the parameter does not have a name.
@raise ParseError: Raised when the parameter doe... |
def wait_until_done(self):
"""
This method will not return until the job is either complete or has
reached an error state. This queries the server periodically to check
for an update in status.
"""
wait = 1
while True:
time.sleep(wait)
self... | This method will not return until the job is either complete or has
reached an error state. This queries the server periodically to check
for an update in status. | Below is the the instruction that describes the task:
### Input:
This method will not return until the job is either complete or has
reached an error state. This queries the server periodically to check
for an update in status.
### Response:
def wait_until_done(self):
"""
This metho... |
def update(self, loadbalancer, name=None, algorithm=None, protocol=None,
halfClosed=None, port=None, timeout=None, httpsRedirect=None):
"""
Provides a way to modify the following attributes of a load balancer:
- name
- algorithm
- protocol
- ha... | Provides a way to modify the following attributes of a load balancer:
- name
- algorithm
- protocol
- halfClosed
- port
- timeout
- httpsRedirect | Below is the the instruction that describes the task:
### Input:
Provides a way to modify the following attributes of a load balancer:
- name
- algorithm
- protocol
- halfClosed
- port
- timeout
- httpsRedirect
### Response:
def up... |
def equivalent_sites(self, scaled_positions, ondublicates='error',
symprec=1e-3):
"""Returns the scaled positions and all their equivalent sites.
Parameters:
scaled_positions: list | array
List of non-equivalent sites given in unit cell coordinates.
... | Returns the scaled positions and all their equivalent sites.
Parameters:
scaled_positions: list | array
List of non-equivalent sites given in unit cell coordinates.
ondublicates : 'keep' | 'replace' | 'warn' | 'error'
Action if `scaled_positions` contain symmetry-equiva... | Below is the the instruction that describes the task:
### Input:
Returns the scaled positions and all their equivalent sites.
Parameters:
scaled_positions: list | array
List of non-equivalent sites given in unit cell coordinates.
ondublicates : 'keep' | 'replace' | 'warn' | 'er... |
def apiv1_root_view():
"""
API root url. Shows a list of active endpoints.
"""
docs_url = current_app.config.get('DOCS_URL',
'http://' + request.host + '/docs')
message = "Welcome to the voeventdb REST API, " \
"interface version '{}'.".format(
... | API root url. Shows a list of active endpoints. | Below is the the instruction that describes the task:
### Input:
API root url. Shows a list of active endpoints.
### Response:
def apiv1_root_view():
"""
API root url. Shows a list of active endpoints.
"""
docs_url = current_app.config.get('DOCS_URL',
'http://'... |
def to_dot(self, f, skip_disconnected=True):
"""Writes a DOT output for the graph to the provided file *f*.
If *skip_disconnected* is set to ``True``, then all distributions
that are not dependent on any other distribution are skipped.
:type f: has to support ``file``-like operations
... | Writes a DOT output for the graph to the provided file *f*.
If *skip_disconnected* is set to ``True``, then all distributions
that are not dependent on any other distribution are skipped.
:type f: has to support ``file``-like operations
:type skip_disconnected: ``bool`` | Below is the the instruction that describes the task:
### Input:
Writes a DOT output for the graph to the provided file *f*.
If *skip_disconnected* is set to ``True``, then all distributions
that are not dependent on any other distribution are skipped.
:type f: has to support ``file``-like... |
def get_namespaces(namespace="", apiserver_url=None):
'''
.. versionadded:: 2016.3.0
Get one or all kubernetes namespaces.
If namespace parameter is omitted, all namespaces will be returned back to user, similar to following kubectl example:
.. code-block:: bash
kubectl get namespaces -o... | .. versionadded:: 2016.3.0
Get one or all kubernetes namespaces.
If namespace parameter is omitted, all namespaces will be returned back to user, similar to following kubectl example:
.. code-block:: bash
kubectl get namespaces -o json
In case namespace is set by user, the output will be si... | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2016.3.0
Get one or all kubernetes namespaces.
If namespace parameter is omitted, all namespaces will be returned back to user, similar to following kubectl example:
.. code-block:: bash
kubectl get namespaces... |
def count(self):
"""
Returns the number of widgets currently displayed (takes child splits
into account).
"""
c = self.main_tab_widget.count()
for child in self.child_splitters:
c += child.count()
return c | Returns the number of widgets currently displayed (takes child splits
into account). | Below is the the instruction that describes the task:
### Input:
Returns the number of widgets currently displayed (takes child splits
into account).
### Response:
def count(self):
"""
Returns the number of widgets currently displayed (takes child splits
into account).
"""
... |
def send(self, request, headers=None, content=None, **kwargs):
"""Prepare and send request object according to configuration.
:param ClientRequest request: The request object to be sent.
:param dict headers: Any headers to add to the request.
:param content: Any body data to add to the ... | Prepare and send request object according to configuration.
:param ClientRequest request: The request object to be sent.
:param dict headers: Any headers to add to the request.
:param content: Any body data to add to the request.
:param config: Any specific config overrides | Below is the the instruction that describes the task:
### Input:
Prepare and send request object according to configuration.
:param ClientRequest request: The request object to be sent.
:param dict headers: Any headers to add to the request.
:param content: Any body data to add to the reque... |
def get_book(self):
"""Gets the ``Book`` at this node.
return: (osid.commenting.Book) - the book represented by this
node
*compliance: mandatory -- This method must be implemented.*
"""
if self._lookup_session is None:
mgr = get_provider_manager('COM... | Gets the ``Book`` at this node.
return: (osid.commenting.Book) - the book represented by this
node
*compliance: mandatory -- This method must be implemented.* | Below is the the instruction that describes the task:
### Input:
Gets the ``Book`` at this node.
return: (osid.commenting.Book) - the book represented by this
node
*compliance: mandatory -- This method must be implemented.*
### Response:
def get_book(self):
"""Gets the ``Bo... |
def _apply_odf_properties(df, headers, model):
"""
Attach properties to the Dataframe to carry along ODF metadata
:param df: The dataframe to be modified
:param headers: The ODF header lines
:param model: The ODF model type
"""
df.headers = headers
df.model = model | Attach properties to the Dataframe to carry along ODF metadata
:param df: The dataframe to be modified
:param headers: The ODF header lines
:param model: The ODF model type | Below is the the instruction that describes the task:
### Input:
Attach properties to the Dataframe to carry along ODF metadata
:param df: The dataframe to be modified
:param headers: The ODF header lines
:param model: The ODF model type
### Response:
def _apply_odf_properties(df, headers, model):
... |
def kick(self, member, reason=None):
"""
Kick an occupant from the MUC.
:param member: The member to kick.
:type member: :class:`Occupant`
:param reason: A reason to show to the members of the conversation
including the kicked member.
:type reason: :class:`st... | Kick an occupant from the MUC.
:param member: The member to kick.
:type member: :class:`Occupant`
:param reason: A reason to show to the members of the conversation
including the kicked member.
:type reason: :class:`str`
:raises aioxmpp.errors.XMPPError: if the serve... | Below is the the instruction that describes the task:
### Input:
Kick an occupant from the MUC.
:param member: The member to kick.
:type member: :class:`Occupant`
:param reason: A reason to show to the members of the conversation
including the kicked member.
:type reason... |
def get(self, index):
"""Gets data values for specified :index:.
:index: Index for which to get data.
:returns: A list in form
[parent, name, priority, comment, done, children].
"""
data = self.data
index2 = self._split(index)
for c in index2[:-1]:
... | Gets data values for specified :index:.
:index: Index for which to get data.
:returns: A list in form
[parent, name, priority, comment, done, children]. | Below is the the instruction that describes the task:
### Input:
Gets data values for specified :index:.
:index: Index for which to get data.
:returns: A list in form
[parent, name, priority, comment, done, children].
### Response:
def get(self, index):
"""Gets data values for spec... |
def update_configs(self, release):
""" Update the fedora-atomic.git repositories for a given release """
git_repo = release['git_repo']
git_cache = release['git_cache']
if not os.path.isdir(git_cache):
self.call(['git', 'clone', '--mirror', git_repo, git_cache])
else:... | Update the fedora-atomic.git repositories for a given release | Below is the the instruction that describes the task:
### Input:
Update the fedora-atomic.git repositories for a given release
### Response:
def update_configs(self, release):
""" Update the fedora-atomic.git repositories for a given release """
git_repo = release['git_repo']
git_cache = re... |
def get_changes(self, extracted_name, similar=False, global_=False):
"""Get the changes this refactoring makes
:parameters:
- `similar`: if `True`, similar expressions/statements are also
replaced.
- `global_`: if `True`, the extracted method/variable will
... | Get the changes this refactoring makes
:parameters:
- `similar`: if `True`, similar expressions/statements are also
replaced.
- `global_`: if `True`, the extracted method/variable will
be global. | Below is the the instruction that describes the task:
### Input:
Get the changes this refactoring makes
:parameters:
- `similar`: if `True`, similar expressions/statements are also
replaced.
- `global_`: if `True`, the extracted method/variable will
be gl... |
def _list_libraries_cached(self, newer_than_secs=-1):
"""
Returns
-------
List of Arctic library names from a cached collection (global per mongo cluster) in mongo.
Long term list_libraries should have a use_cached argument.
"""
_ = self._conn # Ensures the conne... | Returns
-------
List of Arctic library names from a cached collection (global per mongo cluster) in mongo.
Long term list_libraries should have a use_cached argument. | Below is the the instruction that describes the task:
### Input:
Returns
-------
List of Arctic library names from a cached collection (global per mongo cluster) in mongo.
Long term list_libraries should have a use_cached argument.
### Response:
def _list_libraries_cached(self, newer_than_s... |
def resolve_xref(self, env, fromdocname, builder,
typ, target, node, contnode):
# type: (BuildEnvironment, unicode, Builder, unicode, unicode, nodes.Node, nodes.Node) -> nodes.Node # NOQA
"""Resolve the pending_xref *node* with the given *typ* and *target*.
This method sho... | Resolve the pending_xref *node* with the given *typ* and *target*.
This method should return a new node, to replace the xref node,
containing the *contnode* which is the markup content of the
cross-reference.
If no resolution can be found, None can be returned; the xref node will
... | Below is the the instruction that describes the task:
### Input:
Resolve the pending_xref *node* with the given *typ* and *target*.
This method should return a new node, to replace the xref node,
containing the *contnode* which is the markup content of the
cross-reference.
If no re... |
def set_contents(self, stream, chunk_size=None, size=None, size_limit=None,
progress_callback=None):
"""Save contents of stream to file instance.
If a file instance has already been set, this methods raises an
``FileInstanceAlreadySetError`` exception.
:param strea... | Save contents of stream to file instance.
If a file instance has already been set, this methods raises an
``FileInstanceAlreadySetError`` exception.
:param stream: File-like stream.
:param size: Size of stream if known.
:param chunk_size: Desired chunk size to read stream in. I... | Below is the the instruction that describes the task:
### Input:
Save contents of stream to file instance.
If a file instance has already been set, this methods raises an
``FileInstanceAlreadySetError`` exception.
:param stream: File-like stream.
:param size: Size of stream if know... |
def launch(self,
argv=None,
showusageonnoargs=False,
width=0,
helphint="Use with --help for more information.\n",
debug_parser=False):
"""Do the usual stuff to initiallize the program.
Read config files and parse argumen... | Do the usual stuff to initiallize the program.
Read config files and parse arguments, and if the user has used any
of the help/version/settings options, display help and exit.
If debug_parser is false, don't catch ParseErrors and exit with user
friendly help. Crash wit... | Below is the the instruction that describes the task:
### Input:
Do the usual stuff to initiallize the program.
Read config files and parse arguments, and if the user has used any
of the help/version/settings options, display help and exit.
If debug_parser is false, don't ... |
def get_time_as_string(self):
"""stub"""
if self.has_time():
return (str(self.time['hours']).zfill(2) + ':' +
str(self.time['minutes']).zfill(2) + ':' +
str(self.time['seconds']).zfill(2))
raise IllegalState() | stub | Below is the the instruction that describes the task:
### Input:
stub
### Response:
def get_time_as_string(self):
"""stub"""
if self.has_time():
return (str(self.time['hours']).zfill(2) + ':' +
str(self.time['minutes']).zfill(2) + ':' +
str(self.t... |
def filelist(folderpath, ext=None):
'''
Returns a list of all the files contained in the folder specified by `folderpath`.
To filter the files by extension simply add a list containing all the extension with `.` as the second argument.
If `flat` is False, then the Path objects are returned.
'''
... | Returns a list of all the files contained in the folder specified by `folderpath`.
To filter the files by extension simply add a list containing all the extension with `.` as the second argument.
If `flat` is False, then the Path objects are returned. | Below is the the instruction that describes the task:
### Input:
Returns a list of all the files contained in the folder specified by `folderpath`.
To filter the files by extension simply add a list containing all the extension with `.` as the second argument.
If `flat` is False, then the Path objects are r... |
def _get_id2children(id2children, item_id, item_obj):
"""Add the child item IDs for one item object and their children."""
if item_id in id2children:
return id2children[item_id]
child_ids = set()
for child_obj in item_obj.children:
child_id = child_obj.item_id
child_ids.add(child... | Add the child item IDs for one item object and their children. | Below is the the instruction that describes the task:
### Input:
Add the child item IDs for one item object and their children.
### Response:
def _get_id2children(id2children, item_id, item_obj):
"""Add the child item IDs for one item object and their children."""
if item_id in id2children:
return ... |
def create_user_pool(PoolName=None, Policies=None, LambdaConfig=None, AutoVerifiedAttributes=None, AliasAttributes=None, SmsVerificationMessage=None, EmailVerificationMessage=None, EmailVerificationSubject=None, SmsAuthenticationMessage=None, MfaConfiguration=None, DeviceConfiguration=None, EmailConfiguration=None, Sms... | Creates a new Amazon Cognito user pool and sets the password policy for the pool.
See also: AWS API Documentation
:example: response = client.create_user_pool(
PoolName='string',
Policies={
'PasswordPolicy': {
'MinimumLength': 123,
'RequireUp... | Below is the the instruction that describes the task:
### Input:
Creates a new Amazon Cognito user pool and sets the password policy for the pool.
See also: AWS API Documentation
:example: response = client.create_user_pool(
PoolName='string',
Policies={
'PasswordPolicy... |
def victims(self, filters=None, params=None):
"""
Gets all victims from a tag.
"""
victim = self._tcex.ti.victim(None)
for v in self.tc_requests.victims_from_tag(
victim, self.name, filters=filters, params=params
):
yield v | Gets all victims from a tag. | Below is the the instruction that describes the task:
### Input:
Gets all victims from a tag.
### Response:
def victims(self, filters=None, params=None):
"""
Gets all victims from a tag.
"""
victim = self._tcex.ti.victim(None)
for v in self.tc_requests.victims_from_tag(
... |
def authenticationAndCipheringResponse(
AuthenticationParameterSRES_presence=0,
MobileId_presence=0):
"""AUTHENTICATION AND CIPHERING RESPONSE Section 9.4.10"""
a = TpPd(pd=0x3)
b = MessageType(mesType=0x13) # 00010011
c = Ac... | AUTHENTICATION AND CIPHERING RESPONSE Section 9.4.10 | Below is the the instruction that describes the task:
### Input:
AUTHENTICATION AND CIPHERING RESPONSE Section 9.4.10
### Response:
def authenticationAndCipheringResponse(
AuthenticationParameterSRES_presence=0,
MobileId_presence=0):
... |
def deploy_snmp(snmp, host=None, admin_username=None,
admin_password=None, module=None):
'''
Change the QuickDeploy SNMP community string, used for switches as well
CLI Example:
.. code-block:: bash
salt dell dracr.deploy_snmp SNMP_STRING
host=<remote DRAC or CMC> ... | Change the QuickDeploy SNMP community string, used for switches as well
CLI Example:
.. code-block:: bash
salt dell dracr.deploy_snmp SNMP_STRING
host=<remote DRAC or CMC> admin_username=<DRAC user>
admin_password=<DRAC PW>
salt dell dracr.deploy_password diana secret | Below is the the instruction that describes the task:
### Input:
Change the QuickDeploy SNMP community string, used for switches as well
CLI Example:
.. code-block:: bash
salt dell dracr.deploy_snmp SNMP_STRING
host=<remote DRAC or CMC> admin_username=<DRAC user>
admin_pas... |
def lstsq(cls, a, b):
"""Return the least-squares solution to a linear matrix equation.
:param Matrix a: Design matrix with the values of the independent variables.
:param Matrix b: Matrix with the "dependent variable" values.
b can only have one column.
... | Return the least-squares solution to a linear matrix equation.
:param Matrix a: Design matrix with the values of the independent variables.
:param Matrix b: Matrix with the "dependent variable" values.
b can only have one column.
:raise: Raises an ... | Below is the the instruction that describes the task:
### Input:
Return the least-squares solution to a linear matrix equation.
:param Matrix a: Design matrix with the values of the independent variables.
:param Matrix b: Matrix with the "dependent variable" values.
... |
def _generateTabularData(res, oldTabularData = {}, isTerminal=False, canUnicode=True):
"""
Method that recovers the values and columns from the current structure
This method is used by:
- usufyToCsvExport
- usufyToOdsExport
- usufyToXlsExport
- usufyToXlsxExport
Args:
... | Method that recovers the values and columns from the current structure
This method is used by:
- usufyToCsvExport
- usufyToOdsExport
- usufyToXlsExport
- usufyToXlsxExport
Args:
-----
res: New data to export.
oldTabularData: The previous data stored.
... | Below is the the instruction that describes the task:
### Input:
Method that recovers the values and columns from the current structure
This method is used by:
- usufyToCsvExport
- usufyToOdsExport
- usufyToXlsExport
- usufyToXlsxExport
Args:
-----
res: New data... |
def find_components_without_annotation(model, components):
"""
Find model components with empty annotation attributes.
Parameters
----------
model : cobra.Model
A cobrapy metabolic model.
components : {"metabolites", "reactions", "genes"}
A string denoting `cobra.Model` componen... | Find model components with empty annotation attributes.
Parameters
----------
model : cobra.Model
A cobrapy metabolic model.
components : {"metabolites", "reactions", "genes"}
A string denoting `cobra.Model` components.
Returns
-------
list
The components without an... | Below is the the instruction that describes the task:
### Input:
Find model components with empty annotation attributes.
Parameters
----------
model : cobra.Model
A cobrapy metabolic model.
components : {"metabolites", "reactions", "genes"}
A string denoting `cobra.Model` components... |
def _parse_file(filename, relpath=None):
"""
Return a list of :class:`_PyconfigCall` from parsing `filename`.
:param filename: A file to parse
:param relpath: Relative directory to strip (optional)
:type filename: str
:type relpath: str
"""
with open(filename, 'r') as source:
s... | Return a list of :class:`_PyconfigCall` from parsing `filename`.
:param filename: A file to parse
:param relpath: Relative directory to strip (optional)
:type filename: str
:type relpath: str | Below is the the instruction that describes the task:
### Input:
Return a list of :class:`_PyconfigCall` from parsing `filename`.
:param filename: A file to parse
:param relpath: Relative directory to strip (optional)
:type filename: str
:type relpath: str
### Response:
def _parse_file(filename, r... |
def hash_vector(self, v, querying=False):
"""
Hashes the vector and returns the binary bucket key as string.
"""
if scipy.sparse.issparse(v):
# If vector is sparse, make sure we have the CSR representation
# of the projection matrix
if self.normals_csr... | Hashes the vector and returns the binary bucket key as string. | Below is the the instruction that describes the task:
### Input:
Hashes the vector and returns the binary bucket key as string.
### Response:
def hash_vector(self, v, querying=False):
"""
Hashes the vector and returns the binary bucket key as string.
"""
if scipy.sparse.issparse(v):... |
def GetCampaigns(self, client_customer_id):
"""Returns a client account's Campaigns that haven't been removed.
Args:
client_customer_id: str Client Customer Id used to retrieve Campaigns.
Returns:
list List of Campaign data objects.
"""
self.client.SetClientCustomerId(client_customer_i... | Returns a client account's Campaigns that haven't been removed.
Args:
client_customer_id: str Client Customer Id used to retrieve Campaigns.
Returns:
list List of Campaign data objects. | Below is the the instruction that describes the task:
### Input:
Returns a client account's Campaigns that haven't been removed.
Args:
client_customer_id: str Client Customer Id used to retrieve Campaigns.
Returns:
list List of Campaign data objects.
### Response:
def GetCampaigns(self, clien... |
def get_related(page):
"""
Returns list of related Entry instances for specified page.
:param page: the page instance.
:rtype: list.
"""
related = []
entry = Entry.get_for_model(page)
if entry:
related = entry.related
return related | Returns list of related Entry instances for specified page.
:param page: the page instance.
:rtype: list. | Below is the the instruction that describes the task:
### Input:
Returns list of related Entry instances for specified page.
:param page: the page instance.
:rtype: list.
### Response:
def get_related(page):
"""
Returns list of related Entry instances for specified page.
:param page: the page... |
def download_extract(url):
"""download and extract file."""
logger.info("Downloading %s", url)
request = urllib2.Request(url)
request.add_header('User-Agent',
'caelum/0.1 +https://github.com/nrcharles/caelum')
opener = urllib2.build_opener()
with tempfile.TemporaryFile(suf... | download and extract file. | Below is the the instruction that describes the task:
### Input:
download and extract file.
### Response:
def download_extract(url):
"""download and extract file."""
logger.info("Downloading %s", url)
request = urllib2.Request(url)
request.add_header('User-Agent',
'caelum/0.1... |
def reset(self, history=None):
"""
Resets the Runner's internal stats counters.
If history is empty, use default values in history.get().
Args:
history (dict): A dictionary containing an already run experiment's results. Keys should be:
episode_rewards (list ... | Resets the Runner's internal stats counters.
If history is empty, use default values in history.get().
Args:
history (dict): A dictionary containing an already run experiment's results. Keys should be:
episode_rewards (list of rewards), episode_timesteps (lengths of episodes... | Below is the the instruction that describes the task:
### Input:
Resets the Runner's internal stats counters.
If history is empty, use default values in history.get().
Args:
history (dict): A dictionary containing an already run experiment's results. Keys should be:
epis... |
def zone_transfer(address, dns_name):
"""
Tries to perform a zone transfer.
"""
ips = []
try:
print_notification("Attempting dns zone transfer for {} on {}".format(dns_name, address))
z = dns.zone.from_xfr(dns.query.xfr(address, dns_name))
except dns.exception.FormError:
... | Tries to perform a zone transfer. | Below is the the instruction that describes the task:
### Input:
Tries to perform a zone transfer.
### Response:
def zone_transfer(address, dns_name):
"""
Tries to perform a zone transfer.
"""
ips = []
try:
print_notification("Attempting dns zone transfer for {} on {}".format(dns_na... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.