code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _get_struct_fillstyle(self, shape_number):
"""Get the values for the FILLSTYLE record."""
obj = _make_object("FillStyle")
obj.FillStyleType = style_type = unpack_ui8(self._src)
if style_type == 0x00:
if shape_number <= 2:
obj.Color = self._get_struct_rgb(... | Get the values for the FILLSTYLE record. | Below is the the instruction that describes the task:
### Input:
Get the values for the FILLSTYLE record.
### Response:
def _get_struct_fillstyle(self, shape_number):
"""Get the values for the FILLSTYLE record."""
obj = _make_object("FillStyle")
obj.FillStyleType = style_type = unpack_ui8(s... |
def register_callback(self, callback):
""" Register a new callback.
Note:
The callback will be executed in the AlarmTask context and for
this reason it should not block, otherwise we can miss block
changes.
"""
if not callable(callback):
r... | Register a new callback.
Note:
The callback will be executed in the AlarmTask context and for
this reason it should not block, otherwise we can miss block
changes. | Below is the the instruction that describes the task:
### Input:
Register a new callback.
Note:
The callback will be executed in the AlarmTask context and for
this reason it should not block, otherwise we can miss block
changes.
### Response:
def register_callback(self,... |
def compute_consistency_score(returns_test, preds):
"""
Compute Bayesian consistency score.
Parameters
----------
returns_test : pd.Series
Observed cumulative returns.
preds : numpy.array
Multiple (simulated) cumulative returns.
Returns
-------
Consistency score
... | Compute Bayesian consistency score.
Parameters
----------
returns_test : pd.Series
Observed cumulative returns.
preds : numpy.array
Multiple (simulated) cumulative returns.
Returns
-------
Consistency score
Score from 100 (returns_test perfectly on the median line o... | Below is the the instruction that describes the task:
### Input:
Compute Bayesian consistency score.
Parameters
----------
returns_test : pd.Series
Observed cumulative returns.
preds : numpy.array
Multiple (simulated) cumulative returns.
Returns
-------
Consistency scor... |
def add_edge(self, edge):
"Add edge to chart, and see if it extends or predicts another edge."
start, end, lhs, found, expects = edge
if edge not in self.chart[end]:
self.chart[end].append(edge)
if self.trace:
print '%10s: added %s' % (caller(2), edge)
... | Add edge to chart, and see if it extends or predicts another edge. | Below is the the instruction that describes the task:
### Input:
Add edge to chart, and see if it extends or predicts another edge.
### Response:
def add_edge(self, edge):
"Add edge to chart, and see if it extends or predicts another edge."
start, end, lhs, found, expects = edge
if edge not... |
def _parse_fmt(fmt, color_key='colors', ls_key='linestyles',
marker_key='marker'):
'''Modified from matplotlib's _process_plot_format function.'''
try: # Is fmt just a colorspec?
color = mcolors.colorConverter.to_rgb(fmt)
except ValueError:
pass # No, not just a color.
else:
# Eithe... | Modified from matplotlib's _process_plot_format function. | Below is the the instruction that describes the task:
### Input:
Modified from matplotlib's _process_plot_format function.
### Response:
def _parse_fmt(fmt, color_key='colors', ls_key='linestyles',
marker_key='marker'):
'''Modified from matplotlib's _process_plot_format function.'''
try: # Is f... |
def writes(nb, format, **kwargs):
"""Write a notebook to a string in a given format in the current nbformat version.
This function always writes the notebook in the current nbformat version.
Parameters
----------
nb : NotebookNode
The notebook to write.
format : (u'json', u'ipynb', u'p... | Write a notebook to a string in a given format in the current nbformat version.
This function always writes the notebook in the current nbformat version.
Parameters
----------
nb : NotebookNode
The notebook to write.
format : (u'json', u'ipynb', u'py')
The format to write the noteb... | Below is the the instruction that describes the task:
### Input:
Write a notebook to a string in a given format in the current nbformat version.
This function always writes the notebook in the current nbformat version.
Parameters
----------
nb : NotebookNode
The notebook to write.
form... |
def migrate_v0_rules(self):
'''
Remove any v0 (i.e. pre-010) rules from storage and replace them with v1 rules.
Notes:
v0 had two differences user was a username. Replaced with iden of user as 'iden' field.
Also 'iden' was storage as binary. Now it is stored as hex str... | Remove any v0 (i.e. pre-010) rules from storage and replace them with v1 rules.
Notes:
v0 had two differences user was a username. Replaced with iden of user as 'iden' field.
Also 'iden' was storage as binary. Now it is stored as hex string. | Below is the the instruction that describes the task:
### Input:
Remove any v0 (i.e. pre-010) rules from storage and replace them with v1 rules.
Notes:
v0 had two differences user was a username. Replaced with iden of user as 'iden' field.
Also 'iden' was storage as binary. Now it... |
def make_document(self, titlestring):
"""
This method may be used to create a new document for writing as xml
to the OPS subdirectory of the ePub structure.
"""
#root = etree.XML('''<?xml version="1.0"?>\
#<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.1//EN' 'http://www.w3.org/TR/... | This method may be used to create a new document for writing as xml
to the OPS subdirectory of the ePub structure. | Below is the the instruction that describes the task:
### Input:
This method may be used to create a new document for writing as xml
to the OPS subdirectory of the ePub structure.
### Response:
def make_document(self, titlestring):
"""
This method may be used to create a new document for wr... |
def delete(ctx, uri):
"""DELETE the specified URI
Example:
\b
$ wva get files/userfs/WEB/python
{'file_list': ['files/userfs/WEB/python/.ssh',
'files/userfs/WEB/python/README.md']}
$ wva delete files/userfs/WEB/python/README.md
''
$ wva get files/userfs/WEB/python
{'fil... | DELETE the specified URI
Example:
\b
$ wva get files/userfs/WEB/python
{'file_list': ['files/userfs/WEB/python/.ssh',
'files/userfs/WEB/python/README.md']}
$ wva delete files/userfs/WEB/python/README.md
''
$ wva get files/userfs/WEB/python
{'file_list': ['files/userfs/WEB/p... | Below is the the instruction that describes the task:
### Input:
DELETE the specified URI
Example:
\b
$ wva get files/userfs/WEB/python
{'file_list': ['files/userfs/WEB/python/.ssh',
'files/userfs/WEB/python/README.md']}
$ wva delete files/userfs/WEB/python/README.md
''
$ w... |
def unsign(wheelfile):
"""
Remove RECORD.jws from a wheel by truncating the zip file.
RECORD.jws must be at the end of the archive. The zip file must be an
ordinary archive, with the compressed files and the directory in the same
order, and without any non-zip content after the truncation poi... | Remove RECORD.jws from a wheel by truncating the zip file.
RECORD.jws must be at the end of the archive. The zip file must be an
ordinary archive, with the compressed files and the directory in the same
order, and without any non-zip content after the truncation point. | Below is the the instruction that describes the task:
### Input:
Remove RECORD.jws from a wheel by truncating the zip file.
RECORD.jws must be at the end of the archive. The zip file must be an
ordinary archive, with the compressed files and the directory in the same
order, and without any non-zi... |
def serialize_data(data, compression=False, encryption=False, public_key=None):
"""Serializes normal Python datatypes into plaintext using json.
You may also choose to enable compression and encryption when serializing
data to send over the network. Enabling one or both of these options will
incur addi... | Serializes normal Python datatypes into plaintext using json.
You may also choose to enable compression and encryption when serializing
data to send over the network. Enabling one or both of these options will
incur additional overhead.
Args:
data (dict): The data to convert into plain text usin... | Below is the the instruction that describes the task:
### Input:
Serializes normal Python datatypes into plaintext using json.
You may also choose to enable compression and encryption when serializing
data to send over the network. Enabling one or both of these options will
incur additional overhead.
... |
def get_paths(folder, ignore_endswith=ignore_endswith):
'''Return hologram file paths
Parameters
----------
folder: str or pathlib.Path
Path to search folder
ignore_endswith: list
List of filename ending strings indicating which
files should be ignored.
'''
folder = ... | Return hologram file paths
Parameters
----------
folder: str or pathlib.Path
Path to search folder
ignore_endswith: list
List of filename ending strings indicating which
files should be ignored. | Below is the the instruction that describes the task:
### Input:
Return hologram file paths
Parameters
----------
folder: str or pathlib.Path
Path to search folder
ignore_endswith: list
List of filename ending strings indicating which
files should be ignored.
### Response:
... |
def diff_identifiers(a, b):
"""Return list of tuples where identifiers in datasets differ.
Tuple structure:
(identifier, present in a, present in b)
:param a: first :class:`dtoolcore.DataSet`
:param b: second :class:`dtoolcore.DataSet`
:returns: list of tuples where identifiers in datasets dif... | Return list of tuples where identifiers in datasets differ.
Tuple structure:
(identifier, present in a, present in b)
:param a: first :class:`dtoolcore.DataSet`
:param b: second :class:`dtoolcore.DataSet`
:returns: list of tuples where identifiers in datasets differ | Below is the the instruction that describes the task:
### Input:
Return list of tuples where identifiers in datasets differ.
Tuple structure:
(identifier, present in a, present in b)
:param a: first :class:`dtoolcore.DataSet`
:param b: second :class:`dtoolcore.DataSet`
:returns: list of tuples... |
def __create_grid(self):
"""!
@brief Creates CLIQUE grid that consists of CLIQUE blocks for clustering process.
"""
data_sizes, min_corner, max_corner = self.__get_data_size_derscription()
dimension = len(self.__data[0])
cell_sizes = [dimension_length / self.__a... | !
@brief Creates CLIQUE grid that consists of CLIQUE blocks for clustering process. | Below is the the instruction that describes the task:
### Input:
!
@brief Creates CLIQUE grid that consists of CLIQUE blocks for clustering process.
### Response:
def __create_grid(self):
"""!
@brief Creates CLIQUE grid that consists of CLIQUE blocks for clustering process.
""... |
def hex_to_xy(self, h):
"""Converts hexadecimal colors represented as a String to approximate CIE
1931 x and y coordinates.
"""
rgb = self.color.hex_to_rgb(h)
return self.rgb_to_xy(rgb[0], rgb[1], rgb[2]) | Converts hexadecimal colors represented as a String to approximate CIE
1931 x and y coordinates. | Below is the the instruction that describes the task:
### Input:
Converts hexadecimal colors represented as a String to approximate CIE
1931 x and y coordinates.
### Response:
def hex_to_xy(self, h):
"""Converts hexadecimal colors represented as a String to approximate CIE
1931 x and y coor... |
def get_backend():
"""Get backend."""
backend = getattr(settings, 'SIMDITOR_IMAGE_BACKEND', None)
if backend == 'pillow':
from simditor.image import pillow_backend as backend
else:
from simditor.image import dummy_backend as backend
return backend | Get backend. | Below is the the instruction that describes the task:
### Input:
Get backend.
### Response:
def get_backend():
"""Get backend."""
backend = getattr(settings, 'SIMDITOR_IMAGE_BACKEND', None)
if backend == 'pillow':
from simditor.image import pillow_backend as backend
else:
from simd... |
def get(msg_or_dict, key, default=_SENTINEL):
"""Retrieve a key's value from a protobuf Message or dictionary.
Args:
mdg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the
object.
key (str): The key to retrieve from the object.
default (Any): If the key is not p... | Retrieve a key's value from a protobuf Message or dictionary.
Args:
mdg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the
object.
key (str): The key to retrieve from the object.
default (Any): If the key is not present on the object, and a default
is se... | Below is the the instruction that describes the task:
### Input:
Retrieve a key's value from a protobuf Message or dictionary.
Args:
mdg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the
object.
key (str): The key to retrieve from the object.
default (Any): If ... |
def declareLegacyItem(typeName, schemaVersion, attributes, dummyBases=()):
"""
Generate a dummy subclass of Item that will have the given attributes,
and the base Item methods, but no methods of its own. This is for use
with upgrading.
@param typeName: a string, the Axiom TypeName to have attribut... | Generate a dummy subclass of Item that will have the given attributes,
and the base Item methods, but no methods of its own. This is for use
with upgrading.
@param typeName: a string, the Axiom TypeName to have attributes for.
@param schemaVersion: an int, the (old) version of the schema this is a pro... | Below is the the instruction that describes the task:
### Input:
Generate a dummy subclass of Item that will have the given attributes,
and the base Item methods, but no methods of its own. This is for use
with upgrading.
@param typeName: a string, the Axiom TypeName to have attributes for.
@param... |
def set_coeffs(self, values, ls, ms):
"""
Set spherical harmonic coefficients in-place to specified values.
Usage
-----
x.set_coeffs(values, ls, ms)
Parameters
----------
values : float (list)
The value(s) of the spherical harmonic coefficien... | Set spherical harmonic coefficients in-place to specified values.
Usage
-----
x.set_coeffs(values, ls, ms)
Parameters
----------
values : float (list)
The value(s) of the spherical harmonic coefficient(s).
ls : int (list)
The degree(s) of... | Below is the the instruction that describes the task:
### Input:
Set spherical harmonic coefficients in-place to specified values.
Usage
-----
x.set_coeffs(values, ls, ms)
Parameters
----------
values : float (list)
The value(s) of the spherical harmonic... |
def iterate(self, iterable, element_timeout=None):
"""
Iterate over an iterable.
The iterator is executed in the host thread. The threads dynamically
grab the elements. The iterator elements must hence be picklable to
be transferred through the queue.
If there is only o... | Iterate over an iterable.
The iterator is executed in the host thread. The threads dynamically
grab the elements. The iterator elements must hence be picklable to
be transferred through the queue.
If there is only one thread, no special operations are performed.
Otherwise, effe... | Below is the the instruction that describes the task:
### Input:
Iterate over an iterable.
The iterator is executed in the host thread. The threads dynamically
grab the elements. The iterator elements must hence be picklable to
be transferred through the queue.
If there is only one... |
def remove_network(self, action, n_name, **kwargs):
"""
Removes a network.
:param action: Action configuration.
:type action: dockermap.map.runner.ActionConfig
:param n_name: Network name or id.
:type n_name: unicode | str
:param kwargs: Additional keyword argume... | Removes a network.
:param action: Action configuration.
:type action: dockermap.map.runner.ActionConfig
:param n_name: Network name or id.
:type n_name: unicode | str
:param kwargs: Additional keyword arguments.
:type kwargs: dict | Below is the the instruction that describes the task:
### Input:
Removes a network.
:param action: Action configuration.
:type action: dockermap.map.runner.ActionConfig
:param n_name: Network name or id.
:type n_name: unicode | str
:param kwargs: Additional keyword arguments... |
def get_partition_hash(self):
"""
Returns partition hash calculated for serialized object.
Partition hash is used to determine partition of a Data and is calculated using
* PartitioningStrategy during serialization.
* If partition hash is not set then hash_cod... | Returns partition hash calculated for serialized object.
Partition hash is used to determine partition of a Data and is calculated using
* PartitioningStrategy during serialization.
* If partition hash is not set then hash_code() is used.
:return: partition hash | Below is the the instruction that describes the task:
### Input:
Returns partition hash calculated for serialized object.
Partition hash is used to determine partition of a Data and is calculated using
* PartitioningStrategy during serialization.
* If partition hash is no... |
def traverse_setter(obj, attribute, value):
"""
Traverses the object and sets the supplied attribute on the
object. Supports Dimensioned and DimensionedPlot types.
"""
obj.traverse(lambda x: setattr(x, attribute, value)) | Traverses the object and sets the supplied attribute on the
object. Supports Dimensioned and DimensionedPlot types. | Below is the the instruction that describes the task:
### Input:
Traverses the object and sets the supplied attribute on the
object. Supports Dimensioned and DimensionedPlot types.
### Response:
def traverse_setter(obj, attribute, value):
"""
Traverses the object and sets the supplied attribute on the
... |
def restart_agent(self, agent_id, **kwargs):
'''tells the host agent running in this agency to restart the agent.'''
host_medium = self.get_medium('host_agent')
agent = host_medium.get_agent()
d = host_medium.get_document(agent_id)
# This is done like this on purpose, we want to ... | tells the host agent running in this agency to restart the agent. | Below is the the instruction that describes the task:
### Input:
tells the host agent running in this agency to restart the agent.
### Response:
def restart_agent(self, agent_id, **kwargs):
'''tells the host agent running in this agency to restart the agent.'''
host_medium = self.get_medium('host_a... |
def cut_psf(psf_data, psf_size):
"""
cut the psf properly
:param psf_data: image of PSF
:param psf_size: size of psf
:return: re-sized and re-normalized PSF
"""
kernel = image_util.cut_edges(psf_data, psf_size)
kernel = kernel_norm(kernel)
return kernel | cut the psf properly
:param psf_data: image of PSF
:param psf_size: size of psf
:return: re-sized and re-normalized PSF | Below is the the instruction that describes the task:
### Input:
cut the psf properly
:param psf_data: image of PSF
:param psf_size: size of psf
:return: re-sized and re-normalized PSF
### Response:
def cut_psf(psf_data, psf_size):
"""
cut the psf properly
:param psf_data: image of PSF
... |
def get_rows(self):
""" Returns the name of the rows of the extension"""
possible_dataframes = ['F', 'FY', 'M', 'S',
'D_cba', 'D_pba', 'D_imp', 'D_exp',
'D_cba_reg', 'D_pba_reg',
'D_imp_reg', 'D_exp_reg',
... | Returns the name of the rows of the extension | Below is the the instruction that describes the task:
### Input:
Returns the name of the rows of the extension
### Response:
def get_rows(self):
""" Returns the name of the rows of the extension"""
possible_dataframes = ['F', 'FY', 'M', 'S',
'D_cba', 'D_pba', 'D_imp'... |
def headers(self):
""" Returns a list of the last HTTP response headers.
Header keys are normalized to capitalized form, as in `User-Agent`.
"""
headers = self.conn.issue_command("Headers")
res = []
for header in headers.split("\r"):
key, value = header.split(": ", 1)
for line in val... | Returns a list of the last HTTP response headers.
Header keys are normalized to capitalized form, as in `User-Agent`. | Below is the the instruction that describes the task:
### Input:
Returns a list of the last HTTP response headers.
Header keys are normalized to capitalized form, as in `User-Agent`.
### Response:
def headers(self):
""" Returns a list of the last HTTP response headers.
Header keys are normalized to cap... |
def noise_plot(signal, noise, normalise=False, **kwargs):
"""
Plot signal and noise fourier transforms and the difference.
:type signal: `obspy.core.stream.Stream`
:param signal: Stream of "signal" window
:type noise: `obspy.core.stream.Stream`
:param noise: Stream of the "noise" window.
:t... | Plot signal and noise fourier transforms and the difference.
:type signal: `obspy.core.stream.Stream`
:param signal: Stream of "signal" window
:type noise: `obspy.core.stream.Stream`
:param noise: Stream of the "noise" window.
:type normalise: bool
:param normalise: Whether to normalise the dat... | Below is the the instruction that describes the task:
### Input:
Plot signal and noise fourier transforms and the difference.
:type signal: `obspy.core.stream.Stream`
:param signal: Stream of "signal" window
:type noise: `obspy.core.stream.Stream`
:param noise: Stream of the "noise" window.
:ty... |
def getAnalogActionData(self, action, unActionDataSize, ulRestrictToDevice):
"""
Reads the state of an analog action given its handle. This will return VRInputError_WrongType if the type of
action is something other than analog
"""
fn = self.function_table.getAnalogActionData
... | Reads the state of an analog action given its handle. This will return VRInputError_WrongType if the type of
action is something other than analog | Below is the the instruction that describes the task:
### Input:
Reads the state of an analog action given its handle. This will return VRInputError_WrongType if the type of
action is something other than analog
### Response:
def getAnalogActionData(self, action, unActionDataSize, ulRestrictToDevice):
... |
def traverse(obj, target:str, default=nodefault, executable:bool=False, separator:str='.', protect:bool=True):
"""Traverse down an object, using getattr or getitem.
If ``executable`` is ``True`` any executable function encountered will be, with no arguments. Traversal will
continue on the result of that call. You... | Traverse down an object, using getattr or getitem.
If ``executable`` is ``True`` any executable function encountered will be, with no arguments. Traversal will
continue on the result of that call. You can change the separator as desired, i.e. to a '/'.
By default attributes (but not array elements) prefixed wit... | Below is the the instruction that describes the task:
### Input:
Traverse down an object, using getattr or getitem.
If ``executable`` is ``True`` any executable function encountered will be, with no arguments. Traversal will
continue on the result of that call. You can change the separator as desired, i.e. to ... |
def _set_dst_vtep_ip(self, v, load=False):
"""
Setter method for dst_vtep_ip, mapped from YANG variable /overlay/access_list/type/vxlan/standard/seq/dst_vtep_ip (inet:ipv4-address)
If this variable is read-only (config: false) in the
source YANG file, then _set_dst_vtep_ip is considered as a private
... | Setter method for dst_vtep_ip, mapped from YANG variable /overlay/access_list/type/vxlan/standard/seq/dst_vtep_ip (inet:ipv4-address)
If this variable is read-only (config: false) in the
source YANG file, then _set_dst_vtep_ip is considered as a private
method. Backends looking to populate this variable sho... | Below is the the instruction that describes the task:
### Input:
Setter method for dst_vtep_ip, mapped from YANG variable /overlay/access_list/type/vxlan/standard/seq/dst_vtep_ip (inet:ipv4-address)
If this variable is read-only (config: false) in the
source YANG file, then _set_dst_vtep_ip is considered as... |
def fix_e502(self, result):
"""Remove extraneous escape of newline."""
(line_index, _, target) = get_index_offset_contents(result,
self.source)
self.source[line_index] = target.rstrip('\n\r \t\\') + '\n' | Remove extraneous escape of newline. | Below is the the instruction that describes the task:
### Input:
Remove extraneous escape of newline.
### Response:
def fix_e502(self, result):
"""Remove extraneous escape of newline."""
(line_index, _, target) = get_index_offset_contents(result,
... |
def find_revision_number(self, revision=None):
"""Find the local revision number of the given revision."""
# Make sure the local repository exists.
self.create()
# Try to find the revision number of the specified revision.
revision = self.expand_branch_name(revision)
outp... | Find the local revision number of the given revision. | Below is the the instruction that describes the task:
### Input:
Find the local revision number of the given revision.
### Response:
def find_revision_number(self, revision=None):
"""Find the local revision number of the given revision."""
# Make sure the local repository exists.
self.creat... |
def task(self, _fn=None, queue=None, hard_timeout=None, unique=None,
lock=None, lock_key=None, retry=None, retry_on=None,
retry_method=None, schedule=None, batch=False,
max_queue_size=None):
"""
Function decorator that defines the behavior of the function when it i... | Function decorator that defines the behavior of the function when it is
used as a task. To use the default behavior, tasks don't need to be
decorated.
See README.rst for an explanation of the options. | Below is the the instruction that describes the task:
### Input:
Function decorator that defines the behavior of the function when it is
used as a task. To use the default behavior, tasks don't need to be
decorated.
See README.rst for an explanation of the options.
### Response:
def task(s... |
def expire(self, time=None):
"""Remove expired items from the cache."""
if time is None:
time = self.__timer()
root = self.__root
curr = root.next
links = self.__links
cache_delitem = Cache.__delitem__
while curr is not root and curr.expire < time:
... | Remove expired items from the cache. | Below is the the instruction that describes the task:
### Input:
Remove expired items from the cache.
### Response:
def expire(self, time=None):
"""Remove expired items from the cache."""
if time is None:
time = self.__timer()
root = self.__root
curr = root.next
... |
def load_yaml(path):
# type: (str) -> OrderedDict
"""Load YAML file into an ordered dictionary
Args:
path (str): Path to YAML file
Returns:
OrderedDict: Ordered dictionary containing loaded YAML file
"""
with open(path, 'rt') as f:
yamldict = yaml.load(f.read(), Loader=... | Load YAML file into an ordered dictionary
Args:
path (str): Path to YAML file
Returns:
OrderedDict: Ordered dictionary containing loaded YAML file | Below is the the instruction that describes the task:
### Input:
Load YAML file into an ordered dictionary
Args:
path (str): Path to YAML file
Returns:
OrderedDict: Ordered dictionary containing loaded YAML file
### Response:
def load_yaml(path):
# type: (str) -> OrderedDict
"""Lo... |
def update_privilege(self, obj, target):
'''Get privileges from metadata of the source in s3, and apply them to target'''
if 'privilege' in obj['Metadata']:
os.chmod(target, int(obj['Metadata']['privilege'], 8)) | Get privileges from metadata of the source in s3, and apply them to target | Below is the the instruction that describes the task:
### Input:
Get privileges from metadata of the source in s3, and apply them to target
### Response:
def update_privilege(self, obj, target):
'''Get privileges from metadata of the source in s3, and apply them to target'''
if 'privilege' in obj['Metadata... |
def find_children(self, tag=None, namespace=None):
"""Searches child nodes for objects with the desired tag/namespace.
Returns a list of extension elements within this object whose tag
and/or namespace match those passed in. To find all children in
a particular namespace, specify the na... | Searches child nodes for objects with the desired tag/namespace.
Returns a list of extension elements within this object whose tag
and/or namespace match those passed in. To find all children in
a particular namespace, specify the namespace but not the tag name.
If you specify only the ... | Below is the the instruction that describes the task:
### Input:
Searches child nodes for objects with the desired tag/namespace.
Returns a list of extension elements within this object whose tag
and/or namespace match those passed in. To find all children in
a particular namespace, specify... |
def samaccountname(self, base_dn, distinguished_name):
"""Retrieve the sAMAccountName for a specific DistinguishedName
:param str base_dn: The base DN to search within
:param list distinguished_name: The base DN to search within
:param list attributes: Object attributes to populate, def... | Retrieve the sAMAccountName for a specific DistinguishedName
:param str base_dn: The base DN to search within
:param list distinguished_name: The base DN to search within
:param list attributes: Object attributes to populate, defaults to all
:return: A populated ADUser object
:... | Below is the the instruction that describes the task:
### Input:
Retrieve the sAMAccountName for a specific DistinguishedName
:param str base_dn: The base DN to search within
:param list distinguished_name: The base DN to search within
:param list attributes: Object attributes to populate, ... |
def avail_locations(call=None):
'''
List all available locations
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
ret = {}
conn = get_conn(ser... | List all available locations | Below is the the instruction that describes the task:
### Input:
List all available locations
### Response:
def avail_locations(call=None):
'''
List all available locations
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
... |
def validate_file(parser, arg):
"""Validates that `arg` is a valid file."""
if not os.path.isfile(arg):
parser.error("%s is not a file." % arg)
return arg | Validates that `arg` is a valid file. | Below is the the instruction that describes the task:
### Input:
Validates that `arg` is a valid file.
### Response:
def validate_file(parser, arg):
"""Validates that `arg` is a valid file."""
if not os.path.isfile(arg):
parser.error("%s is not a file." % arg)
return arg |
def ids_sharing_same_pgn(id_x, pgn_x, id_y, pgn_y):
# type: (typing.Sequence[canmatrix.ArbitrationId], typing.Sequence[int], typing.Sequence[canmatrix.ArbitrationId], typing.Sequence[int]) -> typing.Iterable[typing.Tuple[canmatrix.ArbitrationId, canmatrix.ArbitrationId]]
"""Yield arbitration ids which has the s... | Yield arbitration ids which has the same pgn. | Below is the the instruction that describes the task:
### Input:
Yield arbitration ids which has the same pgn.
### Response:
def ids_sharing_same_pgn(id_x, pgn_x, id_y, pgn_y):
# type: (typing.Sequence[canmatrix.ArbitrationId], typing.Sequence[int], typing.Sequence[canmatrix.ArbitrationId], typing.Sequence[int... |
def set_wheel_mode(self, ids):
""" Sets the specified motors to wheel mode. """
self.set_control_mode(dict(zip(ids, itertools.repeat('wheel')))) | Sets the specified motors to wheel mode. | Below is the the instruction that describes the task:
### Input:
Sets the specified motors to wheel mode.
### Response:
def set_wheel_mode(self, ids):
""" Sets the specified motors to wheel mode. """
self.set_control_mode(dict(zip(ids, itertools.repeat('wheel')))) |
def server_bind(self):
"""Override of TCPServer.server_bind() that tracks bind-time assigned random ports."""
TCPServer.server_bind(self)
_, self.server_port = self.socket.getsockname()[:2] | Override of TCPServer.server_bind() that tracks bind-time assigned random ports. | Below is the the instruction that describes the task:
### Input:
Override of TCPServer.server_bind() that tracks bind-time assigned random ports.
### Response:
def server_bind(self):
"""Override of TCPServer.server_bind() that tracks bind-time assigned random ports."""
TCPServer.server_bind(self)
_, se... |
def find_repo_by_path(i):
"""
Input: {
path - path to repo
}
Output: {
return - return code = 0, if successful
16, if repo not found (may be warning)
> 0, if error
... | Input: {
path - path to repo
}
Output: {
return - return code = 0, if successful
16, if repo not found (may be warning)
> 0, if error
(error) - error text if retur... | Below is the the instruction that describes the task:
### Input:
Input: {
path - path to repo
}
Output: {
return - return code = 0, if successful
16, if repo not found (may be warning)
... |
def tokenize_annotated(doc, annotation):
"""Tokenize a document and add an annotation attribute to each token
"""
tokens = tokenize(doc, include_hrefs=False)
for tok in tokens:
tok.annotation = annotation
return tokens | Tokenize a document and add an annotation attribute to each token | Below is the the instruction that describes the task:
### Input:
Tokenize a document and add an annotation attribute to each token
### Response:
def tokenize_annotated(doc, annotation):
"""Tokenize a document and add an annotation attribute to each token
"""
tokens = tokenize(doc, include_hrefs=False)... |
def create_cfg_segment(filename, filecontent, description, auth, url):
"""
Takes a str into var filecontent which represents the entire content of a configuration
segment, or partial configuration file. Takes a str into var description which represents the
description of the configuration segment
:p... | Takes a str into var filecontent which represents the entire content of a configuration
segment, or partial configuration file. Takes a str into var description which represents the
description of the configuration segment
:param filename: str containing the name of the configuration segment.
:param fi... | Below is the the instruction that describes the task:
### Input:
Takes a str into var filecontent which represents the entire content of a configuration
segment, or partial configuration file. Takes a str into var description which represents the
description of the configuration segment
:param filename:... |
def create_new_label_by_content_id(self, content_id, label_names, callback=None):
"""
Adds a list of labels to the specified content.
:param content_id (string): A string containing the id of the labels content container.
:param label_names (list): A list of labels (strings) to apply to ... | Adds a list of labels to the specified content.
:param content_id (string): A string containing the id of the labels content container.
:param label_names (list): A list of labels (strings) to apply to the content.
:param callback: OPTIONAL: The callback to execute on the resulting data, before ... | Below is the the instruction that describes the task:
### Input:
Adds a list of labels to the specified content.
:param content_id (string): A string containing the id of the labels content container.
:param label_names (list): A list of labels (strings) to apply to the content.
:param callb... |
def urlToIds(url):
"""
Resolve a ``join.skype.com`` URL and returns various identifiers for the group conversation.
Args:
url (str): public join URL, or identifier from it
Returns:
dict: related conversation's identifiers -- keys: ``id``, ``long``, ``blob``
... | Resolve a ``join.skype.com`` URL and returns various identifiers for the group conversation.
Args:
url (str): public join URL, or identifier from it
Returns:
dict: related conversation's identifiers -- keys: ``id``, ``long``, ``blob`` | Below is the the instruction that describes the task:
### Input:
Resolve a ``join.skype.com`` URL and returns various identifiers for the group conversation.
Args:
url (str): public join URL, or identifier from it
Returns:
dict: related conversation's identifiers -- keys: `... |
def copyCurrentLayout(self, sourceViewSUID, targetViewSUID, body, verbose=None):
"""
Copy one network view layout onto another, setting the node location and view scale to match. This makes visually comparing networks simple.
:param sourceViewSUID: Source network view SUID (or "current")
... | Copy one network view layout onto another, setting the node location and view scale to match. This makes visually comparing networks simple.
:param sourceViewSUID: Source network view SUID (or "current")
:param targetViewSUID: Target network view SUID (or "current")
:param body: Clone the speci... | Below is the the instruction that describes the task:
### Input:
Copy one network view layout onto another, setting the node location and view scale to match. This makes visually comparing networks simple.
:param sourceViewSUID: Source network view SUID (or "current")
:param targetViewSUID: Target ... |
def log_error(msg, logger="TaskLogger"):
"""Log an ERROR message
Convenience function to log a message to the default Logger
Parameters
----------
msg : str
Message to be logged
logger : str, optional (default: "TaskLogger")
Unique name of the logger to retrieve
Returns
... | Log an ERROR message
Convenience function to log a message to the default Logger
Parameters
----------
msg : str
Message to be logged
logger : str, optional (default: "TaskLogger")
Unique name of the logger to retrieve
Returns
-------
logger : TaskLogger | Below is the the instruction that describes the task:
### Input:
Log an ERROR message
Convenience function to log a message to the default Logger
Parameters
----------
msg : str
Message to be logged
logger : str, optional (default: "TaskLogger")
Unique name of the logger to ret... |
def remove_duplicates(vector_tuple):
"""
Remove duplicates rows from N equally-sized arrays
"""
array = np.column_stack(vector_tuple)
a = np.ascontiguousarray(array)
unique_a = np.unique(a.view([('', a.dtype)]*a.shape[1]))
b = unique_a.view(a.dtype).reshape((unique_a.shape[0], a.shape[1]))
... | Remove duplicates rows from N equally-sized arrays | Below is the the instruction that describes the task:
### Input:
Remove duplicates rows from N equally-sized arrays
### Response:
def remove_duplicates(vector_tuple):
"""
Remove duplicates rows from N equally-sized arrays
"""
array = np.column_stack(vector_tuple)
a = np.ascontiguousarray(array)... |
def update_storage_policy(policy, policy_dict, service_instance=None):
'''
Updates a storage policy.
Supported capability types: scalar, set, range.
policy
Name of the policy to update.
policy_dict
Dictionary containing the changes to apply to the policy.
(example in salt.... | Updates a storage policy.
Supported capability types: scalar, set, range.
policy
Name of the policy to update.
policy_dict
Dictionary containing the changes to apply to the policy.
(example in salt.states.pbm)
service_instance
Service instance (vim.ServiceInstance) of... | Below is the the instruction that describes the task:
### Input:
Updates a storage policy.
Supported capability types: scalar, set, range.
policy
Name of the policy to update.
policy_dict
Dictionary containing the changes to apply to the policy.
(example in salt.states.pbm)
... |
def _hash(self, obj, parent, parents_ids=EMPTY_FROZENSET):
"""The main diff method"""
try:
result = self[obj]
except (TypeError, KeyError):
pass
else:
return result
result = not_hashed
if self._skip_this(obj, parent):
ret... | The main diff method | Below is the the instruction that describes the task:
### Input:
The main diff method
### Response:
def _hash(self, obj, parent, parents_ids=EMPTY_FROZENSET):
"""The main diff method"""
try:
result = self[obj]
except (TypeError, KeyError):
pass
else:
... |
def _format_firewall_stdout(cmd_ret):
'''
Helper function to format the stdout from the get_firewall_status function.
cmd_ret
The return dictionary that comes from a cmd.run_all call.
'''
ret_dict = {'success': True,
'rulesets': {}}
for line in cmd_ret['stdout'].splitlin... | Helper function to format the stdout from the get_firewall_status function.
cmd_ret
The return dictionary that comes from a cmd.run_all call. | Below is the the instruction that describes the task:
### Input:
Helper function to format the stdout from the get_firewall_status function.
cmd_ret
The return dictionary that comes from a cmd.run_all call.
### Response:
def _format_firewall_stdout(cmd_ret):
'''
Helper function to format the s... |
def _array_setitem_with_key_seq(self, array_name, index, key_seq, value):
"""
Sets a the array value in the TOML file located by the given key sequence.
Example:
self._array_setitem(array_name, index, ('key1', 'key2', 'key3'), 'text_value')
is equivalent to doing
self.ar... | Sets a the array value in the TOML file located by the given key sequence.
Example:
self._array_setitem(array_name, index, ('key1', 'key2', 'key3'), 'text_value')
is equivalent to doing
self.array(array_name)[index]['key1']['key2']['key3'] = 'text_value' | Below is the the instruction that describes the task:
### Input:
Sets a the array value in the TOML file located by the given key sequence.
Example:
self._array_setitem(array_name, index, ('key1', 'key2', 'key3'), 'text_value')
is equivalent to doing
self.array(array_name)[index]['k... |
def get_turicreate_object_type(url):
'''
Given url where a Turi Create object is persisted, return the Turi
Create object type: 'model', 'graph', 'sframe', or 'sarray'
'''
from .._connect import main as _glconnect
ret = _glconnect.get_unity().get_turicreate_object_type(_make_internal_url(url))
... | Given url where a Turi Create object is persisted, return the Turi
Create object type: 'model', 'graph', 'sframe', or 'sarray' | Below is the the instruction that describes the task:
### Input:
Given url where a Turi Create object is persisted, return the Turi
Create object type: 'model', 'graph', 'sframe', or 'sarray'
### Response:
def get_turicreate_object_type(url):
'''
Given url where a Turi Create object is persisted, retur... |
def unapply_patch(self, patch_name, force=False):
""" Unapply patches up to patch_name. patch_name will end up as top
patch """
self._check(force)
patches = self.db.patches_after(Patch(patch_name))
for patch in reversed(patches):
self._unapply_patch(patch)
... | Unapply patches up to patch_name. patch_name will end up as top
patch | Below is the the instruction that describes the task:
### Input:
Unapply patches up to patch_name. patch_name will end up as top
patch
### Response:
def unapply_patch(self, patch_name, force=False):
""" Unapply patches up to patch_name. patch_name will end up as top
patch """
... |
def compile_mako_files(self, app_config):
'''Compiles the Mako templates within the apps of this system'''
# go through the files in the templates, scripts, and styles directories
for subdir_name in self.SEARCH_DIRS:
subdir = subdir_name.format(
app_path=app_config.pa... | Compiles the Mako templates within the apps of this system | Below is the the instruction that describes the task:
### Input:
Compiles the Mako templates within the apps of this system
### Response:
def compile_mako_files(self, app_config):
'''Compiles the Mako templates within the apps of this system'''
# go through the files in the templates, scripts, and ... |
def orientation(self, value):
'''setter of orientation property.'''
for values in self.__orientation:
if value in values:
# can not set upside-down until api level 18.
self.server.jsonrpc.setOrientation(values[1])
break
else:
... | setter of orientation property. | Below is the the instruction that describes the task:
### Input:
setter of orientation property.
### Response:
def orientation(self, value):
'''setter of orientation property.'''
for values in self.__orientation:
if value in values:
# can not set upside-down until api le... |
def drawcircle(self, x, y, r = 10, colour = None, label = None):
"""
Draws a circle centered on (x, y) with radius r. All these are in the coordinates of your initial image !
You give these x and y in the usual ds9 pixels, (0,0) is bottom left.
I will convert this into the right PIL coor... | Draws a circle centered on (x, y) with radius r. All these are in the coordinates of your initial image !
You give these x and y in the usual ds9 pixels, (0,0) is bottom left.
I will convert this into the right PIL coordiates. | Below is the the instruction that describes the task:
### Input:
Draws a circle centered on (x, y) with radius r. All these are in the coordinates of your initial image !
You give these x and y in the usual ds9 pixels, (0,0) is bottom left.
I will convert this into the right PIL coordiates.
### Resp... |
def get_context(self, data, accepted_media_type, renderer_context):
"""
Returns the context used to render.
"""
view = renderer_context['view']
request = renderer_context['request']
response = renderer_context['response']
renderer = self.get_default_renderer(view... | Returns the context used to render. | Below is the the instruction that describes the task:
### Input:
Returns the context used to render.
### Response:
def get_context(self, data, accepted_media_type, renderer_context):
"""
Returns the context used to render.
"""
view = renderer_context['view']
request = render... |
def lookups(self):
"""
Access the Lookups Twilio Domain
:returns: Lookups Twilio Domain
:rtype: twilio.rest.lookups.Lookups
"""
if self._lookups is None:
from twilio.rest.lookups import Lookups
self._lookups = Lookups(self)
return self._lo... | Access the Lookups Twilio Domain
:returns: Lookups Twilio Domain
:rtype: twilio.rest.lookups.Lookups | Below is the the instruction that describes the task:
### Input:
Access the Lookups Twilio Domain
:returns: Lookups Twilio Domain
:rtype: twilio.rest.lookups.Lookups
### Response:
def lookups(self):
"""
Access the Lookups Twilio Domain
:returns: Lookups Twilio Domain
... |
def register_validator(flag_name,
checker,
message='Flag validation failed',
flag_values=_flagvalues.FLAGS):
"""Adds a constraint, which will be enforced during program execution.
The constraint is validated when flags are initially parsed, and a... | Adds a constraint, which will be enforced during program execution.
The constraint is validated when flags are initially parsed, and after each
change of the corresponding flag's value.
Args:
flag_name: str, name of the flag to be checked.
checker: callable, a function to validate the flag.
input... | Below is the the instruction that describes the task:
### Input:
Adds a constraint, which will be enforced during program execution.
The constraint is validated when flags are initially parsed, and after each
change of the corresponding flag's value.
Args:
flag_name: str, name of the flag to be checked.
... |
def calcDistMatchArr(matchArr, tKey, mKey):
"""Calculate the euclidean distance of all array positions in "matchArr".
:param matchArr: a dictionary of ``numpy.arrays`` containing at least two
entries that are treated as cartesian coordinates.
:param tKey: #TODO: docstring
:param mKey: #TODO: do... | Calculate the euclidean distance of all array positions in "matchArr".
:param matchArr: a dictionary of ``numpy.arrays`` containing at least two
entries that are treated as cartesian coordinates.
:param tKey: #TODO: docstring
:param mKey: #TODO: docstring
:returns: #TODO: docstring
... | Below is the the instruction that describes the task:
### Input:
Calculate the euclidean distance of all array positions in "matchArr".
:param matchArr: a dictionary of ``numpy.arrays`` containing at least two
entries that are treated as cartesian coordinates.
:param tKey: #TODO: docstring
:par... |
def scale_dataset(self, dsid, variable, info):
"""Scale the data set, applying the attributes from the netCDF file"""
variable = remove_empties(variable)
scale = variable.attrs.get('scale_factor', np.array(1))
offset = variable.attrs.get('add_offset', np.array(0))
if np.issubdty... | Scale the data set, applying the attributes from the netCDF file | Below is the the instruction that describes the task:
### Input:
Scale the data set, applying the attributes from the netCDF file
### Response:
def scale_dataset(self, dsid, variable, info):
"""Scale the data set, applying the attributes from the netCDF file"""
variable = remove_empties(variable)
... |
def afterglow(self, src=None, event=None, dst=None, **kargs):
"""Experimental clone attempt of http://sourceforge.net/projects/afterglow
each datum is reduced as src -> event -> dst and the data are graphed.
by default we have IP.src -> IP.dport -> IP.dst"""
if src is None:
s... | Experimental clone attempt of http://sourceforge.net/projects/afterglow
each datum is reduced as src -> event -> dst and the data are graphed.
by default we have IP.src -> IP.dport -> IP.dst | Below is the the instruction that describes the task:
### Input:
Experimental clone attempt of http://sourceforge.net/projects/afterglow
each datum is reduced as src -> event -> dst and the data are graphed.
by default we have IP.src -> IP.dport -> IP.dst
### Response:
def afterglow(self, src=None,... |
def displayhook(value):
"""
Runs all of the registered display hook methods with the given value.
Look at the sys.displayhook documentation for more information.
:param value | <variant>
"""
global _displayhooks
new_hooks = []
for hook_ref in _displayhooks:
hook = hook... | Runs all of the registered display hook methods with the given value.
Look at the sys.displayhook documentation for more information.
:param value | <variant> | Below is the the instruction that describes the task:
### Input:
Runs all of the registered display hook methods with the given value.
Look at the sys.displayhook documentation for more information.
:param value | <variant>
### Response:
def displayhook(value):
"""
Runs all of the registe... |
def get_joystick_buttons(joy):
"""
Returns the state of all buttons of the specified joystick.
Wrapper for:
const unsigned char* glfwGetJoystickButtons(int joy, int* count);
"""
count_value = ctypes.c_int(0)
count = ctypes.pointer(count_value)
result = _glfw.glfwGetJoystickButtons(j... | Returns the state of all buttons of the specified joystick.
Wrapper for:
const unsigned char* glfwGetJoystickButtons(int joy, int* count); | Below is the the instruction that describes the task:
### Input:
Returns the state of all buttons of the specified joystick.
Wrapper for:
const unsigned char* glfwGetJoystickButtons(int joy, int* count);
### Response:
def get_joystick_buttons(joy):
"""
Returns the state of all buttons of the s... |
def _get_start_revision(self, graph, benchmark, entry_name):
"""
Compute the first revision allowed by asv.conf.json.
Revisions correspond to linearized commit history and the
regression detection runs on this order --- the starting commit
thus corresponds to a specific starting... | Compute the first revision allowed by asv.conf.json.
Revisions correspond to linearized commit history and the
regression detection runs on this order --- the starting commit
thus corresponds to a specific starting revision. | Below is the the instruction that describes the task:
### Input:
Compute the first revision allowed by asv.conf.json.
Revisions correspond to linearized commit history and the
regression detection runs on this order --- the starting commit
thus corresponds to a specific starting revision.
#... |
def unescape_LDAP(ldap_string):
# type: (str) -> str
# pylint: disable=C0103
"""
Unespaces an LDAP string
:param ldap_string: The string to unescape
:return: The unprotected string
"""
if ldap_string is None:
return None
if ESCAPE_CHARACTER not in ldap_string:
# No ... | Unespaces an LDAP string
:param ldap_string: The string to unescape
:return: The unprotected string | Below is the the instruction that describes the task:
### Input:
Unespaces an LDAP string
:param ldap_string: The string to unescape
:return: The unprotected string
### Response:
def unescape_LDAP(ldap_string):
# type: (str) -> str
# pylint: disable=C0103
"""
Unespaces an LDAP string
... |
def datetime(self, to_timezone=None, naive=False):
"""Returns a timezone-aware datetime...
Defaulting to UTC (as it should).
Keyword Arguments:
to_timezone {str} -- timezone to convert to (default: None/UTC)
naive {bool} -- if True,
the tzinfo... | Returns a timezone-aware datetime...
Defaulting to UTC (as it should).
Keyword Arguments:
to_timezone {str} -- timezone to convert to (default: None/UTC)
naive {bool} -- if True,
the tzinfo is simply dropped (default: False) | Below is the the instruction that describes the task:
### Input:
Returns a timezone-aware datetime...
Defaulting to UTC (as it should).
Keyword Arguments:
to_timezone {str} -- timezone to convert to (default: None/UTC)
naive {bool} -- if True,
the... |
def get_country_by_name(self, country_name) -> 'Country':
"""
Gets a country in this coalition by its name
Args:
country_name: country name
Returns: Country
"""
VALID_STR.validate(country_name, 'get_country_by_name', exc=ValueError)
if country_name n... | Gets a country in this coalition by its name
Args:
country_name: country name
Returns: Country | Below is the the instruction that describes the task:
### Input:
Gets a country in this coalition by its name
Args:
country_name: country name
Returns: Country
### Response:
def get_country_by_name(self, country_name) -> 'Country':
"""
Gets a country in this coalition ... |
def get_server_networks(self, network, public=False, private=False,
key=None):
"""
Creates the dict of network UUIDs required by Cloud Servers when
creating a new server with isolated networks. By default, the UUID
values are returned with the key of "net-id", which is what n... | Creates the dict of network UUIDs required by Cloud Servers when
creating a new server with isolated networks. By default, the UUID
values are returned with the key of "net-id", which is what novaclient
expects. Other tools may require different values, such as 'uuid'. If
that is the cas... | Below is the the instruction that describes the task:
### Input:
Creates the dict of network UUIDs required by Cloud Servers when
creating a new server with isolated networks. By default, the UUID
values are returned with the key of "net-id", which is what novaclient
expects. Other tools may... |
def headerData(self, section, orientation, role):
"""Get the information to put in the header."""
if role == Qt.TextAlignmentRole:
if orientation == Qt.Horizontal:
return Qt.AlignCenter | Qt.AlignBottom
else:
return Qt.AlignRight | Qt.AlignVC... | Get the information to put in the header. | Below is the the instruction that describes the task:
### Input:
Get the information to put in the header.
### Response:
def headerData(self, section, orientation, role):
"""Get the information to put in the header."""
if role == Qt.TextAlignmentRole:
if orientation == Qt.Horizontal:... |
def distL2(x1,y1,x2,y2):
"""Compute the L2-norm (Euclidean) distance between two points.
The distance is rounded to the closest integer, for compatibility
with the TSPLIB convention.
The two points are located on coordinates (x1,y1) and (x2,y2),
sent as parameters"""
xdiff = x2 - x1
ydiff ... | Compute the L2-norm (Euclidean) distance between two points.
The distance is rounded to the closest integer, for compatibility
with the TSPLIB convention.
The two points are located on coordinates (x1,y1) and (x2,y2),
sent as parameters | Below is the the instruction that describes the task:
### Input:
Compute the L2-norm (Euclidean) distance between two points.
The distance is rounded to the closest integer, for compatibility
with the TSPLIB convention.
The two points are located on coordinates (x1,y1) and (x2,y2),
sent as paramet... |
def str_display_width(s):
'''
from elist.utils import *
str_display_width('a')
str_display_width('去')
'''
s= str(s)
width = 0
len = s.__len__()
for i in range(0,len):
sublen = s[i].encode().__len__()
sublen = int(sublen/2 + 1/2)
width = width + sub... | from elist.utils import *
str_display_width('a')
str_display_width('去') | Below is the the instruction that describes the task:
### Input:
from elist.utils import *
str_display_width('a')
str_display_width('去')
### Response:
def str_display_width(s):
'''
from elist.utils import *
str_display_width('a')
str_display_width('去')
'''
s= str... |
def command_x(self, x, to=None):
"""
Sends a character to the currently active element with Command
pressed. This method takes care of pressing and releasing
Command.
"""
if to is None:
ActionChains(self.driver) \
.send_keys([Keys.COMMAND, x, K... | Sends a character to the currently active element with Command
pressed. This method takes care of pressing and releasing
Command. | Below is the the instruction that describes the task:
### Input:
Sends a character to the currently active element with Command
pressed. This method takes care of pressing and releasing
Command.
### Response:
def command_x(self, x, to=None):
"""
Sends a character to the currently ac... |
def get_concurrency(self):
"""Check account concurrency limits."""
method = 'GET'
endpoint = '/rest/v1.1/users/{}/concurrency'.format(
self.client.sauce_username)
return self.client.request(method, endpoint) | Check account concurrency limits. | Below is the the instruction that describes the task:
### Input:
Check account concurrency limits.
### Response:
def get_concurrency(self):
"""Check account concurrency limits."""
method = 'GET'
endpoint = '/rest/v1.1/users/{}/concurrency'.format(
self.client.sauce_username)
... |
def parent_images(self):
"""
:return: list of parent images -- one image per each stage's FROM instruction
"""
parents = []
for instr in self.structure:
if instr['instruction'] != 'FROM':
continue
image, _ = image_from(instr['value'])
... | :return: list of parent images -- one image per each stage's FROM instruction | Below is the the instruction that describes the task:
### Input:
:return: list of parent images -- one image per each stage's FROM instruction
### Response:
def parent_images(self):
"""
:return: list of parent images -- one image per each stage's FROM instruction
"""
parents = []
... |
def constructRows(self, items):
"""
Build row objects that are serializable using Athena for sending to the
client.
@param items: an iterable of objects compatible with my columns'
C{extractValue} methods.
@return: a list of dictionaries, where each dictionary has a str... | Build row objects that are serializable using Athena for sending to the
client.
@param items: an iterable of objects compatible with my columns'
C{extractValue} methods.
@return: a list of dictionaries, where each dictionary has a string key
for each column name in my list of c... | Below is the the instruction that describes the task:
### Input:
Build row objects that are serializable using Athena for sending to the
client.
@param items: an iterable of objects compatible with my columns'
C{extractValue} methods.
@return: a list of dictionaries, where each dic... |
def get_timing_signal_1d(length,
channels,
min_timescale=1.0,
max_timescale=1.0e4,
start_index=0):
"""Gets a bunch of sinusoids of different frequencies.
Each channel of the input Tensor is incremented by a sinusoid... | Gets a bunch of sinusoids of different frequencies.
Each channel of the input Tensor is incremented by a sinusoid of a different
frequency and phase.
This allows attention to learn to use absolute and relative positions.
Timing signals should be added to some precursors of both the query and the
memory inpu... | Below is the the instruction that describes the task:
### Input:
Gets a bunch of sinusoids of different frequencies.
Each channel of the input Tensor is incremented by a sinusoid of a different
frequency and phase.
This allows attention to learn to use absolute and relative positions.
Timing signals shoul... |
def normalizeGlyphNote(value):
"""
Normalizes Glyph Note.
* **value** must be a :ref:`type-string`.
* Returned value is an unencoded ``unicode`` string
"""
if not isinstance(value, basestring):
raise TypeError("Note must be a string, not %s."
% type(value).__name... | Normalizes Glyph Note.
* **value** must be a :ref:`type-string`.
* Returned value is an unencoded ``unicode`` string | Below is the the instruction that describes the task:
### Input:
Normalizes Glyph Note.
* **value** must be a :ref:`type-string`.
* Returned value is an unencoded ``unicode`` string
### Response:
def normalizeGlyphNote(value):
"""
Normalizes Glyph Note.
* **value** must be a :ref:`type-string... |
def crack_secret_exponent_from_k(generator, signed_value, sig, k):
"""
Given a signature of a signed_value and a known k, return the secret exponent.
"""
r, s = sig
return ((s * k - signed_value) * generator.inverse(r)) % generator.order() | Given a signature of a signed_value and a known k, return the secret exponent. | Below is the the instruction that describes the task:
### Input:
Given a signature of a signed_value and a known k, return the secret exponent.
### Response:
def crack_secret_exponent_from_k(generator, signed_value, sig, k):
"""
Given a signature of a signed_value and a known k, return the secret exponent.... |
def back_slash_to_front_converter(string):
"""
Replacing all \ in the str to /
:param string: single string to modify
:type string: str
"""
try:
if not string or not isinstance(string, str):
return string
return string.replace('\\', '/')
except Exception:
... | Replacing all \ in the str to /
:param string: single string to modify
:type string: str | Below is the the instruction that describes the task:
### Input:
Replacing all \ in the str to /
:param string: single string to modify
:type string: str
### Response:
def back_slash_to_front_converter(string):
"""
Replacing all \ in the str to /
:param string: single string to modify
:type... |
def urlize(text, trim_url_limit=None, nofollow=False):
"""Converts any URLs in text into clickable links. Works on http://,
https:// and www. links. Links can have trailing punctuation (periods,
commas, close-parens) and leading punctuation (opening parens) and
it'll still do the right thing.
If tr... | Converts any URLs in text into clickable links. Works on http://,
https:// and www. links. Links can have trailing punctuation (periods,
commas, close-parens) and leading punctuation (opening parens) and
it'll still do the right thing.
If trim_url_limit is not None, the URLs in link text will be limite... | Below is the the instruction that describes the task:
### Input:
Converts any URLs in text into clickable links. Works on http://,
https:// and www. links. Links can have trailing punctuation (periods,
commas, close-parens) and leading punctuation (opening parens) and
it'll still do the right thing.
... |
def relabel(label_list, projections):
"""
Relabel an entire :py:class:`~audiomate.annotations.LabelList` using user-defined projections.
Labels can be renamed, removed or overlapping labels can be flattened to a single label per segment.
Each entry in the dictionary of projections represents a single p... | Relabel an entire :py:class:`~audiomate.annotations.LabelList` using user-defined projections.
Labels can be renamed, removed or overlapping labels can be flattened to a single label per segment.
Each entry in the dictionary of projections represents a single projection that maps a combination of labels (key)
... | Below is the the instruction that describes the task:
### Input:
Relabel an entire :py:class:`~audiomate.annotations.LabelList` using user-defined projections.
Labels can be renamed, removed or overlapping labels can be flattened to a single label per segment.
Each entry in the dictionary of projections re... |
def _find_server(account, servername=None):
""" Find and return a PlexServer object. """
servers = servers = [s for s in account.resources() if 'server' in s.provides]
# If servername specified find and return it
if servername is not None:
for server in servers:
if server.name == ser... | Find and return a PlexServer object. | Below is the the instruction that describes the task:
### Input:
Find and return a PlexServer object.
### Response:
def _find_server(account, servername=None):
""" Find and return a PlexServer object. """
servers = servers = [s for s in account.resources() if 'server' in s.provides]
# If servername spe... |
def upload(self, remote_path, local_path, progress=None):
"""Uploads resource to remote path on WebDAV server.
In case resource is directory it will upload all nested files and directories.
More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PUT
:param remo... | Uploads resource to remote path on WebDAV server.
In case resource is directory it will upload all nested files and directories.
More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PUT
:param remote_path: the path for uploading resources on WebDAV server. Can be fi... | Below is the the instruction that describes the task:
### Input:
Uploads resource to remote path on WebDAV server.
In case resource is directory it will upload all nested files and directories.
More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PUT
:param remo... |
def iter_contributor_statistics(self, number=-1, etag=None):
"""Iterate over the contributors list.
See also: http://developer.github.com/v3/repos/statistics/
:param int number: (optional), number of weeks to return. Default -1
will return all of the weeks.
:param str etag:... | Iterate over the contributors list.
See also: http://developer.github.com/v3/repos/statistics/
:param int number: (optional), number of weeks to return. Default -1
will return all of the weeks.
:param str etag: (optional), ETag from a previous request to the same
endpoi... | Below is the the instruction that describes the task:
### Input:
Iterate over the contributors list.
See also: http://developer.github.com/v3/repos/statistics/
:param int number: (optional), number of weeks to return. Default -1
will return all of the weeks.
:param str etag: (o... |
def _getH2singleTrait(self, K, verbose=None):
"""
Internal function for parameter initialization
estimate variance components and fixed effect using a linear mixed model with an intercept and 2 random effects (one is noise)
Args:
K: covariance matrix of the non-noise r... | Internal function for parameter initialization
estimate variance components and fixed effect using a linear mixed model with an intercept and 2 random effects (one is noise)
Args:
K: covariance matrix of the non-noise random effect term | Below is the the instruction that describes the task:
### Input:
Internal function for parameter initialization
estimate variance components and fixed effect using a linear mixed model with an intercept and 2 random effects (one is noise)
Args:
K: covariance matrix of the non-nois... |
def transform(self, blocks, y=None):
"""
Computes the content to tag ratio per block, smooths the values, then
predicts content (1) or not-content (0) using a fit k-means cluster model.
Args:
blocks (List[Block]): as output by :class:`Blockifier.blockify`
y (None... | Computes the content to tag ratio per block, smooths the values, then
predicts content (1) or not-content (0) using a fit k-means cluster model.
Args:
blocks (List[Block]): as output by :class:`Blockifier.blockify`
y (None): This isn't used, it's only here for API consistency.
... | Below is the the instruction that describes the task:
### Input:
Computes the content to tag ratio per block, smooths the values, then
predicts content (1) or not-content (0) using a fit k-means cluster model.
Args:
blocks (List[Block]): as output by :class:`Blockifier.blockify`
... |
def job_exists(name=None):
'''
Check whether the job exists in configured Jenkins jobs.
:param name: The name of the job is check if it exists.
:return: True if job exists, False if job does not exist.
CLI Example:
.. code-block:: bash
salt '*' jenkins.job_exists jobname
'''
... | Check whether the job exists in configured Jenkins jobs.
:param name: The name of the job is check if it exists.
:return: True if job exists, False if job does not exist.
CLI Example:
.. code-block:: bash
salt '*' jenkins.job_exists jobname | Below is the the instruction that describes the task:
### Input:
Check whether the job exists in configured Jenkins jobs.
:param name: The name of the job is check if it exists.
:return: True if job exists, False if job does not exist.
CLI Example:
.. code-block:: bash
salt '*' jenkins.j... |
def load_bytes(self,
bytes_data,
key,
bucket_name=None,
replace=False,
encrypt=False):
"""
Loads bytes to S3
This is provided as a convenience to drop a string in S3. It uses the
boto infrastr... | Loads bytes to S3
This is provided as a convenience to drop a string in S3. It uses the
boto infrastructure to ship a file to s3.
:param bytes_data: bytes to set as content for the key.
:type bytes_data: bytes
:param key: S3 key that will point to the file
:type key: st... | Below is the the instruction that describes the task:
### Input:
Loads bytes to S3
This is provided as a convenience to drop a string in S3. It uses the
boto infrastructure to ship a file to s3.
:param bytes_data: bytes to set as content for the key.
:type bytes_data: bytes
... |
async def connect(url, *, apikey=None, insecure=False):
"""Connect to a remote MAAS instance with `apikey`.
Returns a new :class:`Profile` which has NOT been saved. To connect AND
save a new profile::
profile = connect(url, apikey=apikey)
profile = profile.replace(name="mad-hatter")
... | Connect to a remote MAAS instance with `apikey`.
Returns a new :class:`Profile` which has NOT been saved. To connect AND
save a new profile::
profile = connect(url, apikey=apikey)
profile = profile.replace(name="mad-hatter")
with profiles.ProfileStore.open() as config:
con... | Below is the the instruction that describes the task:
### Input:
Connect to a remote MAAS instance with `apikey`.
Returns a new :class:`Profile` which has NOT been saved. To connect AND
save a new profile::
profile = connect(url, apikey=apikey)
profile = profile.replace(name="mad-hatter")
... |
def _sensoryComputeInferenceMode(self, anchorInput):
"""
Infer the location from sensory input. Activate any cells with enough active
synapses to this sensory input. Deactivate all other cells.
@param anchorInput (numpy array)
A sensory input. This will often come from a feature-location pair layer... | Infer the location from sensory input. Activate any cells with enough active
synapses to this sensory input. Deactivate all other cells.
@param anchorInput (numpy array)
A sensory input. This will often come from a feature-location pair layer. | Below is the the instruction that describes the task:
### Input:
Infer the location from sensory input. Activate any cells with enough active
synapses to this sensory input. Deactivate all other cells.
@param anchorInput (numpy array)
A sensory input. This will often come from a feature-location pair l... |
def __expand_cluster(self, index_point):
"""!
@brief Expands cluster from specified point in the input data space.
@param[in] index_point (list): Index of a point from the data.
@return (list) Return tuple of list of indexes that belong to the same cluster and list of poi... | !
@brief Expands cluster from specified point in the input data space.
@param[in] index_point (list): Index of a point from the data.
@return (list) Return tuple of list of indexes that belong to the same cluster and list of points that are marked as noise: (cluster, noise), or No... | Below is the the instruction that describes the task:
### Input:
!
@brief Expands cluster from specified point in the input data space.
@param[in] index_point (list): Index of a point from the data.
@return (list) Return tuple of list of indexes that belong to the same cluster... |
def create_table(self, name, schema):
"""
Create a new table.
If the table already exists, nothing happens.
Example:
>>> db.create_table("foo", (("id", "integer primary key"),
("value", "text")))
Arguments:
name ... | Create a new table.
If the table already exists, nothing happens.
Example:
>>> db.create_table("foo", (("id", "integer primary key"),
("value", "text")))
Arguments:
name (str): The name of the table to create.
schema ... | Below is the the instruction that describes the task:
### Input:
Create a new table.
If the table already exists, nothing happens.
Example:
>>> db.create_table("foo", (("id", "integer primary key"),
("value", "text")))
Arguments:
... |
def update_association(self, association):
"""Add the GO parents of a gene's associated GO IDs to the gene's association."""
bad_goids = set()
# Loop through all sets of GO IDs for all genes
for goids in association.values():
parents = set()
# Iterate thru each GO... | Add the GO parents of a gene's associated GO IDs to the gene's association. | Below is the the instruction that describes the task:
### Input:
Add the GO parents of a gene's associated GO IDs to the gene's association.
### Response:
def update_association(self, association):
"""Add the GO parents of a gene's associated GO IDs to the gene's association."""
bad_goids = set()
... |
def parse_query(self, query_string):
"""
Given a `query_string`, will attempt to return a xapian.Query
Required arguments:
``query_string`` -- A query string to parse
Returns a xapian.Query
"""
if query_string == '*':
return xapian.Query('') # M... | Given a `query_string`, will attempt to return a xapian.Query
Required arguments:
``query_string`` -- A query string to parse
Returns a xapian.Query | Below is the the instruction that describes the task:
### Input:
Given a `query_string`, will attempt to return a xapian.Query
Required arguments:
``query_string`` -- A query string to parse
Returns a xapian.Query
### Response:
def parse_query(self, query_string):
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.