code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _get(self, url,
param_dict=None,
securityHandler=None,
additional_headers=None,
handlers=None,
proxy_url=None,
proxy_port=None,
compress=True,
custom_handlers=None,
out_folder=None,
file... | Performs a GET operation
Inputs:
Output:
returns dictionary, string or None | Below is the the instruction that describes the task:
### Input:
Performs a GET operation
Inputs:
Output:
returns dictionary, string or None
### Response:
def _get(self, url,
param_dict=None,
securityHandler=None,
additional_headers=None,
... |
def add(self, r):
'''Takes an id and a Residue r and adds them to the Sequence.'''
id = r.get_residue_id()
if self.order:
last_id = self.order[-1]
# KAB - allow for multiresidue noncanonicals
if id in self.order:
raise colortext.Exception('War... | Takes an id and a Residue r and adds them to the Sequence. | Below is the the instruction that describes the task:
### Input:
Takes an id and a Residue r and adds them to the Sequence.
### Response:
def add(self, r):
'''Takes an id and a Residue r and adds them to the Sequence.'''
id = r.get_residue_id()
if self.order:
last_id = self.orde... |
def _url_matches(self, url, other, match_querystring=False):
'''
Need to override this so we can fix querystrings breaking regex matching
'''
if not match_querystring:
other = other.split('?', 1)[0]
if responses._is_string(url):
if responses._has_unicode(... | Need to override this so we can fix querystrings breaking regex matching | Below is the the instruction that describes the task:
### Input:
Need to override this so we can fix querystrings breaking regex matching
### Response:
def _url_matches(self, url, other, match_querystring=False):
'''
Need to override this so we can fix querystrings breaking regex matching
'... |
def from_response(response):
"""Returns the correct error type from a ::class::`Response` object."""
if response.code:
return ERRORS[response.code](response)
else:
return Error(response) | Returns the correct error type from a ::class::`Response` object. | Below is the the instruction that describes the task:
### Input:
Returns the correct error type from a ::class::`Response` object.
### Response:
def from_response(response):
"""Returns the correct error type from a ::class::`Response` object."""
if response.code:
return ERRORS[response.... |
def str_dateStrip(astr_datestr, astr_sep='/'):
"""
Simple date strip method. Checks if the <astr_datestr>
contains <astr_sep>. If so, strips these from the string
and returns result.
The actual stripping entails falling through two layers
of exception handling... so it is something of a hack.
"""
try:
... | Simple date strip method. Checks if the <astr_datestr>
contains <astr_sep>. If so, strips these from the string
and returns result.
The actual stripping entails falling through two layers
of exception handling... so it is something of a hack. | Below is the the instruction that describes the task:
### Input:
Simple date strip method. Checks if the <astr_datestr>
contains <astr_sep>. If so, strips these from the string
and returns result.
The actual stripping entails falling through two layers
of exception handling... so it is something of a hack.... |
def mt_modelform_field_restore_original_label(field, make_capfirst=False):
"""
If label of field has suffix with language, you can fix it, for example:
class MyModelForm(models.ModelForm):
class Meta:
model = MyModel
_mt_fields = mt_fields(('title', 'description'), nomaster=... | If label of field has suffix with language, you can fix it, for example:
class MyModelForm(models.ModelForm):
class Meta:
model = MyModel
_mt_fields = mt_fields(('title', 'description'), nomaster=True)
fields = _mt_fields
def __init__(self, *args, **kwargs):
... | Below is the the instruction that describes the task:
### Input:
If label of field has suffix with language, you can fix it, for example:
class MyModelForm(models.ModelForm):
class Meta:
model = MyModel
_mt_fields = mt_fields(('title', 'description'), nomaster=True)
... |
def RegisterOutput(cls, output_class, disabled=False):
"""Registers an output class.
The output classes are identified based on their NAME attribute.
Args:
output_class (type): output module class.
disabled (Optional[bool]): True if the output module is disabled due to
the module not... | Registers an output class.
The output classes are identified based on their NAME attribute.
Args:
output_class (type): output module class.
disabled (Optional[bool]): True if the output module is disabled due to
the module not loading correctly or not.
Raises:
KeyError: if out... | Below is the the instruction that describes the task:
### Input:
Registers an output class.
The output classes are identified based on their NAME attribute.
Args:
output_class (type): output module class.
disabled (Optional[bool]): True if the output module is disabled due to
the mod... |
def load(self, filename):
"""
Loads the settings from the inputed filename.
:param filename | <str>
"""
try:
self._xroot = ElementTree.parse(filename).getroot()
self._xstack = [self._xroot]
except ExpatError:
sel... | Loads the settings from the inputed filename.
:param filename | <str> | Below is the the instruction that describes the task:
### Input:
Loads the settings from the inputed filename.
:param filename | <str>
### Response:
def load(self, filename):
"""
Loads the settings from the inputed filename.
:param filename | <str>
... |
def get_payment_transaction_by_id(cls, payment_transaction_id, **kwargs):
"""Find PaymentTransaction
Return single instance of PaymentTransaction by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> ... | Find PaymentTransaction
Return single instance of PaymentTransaction by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_payment_transaction_by_id(payment_transaction_id, async=True)
... | Below is the the instruction that describes the task:
### Input:
Find PaymentTransaction
Return single instance of PaymentTransaction by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get... |
def parse_config_file():
"""
Find the .tagcube config file in the current directory, or in the
user's home and parse it. The one in the current directory has precedence.
:return: A tuple with:
- email
- api_token
"""
for filename in ('.tagcube', os.path.expan... | Find the .tagcube config file in the current directory, or in the
user's home and parse it. The one in the current directory has precedence.
:return: A tuple with:
- email
- api_token | Below is the the instruction that describes the task:
### Input:
Find the .tagcube config file in the current directory, or in the
user's home and parse it. The one in the current directory has precedence.
:return: A tuple with:
- email
- api_token
### Response:
def par... |
def shutdown(self):
"""Shutdown kernel"""
if self.get_kernel() is not None and not self.slave:
self.shellwidget.kernel_manager.shutdown_kernel()
if self.shellwidget.kernel_client is not None:
background(self.shellwidget.kernel_client.stop_channels) | Shutdown kernel | Below is the the instruction that describes the task:
### Input:
Shutdown kernel
### Response:
def shutdown(self):
"""Shutdown kernel"""
if self.get_kernel() is not None and not self.slave:
self.shellwidget.kernel_manager.shutdown_kernel()
if self.shellwidget.kernel_client i... |
def fBrown(H,T,N,M,dW = None,cholesky = False):
'''
Sample fractional Brownian motion with differentiability index H
on interval [0,T] (H=1/2 yields standard Brownian motion)
:param H: Differentiability, larger than 0
:param T: Final time
:param N: Number of time steps
:param M: Number... | Sample fractional Brownian motion with differentiability index H
on interval [0,T] (H=1/2 yields standard Brownian motion)
:param H: Differentiability, larger than 0
:param T: Final time
:param N: Number of time steps
:param M: Number of samples
:param dW: Driving noise, optional | Below is the the instruction that describes the task:
### Input:
Sample fractional Brownian motion with differentiability index H
on interval [0,T] (H=1/2 yields standard Brownian motion)
:param H: Differentiability, larger than 0
:param T: Final time
:param N: Number of time steps
:param ... |
def sscan(self, name, cursor='0', match=None, count=10):
"""Emulate sscan."""
def value_function():
members = list(self.smembers(name))
members.sort() # sort for consistent order
return members
return self._common_scan(value_function, cursor=cursor, match=mat... | Emulate sscan. | Below is the the instruction that describes the task:
### Input:
Emulate sscan.
### Response:
def sscan(self, name, cursor='0', match=None, count=10):
"""Emulate sscan."""
def value_function():
members = list(self.smembers(name))
members.sort() # sort for consistent order
... |
def alpha(self, **state):
"""
Calculate the alpha value given the material state.
:param **state: material state
:returns: float
"""
return self.k(**state) / self.rho(**state) / self.Cp(**state) | Calculate the alpha value given the material state.
:param **state: material state
:returns: float | Below is the the instruction that describes the task:
### Input:
Calculate the alpha value given the material state.
:param **state: material state
:returns: float
### Response:
def alpha(self, **state):
"""
Calculate the alpha value given the material state.
:param **sta... |
def obtain(date, compressed=True):
"""
Return an integer matrix with the Linke turbidity multiplied by 20. So it
should be divided by 20 in before the usage (over the CPU or the GPU).
Keyword arguments:
date -- the datetime of the file.
compressed -- the true value if it should return a matrix ... | Return an integer matrix with the Linke turbidity multiplied by 20. So it
should be divided by 20 in before the usage (over the CPU or the GPU).
Keyword arguments:
date -- the datetime of the file.
compressed -- the true value if it should return a matrix of integers or
if it should return an uncom... | Below is the the instruction that describes the task:
### Input:
Return an integer matrix with the Linke turbidity multiplied by 20. So it
should be divided by 20 in before the usage (over the CPU or the GPU).
Keyword arguments:
date -- the datetime of the file.
compressed -- the true value if it s... |
def get_array(self, period):
"""
Get the value of the variable for the given period.
If the value is not known, return ``None``.
"""
if self.variable.is_neutralized:
return self.default_array()
value = self._memory_storage.get(period)
if value... | Get the value of the variable for the given period.
If the value is not known, return ``None``. | Below is the the instruction that describes the task:
### Input:
Get the value of the variable for the given period.
If the value is not known, return ``None``.
### Response:
def get_array(self, period):
"""
Get the value of the variable for the given period.
If the va... |
def clean(self, critical=False):
"""Clean the logs list by deleting finished items.
By default, only delete WARNING message.
If critical = True, also delete CRITICAL message.
"""
# Create a new clean list
clean_events_list = []
while self.len() > 0:
i... | Clean the logs list by deleting finished items.
By default, only delete WARNING message.
If critical = True, also delete CRITICAL message. | Below is the the instruction that describes the task:
### Input:
Clean the logs list by deleting finished items.
By default, only delete WARNING message.
If critical = True, also delete CRITICAL message.
### Response:
def clean(self, critical=False):
"""Clean the logs list by deleting fini... |
def serialize(self, format):
"""
Serialize provenance graph in the specified format
"""
if PY3:
return self.prov_g.serialize(format=format).decode('utf-8')
else:
return self.prov_g.serialize(format=format) | Serialize provenance graph in the specified format | Below is the the instruction that describes the task:
### Input:
Serialize provenance graph in the specified format
### Response:
def serialize(self, format):
"""
Serialize provenance graph in the specified format
"""
if PY3:
return self.prov_g.serialize(format=format).d... |
def unshorten_url(short_url):
"""Unshortens the short_url or returns None if not possible."""
short_url = short_url.strip()
if not short_url.startswith('http'):
short_url = 'http://{0}'.format(short_url)
try:
cached_url = UnshortenURL.objects.get(short_url=short_url)
except Unshorte... | Unshortens the short_url or returns None if not possible. | Below is the the instruction that describes the task:
### Input:
Unshortens the short_url or returns None if not possible.
### Response:
def unshorten_url(short_url):
"""Unshortens the short_url or returns None if not possible."""
short_url = short_url.strip()
if not short_url.startswith('http'):
... |
def _reciprocal_condition_number(lu_mat, one_norm):
r"""Compute reciprocal condition number of a matrix.
Args:
lu_mat (numpy.ndarray): A 2D array of a matrix :math:`A` that has been
LU-factored, with the non-diagonal part of :math:`L` stored in the
strictly lower triangle and :m... | r"""Compute reciprocal condition number of a matrix.
Args:
lu_mat (numpy.ndarray): A 2D array of a matrix :math:`A` that has been
LU-factored, with the non-diagonal part of :math:`L` stored in the
strictly lower triangle and :math:`U` stored in the upper triangle.
one_norm (... | Below is the the instruction that describes the task:
### Input:
r"""Compute reciprocal condition number of a matrix.
Args:
lu_mat (numpy.ndarray): A 2D array of a matrix :math:`A` that has been
LU-factored, with the non-diagonal part of :math:`L` stored in the
strictly lower tr... |
def run(self, args):
"""
Deletes a single project specified by project_name in args.
:param args Namespace arguments parsed from the command line
"""
project = self.fetch_project(args, must_exist=True, include_children=False)
if not args.force:
delete_prompt =... | Deletes a single project specified by project_name in args.
:param args Namespace arguments parsed from the command line | Below is the the instruction that describes the task:
### Input:
Deletes a single project specified by project_name in args.
:param args Namespace arguments parsed from the command line
### Response:
def run(self, args):
"""
Deletes a single project specified by project_name in args.
... |
def worker_execute(self, nick, message, channel, task_id, command, workers=None):
"""\
Work on a task from the BotnetBot
"""
if workers:
nicks = workers.split(',')
do_task = self.conn.nick in nicks
else:
do_task = True
if do_ta... | \
Work on a task from the BotnetBot | Below is the the instruction that describes the task:
### Input:
\
Work on a task from the BotnetBot
### Response:
def worker_execute(self, nick, message, channel, task_id, command, workers=None):
"""\
Work on a task from the BotnetBot
"""
if workers:
nicks = wor... |
def link(g: Graph, subject: Node, predicate: URIRef) -> Tuple[Optional[URIRef], Optional[URIRef]]:
"""
Return the link URI and link type for subject and predicate
:param g: graph context
:param subject: subject of linke
:param predicate: link predicate
:return: URI and optional type URI. URI is... | Return the link URI and link type for subject and predicate
:param g: graph context
:param subject: subject of linke
:param predicate: link predicate
:return: URI and optional type URI. URI is None if not a link | Below is the the instruction that describes the task:
### Input:
Return the link URI and link type for subject and predicate
:param g: graph context
:param subject: subject of linke
:param predicate: link predicate
:return: URI and optional type URI. URI is None if not a link
### Response:
def lin... |
def copy_params(get_or_post_params, ignore=None):
"""
copy a :class:`django.http.QueryDict` in a :obj:`dict` ignoring keys in the set ``ignore``
:param django.http.QueryDict get_or_post_params: A GET or POST
:class:`QueryDict<django.http.QueryDict>`
:param set ignore: An optinal... | copy a :class:`django.http.QueryDict` in a :obj:`dict` ignoring keys in the set ``ignore``
:param django.http.QueryDict get_or_post_params: A GET or POST
:class:`QueryDict<django.http.QueryDict>`
:param set ignore: An optinal set of keys to ignore during the copy
:return: A copy of ... | Below is the the instruction that describes the task:
### Input:
copy a :class:`django.http.QueryDict` in a :obj:`dict` ignoring keys in the set ``ignore``
:param django.http.QueryDict get_or_post_params: A GET or POST
:class:`QueryDict<django.http.QueryDict>`
:param set ignore: An opti... |
def _ensure_timestamp_field(dataset_expr, deltas, checkpoints):
"""Verify that the baseline and deltas expressions have a timestamp field.
If there is not a ``TS_FIELD_NAME`` on either of the expressions, it will
be copied from the ``AD_FIELD_NAME``. If one is provided, then we will
verify that it is t... | Verify that the baseline and deltas expressions have a timestamp field.
If there is not a ``TS_FIELD_NAME`` on either of the expressions, it will
be copied from the ``AD_FIELD_NAME``. If one is provided, then we will
verify that it is the correct dshape.
Parameters
----------
dataset_expr : Ex... | Below is the the instruction that describes the task:
### Input:
Verify that the baseline and deltas expressions have a timestamp field.
If there is not a ``TS_FIELD_NAME`` on either of the expressions, it will
be copied from the ``AD_FIELD_NAME``. If one is provided, then we will
verify that it is the... |
def _gather_pillar(pillarenv, pillar_override):
'''
Whenever a state run starts, gather the pillar data fresh
'''
pillar = salt.pillar.get_pillar(
__opts__,
__grains__,
__opts__['id'],
__opts__['saltenv'],
pillar_override=pillar_override,
pillarenv=pillare... | Whenever a state run starts, gather the pillar data fresh | Below is the the instruction that describes the task:
### Input:
Whenever a state run starts, gather the pillar data fresh
### Response:
def _gather_pillar(pillarenv, pillar_override):
'''
Whenever a state run starts, gather the pillar data fresh
'''
pillar = salt.pillar.get_pillar(
__opts_... |
def delete_attr_by_path(self, field):
"""
Function for deleting a field specifying the path in the whole model as described
in :func:`dirty:models.models.BaseModel.perform_function_by_path`
"""
index_list, next_field = self._get_indexes_by_path(field)
if index_list:
... | Function for deleting a field specifying the path in the whole model as described
in :func:`dirty:models.models.BaseModel.perform_function_by_path` | Below is the the instruction that describes the task:
### Input:
Function for deleting a field specifying the path in the whole model as described
in :func:`dirty:models.models.BaseModel.perform_function_by_path`
### Response:
def delete_attr_by_path(self, field):
"""
Function for deleting ... |
def initial_guesses(self):
"""
:return: Initial guesses for every parameter.
"""
return np.array([param.value for param in self.model.params]) | :return: Initial guesses for every parameter. | Below is the the instruction that describes the task:
### Input:
:return: Initial guesses for every parameter.
### Response:
def initial_guesses(self):
"""
:return: Initial guesses for every parameter.
"""
return np.array([param.value for param in self.model.params]) |
def RNN_step(weights, gates):
"""Create a step model for an RNN, given weights and gates functions."""
def rnn_step_fwd(prevstate_inputs, drop=0.0):
prevstate, inputs = prevstate_inputs
cell_tm1, hidden_tm1 = prevstate
acts, bp_acts = weights.begin_update((inputs, hidden_tm1), drop=dro... | Create a step model for an RNN, given weights and gates functions. | Below is the the instruction that describes the task:
### Input:
Create a step model for an RNN, given weights and gates functions.
### Response:
def RNN_step(weights, gates):
"""Create a step model for an RNN, given weights and gates functions."""
def rnn_step_fwd(prevstate_inputs, drop=0.0):
pre... |
def validate(name, re=None, convert=None, doc=None):
"""Decorator. Apply on a :class:`wsgiservice.Resource` or any of it's
methods to validates a parameter on input. When a parameter does not
validate, a :class:`wsgiservice.exceptions.ValidationException` exception
will be thrown.
:param name: Name... | Decorator. Apply on a :class:`wsgiservice.Resource` or any of it's
methods to validates a parameter on input. When a parameter does not
validate, a :class:`wsgiservice.exceptions.ValidationException` exception
will be thrown.
:param name: Name of the input parameter to validate.
:type name: string
... | Below is the the instruction that describes the task:
### Input:
Decorator. Apply on a :class:`wsgiservice.Resource` or any of it's
methods to validates a parameter on input. When a parameter does not
validate, a :class:`wsgiservice.exceptions.ValidationException` exception
will be thrown.
:param n... |
def get_meta_image_url(request, image):
"""
Resize an image for metadata tags, and return an absolute URL to it.
"""
rendition = image.get_rendition(filter='original')
return request.build_absolute_uri(rendition.url) | Resize an image for metadata tags, and return an absolute URL to it. | Below is the the instruction that describes the task:
### Input:
Resize an image for metadata tags, and return an absolute URL to it.
### Response:
def get_meta_image_url(request, image):
"""
Resize an image for metadata tags, and return an absolute URL to it.
"""
rendition = image.get_rendition(fi... |
def keyPressEvent(self, event):
"""Keyboard shortcuts"""
key = event.key()
if key == QtCore.Qt.Key_X:
self.actionXref()
elif key == QtCore.Qt.Key_G:
self.actionGoto()
elif key == QtCore.Qt.Key_X:
self.actionXref()
elif key == QtCore.Qt.... | Keyboard shortcuts | Below is the the instruction that describes the task:
### Input:
Keyboard shortcuts
### Response:
def keyPressEvent(self, event):
"""Keyboard shortcuts"""
key = event.key()
if key == QtCore.Qt.Key_X:
self.actionXref()
elif key == QtCore.Qt.Key_G:
self.actionG... |
def main(argv=None):
"""
Script entry point
:param argv: Script arguments (None for sys.argv)
:return: An exit code or None
"""
# Prepare arguments
parser = argparse.ArgumentParser(
prog="pelix.shell.remote",
parents=[make_common_parser()],
description="Pelix Remote ... | Script entry point
:param argv: Script arguments (None for sys.argv)
:return: An exit code or None | Below is the the instruction that describes the task:
### Input:
Script entry point
:param argv: Script arguments (None for sys.argv)
:return: An exit code or None
### Response:
def main(argv=None):
"""
Script entry point
:param argv: Script arguments (None for sys.argv)
:return: An exit ... |
def rl_make_safe_prompt(prompt: str) -> str: # pragma: no cover
"""Overcome bug in GNU Readline in relation to calculation of prompt length in presence of ANSI escape codes.
:param prompt: original prompt
:return: prompt safe to pass to GNU Readline
"""
if rl_type == RlType.GNU:
# start co... | Overcome bug in GNU Readline in relation to calculation of prompt length in presence of ANSI escape codes.
:param prompt: original prompt
:return: prompt safe to pass to GNU Readline | Below is the the instruction that describes the task:
### Input:
Overcome bug in GNU Readline in relation to calculation of prompt length in presence of ANSI escape codes.
:param prompt: original prompt
:return: prompt safe to pass to GNU Readline
### Response:
def rl_make_safe_prompt(prompt: str) -> str:... |
def detect_intent_with_model_selection(project_id, session_id, audio_file_path,
language_code):
"""Returns the result of detect intent with model selection on an audio file
as input
Using the same `session_id` between requests allows continuation
of the conversaio... | Returns the result of detect intent with model selection on an audio file
as input
Using the same `session_id` between requests allows continuation
of the conversaion. | Below is the the instruction that describes the task:
### Input:
Returns the result of detect intent with model selection on an audio file
as input
Using the same `session_id` between requests allows continuation
of the conversaion.
### Response:
def detect_intent_with_model_selection(project_id, sess... |
def _get_route_info(self, request):
"""Return information about the current URL."""
resolve_match = resolve(request.path)
app_name = resolve_match.app_name # The application namespace for the URL pattern that matches the URL.
namespace = resolve_match.namespace # The instance namesp... | Return information about the current URL. | Below is the the instruction that describes the task:
### Input:
Return information about the current URL.
### Response:
def _get_route_info(self, request):
"""Return information about the current URL."""
resolve_match = resolve(request.path)
app_name = resolve_match.app_name # The appl... |
def deb(state, host, source, present=True, force=False):
'''
Add/remove ``.deb`` file packages.
+ source: filename or URL of the ``.deb`` file
+ present: whether or not the package should exist on the system
+ force: whether to force the package install by passing `--force-yes` to apt
Note:
... | Add/remove ``.deb`` file packages.
+ source: filename or URL of the ``.deb`` file
+ present: whether or not the package should exist on the system
+ force: whether to force the package install by passing `--force-yes` to apt
Note:
When installing, ``apt-get install -f`` will be run to install ... | Below is the the instruction that describes the task:
### Input:
Add/remove ``.deb`` file packages.
+ source: filename or URL of the ``.deb`` file
+ present: whether or not the package should exist on the system
+ force: whether to force the package install by passing `--force-yes` to apt
Note:
... |
def xavier_init(fan_in, fan_out, const=1):
"""Xavier initialization of network weights.
https://stackoverflow.com/questions/33640581/how-to-do-xavier-initialization-on-tensorflow
:param fan_in: fan in of the network (n_features)
:param fan_out: fan out of the network (n_components)
:param const: m... | Xavier initialization of network weights.
https://stackoverflow.com/questions/33640581/how-to-do-xavier-initialization-on-tensorflow
:param fan_in: fan in of the network (n_features)
:param fan_out: fan out of the network (n_components)
:param const: multiplicative constant | Below is the the instruction that describes the task:
### Input:
Xavier initialization of network weights.
https://stackoverflow.com/questions/33640581/how-to-do-xavier-initialization-on-tensorflow
:param fan_in: fan in of the network (n_features)
:param fan_out: fan out of the network (n_components)
... |
def _expectation(p, kern, none1, none2, none3, nghp=None):
"""
Compute the expectation:
<diag(K_{X, X})>_p(X)
- K_{.,.} :: RBF kernel
:return: N
"""
return kern.Kdiag(p.mu) | Compute the expectation:
<diag(K_{X, X})>_p(X)
- K_{.,.} :: RBF kernel
:return: N | Below is the the instruction that describes the task:
### Input:
Compute the expectation:
<diag(K_{X, X})>_p(X)
- K_{.,.} :: RBF kernel
:return: N
### Response:
def _expectation(p, kern, none1, none2, none3, nghp=None):
"""
Compute the expectation:
<diag(K_{X, X})>_p(X)
- K_{.,... |
def method(self, symbol):
'''
Symbol decorator.
'''
assert issubclass(symbol, SymbolBase)
def wrapped(fn):
setattr(symbol, fn.__name__, fn)
return wrapped | Symbol decorator. | Below is the the instruction that describes the task:
### Input:
Symbol decorator.
### Response:
def method(self, symbol):
'''
Symbol decorator.
'''
assert issubclass(symbol, SymbolBase)
def wrapped(fn):
setattr(symbol, fn.__name__, fn)
return wrapped |
def ws_disconnect(message):
"""
Channels connection close.
Deregister the client
"""
language = message.channel_session['knocker']
gr = Group('knocker-{0}'.format(language))
gr.discard(message.reply_channel) | Channels connection close.
Deregister the client | Below is the the instruction that describes the task:
### Input:
Channels connection close.
Deregister the client
### Response:
def ws_disconnect(message):
"""
Channels connection close.
Deregister the client
"""
language = message.channel_session['knocker']
gr = Group('knocker-{0}'.for... |
def fix_ipython_startup(fn):
"""
Attempt to fix IPython startup to not print (Bool_t)1
"""
BADSTR = 'TPython::Exec( "" )'
GOODSTR = 'TPython::Exec( "" );'
if sys.version_info[0] < 3:
consts = fn.im_func.func_code.co_consts
else:
consts = fn.__code__.co_consts
if BADSTR no... | Attempt to fix IPython startup to not print (Bool_t)1 | Below is the the instruction that describes the task:
### Input:
Attempt to fix IPython startup to not print (Bool_t)1
### Response:
def fix_ipython_startup(fn):
"""
Attempt to fix IPython startup to not print (Bool_t)1
"""
BADSTR = 'TPython::Exec( "" )'
GOODSTR = 'TPython::Exec( "" );'
if ... |
def generate_pingback_content(soup, target, max_length, trunc_char='...'):
"""
Generate a description text for the pingback.
"""
link = soup.find('a', href=target)
content = strip_tags(six.text_type(link.findParent()))
index = content.index(link.string)
if len(content) > max_length:
... | Generate a description text for the pingback. | Below is the the instruction that describes the task:
### Input:
Generate a description text for the pingback.
### Response:
def generate_pingback_content(soup, target, max_length, trunc_char='...'):
"""
Generate a description text for the pingback.
"""
link = soup.find('a', href=target)
conte... |
def setup(self):
'''
Make sure the target is ready for fuzzing, including monitors and
controllers
'''
if self.controller:
self.controller.setup()
for monitor in self.monitors:
monitor.setup() | Make sure the target is ready for fuzzing, including monitors and
controllers | Below is the the instruction that describes the task:
### Input:
Make sure the target is ready for fuzzing, including monitors and
controllers
### Response:
def setup(self):
'''
Make sure the target is ready for fuzzing, including monitors and
controllers
'''
if self... |
def remove_expired_nodes(self, node_ids=None):
"""
Removes all expired nodes from the nodelist. If a set of node_ids is
passed in, those ids are checked to ensure they haven't been refreshed
prior to a lock being acquired.
Should only be run with a lock.
:param list no... | Removes all expired nodes from the nodelist. If a set of node_ids is
passed in, those ids are checked to ensure they haven't been refreshed
prior to a lock being acquired.
Should only be run with a lock.
:param list node_ids: optional, a list of node_ids to remove. They
w... | Below is the the instruction that describes the task:
### Input:
Removes all expired nodes from the nodelist. If a set of node_ids is
passed in, those ids are checked to ensure they haven't been refreshed
prior to a lock being acquired.
Should only be run with a lock.
:param list ... |
def _load_latex2unicode_constants(kb_file=None):
"""Load LaTeX2Unicode translation table dictionary.
Load LaTeX2Unicode translation table dictionary and regular
expression object from KB to a global dictionary.
:param kb_file: full path to file containing latex2unicode translations.
... | Load LaTeX2Unicode translation table dictionary.
Load LaTeX2Unicode translation table dictionary and regular
expression object from KB to a global dictionary.
:param kb_file: full path to file containing latex2unicode translations.
Defaults to CFG_ETCDIR/bibconvert/KB/latex-to-unicode.... | Below is the the instruction that describes the task:
### Input:
Load LaTeX2Unicode translation table dictionary.
Load LaTeX2Unicode translation table dictionary and regular
expression object from KB to a global dictionary.
:param kb_file: full path to file containing latex2unicode translations.
... |
def resolve_field_class(field_definition):
"""Return field class most fitting of provided Swimlane field definition"""
try:
return _FIELD_TYPE_MAP[field_definition['$type']]
except KeyError as error:
error.message = 'No field available to handle Swimlane $type "{}"'.format(field_definition)
... | Return field class most fitting of provided Swimlane field definition | Below is the the instruction that describes the task:
### Input:
Return field class most fitting of provided Swimlane field definition
### Response:
def resolve_field_class(field_definition):
"""Return field class most fitting of provided Swimlane field definition"""
try:
return _FIELD_TYPE_MAP[fie... |
def search_env_paths(fname, key_list=None, verbose=None):
r"""
Searches your PATH to see if fname exists
Args:
fname (str): file name to search for (can be glob pattern)
CommandLine:
python -m utool search_env_paths --fname msvcr*.dll
python -m utool search_env_paths --fname '*... | r"""
Searches your PATH to see if fname exists
Args:
fname (str): file name to search for (can be glob pattern)
CommandLine:
python -m utool search_env_paths --fname msvcr*.dll
python -m utool search_env_paths --fname '*flann*'
Example:
>>> # DISABLE_DOCTEST
>>... | Below is the the instruction that describes the task:
### Input:
r"""
Searches your PATH to see if fname exists
Args:
fname (str): file name to search for (can be glob pattern)
CommandLine:
python -m utool search_env_paths --fname msvcr*.dll
python -m utool search_env_paths --f... |
def editUsageReportSettings(self, samplingInterval,
enabled=True, maxHistory=0):
"""
The usage reports settings are applied to the entire site. A POST
request updates the usage reports settings.
Inputs:
samplingInterval - Defines the duration (... | The usage reports settings are applied to the entire site. A POST
request updates the usage reports settings.
Inputs:
samplingInterval - Defines the duration (in minutes) for which
the usage statistics are aggregated or sampled, in-memory,
before being written out t... | Below is the the instruction that describes the task:
### Input:
The usage reports settings are applied to the entire site. A POST
request updates the usage reports settings.
Inputs:
samplingInterval - Defines the duration (in minutes) for which
the usage statistics are aggr... |
def update_local_repo_async(self, task_queue, force=False):
"""Local repo updating suitable for asynchronous, parallel execution.
We still need to run `ensure_local_repo` synchronously because it
does a bunch of non-threadsafe filesystem operations."""
self.ensure_local_repo()
ta... | Local repo updating suitable for asynchronous, parallel execution.
We still need to run `ensure_local_repo` synchronously because it
does a bunch of non-threadsafe filesystem operations. | Below is the the instruction that describes the task:
### Input:
Local repo updating suitable for asynchronous, parallel execution.
We still need to run `ensure_local_repo` synchronously because it
does a bunch of non-threadsafe filesystem operations.
### Response:
def update_local_repo_async(self,... |
def validate_mixture(supports_mixture: SupportsMixture):
"""Validates that the mixture's tuple are valid probabilities."""
mixture_tuple = mixture(supports_mixture, None)
if mixture_tuple is None:
raise TypeError('{}_mixture did not have a _mixture_ method'.format(
supports_mixture))
... | Validates that the mixture's tuple are valid probabilities. | Below is the the instruction that describes the task:
### Input:
Validates that the mixture's tuple are valid probabilities.
### Response:
def validate_mixture(supports_mixture: SupportsMixture):
"""Validates that the mixture's tuple are valid probabilities."""
mixture_tuple = mixture(supports_mixture, Non... |
def compare_timestamp(src, dst):
"""
Compares the timestamps of file *src* and *dst*, returning #True if the
*dst* is out of date or does not exist. Raises an #OSError if the *src*
file does not exist.
"""
try:
dst_time = os.path.getmtime(dst)
except OSError as exc:
if exc.errno == errno.ENOENT:
... | Compares the timestamps of file *src* and *dst*, returning #True if the
*dst* is out of date or does not exist. Raises an #OSError if the *src*
file does not exist. | Below is the the instruction that describes the task:
### Input:
Compares the timestamps of file *src* and *dst*, returning #True if the
*dst* is out of date or does not exist. Raises an #OSError if the *src*
file does not exist.
### Response:
def compare_timestamp(src, dst):
"""
Compares the timestamps of... |
def xlsw_write_row(ws, row_idx, row, fmt=None):
"""
ws:
row_idx: row number
row: a list, data to write
fmt: format for cell
"""
for col_idx in range(len(row)):
ws.write(row_idx, col_idx, row[col_idx], fmt)
row_idx += 1
return row_idx | ws:
row_idx: row number
row: a list, data to write
fmt: format for cell | Below is the the instruction that describes the task:
### Input:
ws:
row_idx: row number
row: a list, data to write
fmt: format for cell
### Response:
def xlsw_write_row(ws, row_idx, row, fmt=None):
"""
ws:
row_idx: row number
row: a list, data to write
fmt: format for cell
"""
... |
def prepare_sentence(self, sentence):
"""Prepare the sentence for segment detection."""
# depending on how the morphological analysis was added, there may be
# phonetic markup. Remove it, if it exists.
for word in sentence:
for analysis in word[ANALYSIS]:
anal... | Prepare the sentence for segment detection. | Below is the the instruction that describes the task:
### Input:
Prepare the sentence for segment detection.
### Response:
def prepare_sentence(self, sentence):
"""Prepare the sentence for segment detection."""
# depending on how the morphological analysis was added, there may be
# phonetic... |
def RetrievePluginAsset(self, run, plugin_name, asset_name):
"""Return the contents for a specific plugin asset from a run.
Args:
run: The string name of the run.
plugin_name: The string name of a plugin.
asset_name: The string name of an asset.
Returns:
The string contents of the ... | Return the contents for a specific plugin asset from a run.
Args:
run: The string name of the run.
plugin_name: The string name of a plugin.
asset_name: The string name of an asset.
Returns:
The string contents of the plugin asset.
Raises:
KeyError: If the asset is not avail... | Below is the the instruction that describes the task:
### Input:
Return the contents for a specific plugin asset from a run.
Args:
run: The string name of the run.
plugin_name: The string name of a plugin.
asset_name: The string name of an asset.
Returns:
The string contents of the... |
def _on_trace(self, sequence, topic, message):
"""Process a trace received from a device.
Args:
sequence (int): The sequence number of the packet received
topic (string): The topic this message was received on
message (dict): The message itself
"""
t... | Process a trace received from a device.
Args:
sequence (int): The sequence number of the packet received
topic (string): The topic this message was received on
message (dict): The message itself | Below is the the instruction that describes the task:
### Input:
Process a trace received from a device.
Args:
sequence (int): The sequence number of the packet received
topic (string): The topic this message was received on
message (dict): The message itself
### Respons... |
def register_arguments(cls, parser):
"""Register command line options.
Implement this method for normal options behavior with protection from
OptionConflictErrors. If you override this method and want the default
--$name option(s) to be registered, be sure to call super().
"""
... | Register command line options.
Implement this method for normal options behavior with protection from
OptionConflictErrors. If you override this method and want the default
--$name option(s) to be registered, be sure to call super(). | Below is the the instruction that describes the task:
### Input:
Register command line options.
Implement this method for normal options behavior with protection from
OptionConflictErrors. If you override this method and want the default
--$name option(s) to be registered, be sure to call s... |
def serialize(script_string):
'''
str -> bytearray
'''
string_tokens = script_string.split()
serialized_script = bytearray()
for token in string_tokens:
if token == 'OP_CODESEPARATOR' or token == 'OP_PUSHDATA4':
raise NotImplementedError('{} is a bad idea.'.format(token))
... | str -> bytearray | Below is the the instruction that describes the task:
### Input:
str -> bytearray
### Response:
def serialize(script_string):
'''
str -> bytearray
'''
string_tokens = script_string.split()
serialized_script = bytearray()
for token in string_tokens:
if token == 'OP_CODESEPARATOR' or... |
def time_partitioning(self):
"""google.cloud.bigquery.table.TimePartitioning: Configures time-based
partitioning for a table.
Raises:
ValueError:
If the value is not :class:`TimePartitioning` or :data:`None`.
"""
prop = self._properties.get("timeParti... | google.cloud.bigquery.table.TimePartitioning: Configures time-based
partitioning for a table.
Raises:
ValueError:
If the value is not :class:`TimePartitioning` or :data:`None`. | Below is the the instruction that describes the task:
### Input:
google.cloud.bigquery.table.TimePartitioning: Configures time-based
partitioning for a table.
Raises:
ValueError:
If the value is not :class:`TimePartitioning` or :data:`None`.
### Response:
def time_parti... |
def _connected(self, link_uri):
""" This callback is called form the Crazyflie API when a Crazyflie
has been connected and the TOCs have been downloaded."""
print('Connected to %s' % link_uri)
mems = self._cf.mem.get_mems(MemoryElement.TYPE_1W)
print('Found {} 1-wire memories'.f... | This callback is called form the Crazyflie API when a Crazyflie
has been connected and the TOCs have been downloaded. | Below is the the instruction that describes the task:
### Input:
This callback is called form the Crazyflie API when a Crazyflie
has been connected and the TOCs have been downloaded.
### Response:
def _connected(self, link_uri):
""" This callback is called form the Crazyflie API when a Crazyflie
... |
def generate_certificate_pure_python(common_name, size=DEFAULT_KEY_SIZE,
digest=DEFAULT_DIGEST):
'''
Generate private key and certificate for https
'''
private_key = OpenSSL.crypto.PKey()
private_key.generate_key(TYPE_RSA, size)
request = OpenSSL.cryp... | Generate private key and certificate for https | Below is the the instruction that describes the task:
### Input:
Generate private key and certificate for https
### Response:
def generate_certificate_pure_python(common_name, size=DEFAULT_KEY_SIZE,
digest=DEFAULT_DIGEST):
'''
Generate private key and certificate... |
def render_form(form):
"""same than {{ form|crispy }} if crispy_forms is installed.
render using a bootstrap3 templating otherwise"""
if 'crispy_forms' in settings.INSTALLED_APPS:
from crispy_forms.templatetags.crispy_forms_filters import as_crispy_form
return as_crispy_form(form)
tem... | same than {{ form|crispy }} if crispy_forms is installed.
render using a bootstrap3 templating otherwise | Below is the the instruction that describes the task:
### Input:
same than {{ form|crispy }} if crispy_forms is installed.
render using a bootstrap3 templating otherwise
### Response:
def render_form(form):
"""same than {{ form|crispy }} if crispy_forms is installed.
render using a bootstrap3 templat... |
def get_all_resources(datasets):
# type: (List['Dataset']) -> List[hdx.data.resource.Resource]
"""Get all resources from a list of datasets (such as returned by search)
Args:
datasets (List[Dataset]): list of datasets
Returns:
List[hdx.data.resource.Resource]: l... | Get all resources from a list of datasets (such as returned by search)
Args:
datasets (List[Dataset]): list of datasets
Returns:
List[hdx.data.resource.Resource]: list of resources within those datasets | Below is the the instruction that describes the task:
### Input:
Get all resources from a list of datasets (such as returned by search)
Args:
datasets (List[Dataset]): list of datasets
Returns:
List[hdx.data.resource.Resource]: list of resources within those datasets
### Re... |
def _get_included_diff_results(self):
"""
Return a list of stages to be included in the diff results.
"""
included = [self._git_diff_tool.diff_committed(self._compare_branch)]
if not self._ignore_staged:
included.append(self._git_diff_tool.diff_staged())
if no... | Return a list of stages to be included in the diff results. | Below is the the instruction that describes the task:
### Input:
Return a list of stages to be included in the diff results.
### Response:
def _get_included_diff_results(self):
"""
Return a list of stages to be included in the diff results.
"""
included = [self._git_diff_tool.diff_c... |
def _set_gre_dscp(self, v, load=False):
"""
Setter method for gre_dscp, mapped from YANG variable /interface/tunnel/gre_dscp (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_gre_dscp is considered as a private
method. Backends looking to populate this variabl... | Setter method for gre_dscp, mapped from YANG variable /interface/tunnel/gre_dscp (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_gre_dscp is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_gre_dscp... | Below is the the instruction that describes the task:
### Input:
Setter method for gre_dscp, mapped from YANG variable /interface/tunnel/gre_dscp (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_gre_dscp is considered as a private
method. Backends looking to popu... |
def parse(filepath, beat_resolution=24, name='unknown'):
"""
Return a :class:`pypianoroll.Multitrack` object loaded from a MIDI
(.mid, .midi, .MID, .MIDI) file.
Parameters
----------
filepath : str
The file path to the MIDI file.
"""
if not filepath.endswith(('.mid', '.midi', '... | Return a :class:`pypianoroll.Multitrack` object loaded from a MIDI
(.mid, .midi, .MID, .MIDI) file.
Parameters
----------
filepath : str
The file path to the MIDI file. | Below is the the instruction that describes the task:
### Input:
Return a :class:`pypianoroll.Multitrack` object loaded from a MIDI
(.mid, .midi, .MID, .MIDI) file.
Parameters
----------
filepath : str
The file path to the MIDI file.
### Response:
def parse(filepath, beat_resolution=24, na... |
def is_mass_balanced(reaction):
"""Confirm that a reaction is mass balanced."""
balance = defaultdict(int)
for metabolite, coefficient in iteritems(reaction.metabolites):
if metabolite.elements is None or len(metabolite.elements) == 0:
return False
for element, amount in iteritem... | Confirm that a reaction is mass balanced. | Below is the the instruction that describes the task:
### Input:
Confirm that a reaction is mass balanced.
### Response:
def is_mass_balanced(reaction):
"""Confirm that a reaction is mass balanced."""
balance = defaultdict(int)
for metabolite, coefficient in iteritems(reaction.metabolites):
if ... |
def _get_external_accounts(self, locals):
'''
Return all known accounts, excluding local accounts.
'''
users = dict()
out = __salt__['cmd.run_all']("passwd -S -a")
if out['retcode']:
# System does not supports all accounts descriptions, just skipping.
... | Return all known accounts, excluding local accounts. | Below is the the instruction that describes the task:
### Input:
Return all known accounts, excluding local accounts.
### Response:
def _get_external_accounts(self, locals):
'''
Return all known accounts, excluding local accounts.
'''
users = dict()
out = __salt__['cmd.run_a... |
def __advancePhase(self):
""" Advance to the next iteration cycle phase
"""
self.__currentPhase = self.__phaseCycler.next()
self.__currentPhase.enterPhase()
return | Advance to the next iteration cycle phase | Below is the the instruction that describes the task:
### Input:
Advance to the next iteration cycle phase
### Response:
def __advancePhase(self):
""" Advance to the next iteration cycle phase
"""
self.__currentPhase = self.__phaseCycler.next()
self.__currentPhase.enterPhase()
return |
def create_database(name, owner=None, owner_host='localhost', charset='utf8',
collate='utf8_general_ci', **kwargs):
"""
Create a MySQL database.
Example::
import burlap
# Create DB if it does not exist
if not burlap.mysql.database_exists('myapp'):
b... | Create a MySQL database.
Example::
import burlap
# Create DB if it does not exist
if not burlap.mysql.database_exists('myapp'):
burlap.mysql.create_database('myapp', owner='dbuser') | Below is the the instruction that describes the task:
### Input:
Create a MySQL database.
Example::
import burlap
# Create DB if it does not exist
if not burlap.mysql.database_exists('myapp'):
burlap.mysql.create_database('myapp', owner='dbuser')
### Response:
def create_... |
def _update_inernal(self, varp_list):
"""Make an update of the internal status by gathering the variational posteriors for all the individual models."""
# The probability for the binary variable for the same latent dimension of any of the models is on.
self._b_prob_all = 1.-param_to_array(varp_l... | Make an update of the internal status by gathering the variational posteriors for all the individual models. | Below is the the instruction that describes the task:
### Input:
Make an update of the internal status by gathering the variational posteriors for all the individual models.
### Response:
def _update_inernal(self, varp_list):
"""Make an update of the internal status by gathering the variational posteriors ... |
def set_kill_on_exit_mode(bKillOnExit = False):
"""
Defines the behavior of the debugged processes when the debugging
thread dies. This method only affects the calling thread.
Works on the following platforms:
- Microsoft Windows XP and above.
- Wine (Windows Emulator... | Defines the behavior of the debugged processes when the debugging
thread dies. This method only affects the calling thread.
Works on the following platforms:
- Microsoft Windows XP and above.
- Wine (Windows Emulator).
Fails on the following platforms:
- Microsoft ... | Below is the the instruction that describes the task:
### Input:
Defines the behavior of the debugged processes when the debugging
thread dies. This method only affects the calling thread.
Works on the following platforms:
- Microsoft Windows XP and above.
- Wine (Windows Emulato... |
def main():
"""Controls the flow of the ddg application"""
'Build the parser and parse the arguments'
parser = argparse.ArgumentParser(
description='www.duckduckgo.com zero-click api for your command-line'
)
parser.add_argument('query', nargs='*', help='the search query')
parser.add_arg... | Controls the flow of the ddg application | Below is the the instruction that describes the task:
### Input:
Controls the flow of the ddg application
### Response:
def main():
"""Controls the flow of the ddg application"""
'Build the parser and parse the arguments'
parser = argparse.ArgumentParser(
description='www.duckduckgo.com zero-c... |
def process_all_common_disease_files(self, limit=None):
"""
Loop through all of the files that we previously fetched from git,
creating the disease-phenotype association.
:param limit:
:return:
"""
LOG.info("Iterating over all common disease files")
commo... | Loop through all of the files that we previously fetched from git,
creating the disease-phenotype association.
:param limit:
:return: | Below is the the instruction that describes the task:
### Input:
Loop through all of the files that we previously fetched from git,
creating the disease-phenotype association.
:param limit:
:return:
### Response:
def process_all_common_disease_files(self, limit=None):
"""
Lo... |
def grid(self, dimensions=None, **kwargs):
"""
Groups data by supplied dimension(s) laying the groups along
the dimension(s) out in a GridSpace.
Args:
dimensions: Dimension/str or list
Dimension or list of dimensions to group by
Returns:
grid: GridSp... | Groups data by supplied dimension(s) laying the groups along
the dimension(s) out in a GridSpace.
Args:
dimensions: Dimension/str or list
Dimension or list of dimensions to group by
Returns:
grid: GridSpace
GridSpace with supplied dimensions | Below is the the instruction that describes the task:
### Input:
Groups data by supplied dimension(s) laying the groups along
the dimension(s) out in a GridSpace.
Args:
dimensions: Dimension/str or list
Dimension or list of dimensions to group by
Returns:
grid: ... |
def global_confirm(question, default=True):
"""Shows a confirmation that applies to all hosts
by temporarily disabling parallel execution in Fabric
"""
if env.abort_on_prompts:
return True
original_parallel = env.parallel
env.parallel = False
result = confirm(question, default)
e... | Shows a confirmation that applies to all hosts
by temporarily disabling parallel execution in Fabric | Below is the the instruction that describes the task:
### Input:
Shows a confirmation that applies to all hosts
by temporarily disabling parallel execution in Fabric
### Response:
def global_confirm(question, default=True):
"""Shows a confirmation that applies to all hosts
by temporarily disabling para... |
def localized_fact(self):
"""Make sure fact has the correct start_time."""
fact = Fact(self.activity.get_text())
if fact.start_time:
fact.date = self.date
else:
fact.start_time = dt.datetime.now()
return fact | Make sure fact has the correct start_time. | Below is the the instruction that describes the task:
### Input:
Make sure fact has the correct start_time.
### Response:
def localized_fact(self):
"""Make sure fact has the correct start_time."""
fact = Fact(self.activity.get_text())
if fact.start_time:
fact.date = self.date
... |
def servers(self):
"""gets all the server resources"""
self.__init()
items = []
for k,v in self._json_dict.items():
if k == "servers":
for s in v:
if 'id' in s:
url = "%s/%s" % (self.root, s['id'])
... | gets all the server resources | Below is the the instruction that describes the task:
### Input:
gets all the server resources
### Response:
def servers(self):
"""gets all the server resources"""
self.__init()
items = []
for k,v in self._json_dict.items():
if k == "servers":
for s in v:... |
def get_output_from_steps(stmt, last_step):
'''
Extract output_from(1), output_from('step_1'), and output_from([1, 2])
to determine dependent steps
'''
opt_values = get_param_of_function(
'output_from', stmt, extra_dict=env.sos_dict.dict())
def step_name(val):
if isinstance(val,... | Extract output_from(1), output_from('step_1'), and output_from([1, 2])
to determine dependent steps | Below is the the instruction that describes the task:
### Input:
Extract output_from(1), output_from('step_1'), and output_from([1, 2])
to determine dependent steps
### Response:
def get_output_from_steps(stmt, last_step):
'''
Extract output_from(1), output_from('step_1'), and output_from([1, 2])
t... |
def send_card(self, user_id, card_id, card_ext=None, account=None):
"""
发送卡券消息
详情请参参考
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140547
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param card_id: 卡券 ID
:param card_ext: 可选,卡券扩展信息
:pa... | 发送卡券消息
详情请参参考
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140547
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param card_id: 卡券 ID
:param card_ext: 可选,卡券扩展信息
:param account: 可选,客服账号
:return: 返回的 JSON 数据包 | Below is the the instruction that describes the task:
### Input:
发送卡券消息
详情请参参考
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140547
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param card_id: 卡券 ID
:param card_ext: 可选,卡券扩展信息
:param account: 可选,客服账... |
def save(self, filepath):
"""Save current configuration to file.
:param str filepath: Path to file where settings will be saved.
:raises: ValueError if supplied filepath cannot be written to.
"""
self._config.add_section("RetryPolicy")
self._config.set("RetryPolicy", "re... | Save current configuration to file.
:param str filepath: Path to file where settings will be saved.
:raises: ValueError if supplied filepath cannot be written to. | Below is the the instruction that describes the task:
### Input:
Save current configuration to file.
:param str filepath: Path to file where settings will be saved.
:raises: ValueError if supplied filepath cannot be written to.
### Response:
def save(self, filepath):
"""Save current config... |
def reverse_list_ipv6(self, subid, params=None):
''' /v1/server/reverse_list_ipv6
GET - account
List the IPv6 reverse DNS entries of a virtual machine. Reverse DNS
entries are only available for virtual machines in the "active" state.
If the virtual machine does not have IPv6 ena... | /v1/server/reverse_list_ipv6
GET - account
List the IPv6 reverse DNS entries of a virtual machine. Reverse DNS
entries are only available for virtual machines in the "active" state.
If the virtual machine does not have IPv6 enabled, then an empty array
is returned.
Link:... | Below is the the instruction that describes the task:
### Input:
/v1/server/reverse_list_ipv6
GET - account
List the IPv6 reverse DNS entries of a virtual machine. Reverse DNS
entries are only available for virtual machines in the "active" state.
If the virtual machine does not have ... |
def compare_lists(old=None, new=None):
'''
Compare before and after results from various salt functions, returning a
dict describing the changes that were made
'''
ret = dict()
for item in new:
if item not in old:
ret['new'] = item
for item in old:
if item not in ... | Compare before and after results from various salt functions, returning a
dict describing the changes that were made | Below is the the instruction that describes the task:
### Input:
Compare before and after results from various salt functions, returning a
dict describing the changes that were made
### Response:
def compare_lists(old=None, new=None):
'''
Compare before and after results from various salt functions, re... |
def main():
"""
This is the main module for the script. The script will accept a file, or a directory, and then
encrypt it with a provided key before pushing it to S3 into a specified bucket.
"""
parser = argparse.ArgumentParser(description=main.__doc__, add_help=True)
parser.add_argument('-M',... | This is the main module for the script. The script will accept a file, or a directory, and then
encrypt it with a provided key before pushing it to S3 into a specified bucket. | Below is the the instruction that describes the task:
### Input:
This is the main module for the script. The script will accept a file, or a directory, and then
encrypt it with a provided key before pushing it to S3 into a specified bucket.
### Response:
def main():
"""
This is the main module for the... |
def get_characters(self, *args, **kwargs):
"""Fetches lists of comic characters with optional filters.
get /v1/public/characters/{characterId}
:returns: CharacterDataWrapper
>>> m = Marvel(public_key, private_key)
>>> cdw = m.get_characters(orderBy="name,-modified", limit="5"... | Fetches lists of comic characters with optional filters.
get /v1/public/characters/{characterId}
:returns: CharacterDataWrapper
>>> m = Marvel(public_key, private_key)
>>> cdw = m.get_characters(orderBy="name,-modified", limit="5", offset="15")
>>> print cdw.data.count
... | Below is the the instruction that describes the task:
### Input:
Fetches lists of comic characters with optional filters.
get /v1/public/characters/{characterId}
:returns: CharacterDataWrapper
>>> m = Marvel(public_key, private_key)
>>> cdw = m.get_characters(orderBy="name,-modif... |
def configureLogger(self):
"""
Configures the python logging system to log to a debug file and to stdout for warn and above.
:return: the base logger.
"""
baseLogLevel = logging.DEBUG if self.isDebugLogging() else logging.INFO
# create recorder app root logger
log... | Configures the python logging system to log to a debug file and to stdout for warn and above.
:return: the base logger. | Below is the the instruction that describes the task:
### Input:
Configures the python logging system to log to a debug file and to stdout for warn and above.
:return: the base logger.
### Response:
def configureLogger(self):
"""
Configures the python logging system to log to a debug file a... |
def sql_context(self, application_name):
"""Create a spark context given the parameters configured in this class.
The caller is responsible for calling ``.close`` on the resulting spark context
Parameters
----------
application_name : string
Returns
-------
... | Create a spark context given the parameters configured in this class.
The caller is responsible for calling ``.close`` on the resulting spark context
Parameters
----------
application_name : string
Returns
-------
sc : SparkContext | Below is the the instruction that describes the task:
### Input:
Create a spark context given the parameters configured in this class.
The caller is responsible for calling ``.close`` on the resulting spark context
Parameters
----------
application_name : string
Returns
... |
def exists(project, credentials):
"""Check if the project exists"""
user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable
printdebug("Checking if project " + project + " exists for " + user)
return os.path.isdir(Project.path(project, user)) | Check if the project exists | Below is the the instruction that describes the task:
### Input:
Check if the project exists
### Response:
def exists(project, credentials):
"""Check if the project exists"""
user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable
printdebug("Checking if pr... |
def _parse_proto(prototxt_fname):
"""Parse Caffe prototxt into symbol string
"""
proto = caffe_parser.read_prototxt(prototxt_fname)
# process data layer
input_name, input_dim, layers = _get_input(proto)
# only support single input, so always use `data` as the input data
mapping = {input_nam... | Parse Caffe prototxt into symbol string | Below is the the instruction that describes the task:
### Input:
Parse Caffe prototxt into symbol string
### Response:
def _parse_proto(prototxt_fname):
"""Parse Caffe prototxt into symbol string
"""
proto = caffe_parser.read_prototxt(prototxt_fname)
# process data layer
input_name, input_dim,... |
def updateHistory(self, activeCells, forceOutput=False):
"""
Computes one cycle of the Union Pooler algorithm. Return the union SDR
Parameters:
----------------------------
@param activeCells: A list that stores indices of active cells
@param forceOutput: if True, a union will be created withou... | Computes one cycle of the Union Pooler algorithm. Return the union SDR
Parameters:
----------------------------
@param activeCells: A list that stores indices of active cells
@param forceOutput: if True, a union will be created without regard to
minHistory | Below is the the instruction that describes the task:
### Input:
Computes one cycle of the Union Pooler algorithm. Return the union SDR
Parameters:
----------------------------
@param activeCells: A list that stores indices of active cells
@param forceOutput: if True, a union will be created withou... |
def find_assign(data, varname):
"""Finds a substring that looks like an assignment.
:param data: Source to search in.
:param varname: Name of the variable for which an assignment should be
found.
"""
ASSIGN_RE = re.compile(BASE_ASSIGN_PATTERN.format(varname))
if len(ASSIGN_... | Finds a substring that looks like an assignment.
:param data: Source to search in.
:param varname: Name of the variable for which an assignment should be
found. | Below is the the instruction that describes the task:
### Input:
Finds a substring that looks like an assignment.
:param data: Source to search in.
:param varname: Name of the variable for which an assignment should be
found.
### Response:
def find_assign(data, varname):
"""Finds a... |
def create_or_update_record(self, dns_type, name, content, **kwargs):
"""
Create a dns record. Update it if the record already exists.
:param dns_type:
:param name:
:param content:
:param kwargs:
:return:
"""
try:
return self.update_rec... | Create a dns record. Update it if the record already exists.
:param dns_type:
:param name:
:param content:
:param kwargs:
:return: | Below is the the instruction that describes the task:
### Input:
Create a dns record. Update it if the record already exists.
:param dns_type:
:param name:
:param content:
:param kwargs:
:return:
### Response:
def create_or_update_record(self, dns_type, name, content, **kwar... |
def create_geoms(self, plot):
"""
This guide is not geom based
Return self if colorbar will be drawn and None if not.
"""
for l in plot.layers:
exclude = set()
if isinstance(l.show_legend, dict):
l.show_legend = rename_aesthetics(l.show_le... | This guide is not geom based
Return self if colorbar will be drawn and None if not. | Below is the the instruction that describes the task:
### Input:
This guide is not geom based
Return self if colorbar will be drawn and None if not.
### Response:
def create_geoms(self, plot):
"""
This guide is not geom based
Return self if colorbar will be drawn and None if not.
... |
def delete(self):
"""
Explicit destructor of the internal SAT oracle and the
:class:`.ITotalizer` object.
"""
if self.oracle:
self.oracle.delete()
self.oracle = None
if self.tot:
self.tot.delete()
self.tot = None | Explicit destructor of the internal SAT oracle and the
:class:`.ITotalizer` object. | Below is the the instruction that describes the task:
### Input:
Explicit destructor of the internal SAT oracle and the
:class:`.ITotalizer` object.
### Response:
def delete(self):
"""
Explicit destructor of the internal SAT oracle and the
:class:`.ITotalizer` object.
... |
def comparable(self):
"""Return a dictionary that can be compared"""
document_dict = self.compare_safe(self._document)
# Remove uncompared fields
self._remove_keys(document_dict, self._uncompared_fields)
# Remove any empty values
clean_document_dict = {}
for k, ... | Return a dictionary that can be compared | Below is the the instruction that describes the task:
### Input:
Return a dictionary that can be compared
### Response:
def comparable(self):
"""Return a dictionary that can be compared"""
document_dict = self.compare_safe(self._document)
# Remove uncompared fields
self._remove_key... |
def _update_plotting_params(self, **kwargs):
"""Some plotting parameters can be changed through the tool; this
updataes those plotting parameters.
"""
scalars = kwargs.get('scalars', None)
if scalars is not None:
old = self.display_params['scalars']
self.d... | Some plotting parameters can be changed through the tool; this
updataes those plotting parameters. | Below is the the instruction that describes the task:
### Input:
Some plotting parameters can be changed through the tool; this
updataes those plotting parameters.
### Response:
def _update_plotting_params(self, **kwargs):
"""Some plotting parameters can be changed through the tool; this
up... |
def menu(self, venue_id, date):
"""Get the menu for the venue corresponding to venue_id,
on date.
:param venue_id:
A string representing the id of a venue, e.g. "abc".
:param date:
A string representing the date of a venue's menu, e.g. "2015-09-20".
>>> com... | Get the menu for the venue corresponding to venue_id,
on date.
:param venue_id:
A string representing the id of a venue, e.g. "abc".
:param date:
A string representing the date of a venue's menu, e.g. "2015-09-20".
>>> commons_menu = din.menu("593", "2015-09-20") | Below is the the instruction that describes the task:
### Input:
Get the menu for the venue corresponding to venue_id,
on date.
:param venue_id:
A string representing the id of a venue, e.g. "abc".
:param date:
A string representing the date of a venue's menu, e.g. "2015... |
def is_token_valid(token, margin=None):
"""Timezone-aware checking of the auth token's expiration timestamp.
Returns ``True`` if the token has not yet expired, otherwise ``False``.
:param token: The openstack_auth.user.Token instance to check
:param margin:
A time margin in seconds to subtract... | Timezone-aware checking of the auth token's expiration timestamp.
Returns ``True`` if the token has not yet expired, otherwise ``False``.
:param token: The openstack_auth.user.Token instance to check
:param margin:
A time margin in seconds to subtract from the real token's validity.
An exam... | Below is the the instruction that describes the task:
### Input:
Timezone-aware checking of the auth token's expiration timestamp.
Returns ``True`` if the token has not yet expired, otherwise ``False``.
:param token: The openstack_auth.user.Token instance to check
:param margin:
A time margin ... |
def _get_instance_path(self, name):
"Return a path to the pickled data with key ``name``."
fname = self.pattern.format(**{'name': name})
logger.debug(f'path {self.create_path}: {self.create_path.exists()}')
self._create_path_dir()
return Path(self.create_path, fname) | Return a path to the pickled data with key ``name``. | Below is the the instruction that describes the task:
### Input:
Return a path to the pickled data with key ``name``.
### Response:
def _get_instance_path(self, name):
"Return a path to the pickled data with key ``name``."
fname = self.pattern.format(**{'name': name})
logger.debug(f'path {s... |
def _get_dynamic_base(self, bases_):
"""Create or get the base space from a list of spaces
if a direct base space in `bases` is dynamic, replace it with
its base.
"""
bases = tuple(
base.bases[0] if base.is_dynamic() else base for base in bases_
)
if... | Create or get the base space from a list of spaces
if a direct base space in `bases` is dynamic, replace it with
its base. | Below is the the instruction that describes the task:
### Input:
Create or get the base space from a list of spaces
if a direct base space in `bases` is dynamic, replace it with
its base.
### Response:
def _get_dynamic_base(self, bases_):
"""Create or get the base space from a list of spac... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.