code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def set_dimmer(self, dimmer, transition_time=None):
"""Set dimmer value of a group.
dimmer: Integer between 0..255
transition_time: Integer representing tenth of a second (default None)
"""
values = {
ATTR_LIGHT_DIMMER: dimmer,
}
if transition_time is... | Set dimmer value of a group.
dimmer: Integer between 0..255
transition_time: Integer representing tenth of a second (default None) | Below is the the instruction that describes the task:
### Input:
Set dimmer value of a group.
dimmer: Integer between 0..255
transition_time: Integer representing tenth of a second (default None)
### Response:
def set_dimmer(self, dimmer, transition_time=None):
"""Set dimmer value of a gro... |
def next_frame_sv2p_cutoff():
"""SV2P model with additional cutoff in L2 loss for environments like pong."""
hparams = next_frame_sv2p()
hparams.video_modality_loss_cutoff = 0.4
hparams.video_num_input_frames = 4
hparams.video_num_target_frames = 1
return hparams | SV2P model with additional cutoff in L2 loss for environments like pong. | Below is the the instruction that describes the task:
### Input:
SV2P model with additional cutoff in L2 loss for environments like pong.
### Response:
def next_frame_sv2p_cutoff():
"""SV2P model with additional cutoff in L2 loss for environments like pong."""
hparams = next_frame_sv2p()
hparams.video_modali... |
def _process_ortholog_classes(self, limit=None):
"""
This method add the KEGG orthology classes to the graph.
If there's an embedded enzyme commission number,
that is added as an xref.
Triples created:
<orthology_class_id> is a class
<orthology_class_id> has lab... | This method add the KEGG orthology classes to the graph.
If there's an embedded enzyme commission number,
that is added as an xref.
Triples created:
<orthology_class_id> is a class
<orthology_class_id> has label <orthology_symbols>
<orthology_class_id> has description <... | Below is the the instruction that describes the task:
### Input:
This method add the KEGG orthology classes to the graph.
If there's an embedded enzyme commission number,
that is added as an xref.
Triples created:
<orthology_class_id> is a class
<orthology_class_id> has lab... |
def prob_t_profiles(self, profile_pair, multiplicity, t,
return_log=False, ignore_gaps=True):
'''
Calculate the probability of observing a node pair at a distance t
Parameters
----------
profile_pair: numpy arrays
Probability distributions ... | Calculate the probability of observing a node pair at a distance t
Parameters
----------
profile_pair: numpy arrays
Probability distributions of the nucleotides at either
end of the branch. pp[0] = parent, pp[1] = child
multiplicity : numpy array
... | Below is the the instruction that describes the task:
### Input:
Calculate the probability of observing a node pair at a distance t
Parameters
----------
profile_pair: numpy arrays
Probability distributions of the nucleotides at either
end of the branch. pp[0] = p... |
def send(self, *args, **kwargs):
"""
Send email message, render if it is not rendered yet.
Note
----
Any extra arguments are passed to
:class:`EmailMultiAlternatives.send() <django.core.mail.EmailMessage>`.
Keyword Arguments
-----------------
cle... | Send email message, render if it is not rendered yet.
Note
----
Any extra arguments are passed to
:class:`EmailMultiAlternatives.send() <django.core.mail.EmailMessage>`.
Keyword Arguments
-----------------
clean : bool
If ``True``, remove any templat... | Below is the the instruction that describes the task:
### Input:
Send email message, render if it is not rendered yet.
Note
----
Any extra arguments are passed to
:class:`EmailMultiAlternatives.send() <django.core.mail.EmailMessage>`.
Keyword Arguments
-------------... |
def snapengage(parser, token):
"""
SnapEngage set-up template tag.
Renders Javascript code to set-up SnapEngage chat. You must supply
your widget ID in the ``SNAPENGAGE_WIDGET_ID`` setting.
"""
bits = token.split_contents()
if len(bits) > 1:
raise TemplateSyntaxError("'%s' takes no... | SnapEngage set-up template tag.
Renders Javascript code to set-up SnapEngage chat. You must supply
your widget ID in the ``SNAPENGAGE_WIDGET_ID`` setting. | Below is the the instruction that describes the task:
### Input:
SnapEngage set-up template tag.
Renders Javascript code to set-up SnapEngage chat. You must supply
your widget ID in the ``SNAPENGAGE_WIDGET_ID`` setting.
### Response:
def snapengage(parser, token):
"""
SnapEngage set-up template t... |
def interact(self, unique_id, case_id, question_prompt, answer, choices=None, randomize=True):
"""Reads student input for unlocking tests until the student
answers correctly.
PARAMETERS:
unique_id -- str; the ID that is recorded with this unlocking
attem... | Reads student input for unlocking tests until the student
answers correctly.
PARAMETERS:
unique_id -- str; the ID that is recorded with this unlocking
attempt.
case_id -- str; the ID that is recorded with this unlocking
... | Below is the the instruction that describes the task:
### Input:
Reads student input for unlocking tests until the student
answers correctly.
PARAMETERS:
unique_id -- str; the ID that is recorded with this unlocking
attempt.
case_id -- str; t... |
def __get_type_args(for_type=None, for_types=None):
"""Parse the arguments and return a tuple of types to implement for.
Raises:
ValueError or TypeError as appropriate.
"""
if for_type:
if for_types:
raise ValueError("Cannot pass both for_type and... | Parse the arguments and return a tuple of types to implement for.
Raises:
ValueError or TypeError as appropriate. | Below is the the instruction that describes the task:
### Input:
Parse the arguments and return a tuple of types to implement for.
Raises:
ValueError or TypeError as appropriate.
### Response:
def __get_type_args(for_type=None, for_types=None):
"""Parse the arguments and return a tuple... |
def Environ(variable, default):
"""A wrapper for `os.environ.get` that works the same way in both Pythons.
Args:
variable: A name of the variable to get the value of.
default: A default value to return in case no value for the given variable
is set.
Returns:
An environment value of the given v... | A wrapper for `os.environ.get` that works the same way in both Pythons.
Args:
variable: A name of the variable to get the value of.
default: A default value to return in case no value for the given variable
is set.
Returns:
An environment value of the given variable. | Below is the the instruction that describes the task:
### Input:
A wrapper for `os.environ.get` that works the same way in both Pythons.
Args:
variable: A name of the variable to get the value of.
default: A default value to return in case no value for the given variable
is set.
Returns:
An ... |
def get_pipeline(self, id=None, params=None):
"""
`<https://www.elastic.co/guide/en/elasticsearch/plugins/current/ingest.html>`_
:arg id: Comma separated list of pipeline ids. Wildcards supported
:arg master_timeout: Explicit operation timeout for connection to master
node
... | `<https://www.elastic.co/guide/en/elasticsearch/plugins/current/ingest.html>`_
:arg id: Comma separated list of pipeline ids. Wildcards supported
:arg master_timeout: Explicit operation timeout for connection to master
node | Below is the the instruction that describes the task:
### Input:
`<https://www.elastic.co/guide/en/elasticsearch/plugins/current/ingest.html>`_
:arg id: Comma separated list of pipeline ids. Wildcards supported
:arg master_timeout: Explicit operation timeout for connection to master
nod... |
def make_python_xref_nodes(py_typestr, state, hide_namespace=False):
"""Make docutils nodes containing a cross-reference to a Python object.
Parameters
----------
py_typestr : `str`
Name of the Python object. For example
``'mypackage.mymodule.MyClass'``. If you have the object itself, o... | Make docutils nodes containing a cross-reference to a Python object.
Parameters
----------
py_typestr : `str`
Name of the Python object. For example
``'mypackage.mymodule.MyClass'``. If you have the object itself, or
its type, use the `make_python_xref_nodes_for_type` function inste... | Below is the the instruction that describes the task:
### Input:
Make docutils nodes containing a cross-reference to a Python object.
Parameters
----------
py_typestr : `str`
Name of the Python object. For example
``'mypackage.mymodule.MyClass'``. If you have the object itself, or
... |
def _expand_wildcard_placeholder(original_module, originals_map, placeholder):
"""Expand a wildcard placeholder to a sequence of named placeholders.
:param original_module: The data dictionary of the module
that the placeholder is imported from.
:type original_module: dict
:param originals_map:... | Expand a wildcard placeholder to a sequence of named placeholders.
:param original_module: The data dictionary of the module
that the placeholder is imported from.
:type original_module: dict
:param originals_map: A map of the names of children under the module
to their data dictionaries.
... | Below is the the instruction that describes the task:
### Input:
Expand a wildcard placeholder to a sequence of named placeholders.
:param original_module: The data dictionary of the module
that the placeholder is imported from.
:type original_module: dict
:param originals_map: A map of the nam... |
def write_bif(self, filename):
"""
Writes the BIF data into a file
Parameters
----------
filename : Name of the file
Example
-------
>>> from pgmpy.readwrite import BIFReader, BIFWriter
>>> model = BIFReader('dog-problem.bif').get_model()
... | Writes the BIF data into a file
Parameters
----------
filename : Name of the file
Example
-------
>>> from pgmpy.readwrite import BIFReader, BIFWriter
>>> model = BIFReader('dog-problem.bif').get_model()
>>> writer = BIFWriter(model)
>>> writer.w... | Below is the the instruction that describes the task:
### Input:
Writes the BIF data into a file
Parameters
----------
filename : Name of the file
Example
-------
>>> from pgmpy.readwrite import BIFReader, BIFWriter
>>> model = BIFReader('dog-problem.bif').g... |
def coinc(self, s0, s1, slide, step): # pylint:disable=unused-argument
"""Calculate the final coinc ranking statistic"""
# Approximate log likelihood ratio by summing single-ifo negative
# log noise likelihoods
loglr = - s0 - s1
# add squares of threshold stat values via idealize... | Calculate the final coinc ranking statistic | Below is the the instruction that describes the task:
### Input:
Calculate the final coinc ranking statistic
### Response:
def coinc(self, s0, s1, slide, step): # pylint:disable=unused-argument
"""Calculate the final coinc ranking statistic"""
# Approximate log likelihood ratio by summing single-if... |
def orip(ip, rc=None, r=None, fl=None, fs=None, ot=None, coe=None, moc=None):
# pylint: disable=too-many-arguments, redefined-outer-name, invalid-name
"""
This function is a wrapper for
:meth:`~pywbem.WBEMConnection.OpenReferenceInstancePaths`.
Open an enumeration session to retrieve the instance p... | This function is a wrapper for
:meth:`~pywbem.WBEMConnection.OpenReferenceInstancePaths`.
Open an enumeration session to retrieve the instance paths of the
association instances that reference a source instance.
Use the :func:`~wbemcli.pip` function to retrieve the next set of
instance paths or th... | Below is the the instruction that describes the task:
### Input:
This function is a wrapper for
:meth:`~pywbem.WBEMConnection.OpenReferenceInstancePaths`.
Open an enumeration session to retrieve the instance paths of the
association instances that reference a source instance.
Use the :func:`~wbemc... |
def bump(self):
""" Fix indicator in case of unnanounced departments. """
# read client
values = self.client.mget(self.keys.indicator, self.keys.dispenser)
indicator, dispenser = map(int, values)
# determine active users
numbers = range(indicator, dispenser + 1)
... | Fix indicator in case of unnanounced departments. | Below is the the instruction that describes the task:
### Input:
Fix indicator in case of unnanounced departments.
### Response:
def bump(self):
""" Fix indicator in case of unnanounced departments. """
# read client
values = self.client.mget(self.keys.indicator, self.keys.dispenser)
... |
def _complete_el(self, symbol, attribute, fullsymbol):
"""Suggests a list of completions based on the el_* attributes
of the user_context."""
if symbol != fullsymbol:
#We have a sym%sym%... chain and the completion just needs to
#be a member variable or method of the type... | Suggests a list of completions based on the el_* attributes
of the user_context. | Below is the the instruction that describes the task:
### Input:
Suggests a list of completions based on the el_* attributes
of the user_context.
### Response:
def _complete_el(self, symbol, attribute, fullsymbol):
"""Suggests a list of completions based on the el_* attributes
of the user_c... |
def parse(cls, s):
""" Parse a string to produce a :class:`.Date`.
Accepted formats:
'YYYY-MM-DD'
:param s:
:return:
"""
try:
numbers = map(int, s.split("-"))
except (ValueError, AttributeError):
raise ValueError("Date string ... | Parse a string to produce a :class:`.Date`.
Accepted formats:
'YYYY-MM-DD'
:param s:
:return: | Below is the the instruction that describes the task:
### Input:
Parse a string to produce a :class:`.Date`.
Accepted formats:
'YYYY-MM-DD'
:param s:
:return:
### Response:
def parse(cls, s):
""" Parse a string to produce a :class:`.Date`.
Accepted formats:
... |
def p_scalar_namespace_name(p):
'''scalar : namespace_name
| NS_SEPARATOR namespace_name
| NAMESPACE NS_SEPARATOR namespace_name'''
if len(p) == 2:
p[0] = ast.Constant(p[1], lineno=p.lineno(1))
elif len(p) == 3:
p[0] = ast.Constant(p[1] + p[2], lineno=p.lineno(1))... | scalar : namespace_name
| NS_SEPARATOR namespace_name
| NAMESPACE NS_SEPARATOR namespace_name | Below is the the instruction that describes the task:
### Input:
scalar : namespace_name
| NS_SEPARATOR namespace_name
| NAMESPACE NS_SEPARATOR namespace_name
### Response:
def p_scalar_namespace_name(p):
'''scalar : namespace_name
| NS_SEPARATOR namespace_name
... |
def slicewise(self, fn, *inputs):
"""Execute a function in parallel on all slices.
Args:
fn: a function from tf.Tensors to tf.Tensor or a tuple of tf.Tensors.
*inputs: a list of inputs. Each input is either a LaidOutTensor or
is convertible to a tf.Tensor.
Returns:
a LaidOutTenso... | Execute a function in parallel on all slices.
Args:
fn: a function from tf.Tensors to tf.Tensor or a tuple of tf.Tensors.
*inputs: a list of inputs. Each input is either a LaidOutTensor or
is convertible to a tf.Tensor.
Returns:
a LaidOutTensor, or a tuple of LaidOutTensors if fn ret... | Below is the the instruction that describes the task:
### Input:
Execute a function in parallel on all slices.
Args:
fn: a function from tf.Tensors to tf.Tensor or a tuple of tf.Tensors.
*inputs: a list of inputs. Each input is either a LaidOutTensor or
is convertible to a tf.Tensor.
R... |
def _extract_docs_other(self):
"""Extract other specific sections"""
if self.dst.style['in'] == 'numpydoc':
data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for d in self.docs['in']['raw'].splitlines()])
lst = self.dst.numpydoc.get_list_key(data, 'also')
... | Extract other specific sections | Below is the the instruction that describes the task:
### Input:
Extract other specific sections
### Response:
def _extract_docs_other(self):
"""Extract other specific sections"""
if self.dst.style['in'] == 'numpydoc':
data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '',... |
def partial(self,start=0,end=None,run=0):
'''chops the stimulus by only including time points ``start`` through ``end`` (in reps, inclusive; ``None``=until the end)
if using stim_times-style simulus, will change the ``run``'th run. If a column, will just chop the column'''
self.read_file()
... | chops the stimulus by only including time points ``start`` through ``end`` (in reps, inclusive; ``None``=until the end)
if using stim_times-style simulus, will change the ``run``'th run. If a column, will just chop the column | Below is the the instruction that describes the task:
### Input:
chops the stimulus by only including time points ``start`` through ``end`` (in reps, inclusive; ``None``=until the end)
if using stim_times-style simulus, will change the ``run``'th run. If a column, will just chop the column
### Response:
de... |
def filter_unnecessary_segments(query):
"""Filter segments are not needed on CVX"""
segment_model = segment_models.NetworkSegment
network_model = models_v2.Network
query = (query
.join_if_necessary(network_model)
.join_if_necessary(segment_model)
.filter(network_mo... | Filter segments are not needed on CVX | Below is the the instruction that describes the task:
### Input:
Filter segments are not needed on CVX
### Response:
def filter_unnecessary_segments(query):
"""Filter segments are not needed on CVX"""
segment_model = segment_models.NetworkSegment
network_model = models_v2.Network
query = (query
... |
def fig2x(figure, format):
"""Returns svg from matplotlib chart"""
# Save svg to file like object svg_io
io = StringIO()
figure.savefig(io, format=format)
# Rewind the file like object
io.seek(0)
data = io.getvalue()
io.close()
return data | Returns svg from matplotlib chart | Below is the the instruction that describes the task:
### Input:
Returns svg from matplotlib chart
### Response:
def fig2x(figure, format):
"""Returns svg from matplotlib chart"""
# Save svg to file like object svg_io
io = StringIO()
figure.savefig(io, format=format)
# Rewind the file like ob... |
def twoplustwo_player(username):
"""Get profile information about a Two plus Two Forum member given the username."""
from .website.twoplustwo import ForumMember, AmbiguousUserNameError, UserNotFoundError
try:
member = ForumMember(username)
except UserNotFoundError:
raise click.ClickExc... | Get profile information about a Two plus Two Forum member given the username. | Below is the the instruction that describes the task:
### Input:
Get profile information about a Two plus Two Forum member given the username.
### Response:
def twoplustwo_player(username):
"""Get profile information about a Two plus Two Forum member given the username."""
from .website.twoplustwo import ... |
def _crop_pad_default(x, size, padding_mode='reflection', row_pct:uniform = 0.5, col_pct:uniform = 0.5):
"Crop and pad tfm - `row_pct`,`col_pct` sets focal point."
padding_mode = _pad_mode_convert[padding_mode]
size = tis2hw(size)
if x.shape[1:] == torch.Size(size): return x
rows,cols = size
row... | Crop and pad tfm - `row_pct`,`col_pct` sets focal point. | Below is the the instruction that describes the task:
### Input:
Crop and pad tfm - `row_pct`,`col_pct` sets focal point.
### Response:
def _crop_pad_default(x, size, padding_mode='reflection', row_pct:uniform = 0.5, col_pct:uniform = 0.5):
"Crop and pad tfm - `row_pct`,`col_pct` sets focal point."
padding... |
def add(self, word, count=1):
"""Add a word to the vocabulary and return its index.
:param word: word to add to the dictionary.
:param count: how many times to add the word.
:return: index of the added word.
WARNING: this function assumes that if the Vocab currently has N wor... | Add a word to the vocabulary and return its index.
:param word: word to add to the dictionary.
:param count: how many times to add the word.
:return: index of the added word.
WARNING: this function assumes that if the Vocab currently has N words, then
there is a perfect bijec... | Below is the the instruction that describes the task:
### Input:
Add a word to the vocabulary and return its index.
:param word: word to add to the dictionary.
:param count: how many times to add the word.
:return: index of the added word.
WARNING: this function assumes that if t... |
def expectation_sensitivity(T, a):
r"""Sensitivity of expectation value of observable A=(a_i).
Parameters
----------
T : (M, M) ndarray
Transition matrix
a : (M,) ndarray
Observable, a[i] is the value of the observable at state i.
Returns
-------
S : (M, M) ndarray
... | r"""Sensitivity of expectation value of observable A=(a_i).
Parameters
----------
T : (M, M) ndarray
Transition matrix
a : (M,) ndarray
Observable, a[i] is the value of the observable at state i.
Returns
-------
S : (M, M) ndarray
Sensitivity matrix of the expectati... | Below is the the instruction that describes the task:
### Input:
r"""Sensitivity of expectation value of observable A=(a_i).
Parameters
----------
T : (M, M) ndarray
Transition matrix
a : (M,) ndarray
Observable, a[i] is the value of the observable at state i.
Returns
-----... |
def assign(self, **kwargs):
r"""
Assign new columns to a DataFrame.
Returns a new object with all original columns in addition to new ones.
Existing columns that are re-assigned will be overwritten.
Parameters
----------
**kwargs : dict of {str: callable or Seri... | r"""
Assign new columns to a DataFrame.
Returns a new object with all original columns in addition to new ones.
Existing columns that are re-assigned will be overwritten.
Parameters
----------
**kwargs : dict of {str: callable or Series}
The column names are... | Below is the the instruction that describes the task:
### Input:
r"""
Assign new columns to a DataFrame.
Returns a new object with all original columns in addition to new ones.
Existing columns that are re-assigned will be overwritten.
Parameters
----------
**kwargs... |
def filters_in_format(self, value):
"""
Setter for **self.__filters_in_format** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
... | Setter for **self.__filters_in_format** attribute.
:param value: Attribute value.
:type value: unicode | Below is the the instruction that describes the task:
### Input:
Setter for **self.__filters_in_format** attribute.
:param value: Attribute value.
:type value: unicode
### Response:
def filters_in_format(self, value):
"""
Setter for **self.__filters_in_format** attribute.
... |
def create_string_array(self, key, value):
"""Create method of CRUD operation for string array data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write.
"""
dat... | Create method of CRUD operation for string array data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write. | Below is the the instruction that describes the task:
### Input:
Create method of CRUD operation for string array data.
Args:
key (string): The variable to write to the DB.
value (any): The data to write to the DB.
Returns:
(string): Result of DB write.
### Resp... |
def _el_orb(string):
"""Parse the element and orbital argument strings.
The presence of an element without any orbitals means that we want to plot
all of its orbitals.
Args:
string (str): The element and orbitals as a string, in the form
``"C.s.p,O"``.
Returns:
dict: T... | Parse the element and orbital argument strings.
The presence of an element without any orbitals means that we want to plot
all of its orbitals.
Args:
string (str): The element and orbitals as a string, in the form
``"C.s.p,O"``.
Returns:
dict: The elements and orbitals as ... | Below is the the instruction that describes the task:
### Input:
Parse the element and orbital argument strings.
The presence of an element without any orbitals means that we want to plot
all of its orbitals.
Args:
string (str): The element and orbitals as a string, in the form
``"... |
def set_env_from_file(env_file):
'''Restore the current environment from an environment stored in a yaml
yaml file.
:param env_file: Path to environment yaml file.
'''
with open(env_file, 'r') as f:
env_dict = yaml.load(f.read())
if 'environment' in env_dict:
env_dict = env_di... | Restore the current environment from an environment stored in a yaml
yaml file.
:param env_file: Path to environment yaml file. | Below is the the instruction that describes the task:
### Input:
Restore the current environment from an environment stored in a yaml
yaml file.
:param env_file: Path to environment yaml file.
### Response:
def set_env_from_file(env_file):
'''Restore the current environment from an environment stored ... |
def pct_negative(self, threshold=0.0):
"""Pct. of periods in which `self` is less than `threshold.`
Parameters
----------
threshold : {float, TSeries, pd.Series}, default 0.
Returns
-------
float
"""
return np.count_nonzero(self[self < threshold... | Pct. of periods in which `self` is less than `threshold.`
Parameters
----------
threshold : {float, TSeries, pd.Series}, default 0.
Returns
-------
float | Below is the the instruction that describes the task:
### Input:
Pct. of periods in which `self` is less than `threshold.`
Parameters
----------
threshold : {float, TSeries, pd.Series}, default 0.
Returns
-------
float
### Response:
def pct_negative(self, threshold... |
def listen_init(self):
"""Setup the service to listen for clients."""
self.dispatcher = ObjectDispatch(self)
self.factory = MsgPackProtocolFactory(self.dispatcher)
self.server = UnixServer(self.loop, self.factory, self.path)
self.server.start() | Setup the service to listen for clients. | Below is the the instruction that describes the task:
### Input:
Setup the service to listen for clients.
### Response:
def listen_init(self):
"""Setup the service to listen for clients."""
self.dispatcher = ObjectDispatch(self)
self.factory = MsgPackProtocolFactory(self.dispatcher)
... |
def set_lock(i):
"""
Input: {
path - path to be locked
(get_lock) - if 'yes', lock this entry
(lock_retries) - number of retries to aquire lock (default=11)
(lock_retry_delay) - delay in seconds before trying to aquire lock agai... | Input: {
path - path to be locked
(get_lock) - if 'yes', lock this entry
(lock_retries) - number of retries to aquire lock (default=11)
(lock_retry_delay) - delay in seconds before trying to aquire lock again (default=3)
(... | Below is the the instruction that describes the task:
### Input:
Input: {
path - path to be locked
(get_lock) - if 'yes', lock this entry
(lock_retries) - number of retries to aquire lock (default=11)
(lock_retry_delay) - delay in s... |
def sub_dirs(path, invisible=False):
"""
Child directories (non-recursive)
"""
dirs = [x for x in os.listdir(path) if os.path.isdir(os.path.join(path, x))]
if not invisible:
dirs = [x for x in dirs if not x.startswith('.')]
return dirs | Child directories (non-recursive) | Below is the the instruction that describes the task:
### Input:
Child directories (non-recursive)
### Response:
def sub_dirs(path, invisible=False):
"""
Child directories (non-recursive)
"""
dirs = [x for x in os.listdir(path) if os.path.isdir(os.path.join(path, x))]
if not invisible:
... |
def build_sh_cmd(cmd, cwd=None):
"""Build a `sh.Command` from a string.
:param cmd: String with the command to convert.
:param cwd: Optional path to use as working directory.
:return: `sh.Command`
"""
args = cmd.split()
return getattr(sh, args[0]).bake(_cwd=cwd, *args[1:]) | Build a `sh.Command` from a string.
:param cmd: String with the command to convert.
:param cwd: Optional path to use as working directory.
:return: `sh.Command` | Below is the the instruction that describes the task:
### Input:
Build a `sh.Command` from a string.
:param cmd: String with the command to convert.
:param cwd: Optional path to use as working directory.
:return: `sh.Command`
### Response:
def build_sh_cmd(cmd, cwd=None):
"""Build a `sh.Command` f... |
def read_csv(self, file_path, use_whole_file=False, names=None, skiprows=0,
*args, **kwargs):
"""Read a CSV file in and parse it into Pandas DataFrames. By default,
the first row from the first partition of that data is parsed and used
as the column names for the data from. If n... | Read a CSV file in and parse it into Pandas DataFrames. By default,
the first row from the first partition of that data is parsed and used
as the column names for the data from. If no 'names' param is
provided we parse the first row of the first partition of data and
use it for column na... | Below is the the instruction that describes the task:
### Input:
Read a CSV file in and parse it into Pandas DataFrames. By default,
the first row from the first partition of that data is parsed and used
as the column names for the data from. If no 'names' param is
provided we parse the firs... |
def _prune_all_if_small(self, small_size, a_or_u):
"Return True and delete children if small enough."
if self._nodes is None:
return True
total_size = (self.app_size() if a_or_u else self.use_size())
if total_size < small_size:
if a_or_u:
self._se... | Return True and delete children if small enough. | Below is the the instruction that describes the task:
### Input:
Return True and delete children if small enough.
### Response:
def _prune_all_if_small(self, small_size, a_or_u):
"Return True and delete children if small enough."
if self._nodes is None:
return True
total_size =... |
def plotInferenceStats(self,
fields,
plotDir="plots",
experimentID=0,
onePlot=True):
"""
Plots and saves the desired inference statistics.
Parameters:
----------------------------
@param fields (li... | Plots and saves the desired inference statistics.
Parameters:
----------------------------
@param fields (list(str))
List of fields to include in the plots
@param experimentID (int)
ID of the experiment (usually 0 if only one was conducted)
@param onePlot (bool)
... | Below is the the instruction that describes the task:
### Input:
Plots and saves the desired inference statistics.
Parameters:
----------------------------
@param fields (list(str))
List of fields to include in the plots
@param experimentID (int)
ID of the experiment ... |
def add_deferred_effect(self, effect, pos):
""" Pushes an (pos, effect) tuple onto a stack to later be executed if the
state reaches the 'pos'."""
if not isinstance(pos, (unicode, str)):
raise Exception("Invalid POS tag. Must be string not %d" % (type(pos)))
if self['speaker_... | Pushes an (pos, effect) tuple onto a stack to later be executed if the
state reaches the 'pos'. | Below is the the instruction that describes the task:
### Input:
Pushes an (pos, effect) tuple onto a stack to later be executed if the
state reaches the 'pos'.
### Response:
def add_deferred_effect(self, effect, pos):
""" Pushes an (pos, effect) tuple onto a stack to later be executed if the
... |
async def download_media_by_id(self, media_id):
"""Given a message ID, finds the media this message contained and
downloads it.
"""
try:
msg = self.found_media[int(media_id)]
except (ValueError, KeyError):
# ValueError when parsing, KeyError when access... | Given a message ID, finds the media this message contained and
downloads it. | Below is the the instruction that describes the task:
### Input:
Given a message ID, finds the media this message contained and
downloads it.
### Response:
async def download_media_by_id(self, media_id):
"""Given a message ID, finds the media this message contained and
downloads it.
... |
def check_num_tasks(chain, task_count):
"""Make sure there are a specific number of specific task types.
Currently we only check decision tasks.
Args:
chain (ChainOfTrust): the chain we're operating on
task_count (dict): mapping task type to the number of links.
Raises:
CoTErr... | Make sure there are a specific number of specific task types.
Currently we only check decision tasks.
Args:
chain (ChainOfTrust): the chain we're operating on
task_count (dict): mapping task type to the number of links.
Raises:
CoTError: on failure. | Below is the the instruction that describes the task:
### Input:
Make sure there are a specific number of specific task types.
Currently we only check decision tasks.
Args:
chain (ChainOfTrust): the chain we're operating on
task_count (dict): mapping task type to the number of links.
... |
def get_comments(self):
"""Get a list of the top-level comments."""
url = self._imgur._base_url + "/3/gallery/{0}/comments".format(self.id)
resp = self._imgur._send_request(url)
return [Comment(com, self._imgur) for com in resp] | Get a list of the top-level comments. | Below is the the instruction that describes the task:
### Input:
Get a list of the top-level comments.
### Response:
def get_comments(self):
"""Get a list of the top-level comments."""
url = self._imgur._base_url + "/3/gallery/{0}/comments".format(self.id)
resp = self._imgur._send_request(u... |
def process_pubmed_abstract(pubmed_id, offline=False,
output_fname=default_output_fname, **kwargs):
"""Return a ReachProcessor by processing an abstract with a given Pubmed id.
Uses the Pubmed client to get the abstract. If that fails, None is
returned.
Parameters
-----... | Return a ReachProcessor by processing an abstract with a given Pubmed id.
Uses the Pubmed client to get the abstract. If that fails, None is
returned.
Parameters
----------
pubmed_id : str
The ID of a Pubmed article. The string may start with PMID but
passing just the ID also works... | Below is the the instruction that describes the task:
### Input:
Return a ReachProcessor by processing an abstract with a given Pubmed id.
Uses the Pubmed client to get the abstract. If that fails, None is
returned.
Parameters
----------
pubmed_id : str
The ID of a Pubmed article. The ... |
def get_kde_contour(self, xax="area_um", yax="deform", xacc=None,
yacc=None, kde_type="histogram", kde_kwargs={},
xscale="linear", yscale="linear"):
"""Evaluate the kernel density estimate for contour plots
Parameters
----------
xax: str
... | Evaluate the kernel density estimate for contour plots
Parameters
----------
xax: str
Identifier for X axis (e.g. "area_um", "aspect", "deform")
yax: str
Identifier for Y axis
xacc: float
Contour accuracy in x direction
yacc: float
... | Below is the the instruction that describes the task:
### Input:
Evaluate the kernel density estimate for contour plots
Parameters
----------
xax: str
Identifier for X axis (e.g. "area_um", "aspect", "deform")
yax: str
Identifier for Y axis
xacc: floa... |
async def kick(self, count):
"""
Kick `count` tasks from queue
:param count: Tasks count to kick
:return: Number of tasks actually kicked
"""
args = (count,)
res = await self.conn.call(self.__funcs['kick'], args)
if self.conn.version < (1, 7):... | Kick `count` tasks from queue
:param count: Tasks count to kick
:return: Number of tasks actually kicked | Below is the the instruction that describes the task:
### Input:
Kick `count` tasks from queue
:param count: Tasks count to kick
:return: Number of tasks actually kicked
### Response:
async def kick(self, count):
"""
Kick `count` tasks from queue
:param cou... |
def run(uri,
user_entry_point,
args,
env_vars=None,
wait=True,
capture_error=False,
runner=_runner.ProcessRunnerType,
extra_opts=None):
# type: (str, str, List[str], Dict[str, str], bool, bool, _runner.RunnerType, Dict[str, str]) -> None
"""Download, prepa... | Download, prepare and executes a compressed tar file from S3 or provided directory as an user
entrypoint. Runs the user entry point, passing env_vars as environment variables and args as command
arguments.
If the entry point is:
- A Python package: executes the packages as >>> env_vars python -m mo... | Below is the the instruction that describes the task:
### Input:
Download, prepare and executes a compressed tar file from S3 or provided directory as an user
entrypoint. Runs the user entry point, passing env_vars as environment variables and args as command
arguments.
If the entry point is:
-... |
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_3):
"""
Read the data encoding the ValidationInformation structure and decode
it into its constituent parts.
Args:
input_buffer (stream): A data stream containing encoded object
data, supporti... | Read the data encoding the ValidationInformation structure and decode
it into its constituent parts.
Args:
input_buffer (stream): A data stream containing encoded object
data, supporting a read method; usually a BytearrayStream
object.
kmip_versio... | Below is the the instruction that describes the task:
### Input:
Read the data encoding the ValidationInformation structure and decode
it into its constituent parts.
Args:
input_buffer (stream): A data stream containing encoded object
data, supporting a read method; usua... |
def newPosition(self, globalBestPosition, rng):
"""See comments in base class."""
# First, update the velocity. The new velocity is given as:
# v = (inertia * v) + (cogRate * r1 * (localBest-pos))
# + (socRate * r2 * (globalBest-pos))
#
# where r1 and r2 are random numbers be... | See comments in base class. | Below is the the instruction that describes the task:
### Input:
See comments in base class.
### Response:
def newPosition(self, globalBestPosition, rng):
"""See comments in base class."""
# First, update the velocity. The new velocity is given as:
# v = (inertia * v) + (cogRate * r1 * (localBest-pos)... |
def get_images(self, obj):
"""Object of images serialized by tag name."""
return {str(i.tag): i.image.url for i in obj.images.all()} | Object of images serialized by tag name. | Below is the the instruction that describes the task:
### Input:
Object of images serialized by tag name.
### Response:
def get_images(self, obj):
"""Object of images serialized by tag name."""
return {str(i.tag): i.image.url for i in obj.images.all()} |
def delete_channel_cb(self, viewer, channel):
"""Called when a channel is deleted from the main interface.
Parameter is channel (a bunch)."""
chname_del = channel.name
# TODO: delete thumbs for this channel!
self.logger.debug("deleting thumbs for channel '%s'" % (chname_del))
... | Called when a channel is deleted from the main interface.
Parameter is channel (a bunch). | Below is the the instruction that describes the task:
### Input:
Called when a channel is deleted from the main interface.
Parameter is channel (a bunch).
### Response:
def delete_channel_cb(self, viewer, channel):
"""Called when a channel is deleted from the main interface.
Parameter is ch... |
def set_pubsubhubbub(self):
"""Parses pubsubhubbub and email then sets value"""
self.pubsubhubbub = None
atom_links = self.soup.findAll('atom:link')
for atom_link in atom_links:
rel = atom_link.get('rel')
if rel == "hub":
self.pubsubhubbub = atom_l... | Parses pubsubhubbub and email then sets value | Below is the the instruction that describes the task:
### Input:
Parses pubsubhubbub and email then sets value
### Response:
def set_pubsubhubbub(self):
"""Parses pubsubhubbub and email then sets value"""
self.pubsubhubbub = None
atom_links = self.soup.findAll('atom:link')
for atom_... |
def delete_service(self, service_id):
"""Delete a service."""
content = self._fetch("/service/%s" % service_id, method="DELETE")
return self._status(content) | Delete a service. | Below is the the instruction that describes the task:
### Input:
Delete a service.
### Response:
def delete_service(self, service_id):
"""Delete a service."""
content = self._fetch("/service/%s" % service_id, method="DELETE")
return self._status(content) |
def _ast_optree_node_to_code(self, node, **kwargs):
"""Convert an abstract syntax operator tree to python source code."""
opnode = node.opnode
if opnode is None:
return self._ast_to_code(node.operands[0])
else:
operator = opnode.operator
if operator is OP_ALTERNATE:
return self... | Convert an abstract syntax operator tree to python source code. | Below is the the instruction that describes the task:
### Input:
Convert an abstract syntax operator tree to python source code.
### Response:
def _ast_optree_node_to_code(self, node, **kwargs):
"""Convert an abstract syntax operator tree to python source code."""
opnode = node.opnode
if opnode is None... |
def _execute_lua(self, keys, args, client):
"""
Sets KEYS and ARGV alongwith redis.call() function in lua globals
and executes the lua redis script
"""
lua, lua_globals = Script._import_lua(self.load_dependencies)
lua_globals.KEYS = self._python_to_lua(keys)
lua_g... | Sets KEYS and ARGV alongwith redis.call() function in lua globals
and executes the lua redis script | Below is the the instruction that describes the task:
### Input:
Sets KEYS and ARGV alongwith redis.call() function in lua globals
and executes the lua redis script
### Response:
def _execute_lua(self, keys, args, client):
"""
Sets KEYS and ARGV alongwith redis.call() function in lua global... |
def add_event(self, key, event):
"""Add an event and its corresponding key to the store."""
if self.key_exists(key):
# This check might actually also be done further up in the chain
# (read: SQLiteEventStore). Could potentially be removed if it
# requires a lot of pro... | Add an event and its corresponding key to the store. | Below is the the instruction that describes the task:
### Input:
Add an event and its corresponding key to the store.
### Response:
def add_event(self, key, event):
"""Add an event and its corresponding key to the store."""
if self.key_exists(key):
# This check might actually also be do... |
def get_syslog_facility():
"""Get syslog facility from ENV var"""
facil = os.getenv('WALE_SYSLOG_FACILITY', 'user')
valid_facility = True
try:
facility = handlers.SysLogHandler.facility_names[facil.lower()]
except KeyError:
valid_facility = False
facility = handlers.SysLogHa... | Get syslog facility from ENV var | Below is the the instruction that describes the task:
### Input:
Get syslog facility from ENV var
### Response:
def get_syslog_facility():
"""Get syslog facility from ENV var"""
facil = os.getenv('WALE_SYSLOG_FACILITY', 'user')
valid_facility = True
try:
facility = handlers.SysLogHandler.f... |
def _write_packed_data(self, data_out, table):
"""This is kind of legacy function - this functionality may be useful for some people, so even though
now the default of writing CSV is writing unpacked data (divided by independent variable) this method is
still available and accessible if ```pack`... | This is kind of legacy function - this functionality may be useful for some people, so even though
now the default of writing CSV is writing unpacked data (divided by independent variable) this method is
still available and accessible if ```pack``` flag is specified in Writer's options
:param o... | Below is the the instruction that describes the task:
### Input:
This is kind of legacy function - this functionality may be useful for some people, so even though
now the default of writing CSV is writing unpacked data (divided by independent variable) this method is
still available and accessible ... |
def break_edge(self, from_index, to_index, to_jimage=None, allow_reverse=False):
"""
Remove an edge from the StructureGraph. If no image is given, this method will fail.
:param from_index: int
:param to_index: int
:param to_jimage: tuple
:param allow_reverse: If allow_re... | Remove an edge from the StructureGraph. If no image is given, this method will fail.
:param from_index: int
:param to_index: int
:param to_jimage: tuple
:param allow_reverse: If allow_reverse is True, then break_edge will
attempt to break both (from_index, to_index) and, failing... | Below is the the instruction that describes the task:
### Input:
Remove an edge from the StructureGraph. If no image is given, this method will fail.
:param from_index: int
:param to_index: int
:param to_jimage: tuple
:param allow_reverse: If allow_reverse is True, then break_edge w... |
def split_matrix(M, contigs):
"""Split multiple chromosome matrix
Split a labeled matrix with multiple chromosomes
into unlabeled single-chromosome matrices. Inter chromosomal
contacts are discarded.
Parameters
----------
M : array_like
The multiple chromosome matrix to be split
... | Split multiple chromosome matrix
Split a labeled matrix with multiple chromosomes
into unlabeled single-chromosome matrices. Inter chromosomal
contacts are discarded.
Parameters
----------
M : array_like
The multiple chromosome matrix to be split
contigs : list or array_like
... | Below is the the instruction that describes the task:
### Input:
Split multiple chromosome matrix
Split a labeled matrix with multiple chromosomes
into unlabeled single-chromosome matrices. Inter chromosomal
contacts are discarded.
Parameters
----------
M : array_like
The multiple... |
def _is_dataset(uri, config_path):
"""Helper function for determining if a URI is a dataset."""
uri = dtoolcore.utils.sanitise_uri(uri)
storage_broker = _get_storage_broker(uri, config_path)
return storage_broker.has_admin_metadata() | Helper function for determining if a URI is a dataset. | Below is the the instruction that describes the task:
### Input:
Helper function for determining if a URI is a dataset.
### Response:
def _is_dataset(uri, config_path):
"""Helper function for determining if a URI is a dataset."""
uri = dtoolcore.utils.sanitise_uri(uri)
storage_broker = _get_storage_bro... |
def validate_intervals(intervals):
"""Checks that an (n, 2) interval ndarray is well-formed, and raises errors
if not.
Parameters
----------
intervals : np.ndarray, shape=(n, 2)
Array of interval start/end locations.
"""
# Validate interval shape
if intervals.ndim != 2 or inte... | Checks that an (n, 2) interval ndarray is well-formed, and raises errors
if not.
Parameters
----------
intervals : np.ndarray, shape=(n, 2)
Array of interval start/end locations. | Below is the the instruction that describes the task:
### Input:
Checks that an (n, 2) interval ndarray is well-formed, and raises errors
if not.
Parameters
----------
intervals : np.ndarray, shape=(n, 2)
Array of interval start/end locations.
### Response:
def validate_intervals(intervals... |
def pre_encrypt_assertion(response):
"""
Move the assertion to within a encrypted_assertion
:param response: The response with one assertion
:return: The response but now with the assertion within an
encrypted_assertion.
"""
assertion = response.assertion
response.assertion = None
... | Move the assertion to within a encrypted_assertion
:param response: The response with one assertion
:return: The response but now with the assertion within an
encrypted_assertion. | Below is the the instruction that describes the task:
### Input:
Move the assertion to within a encrypted_assertion
:param response: The response with one assertion
:return: The response but now with the assertion within an
encrypted_assertion.
### Response:
def pre_encrypt_assertion(response):
... |
def get_comment_book_session(self):
"""Gets the session for retrieving comment to book mappings.
return: (osid.commenting.CommentBookSession) - a
``CommentBookSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_comment_book()... | Gets the session for retrieving comment to book mappings.
return: (osid.commenting.CommentBookSession) - a
``CommentBookSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_comment_book()`` is ``false``
*compliance: optional -... | Below is the the instruction that describes the task:
### Input:
Gets the session for retrieving comment to book mappings.
return: (osid.commenting.CommentBookSession) - a
``CommentBookSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``s... |
def _timedelta_from_elements(elements):
"""
Return a timedelta from a dict of date elements.
Accepts a dict containing any of the following:
- years
- months
- days
- hours
- minutes
- seconds
If years and/or months are provided, it will use a naive calcuation
o... | Return a timedelta from a dict of date elements.
Accepts a dict containing any of the following:
- years
- months
- days
- hours
- minutes
- seconds
If years and/or months are provided, it will use a naive calcuation
of 365 days in a year and 30 days in a month. | Below is the the instruction that describes the task:
### Input:
Return a timedelta from a dict of date elements.
Accepts a dict containing any of the following:
- years
- months
- days
- hours
- minutes
- seconds
If years and/or months are provided, it will use a naive... |
def get_events(self, user_id, start_date=None):
"""Gets the event log for a specific user, default start_date is 30 days ago
:param int id: User id to view
:param string start_date: "%Y-%m-%dT%H:%M:%s.0000-06:00" is the full formatted string.
The Timezone part ... | Gets the event log for a specific user, default start_date is 30 days ago
:param int id: User id to view
:param string start_date: "%Y-%m-%dT%H:%M:%s.0000-06:00" is the full formatted string.
The Timezone part has to be HH:MM, notice the : there.
:returns: http... | Below is the the instruction that describes the task:
### Input:
Gets the event log for a specific user, default start_date is 30 days ago
:param int id: User id to view
:param string start_date: "%Y-%m-%dT%H:%M:%s.0000-06:00" is the full formatted string.
The Time... |
def create_shell_stream(self, kernel_id):
"""Create a new shell stream."""
self._check_kernel_id(kernel_id)
return super(MappingKernelManager, self).create_shell_stream(kernel_id) | Create a new shell stream. | Below is the the instruction that describes the task:
### Input:
Create a new shell stream.
### Response:
def create_shell_stream(self, kernel_id):
"""Create a new shell stream."""
self._check_kernel_id(kernel_id)
return super(MappingKernelManager, self).create_shell_stream(kernel_id) |
def read_bits(self, num):
"""Read ``num`` number of bits from the stream
:num: number of bits to read
:returns: a list of ``num`` bits, or an empty list if EOF has been reached
"""
if num > len(self._bits):
needed = num - len(self._bits)
num_bytes = int(m... | Read ``num`` number of bits from the stream
:num: number of bits to read
:returns: a list of ``num`` bits, or an empty list if EOF has been reached | Below is the the instruction that describes the task:
### Input:
Read ``num`` number of bits from the stream
:num: number of bits to read
:returns: a list of ``num`` bits, or an empty list if EOF has been reached
### Response:
def read_bits(self, num):
"""Read ``num`` number of bits from t... |
def generateOneTimePad(self, userStore):
"""
Generate a pad which can be used to authenticate via AMP. This pad
will expire in L{ONE_TIME_PAD_DURATION} seconds.
"""
pad = secureRandom(16).encode('hex')
self._oneTimePads[pad] = userStore.idInParent
def expirePad()... | Generate a pad which can be used to authenticate via AMP. This pad
will expire in L{ONE_TIME_PAD_DURATION} seconds. | Below is the the instruction that describes the task:
### Input:
Generate a pad which can be used to authenticate via AMP. This pad
will expire in L{ONE_TIME_PAD_DURATION} seconds.
### Response:
def generateOneTimePad(self, userStore):
"""
Generate a pad which can be used to authenticate v... |
def get_compositions_by_asset(self, asset_id):
"""Gets a list of compositions including the given asset.
arg: asset_id (osid.id.Id): ``Id`` of the ``Asset``
return: (osid.repository.CompositionList) - the returned
``Composition list``
raise: NotFound - ``asset_id`` i... | Gets a list of compositions including the given asset.
arg: asset_id (osid.id.Id): ``Id`` of the ``Asset``
return: (osid.repository.CompositionList) - the returned
``Composition list``
raise: NotFound - ``asset_id`` is not found
raise: NullArgument - ``asset_id`` is... | Below is the the instruction that describes the task:
### Input:
Gets a list of compositions including the given asset.
arg: asset_id (osid.id.Id): ``Id`` of the ``Asset``
return: (osid.repository.CompositionList) - the returned
``Composition list``
raise: NotFound - ``a... |
def get_time(self, **params):
"""https://developers.coinbase.com/api/v2#time"""
response = self._get('v2', 'time', params=params)
return self._make_api_object(response, APIObject) | https://developers.coinbase.com/api/v2#time | Below is the the instruction that describes the task:
### Input:
https://developers.coinbase.com/api/v2#time
### Response:
def get_time(self, **params):
"""https://developers.coinbase.com/api/v2#time"""
response = self._get('v2', 'time', params=params)
return self._make_api_object(response,... |
def _set_active_policy(self, v, load=False):
"""
Setter method for active_policy, mapped from YANG variable /rbridge_id/secpolicy/active_policy (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_active_policy is considered as a private
method. Backends looki... | Setter method for active_policy, mapped from YANG variable /rbridge_id/secpolicy/active_policy (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_active_policy is considered as a private
method. Backends looking to populate this variable should
do so via calling... | Below is the the instruction that describes the task:
### Input:
Setter method for active_policy, mapped from YANG variable /rbridge_id/secpolicy/active_policy (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_active_policy is considered as a private
method. Ba... |
def quaternion_rotate(X, Y):
"""
Calculate the rotation
Parameters
----------
X : array
(N,D) matrix, where N is points and D is dimension.
Y: array
(N,D) matrix, where N is points and D is dimension.
Returns
-------
rot : matrix
Rotation matrix (D,D)
""... | Calculate the rotation
Parameters
----------
X : array
(N,D) matrix, where N is points and D is dimension.
Y: array
(N,D) matrix, where N is points and D is dimension.
Returns
-------
rot : matrix
Rotation matrix (D,D) | Below is the the instruction that describes the task:
### Input:
Calculate the rotation
Parameters
----------
X : array
(N,D) matrix, where N is points and D is dimension.
Y: array
(N,D) matrix, where N is points and D is dimension.
Returns
-------
rot : matrix
... |
def _build_headers(self, method, auth_session):
"""Create headers for the request.
Parameters
method (str)
HTTP method (e.g. 'POST').
auth_session (Session)
The Session object containing OAuth 2.0 credentials.
Returns
headers (d... | Create headers for the request.
Parameters
method (str)
HTTP method (e.g. 'POST').
auth_session (Session)
The Session object containing OAuth 2.0 credentials.
Returns
headers (dict)
Dictionary of access headers to attach... | Below is the the instruction that describes the task:
### Input:
Create headers for the request.
Parameters
method (str)
HTTP method (e.g. 'POST').
auth_session (Session)
The Session object containing OAuth 2.0 credentials.
Returns
... |
def plot_word(self,position):
'''Blits a rendered word on to the main display surface'''
posrectangle = pygame.Rect(position,self.word_size)
self.used_pos.append(posrectangle)
self.cloud.blit(self.rendered_word,position) | Blits a rendered word on to the main display surface | Below is the the instruction that describes the task:
### Input:
Blits a rendered word on to the main display surface
### Response:
def plot_word(self,position):
'''Blits a rendered word on to the main display surface'''
posrectangle = pygame.Rect(position,self.word_size)
self.used_pos.appe... |
def rect(self):
"""rect(self) -> PyObject *"""
CheckParent(self)
val = _fitz.Link_rect(self)
val = Rect(val)
return val | rect(self) -> PyObject * | Below is the the instruction that describes the task:
### Input:
rect(self) -> PyObject *
### Response:
def rect(self):
"""rect(self) -> PyObject *"""
CheckParent(self)
val = _fitz.Link_rect(self)
val = Rect(val)
return val |
def segment_kmeans(self, rgb_weight, num_clusters, hue_weight=0.0):
"""
Segment a color image using KMeans based on spatial and color distances.
Black pixels will automatically be assigned to their own 'background' cluster.
Parameters
----------
rgb_weight : float
... | Segment a color image using KMeans based on spatial and color distances.
Black pixels will automatically be assigned to their own 'background' cluster.
Parameters
----------
rgb_weight : float
weighting of RGB distance relative to spatial and hue distance
num_cluster... | Below is the the instruction that describes the task:
### Input:
Segment a color image using KMeans based on spatial and color distances.
Black pixels will automatically be assigned to their own 'background' cluster.
Parameters
----------
rgb_weight : float
weighting of ... |
def import_family(self, rfa_file):
"""Append a import family entry to the journal.
This instructs Revit to import a family into the opened model.
Args:
rfa_file (str): full path of the family file
"""
self._add_entry(templates.IMPORT_FAMILY
... | Append a import family entry to the journal.
This instructs Revit to import a family into the opened model.
Args:
rfa_file (str): full path of the family file | Below is the the instruction that describes the task:
### Input:
Append a import family entry to the journal.
This instructs Revit to import a family into the opened model.
Args:
rfa_file (str): full path of the family file
### Response:
def import_family(self, rfa_file):
"""A... |
def echo_with_markers(text, marker='=', marker_color='blue', text_color=None):
"""Print a text to the screen with markers surrounding it.
The output looks like:
======== text ========
with marker='=' right now.
In the event that the terminal window is too small, the text is printed
without mar... | Print a text to the screen with markers surrounding it.
The output looks like:
======== text ========
with marker='=' right now.
In the event that the terminal window is too small, the text is printed
without markers.
:param str text: the text to echo
:param str marker: the marker to surr... | Below is the the instruction that describes the task:
### Input:
Print a text to the screen with markers surrounding it.
The output looks like:
======== text ========
with marker='=' right now.
In the event that the terminal window is too small, the text is printed
without markers.
:param... |
def main_bigg(args=None, urlopen=urlopen):
"""Entry point for BiGG import program.
If the ``args`` are provided, these should be a list of strings that will
be used instead of ``sys.argv[1:]``. This is mostly useful for testing.
"""
parser = argparse.ArgumentParser(
description='Import from... | Entry point for BiGG import program.
If the ``args`` are provided, these should be a list of strings that will
be used instead of ``sys.argv[1:]``. This is mostly useful for testing. | Below is the the instruction that describes the task:
### Input:
Entry point for BiGG import program.
If the ``args`` are provided, these should be a list of strings that will
be used instead of ``sys.argv[1:]``. This is mostly useful for testing.
### Response:
def main_bigg(args=None, urlopen=urlopen):
... |
def get_dc_owner(raises, mask_if_self):
""" Convenience function to return owner of /dev/console.
If raises is True, this raises an exception on any error.
If not, it returns any error string as the owner name.
If owner is self, and if mask_if_self, returns "<self>"."""
try:
from pwd import ... | Convenience function to return owner of /dev/console.
If raises is True, this raises an exception on any error.
If not, it returns any error string as the owner name.
If owner is self, and if mask_if_self, returns "<self>". | Below is the the instruction that describes the task:
### Input:
Convenience function to return owner of /dev/console.
If raises is True, this raises an exception on any error.
If not, it returns any error string as the owner name.
If owner is self, and if mask_if_self, returns "<self>".
### Response:
... |
def spawn_batch_jobs(job, shared_ids, input_args):
"""
Spawns an alignment job for every sample in the input configuration file
"""
samples = []
config = input_args['config']
with open(config, 'r') as f_in:
for line in f_in:
line = line.strip().split(',')
uuid = l... | Spawns an alignment job for every sample in the input configuration file | Below is the the instruction that describes the task:
### Input:
Spawns an alignment job for every sample in the input configuration file
### Response:
def spawn_batch_jobs(job, shared_ids, input_args):
"""
Spawns an alignment job for every sample in the input configuration file
"""
samples = []
... |
def _to_service(self, thing):
"""Convert to Analysis Service
:param thing: UID/Catalog Brain/Object/Something
:returns: Analysis Service object or None
"""
# Convert UIDs to objects
if api.is_uid(thing):
thing = api.get_object_by_uid(thing, None)
# ... | Convert to Analysis Service
:param thing: UID/Catalog Brain/Object/Something
:returns: Analysis Service object or None | Below is the the instruction that describes the task:
### Input:
Convert to Analysis Service
:param thing: UID/Catalog Brain/Object/Something
:returns: Analysis Service object or None
### Response:
def _to_service(self, thing):
"""Convert to Analysis Service
:param thing: UID/Cata... |
def add_parameterized_validator(param_validator, base_tag, tag_prefix=None):
"""
Add a parameterized validator for the given tag prefix.
If tag_prefix is None, it is automatically constructed as
u'!~%s(' % param_validator.__name__
A parametrized validator is a function that accepts a document node
... | Add a parameterized validator for the given tag prefix.
If tag_prefix is None, it is automatically constructed as
u'!~%s(' % param_validator.__name__
A parametrized validator is a function that accepts a document node
(in the form of a Python object), a schema node (also a Python
object), and other ... | Below is the the instruction that describes the task:
### Input:
Add a parameterized validator for the given tag prefix.
If tag_prefix is None, it is automatically constructed as
u'!~%s(' % param_validator.__name__
A parametrized validator is a function that accepts a document node
(in the form of a... |
def relative_date_to_date(p_date, p_offset=None):
"""
Transforms a relative date into a date object.
The following formats are understood:
* [0-9][dwmy]
* 'yesterday', 'today' or 'tomorrow'
* days of the week (in full or abbreviated)
"""
result = None
p_date = p_date.lower()
p_... | Transforms a relative date into a date object.
The following formats are understood:
* [0-9][dwmy]
* 'yesterday', 'today' or 'tomorrow'
* days of the week (in full or abbreviated) | Below is the the instruction that describes the task:
### Input:
Transforms a relative date into a date object.
The following formats are understood:
* [0-9][dwmy]
* 'yesterday', 'today' or 'tomorrow'
* days of the week (in full or abbreviated)
### Response:
def relative_date_to_date(p_date, p_of... |
def run_from_argv(self, argv):
"""
Set up any environment changes requested (e.g., Python path
and Django settings), then run this command.
"""
parser = self.create_parser(argv[0], argv[1])
self.arguments = parser.parse_args(argv[2:])
handle_default_options(self.... | Set up any environment changes requested (e.g., Python path
and Django settings), then run this command. | Below is the the instruction that describes the task:
### Input:
Set up any environment changes requested (e.g., Python path
and Django settings), then run this command.
### Response:
def run_from_argv(self, argv):
"""
Set up any environment changes requested (e.g., Python path
and ... |
def old_tracer_correlation( self ):
"""
Deprecated tracer correlation factor for this simulation.
Args:
None
Returns:
(Float): The tracer correlation factor, f.
Notes:
This function assumes that the jump distance between sites has
... | Deprecated tracer correlation factor for this simulation.
Args:
None
Returns:
(Float): The tracer correlation factor, f.
Notes:
This function assumes that the jump distance between sites has
been normalised to a=1. If the jump distance is... | Below is the the instruction that describes the task:
### Input:
Deprecated tracer correlation factor for this simulation.
Args:
None
Returns:
(Float): The tracer correlation factor, f.
Notes:
This function assumes that the jump distance between ... |
def strftimegen(start_dt, end_dt):
"""
Return a generator function for datetime format strings.
The generator produce a day-by-day sequence starting from the first datetime
to the second datetime argument.
"""
if start_dt > end_dt:
raise ValueError("the start datetime is after the end da... | Return a generator function for datetime format strings.
The generator produce a day-by-day sequence starting from the first datetime
to the second datetime argument. | Below is the the instruction that describes the task:
### Input:
Return a generator function for datetime format strings.
The generator produce a day-by-day sequence starting from the first datetime
to the second datetime argument.
### Response:
def strftimegen(start_dt, end_dt):
"""
Return a gener... |
def get_assessments_by_banks(self, bank_ids):
"""Gets the list of ``Assessments`` corresponding to a list of ``Banks``.
arg: bank_ids (osid.id.IdList): list of bank ``Ids``
return: (osid.assessment.AssessmentList) - list of assessments
raise: NullArgument - ``bank_ids`` is ``null``
... | Gets the list of ``Assessments`` corresponding to a list of ``Banks``.
arg: bank_ids (osid.id.IdList): list of bank ``Ids``
return: (osid.assessment.AssessmentList) - list of assessments
raise: NullArgument - ``bank_ids`` is ``null``
raise: OperationFailed - unable to complete requ... | Below is the the instruction that describes the task:
### Input:
Gets the list of ``Assessments`` corresponding to a list of ``Banks``.
arg: bank_ids (osid.id.IdList): list of bank ``Ids``
return: (osid.assessment.AssessmentList) - list of assessments
raise: NullArgument - ``bank_ids`` ... |
def go_standby(self, comment=None):
"""
Executes a Go-Standby operation on the specified node.
To get the status of the current node/s, run :func:`status`
:param str comment: optional comment to audit
:raises NodeCommandFailed: engine cannot go standby
:return: None
... | Executes a Go-Standby operation on the specified node.
To get the status of the current node/s, run :func:`status`
:param str comment: optional comment to audit
:raises NodeCommandFailed: engine cannot go standby
:return: None | Below is the the instruction that describes the task:
### Input:
Executes a Go-Standby operation on the specified node.
To get the status of the current node/s, run :func:`status`
:param str comment: optional comment to audit
:raises NodeCommandFailed: engine cannot go standby
:retu... |
def get_session_info(self, session=0):
"""get info about a session
Parameters
----------
session : int
Session number to retrieve. The current session is 0, and negative
numbers count back from current session, so -1 is previous session.
Returns
... | get info about a session
Parameters
----------
session : int
Session number to retrieve. The current session is 0, and negative
numbers count back from current session, so -1 is previous session.
Returns
-------
(session_id [int], start [dateti... | Below is the the instruction that describes the task:
### Input:
get info about a session
Parameters
----------
session : int
Session number to retrieve. The current session is 0, and negative
numbers count back from current session, so -1 is previous session.
... |
def retrieve(self, id) :
"""
Retrieve a single contact
Returns a single contact available to the user, according to the unique contact ID provided
If the specified contact does not exist, the request will return an error
:calls: ``get /contacts/{id}``
:param int id: Uni... | Retrieve a single contact
Returns a single contact available to the user, according to the unique contact ID provided
If the specified contact does not exist, the request will return an error
:calls: ``get /contacts/{id}``
:param int id: Unique identifier of a Contact.
:return:... | Below is the the instruction that describes the task:
### Input:
Retrieve a single contact
Returns a single contact available to the user, according to the unique contact ID provided
If the specified contact does not exist, the request will return an error
:calls: ``get /contacts/{id}``
... |
def _select(self, current_venvs, requirements=None, interpreter='', uuid='', options=None):
"""Select which venv satisfy the received requirements."""
if uuid:
logger.debug("Searching a venv by uuid: %s", uuid)
venv = self._match_by_uuid(current_venvs, uuid)
else:
... | Select which venv satisfy the received requirements. | Below is the the instruction that describes the task:
### Input:
Select which venv satisfy the received requirements.
### Response:
def _select(self, current_venvs, requirements=None, interpreter='', uuid='', options=None):
"""Select which venv satisfy the received requirements."""
if uuid:
... |
def set_disk_cache(self, results, key=None):
"""Store result in disk cache with key matching model state."""
if not getattr(self, 'disk_cache_location', False):
self.init_disk_cache()
disk_cache = shelve.open(self.disk_cache_location)
key = self.model.hash if key is None else... | Store result in disk cache with key matching model state. | Below is the the instruction that describes the task:
### Input:
Store result in disk cache with key matching model state.
### Response:
def set_disk_cache(self, results, key=None):
"""Store result in disk cache with key matching model state."""
if not getattr(self, 'disk_cache_location', False):
... |
def intermediates(self):
"""
A list of asn1crypto.x509.Certificate objects that were presented as
intermediates by the server
"""
if self._ssl is None:
self._raise_closed()
if self._certificate is None:
self._read_certificates()
return s... | A list of asn1crypto.x509.Certificate objects that were presented as
intermediates by the server | Below is the the instruction that describes the task:
### Input:
A list of asn1crypto.x509.Certificate objects that were presented as
intermediates by the server
### Response:
def intermediates(self):
"""
A list of asn1crypto.x509.Certificate objects that were presented as
intermedi... |
def get_var_name(nc):
"""Guesses the variable_name of an open NetCDF file
"""
non_variable_names = [
'lat',
'lat_bnds',
'lon',
'lon_bnds',
'time',
'latitude',
'longitude',
'bnds'
]
_vars = set(nc.variables.keys())
_vars.difference... | Guesses the variable_name of an open NetCDF file | Below is the the instruction that describes the task:
### Input:
Guesses the variable_name of an open NetCDF file
### Response:
def get_var_name(nc):
"""Guesses the variable_name of an open NetCDF file
"""
non_variable_names = [
'lat',
'lat_bnds',
'lon',
'lon_bnds',
... |
def _get_df(self):
"""Returns stellar model grid with desired bandpasses and with standard column names
bands must be iterable, and are parsed according to :func:``get_band``
"""
grids = {}
df = pd.DataFrame()
for bnd in self.bands:
s,b = self.get_band(bnd, *... | Returns stellar model grid with desired bandpasses and with standard column names
bands must be iterable, and are parsed according to :func:``get_band`` | Below is the the instruction that describes the task:
### Input:
Returns stellar model grid with desired bandpasses and with standard column names
bands must be iterable, and are parsed according to :func:``get_band``
### Response:
def _get_df(self):
"""Returns stellar model grid with desired band... |
def adafactor_optimizer_from_hparams(hparams, lr):
"""Create an Adafactor optimizer based on model hparams.
Args:
hparams: model hyperparameters
lr: learning rate scalar.
Returns:
an AdafactorOptimizer
Raises:
ValueError: on illegal values
"""
if hparams.optimizer_adafactor_decay_type == "A... | Create an Adafactor optimizer based on model hparams.
Args:
hparams: model hyperparameters
lr: learning rate scalar.
Returns:
an AdafactorOptimizer
Raises:
ValueError: on illegal values | Below is the the instruction that describes the task:
### Input:
Create an Adafactor optimizer based on model hparams.
Args:
hparams: model hyperparameters
lr: learning rate scalar.
Returns:
an AdafactorOptimizer
Raises:
ValueError: on illegal values
### Response:
def adafactor_optimizer_fro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.