code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def unstack(self, level=-1, fill_value=None):
"""
Pivot a level of the (necessarily hierarchical) index labels, returning
a DataFrame having a new level of column labels whose inner-most level
consists of the pivoted index labels.
If the index is not a MultiIndex, the output wil... | Pivot a level of the (necessarily hierarchical) index labels, returning
a DataFrame having a new level of column labels whose inner-most level
consists of the pivoted index labels.
If the index is not a MultiIndex, the output will be a Series
(the analogue of stack when the columns are ... | Below is the the instruction that describes the task:
### Input:
Pivot a level of the (necessarily hierarchical) index labels, returning
a DataFrame having a new level of column labels whose inner-most level
consists of the pivoted index labels.
If the index is not a MultiIndex, the output ... |
def headers(self):
''' An instance of :class:`HeaderDict`, a case-insensitive dict-like
view on the response headers. '''
self.__dict__['headers'] = hdict = HeaderDict()
hdict.dict = self._headers
return hdict | An instance of :class:`HeaderDict`, a case-insensitive dict-like
view on the response headers. | Below is the the instruction that describes the task:
### Input:
An instance of :class:`HeaderDict`, a case-insensitive dict-like
view on the response headers.
### Response:
def headers(self):
''' An instance of :class:`HeaderDict`, a case-insensitive dict-like
view on the response ... |
def get_devices(self, hid_filter = None):
"""Filter a HID device list by current object parameters. Devices
must match the all of the filtering parameters
"""
if not hid_filter: #empty list or called without any parameters
if type(hid_filter) == type(None):
... | Filter a HID device list by current object parameters. Devices
must match the all of the filtering parameters | Below is the the instruction that describes the task:
### Input:
Filter a HID device list by current object parameters. Devices
must match the all of the filtering parameters
### Response:
def get_devices(self, hid_filter = None):
"""Filter a HID device list by current object parameters. Devices
... |
def feed(self, can):
"""Attempt to feed an incoming CAN frame into the state machine"""
if not isinstance(can, CAN):
raise Scapy_Exception("argument is not a CAN frame")
identifier = can.identifier
data = bytes(can.data)
if len(data) > 1 and self.use_ext_addr is not ... | Attempt to feed an incoming CAN frame into the state machine | Below is the the instruction that describes the task:
### Input:
Attempt to feed an incoming CAN frame into the state machine
### Response:
def feed(self, can):
"""Attempt to feed an incoming CAN frame into the state machine"""
if not isinstance(can, CAN):
raise Scapy_Exception("argumen... |
def loadtxt_str(path:PathOrStr)->np.ndarray:
"Return `ndarray` of `str` of lines of text from `path`."
with open(path, 'r') as f: lines = f.readlines()
return np.array([l.strip() for l in lines]) | Return `ndarray` of `str` of lines of text from `path`. | Below is the the instruction that describes the task:
### Input:
Return `ndarray` of `str` of lines of text from `path`.
### Response:
def loadtxt_str(path:PathOrStr)->np.ndarray:
"Return `ndarray` of `str` of lines of text from `path`."
with open(path, 'r') as f: lines = f.readlines()
return np.array(... |
def create_record_task(self, frame_parameters: dict=None, channels_enabled: typing.List[bool]=None) -> RecordTask:
"""Create a record task for this hardware source.
.. versionadded:: 1.0
:param frame_parameters: The frame parameters for the record. Pass None for defaults.
:type frame_p... | Create a record task for this hardware source.
.. versionadded:: 1.0
:param frame_parameters: The frame parameters for the record. Pass None for defaults.
:type frame_parameters: :py:class:`FrameParameters`
:param channels_enabled: The enabled channels for the record. Pass None for def... | Below is the the instruction that describes the task:
### Input:
Create a record task for this hardware source.
.. versionadded:: 1.0
:param frame_parameters: The frame parameters for the record. Pass None for defaults.
:type frame_parameters: :py:class:`FrameParameters`
:param cha... |
def sys_lseek(self, fd, offset, whence):
"""
lseek - reposition read/write file offset
The lseek() function repositions the file offset of the open file description associated
with the file descriptor fd to the argument offset according to the directive whence
:param fd: a val... | lseek - reposition read/write file offset
The lseek() function repositions the file offset of the open file description associated
with the file descriptor fd to the argument offset according to the directive whence
:param fd: a valid file descriptor
:param offset: the offset in bytes... | Below is the the instruction that describes the task:
### Input:
lseek - reposition read/write file offset
The lseek() function repositions the file offset of the open file description associated
with the file descriptor fd to the argument offset according to the directive whence
:param f... |
def discrete_rainbow(N=7, cmap=cm.Set1, usepreset=True, shuffle=False, \
plot=False):
"""
Return a discrete colormap and the set of colors.
modified from
<http://www.scipy.org/Cookbook/Matplotlib/ColormapTransformations>
cmap: colormap instance, eg. cm.jet.
N: Number of co... | Return a discrete colormap and the set of colors.
modified from
<http://www.scipy.org/Cookbook/Matplotlib/ColormapTransformations>
cmap: colormap instance, eg. cm.jet.
N: Number of colors.
Example
>>> x = resize(arange(100), (5,100))
>>> djet = cmap_discretize(cm.jet, 5)
>>> imshow(x,... | Below is the the instruction that describes the task:
### Input:
Return a discrete colormap and the set of colors.
modified from
<http://www.scipy.org/Cookbook/Matplotlib/ColormapTransformations>
cmap: colormap instance, eg. cm.jet.
N: Number of colors.
Example
>>> x = resize(arange(100),... |
def print_errors(function):
"""Prints the exceptions raised by the decorated function
without interfering. For debugging purpose."""
def wrapper(*args, **kwargs):
try:
return function(*args, **kwargs)
except BaseException as e:
print ("Exception raise calling %s: %s"... | Prints the exceptions raised by the decorated function
without interfering. For debugging purpose. | Below is the the instruction that describes the task:
### Input:
Prints the exceptions raised by the decorated function
without interfering. For debugging purpose.
### Response:
def print_errors(function):
"""Prints the exceptions raised by the decorated function
without interfering. For debugging purp... |
def selected(self, sel):
"""Called when this item has been selected (sel=True) OR deselected (sel=False)"""
ParameterItem.selected(self, sel)
if self.widget is None:
return
if sel and self.param.writable():
self.showEditor()
elif self.hideWidget:
... | Called when this item has been selected (sel=True) OR deselected (sel=False) | Below is the the instruction that describes the task:
### Input:
Called when this item has been selected (sel=True) OR deselected (sel=False)
### Response:
def selected(self, sel):
"""Called when this item has been selected (sel=True) OR deselected (sel=False)"""
ParameterItem.selected(self, sel)
... |
def get_argument( # noqa: F811
self,
name: str,
default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT,
strip: bool = True,
) -> Optional[str]:
"""Returns the value of the argument with the given name.
If default is not provided, the argument is considered to b... | Returns the value of the argument with the given name.
If default is not provided, the argument is considered to be
required, and we raise a `MissingArgumentError` if it is missing.
If the argument appears in the request more than once, we return the
last value.
This method se... | Below is the the instruction that describes the task:
### Input:
Returns the value of the argument with the given name.
If default is not provided, the argument is considered to be
required, and we raise a `MissingArgumentError` if it is missing.
If the argument appears in the request more... |
def c_hashes(self):
"""Get the hashes of the module including functions and DLLs.
"""
if callable(self.opts.hash_func):
hashes = [
'# define {}{} {}\n'.format(
self.opts.prefix, name, self.opts.hash_func(name)
) for name, dummy_args... | Get the hashes of the module including functions and DLLs. | Below is the the instruction that describes the task:
### Input:
Get the hashes of the module including functions and DLLs.
### Response:
def c_hashes(self):
"""Get the hashes of the module including functions and DLLs.
"""
if callable(self.opts.hash_func):
hashes = [
... |
def t_name(self, s):
r'[A-Za-z_][A-Za-z_0-9]*'
if s in RESERVED_WORDS:
self.add_token(s.upper(), s)
else:
self.add_token('NAME', s) | r'[A-Za-z_][A-Za-z_0-9]* | Below is the the instruction that describes the task:
### Input:
r'[A-Za-z_][A-Za-z_0-9]*
### Response:
def t_name(self, s):
r'[A-Za-z_][A-Za-z_0-9]*'
if s in RESERVED_WORDS:
self.add_token(s.upper(), s)
else:
self.add_token('NAME', s) |
def post_parse(self, uri, params={}, data={}):
'''Convenience method to call post() on an arbitrary URI and parse the response
into a JSON object. Raises an error on non-200 response status.
'''
return self._request_parse(self.post, uri, params, data) | Convenience method to call post() on an arbitrary URI and parse the response
into a JSON object. Raises an error on non-200 response status. | Below is the the instruction that describes the task:
### Input:
Convenience method to call post() on an arbitrary URI and parse the response
into a JSON object. Raises an error on non-200 response status.
### Response:
def post_parse(self, uri, params={}, data={}):
'''Convenience method to call po... |
def search_command_record(
self,
after_context, before_context, context, context_type,
**kwds):
"""
Search command history.
:rtype: [CommandRecord]
"""
if after_context or before_context or context:
kwds['condition_as_column'] = T... | Search command history.
:rtype: [CommandRecord] | Below is the the instruction that describes the task:
### Input:
Search command history.
:rtype: [CommandRecord]
### Response:
def search_command_record(
self,
after_context, before_context, context, context_type,
**kwds):
"""
Search command history.
... |
def _compute_baseline_survival(self):
"""
Importantly, this agrees with what the KaplanMeierFitter produces. Ex:
Example
-------
>>> from lifelines.datasets import load_rossi
>>> from lifelines import CoxPHFitter, KaplanMeierFitter
>>> rossi = load_rossi()
... | Importantly, this agrees with what the KaplanMeierFitter produces. Ex:
Example
-------
>>> from lifelines.datasets import load_rossi
>>> from lifelines import CoxPHFitter, KaplanMeierFitter
>>> rossi = load_rossi()
>>> kmf = KaplanMeierFitter()
>>> kmf.fit(rossi[... | Below is the the instruction that describes the task:
### Input:
Importantly, this agrees with what the KaplanMeierFitter produces. Ex:
Example
-------
>>> from lifelines.datasets import load_rossi
>>> from lifelines import CoxPHFitter, KaplanMeierFitter
>>> rossi = load_ros... |
def are_tokens_valid(self, tokens):
"""
Check if tokens are valid tokens for the locale.
:param tokens:
a list of string or unicode tokens.
:type tokens: list
:return: True if tokens are valid, False otherwise.
"""
match_relative_regex = self._get_ma... | Check if tokens are valid tokens for the locale.
:param tokens:
a list of string or unicode tokens.
:type tokens: list
:return: True if tokens are valid, False otherwise. | Below is the the instruction that describes the task:
### Input:
Check if tokens are valid tokens for the locale.
:param tokens:
a list of string or unicode tokens.
:type tokens: list
:return: True if tokens are valid, False otherwise.
### Response:
def are_tokens_valid(self, ... |
def crtGauss2D(varSizeX, varSizeY, varPosX, varPosY, varSd):
"""Create 2D Gaussian kernel.
Parameters
----------
varSizeX : int, positive
Width of the visual field.
varSizeY : int, positive
Height of the visual field..
varPosX : int, positive
X position of centre of 2D G... | Create 2D Gaussian kernel.
Parameters
----------
varSizeX : int, positive
Width of the visual field.
varSizeY : int, positive
Height of the visual field..
varPosX : int, positive
X position of centre of 2D Gauss.
varPosY : int, positive
Y position of centre of 2D... | Below is the the instruction that describes the task:
### Input:
Create 2D Gaussian kernel.
Parameters
----------
varSizeX : int, positive
Width of the visual field.
varSizeY : int, positive
Height of the visual field..
varPosX : int, positive
X position of centre of 2D ... |
def freqItems(self, cols, support=None):
"""
Finding frequent items for columns, possibly with false positives. Using the
frequent element count algorithm described in
"https://doi.org/10.1145/762471.762473, proposed by Karp, Schenker, and Papadimitriou".
:func:`DataFrame.freqIte... | Finding frequent items for columns, possibly with false positives. Using the
frequent element count algorithm described in
"https://doi.org/10.1145/762471.762473, proposed by Karp, Schenker, and Papadimitriou".
:func:`DataFrame.freqItems` and :func:`DataFrameStatFunctions.freqItems` are aliases.... | Below is the the instruction that describes the task:
### Input:
Finding frequent items for columns, possibly with false positives. Using the
frequent element count algorithm described in
"https://doi.org/10.1145/762471.762473, proposed by Karp, Schenker, and Papadimitriou".
:func:`DataFrame... |
def cnfwAlpha(self, R, Rs, rho0, r_core, ax_x, ax_y):
"""
deflection angel of NFW profile along the projection to coordinate axis
:param R: radius of interest
:type R: float/numpy array
:param Rs: scale radius
:type Rs: float
:param rho0: density normalization (c... | deflection angel of NFW profile along the projection to coordinate axis
:param R: radius of interest
:type R: float/numpy array
:param Rs: scale radius
:type Rs: float
:param rho0: density normalization (characteristic density)
:type rho0: float
:param r200: radi... | Below is the the instruction that describes the task:
### Input:
deflection angel of NFW profile along the projection to coordinate axis
:param R: radius of interest
:type R: float/numpy array
:param Rs: scale radius
:type Rs: float
:param rho0: density normalization (charac... |
async def get_property(self, command):
"""Get property state from device."""
_LOGGER.debug("Getting property %s", command)
if self.__checkLock():
return BUSY
timeout = self.__get_timeout(command)
response = await self.send_request(
timeout=timeout,
... | Get property state from device. | Below is the the instruction that describes the task:
### Input:
Get property state from device.
### Response:
async def get_property(self, command):
"""Get property state from device."""
_LOGGER.debug("Getting property %s", command)
if self.__checkLock():
return BUSY
ti... |
def reset(self, rabaClass, namespace = None) :
"""rabaClass can either be a raba class of a string of a raba class name. In the latter case you must provide the namespace argument.
If it's a Raba Class the argument is ignored. If you fear cicular imports use strings"""
if type(rabaClass) is types.StringType :
... | rabaClass can either be a raba class of a string of a raba class name. In the latter case you must provide the namespace argument.
If it's a Raba Class the argument is ignored. If you fear cicular imports use strings | Below is the the instruction that describes the task:
### Input:
rabaClass can either be a raba class of a string of a raba class name. In the latter case you must provide the namespace argument.
If it's a Raba Class the argument is ignored. If you fear cicular imports use strings
### Response:
def reset(self, r... |
def relevent_issue(issue, after):
"""Returns True iff this issue is something we should show in the changelog."""
return (closed_issue(issue, after) and
issue_completed(issue) and
issue_section(issue)) | Returns True iff this issue is something we should show in the changelog. | Below is the the instruction that describes the task:
### Input:
Returns True iff this issue is something we should show in the changelog.
### Response:
def relevent_issue(issue, after):
"""Returns True iff this issue is something we should show in the changelog."""
return (closed_issue(issue, after) and
... |
def __parseResponseServer(self):
"""Parses the response of the server.
Exception
---------
A Sitools2Exception is raised when the server does not send back a success."""
self.__logger.debug(Sitools2Abstract.getBaseUrl(self) + SITools2Instance.PROJECTS_URI)
... | Parses the response of the server.
Exception
---------
A Sitools2Exception is raised when the server does not send back a success. | Below is the the instruction that describes the task:
### Input:
Parses the response of the server.
Exception
---------
A Sitools2Exception is raised when the server does not send back a success.
### Response:
def __parseResponseServer(self):
"""Parses the response of the server.
... |
def load(self, file_name):
"""Load a raw data-file
Args:
file_name (path)
Returns:
loaded test
"""
new_rundata = self.loader(file_name)
new_rundata = self.inspect(new_rundata)
return new_rundata | Load a raw data-file
Args:
file_name (path)
Returns:
loaded test | Below is the the instruction that describes the task:
### Input:
Load a raw data-file
Args:
file_name (path)
Returns:
loaded test
### Response:
def load(self, file_name):
"""Load a raw data-file
Args:
file_name (path)
Returns:
... |
def permute_graph(G, order):
'''Reorder the graph's vertices, returning a copy of the input graph.
order : integer array-like, some permutation of range(G.num_vertices()).
'''
adj = G.matrix('dense')
adj = adj[np.ix_(order, order)]
return Graph.from_adj_matrix(adj) | Reorder the graph's vertices, returning a copy of the input graph.
order : integer array-like, some permutation of range(G.num_vertices()). | Below is the the instruction that describes the task:
### Input:
Reorder the graph's vertices, returning a copy of the input graph.
order : integer array-like, some permutation of range(G.num_vertices()).
### Response:
def permute_graph(G, order):
'''Reorder the graph's vertices, returning a copy of the input ... |
def _init_create_child(self):
"""
Initialize the base class :attr:`create_child` and
:attr:`create_child_args` according to whether we need a PTY or not.
"""
if self._requires_pty():
self.create_child = mitogen.parent.hybrid_tty_create_child
else:
... | Initialize the base class :attr:`create_child` and
:attr:`create_child_args` according to whether we need a PTY or not. | Below is the the instruction that describes the task:
### Input:
Initialize the base class :attr:`create_child` and
:attr:`create_child_args` according to whether we need a PTY or not.
### Response:
def _init_create_child(self):
"""
Initialize the base class :attr:`create_child` and
... |
def mass_3d(self, r, rho0, gamma):
"""
mass enclosed a 3d sphere or radius r
:param r:
:param a:
:param s:
:return:
"""
mass_3d = 4 * np.pi * rho0 /(-gamma + 3) * r ** (-gamma + 3)
return mass_3d | mass enclosed a 3d sphere or radius r
:param r:
:param a:
:param s:
:return: | Below is the the instruction that describes the task:
### Input:
mass enclosed a 3d sphere or radius r
:param r:
:param a:
:param s:
:return:
### Response:
def mass_3d(self, r, rho0, gamma):
"""
mass enclosed a 3d sphere or radius r
:param r:
:param a... |
def disassociate_hosting_device_with_config_agent(
self, client, config_agent_id, hosting_device_id):
"""Disassociates a hosting_device with a config agent."""
return client.delete((ConfigAgentHandlingHostingDevice.resource_path +
CFG_AGENT_HOSTING_DEVICES + "/%... | Disassociates a hosting_device with a config agent. | Below is the the instruction that describes the task:
### Input:
Disassociates a hosting_device with a config agent.
### Response:
def disassociate_hosting_device_with_config_agent(
self, client, config_agent_id, hosting_device_id):
"""Disassociates a hosting_device with a config agent."""
... |
def _etree_py26_write(f, tree):
"""
Compatibility workaround for ElementTree shipped with py2.6
"""
f.write("<?xml version='1.0' encoding='utf-8'?>\n".encode('utf-8'))
if etree.VERSION[:3] == '1.2':
def fixtag(tag, namespaces):
if tag == XML_NS + 'lang':
return '... | Compatibility workaround for ElementTree shipped with py2.6 | Below is the the instruction that describes the task:
### Input:
Compatibility workaround for ElementTree shipped with py2.6
### Response:
def _etree_py26_write(f, tree):
"""
Compatibility workaround for ElementTree shipped with py2.6
"""
f.write("<?xml version='1.0' encoding='utf-8'?>\n".encode('u... |
def fetch(self, url, open_graph=None, twitter_card=None, touch_icon=None,
favicon=None, all_images=None, parser=None, handle_file_content=None,
canonical=None):
"""Retrieves content from the specified url, parses it, and returns
a beautifully crafted dictionary of important i... | Retrieves content from the specified url, parses it, and returns
a beautifully crafted dictionary of important information about that
web page.
Priority tree is as follows:
1. OEmbed
2. Open Graph
3. Twitter Card
4. Other meta content (i.e. descri... | Below is the the instruction that describes the task:
### Input:
Retrieves content from the specified url, parses it, and returns
a beautifully crafted dictionary of important information about that
web page.
Priority tree is as follows:
1. OEmbed
2. Open Graph
... |
def reject(self):
"""
Emits the accepted signal and closes the popup.
"""
self._result = 0
if not self.signalsBlocked():
self.rejected.emit()
if self.autoCloseOnReject():
self.close() | Emits the accepted signal and closes the popup. | Below is the the instruction that describes the task:
### Input:
Emits the accepted signal and closes the popup.
### Response:
def reject(self):
"""
Emits the accepted signal and closes the popup.
"""
self._result = 0
if not self.signalsBlocked():
self.reje... |
def get_recent_async(self, count, callback):
"""Similar to `get_recent` except instead of returning an iterable, passes each dict to the given function which
must accept a single argument. Returns the request.
`callback` (mandatory) (function) instead of returning an iterable, pass each dict (a... | Similar to `get_recent` except instead of returning an iterable, passes each dict to the given function which
must accept a single argument. Returns the request.
`callback` (mandatory) (function) instead of returning an iterable, pass each dict (as described above) to the
given function which m... | Below is the the instruction that describes the task:
### Input:
Similar to `get_recent` except instead of returning an iterable, passes each dict to the given function which
must accept a single argument. Returns the request.
`callback` (mandatory) (function) instead of returning an iterable, pass... |
def _sim_strlen(self, str_addr):
"""
Return the result of invoking the strlen simprocedure on `str_addr`.
"""
from .. import SIM_PROCEDURES
strlen = SIM_PROCEDURES['libc']['strlen']
return self.inline_call(strlen, str_addr).ret_expr | Return the result of invoking the strlen simprocedure on `str_addr`. | Below is the the instruction that describes the task:
### Input:
Return the result of invoking the strlen simprocedure on `str_addr`.
### Response:
def _sim_strlen(self, str_addr):
"""
Return the result of invoking the strlen simprocedure on `str_addr`.
"""
from .. import SIM_PROCE... |
def recRemoveTreeFormating(element):
"""Removes whitespace characters, which are leftovers from previous xml
formatting.
:param element: an instance of lxml.etree._Element
str.strip() is applied to the "text" and the "tail" attribute of the
element and recursively to all child elements.
"""
... | Removes whitespace characters, which are leftovers from previous xml
formatting.
:param element: an instance of lxml.etree._Element
str.strip() is applied to the "text" and the "tail" attribute of the
element and recursively to all child elements. | Below is the the instruction that describes the task:
### Input:
Removes whitespace characters, which are leftovers from previous xml
formatting.
:param element: an instance of lxml.etree._Element
str.strip() is applied to the "text" and the "tail" attribute of the
element and recursively to all c... |
def add_dispatcher(self, dsp, inputs, outputs, dsp_id=None,
input_domain=None, weight=None, inp_weight=None,
description=None, include_defaults=False,
await_domain=None, **kwargs):
"""
Add a single sub-dispatcher node to dispatcher.
... | Add a single sub-dispatcher node to dispatcher.
:param dsp:
Child dispatcher that is added as sub-dispatcher node to the parent
dispatcher.
:type dsp: Dispatcher | dict[str, list]
:param inputs:
Inputs mapping. Data node ids from parent dispatcher to child
... | Below is the the instruction that describes the task:
### Input:
Add a single sub-dispatcher node to dispatcher.
:param dsp:
Child dispatcher that is added as sub-dispatcher node to the parent
dispatcher.
:type dsp: Dispatcher | dict[str, list]
:param inputs:
... |
def get_table(self, dataset, table, project_id=None):
""" Retrieve a table if it exists, otherwise return an empty dict.
Parameters
----------
dataset : str
The dataset that the table is in
table : str
The name of the table
project_id: str, option... | Retrieve a table if it exists, otherwise return an empty dict.
Parameters
----------
dataset : str
The dataset that the table is in
table : str
The name of the table
project_id: str, optional
The project that the table is in
Returns
... | Below is the the instruction that describes the task:
### Input:
Retrieve a table if it exists, otherwise return an empty dict.
Parameters
----------
dataset : str
The dataset that the table is in
table : str
The name of the table
project_id: str, opt... |
def validate_config_parameters(config_json, allowed_keys, allowed_types):
"""Validate parameters in config file."""
custom_fields = config_json.get(defs.PARAMETERS, [])
for field in custom_fields:
validate_field(field, allowed_keys, allowed_types)
default = field.get(defs.DEFAULT)
fi... | Validate parameters in config file. | Below is the the instruction that describes the task:
### Input:
Validate parameters in config file.
### Response:
def validate_config_parameters(config_json, allowed_keys, allowed_types):
"""Validate parameters in config file."""
custom_fields = config_json.get(defs.PARAMETERS, [])
for field in custom... |
def get_ntp_servers(self):
"""Return the NTP servers configured on the device."""
ntp_table = junos_views.junos_ntp_servers_config_table(self.device)
ntp_table.get()
ntp_servers = ntp_table.items()
if not ntp_servers:
return {}
return {napalm_base.helpers.i... | Return the NTP servers configured on the device. | Below is the the instruction that describes the task:
### Input:
Return the NTP servers configured on the device.
### Response:
def get_ntp_servers(self):
"""Return the NTP servers configured on the device."""
ntp_table = junos_views.junos_ntp_servers_config_table(self.device)
ntp_table.get... |
def _mb_model(self, beta, mini_batch):
""" Creates the structure of the model
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
lambda : np.array
Contains the values for t... | Creates the structure of the model
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
lambda : np.array
Contains the values for the conditional volatility series
Y : np.ar... | Below is the the instruction that describes the task:
### Input:
Creates the structure of the model
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
lambda : np.array
Contain... |
def list_certificates(self):
"""Get the attributes of the current array certificate.
:param \*\*kwargs: See the REST API Guide on your array for the
documentation on the request:
**GET cert**
:type \*\*kwargs: optional
:returns: A l... | Get the attributes of the current array certificate.
:param \*\*kwargs: See the REST API Guide on your array for the
documentation on the request:
**GET cert**
:type \*\*kwargs: optional
:returns: A list of dictionaries describing all confi... | Below is the the instruction that describes the task:
### Input:
Get the attributes of the current array certificate.
:param \*\*kwargs: See the REST API Guide on your array for the
documentation on the request:
**GET cert**
:type \*\*kwargs: op... |
def consume_message_with_notify(
notifier_uri_getter):
"""
Decorator for methods handling requests from RabbitMQ
This decorator builds on the :py:func:`consume_message` decorator. It extents
it by logic for notifying a client of the result of handling the
request.
The *notifier_uri_get... | Decorator for methods handling requests from RabbitMQ
This decorator builds on the :py:func:`consume_message` decorator. It extents
it by logic for notifying a client of the result of handling the
request.
The *notifier_uri_getter* argument must be a callable which accepts
*self* and returns the u... | Below is the the instruction that describes the task:
### Input:
Decorator for methods handling requests from RabbitMQ
This decorator builds on the :py:func:`consume_message` decorator. It extents
it by logic for notifying a client of the result of handling the
request.
The *notifier_uri_getter* a... |
def preserve_order(self, value):
"""
Setter method for **self.__preserve_order** attribute.
:param value: Attribute value.
:type value: bool
"""
if value is not None:
assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("preserve_o... | Setter method for **self.__preserve_order** attribute.
:param value: Attribute value.
:type value: bool | Below is the the instruction that describes the task:
### Input:
Setter method for **self.__preserve_order** attribute.
:param value: Attribute value.
:type value: bool
### Response:
def preserve_order(self, value):
"""
Setter method for **self.__preserve_order** attribute.
... |
def spell_check(request):
"""
Returns a HttpResponse that implements the TinyMCE spellchecker protocol.
"""
try:
if not enchant:
raise RuntimeError("install pyenchant for spellchecker functionality")
raw = force_text(request.body)
input = json.loads(raw)
id =... | Returns a HttpResponse that implements the TinyMCE spellchecker protocol. | Below is the the instruction that describes the task:
### Input:
Returns a HttpResponse that implements the TinyMCE spellchecker protocol.
### Response:
def spell_check(request):
"""
Returns a HttpResponse that implements the TinyMCE spellchecker protocol.
"""
try:
if not enchant:
... |
def equinox(date, eop_correction=True, terms=106, kinematic=True):
"""Equinox equation in degrees
"""
epsilon_bar, delta_psi, delta_eps = _nutation(date, eop_correction, terms)
equin = delta_psi * 3600. * np.cos(np.deg2rad(epsilon_bar))
if date.d >= 50506 and kinematic:
# Starting 1992-02-... | Equinox equation in degrees | Below is the the instruction that describes the task:
### Input:
Equinox equation in degrees
### Response:
def equinox(date, eop_correction=True, terms=106, kinematic=True):
"""Equinox equation in degrees
"""
epsilon_bar, delta_psi, delta_eps = _nutation(date, eop_correction, terms)
equin = delta_... |
def get_ip_addresses(self, **kwargs):
"""
Get IP Addresses already set on an Interface.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet etc).
name (str): Name of interface id.
(For interface: 1/0/5, 1/0/10 e... | Get IP Addresses already set on an Interface.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet etc).
name (str): Name of interface id.
(For interface: 1/0/5, 1/0/10 etc).
version (int): 4 or 6 to represent IPv4 o... | Below is the the instruction that describes the task:
### Input:
Get IP Addresses already set on an Interface.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet etc).
name (str): Name of interface id.
(For interface: 1/0/... |
def get_wordpress(self, service_id, version_number, name):
"""Get information on a specific wordpress."""
content = self._fetch("/service/%s/version/%d/wordpress/%s" % (service_id, version_number, name))
return FastlyWordpress(self, content) | Get information on a specific wordpress. | Below is the the instruction that describes the task:
### Input:
Get information on a specific wordpress.
### Response:
def get_wordpress(self, service_id, version_number, name):
"""Get information on a specific wordpress."""
content = self._fetch("/service/%s/version/%d/wordpress/%s" % (service_id, version_nu... |
def delete_event_subscription(self, url):
"""Deregister a callback URL as an event subscriber.
:param str url: callback URL
:returns: the deleted event subscription
:rtype: dict
"""
params = {'callbackUrl': url}
response = self._do_request('DELETE', '/v2/eventSu... | Deregister a callback URL as an event subscriber.
:param str url: callback URL
:returns: the deleted event subscription
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Deregister a callback URL as an event subscriber.
:param str url: callback URL
:returns: the deleted event subscription
:rtype: dict
### Response:
def delete_event_subscription(self, url):
"""Deregister a callback UR... |
def count_rows(self, table, cols='*'):
"""Get the number of rows in a particular table."""
query = 'SELECT COUNT({0}) FROM {1}'.format(join_cols(cols), wrap(table))
result = self.fetch(query)
return result if result is not None else 0 | Get the number of rows in a particular table. | Below is the the instruction that describes the task:
### Input:
Get the number of rows in a particular table.
### Response:
def count_rows(self, table, cols='*'):
"""Get the number of rows in a particular table."""
query = 'SELECT COUNT({0}) FROM {1}'.format(join_cols(cols), wrap(table))
r... |
def c_var_decls(self):
"""Get the needed variable definitions."""
if self.opts.no_structs:
mod_decl = 'HMODULE {} = NULL;\n'.format(self.name)
return [mod_decl] + [
'{} *{} = NULL;\n'.format(
self._c_type_name(name), name
)
... | Get the needed variable definitions. | Below is the the instruction that describes the task:
### Input:
Get the needed variable definitions.
### Response:
def c_var_decls(self):
"""Get the needed variable definitions."""
if self.opts.no_structs:
mod_decl = 'HMODULE {} = NULL;\n'.format(self.name)
return [mod_decl... |
def like(self, **kwargs):
'''
When provided with keyword arguments of the form ``col=pattern``, this
will limit the entities returned to those that include the provided
pattern. Note that 'like' queries require that the ``prefix=True``
option must have been provided as part of th... | When provided with keyword arguments of the form ``col=pattern``, this
will limit the entities returned to those that include the provided
pattern. Note that 'like' queries require that the ``prefix=True``
option must have been provided as part of the column definition.
Patterns allow f... | Below is the the instruction that describes the task:
### Input:
When provided with keyword arguments of the form ``col=pattern``, this
will limit the entities returned to those that include the provided
pattern. Note that 'like' queries require that the ``prefix=True``
option must have been... |
def marshal(self, v):
"""
Turn this value into API format.
Do a reverse dictionary lookup on choices to find the original value. If
there are no keys or too many keys for now we raise a NotImplementedError
as marshal is not used anywhere currently. In the future we will want to
... | Turn this value into API format.
Do a reverse dictionary lookup on choices to find the original value. If
there are no keys or too many keys for now we raise a NotImplementedError
as marshal is not used anywhere currently. In the future we will want to
fail gracefully. | Below is the the instruction that describes the task:
### Input:
Turn this value into API format.
Do a reverse dictionary lookup on choices to find the original value. If
there are no keys or too many keys for now we raise a NotImplementedError
as marshal is not used anywhere currently. In ... |
def beacon(config):
'''
Read the log file and return match whole string
.. code-block:: yaml
beacons:
log:
- file: <path>
- tags:
<tag>:
regex: <pattern>
.. note::
regex matching is based on the `re`_ modul... | Read the log file and return match whole string
.. code-block:: yaml
beacons:
log:
- file: <path>
- tags:
<tag>:
regex: <pattern>
.. note::
regex matching is based on the `re`_ module
.. _re: https://docs.pyth... | Below is the the instruction that describes the task:
### Input:
Read the log file and return match whole string
.. code-block:: yaml
beacons:
log:
- file: <path>
- tags:
<tag>:
regex: <pattern>
.. note::
regex... |
def policy_assignments(self):
"""Instance depends on the API version:
* 2015-10-01-preview: :class:`PolicyAssignmentsOperations<azure.mgmt.resource.policy.v2015_10_01_preview.operations.PolicyAssignmentsOperations>`
* 2016-04-01: :class:`PolicyAssignmentsOperations<azure.mgmt.resource.pol... | Instance depends on the API version:
* 2015-10-01-preview: :class:`PolicyAssignmentsOperations<azure.mgmt.resource.policy.v2015_10_01_preview.operations.PolicyAssignmentsOperations>`
* 2016-04-01: :class:`PolicyAssignmentsOperations<azure.mgmt.resource.policy.v2016_04_01.operations.PolicyAssignme... | Below is the the instruction that describes the task:
### Input:
Instance depends on the API version:
* 2015-10-01-preview: :class:`PolicyAssignmentsOperations<azure.mgmt.resource.policy.v2015_10_01_preview.operations.PolicyAssignmentsOperations>`
* 2016-04-01: :class:`PolicyAssignmentsOperat... |
def info(self, token):
"""
Return token information.
:param token: A token
:return: dictionary with info about the token
"""
_res = dict(zip(['_id', 'type', 'sid', 'exp'],
self.split_token(token)))
if _res['type'] != self.type:
... | Return token information.
:param token: A token
:return: dictionary with info about the token | Below is the the instruction that describes the task:
### Input:
Return token information.
:param token: A token
:return: dictionary with info about the token
### Response:
def info(self, token):
"""
Return token information.
:param token: A token
:return: dictiona... |
def receiveVolumeInfo(self, paths):
""" Return Context Manager for a file-like (stream) object to store volume info. """
path = self.selectReceivePath(paths)
path = path + Store.theInfoExtension
if self._skipDryRun(logger)("receive info in '%s'", path):
return None
... | Return Context Manager for a file-like (stream) object to store volume info. | Below is the the instruction that describes the task:
### Input:
Return Context Manager for a file-like (stream) object to store volume info.
### Response:
def receiveVolumeInfo(self, paths):
""" Return Context Manager for a file-like (stream) object to store volume info. """
path = self.selectRece... |
def xsl_withparam(self, name, value, parent):
"""Construct an XSLT 'with-param' element.
`parent` is this element's parent.
`name` is the parameter name.
`value` is the parameter value.
"""
res = ET.SubElement(parent, "with-param", name=name)
res.text = value
... | Construct an XSLT 'with-param' element.
`parent` is this element's parent.
`name` is the parameter name.
`value` is the parameter value. | Below is the the instruction that describes the task:
### Input:
Construct an XSLT 'with-param' element.
`parent` is this element's parent.
`name` is the parameter name.
`value` is the parameter value.
### Response:
def xsl_withparam(self, name, value, parent):
"""Construct an XSLT... |
def launch():
"""Launch the experiment."""
exp = experiment(db.init_db(drop_all=False))
exp.log("Launching experiment...", "-----")
init_db()
exp.recruiter().open_recruitment(n=exp.initial_recruitment_size)
session_psiturk.commit()
session.commit()
return success_response(request_type="... | Launch the experiment. | Below is the the instruction that describes the task:
### Input:
Launch the experiment.
### Response:
def launch():
"""Launch the experiment."""
exp = experiment(db.init_db(drop_all=False))
exp.log("Launching experiment...", "-----")
init_db()
exp.recruiter().open_recruitment(n=exp.initial_recr... |
def index_dir(self, folder):
"""
Creates a nested dictionary that represents the folder structure of folder.
Also extracts meta data from all markdown posts and adds to the dictionary.
"""
folder_path = folder
print('Indexing folder: ' + folder_path)
nested_dir = ... | Creates a nested dictionary that represents the folder structure of folder.
Also extracts meta data from all markdown posts and adds to the dictionary. | Below is the the instruction that describes the task:
### Input:
Creates a nested dictionary that represents the folder structure of folder.
Also extracts meta data from all markdown posts and adds to the dictionary.
### Response:
def index_dir(self, folder):
"""
Creates a nested dictionary... |
def function_trace(function_name):
"""
Wraps a chunk of code that we want to appear as a separate, explicit,
segment in our monitoring tools.
"""
if newrelic:
nr_transaction = newrelic.agent.current_transaction()
with newrelic.agent.FunctionTrace(nr_transaction, function_name):
... | Wraps a chunk of code that we want to appear as a separate, explicit,
segment in our monitoring tools. | Below is the the instruction that describes the task:
### Input:
Wraps a chunk of code that we want to appear as a separate, explicit,
segment in our monitoring tools.
### Response:
def function_trace(function_name):
"""
Wraps a chunk of code that we want to appear as a separate, explicit,
segment ... |
def _init_item_marks(item_marks):
"""Initialize the makred item dict."""
if isinstance(item_marks, dict):
return item_marks
if item_marks:
return {item_id:'>' for item_id in item_marks} | Initialize the makred item dict. | Below is the the instruction that describes the task:
### Input:
Initialize the makred item dict.
### Response:
def _init_item_marks(item_marks):
"""Initialize the makred item dict."""
if isinstance(item_marks, dict):
return item_marks
if item_marks:
return {item_id:... |
def backward_smoothing_pass(self,
filtered_means,
filtered_covs,
predicted_means,
predicted_covs):
"""Run the backward pass in Kalman smoother.
The backward smoothing is using Rauch, Tung and... | Run the backward pass in Kalman smoother.
The backward smoothing is using Rauch, Tung and Striebel smoother as
as discussed in section 18.3.2 of Kevin P. Murphy, 2012, Machine Learning:
A Probabilistic Perspective, The MIT Press. The inputs are returned by
`forward_filter` function.
Args:
fi... | Below is the the instruction that describes the task:
### Input:
Run the backward pass in Kalman smoother.
The backward smoothing is using Rauch, Tung and Striebel smoother as
as discussed in section 18.3.2 of Kevin P. Murphy, 2012, Machine Learning:
A Probabilistic Perspective, The MIT Press. The inpu... |
def out_name(stem, timestep=None):
"""Return StagPy out file name.
Args:
stem (str): short description of file content.
timestep (int): timestep if relevant.
Returns:
str: the output file name.
Other Parameters:
conf.core.outname (str): the generic name stem, defaults ... | Return StagPy out file name.
Args:
stem (str): short description of file content.
timestep (int): timestep if relevant.
Returns:
str: the output file name.
Other Parameters:
conf.core.outname (str): the generic name stem, defaults to
``'stagpy'``. | Below is the the instruction that describes the task:
### Input:
Return StagPy out file name.
Args:
stem (str): short description of file content.
timestep (int): timestep if relevant.
Returns:
str: the output file name.
Other Parameters:
conf.core.outname (str): the g... |
async def modify_tree(self, tree, modifications):
'''The modifications are a map of the form, {path: TreeEntry}. The tree
can be None to indicate an empty starting tree. The entries can be
either blobs or trees, or None to indicate a deletion. The return value
is either the hash of the r... | The modifications are a map of the form, {path: TreeEntry}. The tree
can be None to indicate an empty starting tree. The entries can be
either blobs or trees, or None to indicate a deletion. The return value
is either the hash of the resulting tree, or None if the resulting tree
is empty... | Below is the the instruction that describes the task:
### Input:
The modifications are a map of the form, {path: TreeEntry}. The tree
can be None to indicate an empty starting tree. The entries can be
either blobs or trees, or None to indicate a deletion. The return value
is either the hash ... |
def purge(self, doc_ids):
'''
a method to remove docs from the collection
:param doc_ids: string or list of strings with document ids to purge
:return: list of strings of doc ids purged
'''
# https://developer.couchbase.com/documentation/mobile... | a method to remove docs from the collection
:param doc_ids: string or list of strings with document ids to purge
:return: list of strings of doc ids purged | Below is the the instruction that describes the task:
### Input:
a method to remove docs from the collection
:param doc_ids: string or list of strings with document ids to purge
:return: list of strings of doc ids purged
### Response:
def purge(self, doc_ids):
'''
... |
def update(self, data, offset, is_last, buffer_index=0):
"""
Update the buffer at the given index.
Args:
data (np.ndarray): The frames.
offset (int): The index of the first frame in `data` within the sequence.
is_last (bool): Whether this is the last block of... | Update the buffer at the given index.
Args:
data (np.ndarray): The frames.
offset (int): The index of the first frame in `data` within the sequence.
is_last (bool): Whether this is the last block of frames in the sequence.
buffer_index (int): The index of the buf... | Below is the the instruction that describes the task:
### Input:
Update the buffer at the given index.
Args:
data (np.ndarray): The frames.
offset (int): The index of the first frame in `data` within the sequence.
is_last (bool): Whether this is the last block of frames ... |
def predict(fqdn, result, *argl, **argd):
"""Analyzes the result of a generic predict operation performed by
`sklearn`.
Args:
fqdn (str): full-qualified name of the method that was called.
result: result of calling the method with `fqdn`.
argl (tuple): positional arguments passed to... | Analyzes the result of a generic predict operation performed by
`sklearn`.
Args:
fqdn (str): full-qualified name of the method that was called.
result: result of calling the method with `fqdn`.
argl (tuple): positional arguments passed to the method call.
argd (dict): keyword ar... | Below is the the instruction that describes the task:
### Input:
Analyzes the result of a generic predict operation performed by
`sklearn`.
Args:
fqdn (str): full-qualified name of the method that was called.
result: result of calling the method with `fqdn`.
argl (tuple): positional... |
def parse(self, rev_string):
"""
:param rev_string:
:type rev_string: str
"""
elements = rev_string.split(MESSAGE_LINE_SEPARATOR)
heading = elements[0]
heading_elements = heading.split(" ")
self.revision_id = heading_elements[2]
datetime_str = "... | :param rev_string:
:type rev_string: str | Below is the the instruction that describes the task:
### Input:
:param rev_string:
:type rev_string: str
### Response:
def parse(self, rev_string):
"""
:param rev_string:
:type rev_string: str
"""
elements = rev_string.split(MESSAGE_LINE_SEPARATOR)
heading ... |
def getBoneName(self, action, nBoneIndex, pchBoneName, unNameBufferSize):
"""Fills the given buffer with the name of the bone at the given index in the skeleton associated with the given action"""
fn = self.function_table.getBoneName
result = fn(action, nBoneIndex, pchBoneName, unNameBufferSize... | Fills the given buffer with the name of the bone at the given index in the skeleton associated with the given action | Below is the the instruction that describes the task:
### Input:
Fills the given buffer with the name of the bone at the given index in the skeleton associated with the given action
### Response:
def getBoneName(self, action, nBoneIndex, pchBoneName, unNameBufferSize):
"""Fills the given buffer with the na... |
def delete_snapshot(self, snapshot_id):
"""Remove a previously created snapshot."""
query = self.query_factory(
action="DeleteSnapshot", creds=self.creds, endpoint=self.endpoint,
other_params={"SnapshotId": snapshot_id})
d = query.submit()
return d.addCallback(sel... | Remove a previously created snapshot. | Below is the the instruction that describes the task:
### Input:
Remove a previously created snapshot.
### Response:
def delete_snapshot(self, snapshot_id):
"""Remove a previously created snapshot."""
query = self.query_factory(
action="DeleteSnapshot", creds=self.creds, endpoint=self.e... |
def set_gcc():
"""Try to use GCC on OSX for OpenMP support."""
# For macports and homebrew
if 'darwin' in platform.platform().lower():
gcc = extract_gcc_binaries()
if gcc is not None:
os.environ["CC"] = gcc
os.environ["CXX"] = gcc
else:
global u... | Try to use GCC on OSX for OpenMP support. | Below is the the instruction that describes the task:
### Input:
Try to use GCC on OSX for OpenMP support.
### Response:
def set_gcc():
"""Try to use GCC on OSX for OpenMP support."""
# For macports and homebrew
if 'darwin' in platform.platform().lower():
gcc = extract_gcc_binaries()
... |
def getSubstitutionElement(self, elt, ps):
'''if elt matches a member of the head substitutionGroup, return
the GED typecode representation of the member.
head -- ElementDeclaration typecode,
elt -- the DOM element being parsed
ps -- ParsedSoap instance
'''
nsu... | if elt matches a member of the head substitutionGroup, return
the GED typecode representation of the member.
head -- ElementDeclaration typecode,
elt -- the DOM element being parsed
ps -- ParsedSoap instance | Below is the the instruction that describes the task:
### Input:
if elt matches a member of the head substitutionGroup, return
the GED typecode representation of the member.
head -- ElementDeclaration typecode,
elt -- the DOM element being parsed
ps -- ParsedSoap instance
### Resp... |
def set_default_subparser(self, name, args=None):
"""default subparser selection. Call after setup, just before parse_args()
name: is the name of the subparser to call by default
args: if set is the argument list handed to parse_args()
, tested with 2.7, 3.2, 3.3, 3.4
it works with 2.6 assuming arg... | default subparser selection. Call after setup, just before parse_args()
name: is the name of the subparser to call by default
args: if set is the argument list handed to parse_args()
, tested with 2.7, 3.2, 3.3, 3.4
it works with 2.6 assuming argparse is installed | Below is the the instruction that describes the task:
### Input:
default subparser selection. Call after setup, just before parse_args()
name: is the name of the subparser to call by default
args: if set is the argument list handed to parse_args()
, tested with 2.7, 3.2, 3.3, 3.4
it works with 2.6 ... |
def start_daemon():
"""
Start a thread to continuously read log files and append lines in DB.
Work in progress. Currently the thread doesn't append anything,
it only print the information parsed from each line read.
Returns:
thread: the started thread.
"""
... | Start a thread to continuously read log files and append lines in DB.
Work in progress. Currently the thread doesn't append anything,
it only print the information parsed from each line read.
Returns:
thread: the started thread. | Below is the the instruction that describes the task:
### Input:
Start a thread to continuously read log files and append lines in DB.
Work in progress. Currently the thread doesn't append anything,
it only print the information parsed from each line read.
Returns:
thread: the ... |
def conf(self, key):
'''get config'''
return self.__conf[key] if key in self.__conf else _YunpianConf.YP_CONF.get(key) | get config | Below is the the instruction that describes the task:
### Input:
get config
### Response:
def conf(self, key):
'''get config'''
return self.__conf[key] if key in self.__conf else _YunpianConf.YP_CONF.get(key) |
def autoLayout(self, size=None):
"""
Updates the layout for the graphics within this scene.
"""
if size is None:
size = self._view.size()
self.setSceneRect(0, 0, size.width(), size.height())
for item in self.items():
if isinstance... | Updates the layout for the graphics within this scene. | Below is the the instruction that describes the task:
### Input:
Updates the layout for the graphics within this scene.
### Response:
def autoLayout(self, size=None):
"""
Updates the layout for the graphics within this scene.
"""
if size is None:
size = self._view.s... |
def elemDump(self, f, cur):
"""Dump an XML/HTML node, recursive behaviour, children are
printed too. """
if cur is None: cur__o = None
else: cur__o = cur._o
libxml2mod.xmlElemDump(f, self._o, cur__o) | Dump an XML/HTML node, recursive behaviour, children are
printed too. | Below is the the instruction that describes the task:
### Input:
Dump an XML/HTML node, recursive behaviour, children are
printed too.
### Response:
def elemDump(self, f, cur):
"""Dump an XML/HTML node, recursive behaviour, children are
printed too. """
if cur is None: cur__o ... |
def show_active(self, **kwargs):
"""Draws the network, highlighting active queues.
The colored vertices represent vertices that have at least one
queue on an in-edge that is active. Dark edges represent
queues that are active, light edges represent queues that are
inactive.
... | Draws the network, highlighting active queues.
The colored vertices represent vertices that have at least one
queue on an in-edge that is active. Dark edges represent
queues that are active, light edges represent queues that are
inactive.
Parameters
----------
*... | Below is the the instruction that describes the task:
### Input:
Draws the network, highlighting active queues.
The colored vertices represent vertices that have at least one
queue on an in-edge that is active. Dark edges represent
queues that are active, light edges represent queues that a... |
def add_name(self, name_attr, space_attr, new_schema):
# type: (Text, Optional[Text], NamedSchema) -> Name
"""
Add a new schema object to the name set.
@arg name_attr: name value read in schema
@arg space_attr: namespace value read in schema.
@return: the Name tha... | Add a new schema object to the name set.
@arg name_attr: name value read in schema
@arg space_attr: namespace value read in schema.
@return: the Name that was just added. | Below is the the instruction that describes the task:
### Input:
Add a new schema object to the name set.
@arg name_attr: name value read in schema
@arg space_attr: namespace value read in schema.
@return: the Name that was just added.
### Response:
def add_name(self, name_attr, spa... |
def descriptor(obj, path=''):
"""Return descriptor of given object.
If ``path`` is specified, only the content on that path is
returned.
"""
if isinstance(obj, dict):
# Current object is hydrated, so we need to get descriptor from
# dict representation.
desc = obj['__descrip... | Return descriptor of given object.
If ``path`` is specified, only the content on that path is
returned. | Below is the the instruction that describes the task:
### Input:
Return descriptor of given object.
If ``path`` is specified, only the content on that path is
returned.
### Response:
def descriptor(obj, path=''):
"""Return descriptor of given object.
If ``path`` is specified, only the content on ... |
async def get_conversations(self, service_url: str, continuation_token: str=None):
"""
Lists the Conversations in which this bot has participated for a given channel server. The channel server
returns results in pages and each page will include a `continuationToken` that can be used to fetch the... | Lists the Conversations in which this bot has participated for a given channel server. The channel server
returns results in pages and each page will include a `continuationToken` that can be used to fetch the next
page of results from the server.
:param service_url:
:param continuation_... | Below is the the instruction that describes the task:
### Input:
Lists the Conversations in which this bot has participated for a given channel server. The channel server
returns results in pages and each page will include a `continuationToken` that can be used to fetch the next
page of results from... |
def purge_files(self, exclude_files=["index.html", "error.html"]):
"""
To delete files that are in the manifest
:param excludes_files: list : files to not delete
:return:
"""
for chunk in utils.chunk_list(self._get_manifest_data(), 1000):
try:
... | To delete files that are in the manifest
:param excludes_files: list : files to not delete
:return: | Below is the the instruction that describes the task:
### Input:
To delete files that are in the manifest
:param excludes_files: list : files to not delete
:return:
### Response:
def purge_files(self, exclude_files=["index.html", "error.html"]):
"""
To delete files that are in the m... |
def peptide(infile, outfile, context, parametric, pfdr, pi0_lambda, pi0_method, pi0_smooth_df, pi0_smooth_log_pi0, lfdr_truncate, lfdr_monotone, lfdr_transformation, lfdr_adj, lfdr_eps):
"""
Infer peptides and conduct error-rate estimation in different contexts.
"""
if outfile is None:
outfile ... | Infer peptides and conduct error-rate estimation in different contexts. | Below is the the instruction that describes the task:
### Input:
Infer peptides and conduct error-rate estimation in different contexts.
### Response:
def peptide(infile, outfile, context, parametric, pfdr, pi0_lambda, pi0_method, pi0_smooth_df, pi0_smooth_log_pi0, lfdr_truncate, lfdr_monotone, lfdr_transformation... |
def get_subplot_at(self, row, column):
"""Return the subplot at row, column position.
:param row,column: specify the subplot.
"""
idx = row * self.columns + column
return self.subplots[idx] | Return the subplot at row, column position.
:param row,column: specify the subplot. | Below is the the instruction that describes the task:
### Input:
Return the subplot at row, column position.
:param row,column: specify the subplot.
### Response:
def get_subplot_at(self, row, column):
"""Return the subplot at row, column position.
:param row,column: specify the subplot.
... |
def randomize_colors(im, keep_vals=[0]):
r'''
Takes a greyscale image and randomly shuffles the greyscale values, so that
all voxels labeled X will be labelled Y, and all voxels labeled Y will be
labeled Z, where X, Y, Z and so on are randomly selected from the values
in the input image.
This f... | r'''
Takes a greyscale image and randomly shuffles the greyscale values, so that
all voxels labeled X will be labelled Y, and all voxels labeled Y will be
labeled Z, where X, Y, Z and so on are randomly selected from the values
in the input image.
This function is useful for improving the visibilit... | Below is the the instruction that describes the task:
### Input:
r'''
Takes a greyscale image and randomly shuffles the greyscale values, so that
all voxels labeled X will be labelled Y, and all voxels labeled Y will be
labeled Z, where X, Y, Z and so on are randomly selected from the values
in the ... |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extracting dictionary of coefficients specific to required
#... | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values. | Below is the the instruction that describes the task:
### Input:
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
### Response:
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :m... |
def _simplify_doc(doc):
"""
Limit a document to just the three fields we should upload.
"""
# Mutate a copy of the document to fill in missing fields
doc = dict(doc)
if 'text' not in doc:
raise ValueError("The document {!r} has no text field".format(doc))
return {
'text': doc... | Limit a document to just the three fields we should upload. | Below is the the instruction that describes the task:
### Input:
Limit a document to just the three fields we should upload.
### Response:
def _simplify_doc(doc):
"""
Limit a document to just the three fields we should upload.
"""
# Mutate a copy of the document to fill in missing fields
doc = ... |
def parse_at_element(
self,
element, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the primitive value at the XML element."""
if self._attribute:
parsed_value = self._parse_attribute(element, self._attribut... | Parse the primitive value at the XML element. | Below is the the instruction that describes the task:
### Input:
Parse the primitive value at the XML element.
### Response:
def parse_at_element(
self,
element, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the primitive... |
def _dispatch(self, method, params):
"""Customise exception handling"""
self._count += 1
func = getattr(self, method)
try:
return func(*params)
except Exception as e:
traceback.print_exc()
raise e | Customise exception handling | Below is the the instruction that describes the task:
### Input:
Customise exception handling
### Response:
def _dispatch(self, method, params):
"""Customise exception handling"""
self._count += 1
func = getattr(self, method)
try:
return func(*params)
except Exc... |
def _scale_steps(self, duration, commands, *steps):
""" Scale steps
:param duration: Total time (in seconds)
:param commands: Number of commands to be executed.
:param steps: Steps for one or many properties to take.
:return: Steps scaled to time and total.
"""
f... | Scale steps
:param duration: Total time (in seconds)
:param commands: Number of commands to be executed.
:param steps: Steps for one or many properties to take.
:return: Steps scaled to time and total. | Below is the the instruction that describes the task:
### Input:
Scale steps
:param duration: Total time (in seconds)
:param commands: Number of commands to be executed.
:param steps: Steps for one or many properties to take.
:return: Steps scaled to time and total.
### Response:
d... |
def result(self):
'''
The result from the executed task. Raises NotExecutedYet if not yet
executed.
'''
if self.cancelled or (self._fn is not None):
raise NotExecutedYet()
if self._fn_exc is not None:
six.reraise(*self._fn_exc)
else:
... | The result from the executed task. Raises NotExecutedYet if not yet
executed. | Below is the the instruction that describes the task:
### Input:
The result from the executed task. Raises NotExecutedYet if not yet
executed.
### Response:
def result(self):
'''
The result from the executed task. Raises NotExecutedYet if not yet
executed.
'''
if s... |
def loadFromURL(self, url, schema=None):
"""Return an XMLSchema instance loaded from the given url.
url -- URL to dereference
schema -- Optional XMLSchema instance.
"""
reader = self.__readerClass()
if self.__base_url:
url = basejoin(self.__base_url,url)... | Return an XMLSchema instance loaded from the given url.
url -- URL to dereference
schema -- Optional XMLSchema instance. | Below is the the instruction that describes the task:
### Input:
Return an XMLSchema instance loaded from the given url.
url -- URL to dereference
schema -- Optional XMLSchema instance.
### Response:
def loadFromURL(self, url, schema=None):
"""Return an XMLSchema instance loaded from ... |
def set_tensor_symmetry_old(force_constants,
lattice, # column vectors
positions,
symmetry):
"""Full force constants are symmetrized using crystal symmetry.
This method extracts symmetrically equivalent sets of atomic pairs an... | Full force constants are symmetrized using crystal symmetry.
This method extracts symmetrically equivalent sets of atomic pairs and
take sum of their force constants and average the sum.
Since get_force_constants_disps may include crystal symmetry, this method
is usually meaningless. | Below is the the instruction that describes the task:
### Input:
Full force constants are symmetrized using crystal symmetry.
This method extracts symmetrically equivalent sets of atomic pairs and
take sum of their force constants and average the sum.
Since get_force_constants_disps may include crysta... |
def unmount(self, force=None, auth_no_user_interaction=None):
"""Unmount filesystem."""
return self._M.Filesystem.Unmount(
'(a{sv})',
filter_opt({
'force': ('b', force),
'auth.no_user_interaction': ('b', auth_no_user_interaction),
})
... | Unmount filesystem. | Below is the the instruction that describes the task:
### Input:
Unmount filesystem.
### Response:
def unmount(self, force=None, auth_no_user_interaction=None):
"""Unmount filesystem."""
return self._M.Filesystem.Unmount(
'(a{sv})',
filter_opt({
'force': ('b'... |
def keyboard(table, day=None):
"""Handler for showing the keyboard statistics page."""
cols, group = "realkey AS key, COUNT(*) AS count", "realkey"
where = (("day", day),) if day else ()
counts_display = counts = db.fetch(table, cols, where, group, "count DESC")
if "combos" == table:
c... | Handler for showing the keyboard statistics page. | Below is the the instruction that describes the task:
### Input:
Handler for showing the keyboard statistics page.
### Response:
def keyboard(table, day=None):
"""Handler for showing the keyboard statistics page."""
cols, group = "realkey AS key, COUNT(*) AS count", "realkey"
where = (("day", day),)... |
def mag_calibration(self):
"""Perform magnetometer calibration for current IMU."""
self.calibration_state = self.CAL_MAG
self.mag_dialog = SK8MagDialog(self.sk8.get_imu(self.spinIMU.value()), self)
if self.mag_dialog.exec_() == QDialog.Rejected:
return
self.calculate... | Perform magnetometer calibration for current IMU. | Below is the the instruction that describes the task:
### Input:
Perform magnetometer calibration for current IMU.
### Response:
def mag_calibration(self):
"""Perform magnetometer calibration for current IMU."""
self.calibration_state = self.CAL_MAG
self.mag_dialog = SK8MagDialog(self.sk8.g... |
def print_result_from_timeit(stmt='pass', setup='pass', number=1000000):
"""
Clean function to know how much time took the execution of one statement
"""
units = ["s", "ms", "us", "ns"]
duration = timeit(stmt, setup, number=int(number))
avg_duration = duration / float(number)
thousands = int... | Clean function to know how much time took the execution of one statement | Below is the the instruction that describes the task:
### Input:
Clean function to know how much time took the execution of one statement
### Response:
def print_result_from_timeit(stmt='pass', setup='pass', number=1000000):
"""
Clean function to know how much time took the execution of one statement
"... |
def deactivate_in_ec(self, ec_index):
'''Deactivate this component in an execution context.
@param ec_index The index of the execution context to deactivate in.
This index is into the total array of contexts, that
is both owned and participating contexts.... | Deactivate this component in an execution context.
@param ec_index The index of the execution context to deactivate in.
This index is into the total array of contexts, that
is both owned and participating contexts. If the value
of ec_index... | Below is the the instruction that describes the task:
### Input:
Deactivate this component in an execution context.
@param ec_index The index of the execution context to deactivate in.
This index is into the total array of contexts, that
is both owned and par... |
def add_layer3_cluster_interface(self, interface_id, cluster_virtual=None,
network_value=None, macaddress=None, nodes=None, cvi_mode='packetdispatch',
zone_ref=None, comment=None, **kw):
"""
Add cluster virtual interface. A "CVI" interface is used as a VIP
address for clu... | Add cluster virtual interface. A "CVI" interface is used as a VIP
address for clustered engines. Providing 'nodes' will create the
node specific interfaces. You can also add a cluster address with only
a CVI, or only NDI's.
Add CVI only::
engine.physic... | Below is the the instruction that describes the task:
### Input:
Add cluster virtual interface. A "CVI" interface is used as a VIP
address for clustered engines. Providing 'nodes' will create the
node specific interfaces. You can also add a cluster address with only
a CVI, or only NDI's.
... |
def _extract_battery_info_from_sys(self):
"""
Extract the percent charged, charging state, time remaining,
and capacity for a battery, using Linux's kernel /sys interface
Only available in kernel 2.6.24(?) and newer. Before kernel provided
a similar, yet incompatible interface i... | Extract the percent charged, charging state, time remaining,
and capacity for a battery, using Linux's kernel /sys interface
Only available in kernel 2.6.24(?) and newer. Before kernel provided
a similar, yet incompatible interface in /proc | Below is the the instruction that describes the task:
### Input:
Extract the percent charged, charging state, time remaining,
and capacity for a battery, using Linux's kernel /sys interface
Only available in kernel 2.6.24(?) and newer. Before kernel provided
a similar, yet incompatible inte... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.