code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def all(self, store_id, product_id, get_all=False, **queryparams):
"""
Get information about a product’s images.
:param store_id: The store id.
:type store_id: :py:class:`str`
:param product_id: The id for the product of a store.
:type product_id: :py:class:`str`
... | Get information about a product’s images.
:param store_id: The store id.
:type store_id: :py:class:`str`
:param product_id: The id for the product of a store.
:type product_id: :py:class:`str`
:param get_all: Should the query get all results
:type get_all: :py:class:`boo... | Below is the the instruction that describes the task:
### Input:
Get information about a product’s images.
:param store_id: The store id.
:type store_id: :py:class:`str`
:param product_id: The id for the product of a store.
:type product_id: :py:class:`str`
:param get_all: S... |
def trigger(self, name, *args, **kwargs):
"""
Triggers an event to run through middleware. This method will execute
a chain of relevant trigger callbacks, until one of the callbacks
returns the `break_trigger`.
"""
# Relevant middleware is cached so we don't have to redi... | Triggers an event to run through middleware. This method will execute
a chain of relevant trigger callbacks, until one of the callbacks
returns the `break_trigger`. | Below is the the instruction that describes the task:
### Input:
Triggers an event to run through middleware. This method will execute
a chain of relevant trigger callbacks, until one of the callbacks
returns the `break_trigger`.
### Response:
def trigger(self, name, *args, **kwargs):
"""
... |
def add_graph(
self,
y,
x_label=None,
y_label="",
title="",
x_run=None,
y_run=None,
svg_size_px=None,
key_position="bottom right",
):
"""
Add a new graph to the overlap report.
Args:
y (str): Value plotted on y-axis.
x_label ... | Add a new graph to the overlap report.
Args:
y (str): Value plotted on y-axis.
x_label (str): Label on x-axis.
y_label (str): Label on y-axis.
title (str): Title of the plot.
x_run ((float,float)): x-range.
y_run ((int,int)): y-rang.
svg_size_px ((int,int): Size of SVG image in pixels.
key_po... | Below is the the instruction that describes the task:
### Input:
Add a new graph to the overlap report.
Args:
y (str): Value plotted on y-axis.
x_label (str): Label on x-axis.
y_label (str): Label on y-axis.
title (str): Title of the plot.
x_run ((float,float)): x-range.
y_run ((int,int)): y-ra... |
def delete_run():
"""
Delete the selected run from the database.
:return:
"""
assert request.method == "POST", "POST request expected received {}".format(request.method)
if request.method == "POST":
try:
selections = json.loads(request.form["selections"])
utils.dr... | Delete the selected run from the database.
:return: | Below is the the instruction that describes the task:
### Input:
Delete the selected run from the database.
:return:
### Response:
def delete_run():
"""
Delete the selected run from the database.
:return:
"""
assert request.method == "POST", "POST request expected received {}".format(reques... |
def init_gaussian_hmm(observations, nstates, lag=1, reversible=True):
""" Use a heuristic scheme to generate an initial model.
Parameters
----------
observations : list of ndarray((T_i))
list of arrays of length T_i with observation data
nstates : int
The number of states.
Exam... | Use a heuristic scheme to generate an initial model.
Parameters
----------
observations : list of ndarray((T_i))
list of arrays of length T_i with observation data
nstates : int
The number of states.
Examples
--------
Generate initial model for a gaussian output model.
... | Below is the the instruction that describes the task:
### Input:
Use a heuristic scheme to generate an initial model.
Parameters
----------
observations : list of ndarray((T_i))
list of arrays of length T_i with observation data
nstates : int
The number of states.
Examples
... |
def compute_geometric_median(X, eps=1e-5):
"""
Estimate the geometric median of points in 2D.
Code from https://stackoverflow.com/a/30305181
Parameters
----------
X : (N,2) ndarray
Points in 2D. Second axis must be given in xy-form.
eps : float, optional
Distance threshold... | Estimate the geometric median of points in 2D.
Code from https://stackoverflow.com/a/30305181
Parameters
----------
X : (N,2) ndarray
Points in 2D. Second axis must be given in xy-form.
eps : float, optional
Distance threshold when to return the median.
Returns
-------
... | Below is the the instruction that describes the task:
### Input:
Estimate the geometric median of points in 2D.
Code from https://stackoverflow.com/a/30305181
Parameters
----------
X : (N,2) ndarray
Points in 2D. Second axis must be given in xy-form.
eps : float, optional
Dist... |
def stats_timing(stats_key, stats_logger):
"""Provide a transactional scope around a series of operations."""
start_ts = now_as_float()
try:
yield start_ts
except Exception as e:
raise e
finally:
stats_logger.timing(stats_key, now_as_float() - start_ts) | Provide a transactional scope around a series of operations. | Below is the the instruction that describes the task:
### Input:
Provide a transactional scope around a series of operations.
### Response:
def stats_timing(stats_key, stats_logger):
"""Provide a transactional scope around a series of operations."""
start_ts = now_as_float()
try:
yield start_ts... |
def find_by_ids(ids, _connection=None, page_size=100, page_number=0,
sort_by=enums.DEFAULT_SORT_BY, sort_order=enums.DEFAULT_SORT_ORDER):
"""
List all videos identified by a list of Brightcove video ids
"""
if not isinstance(ids, (list, tuple)):
err = "Video.find_by_i... | List all videos identified by a list of Brightcove video ids | Below is the the instruction that describes the task:
### Input:
List all videos identified by a list of Brightcove video ids
### Response:
def find_by_ids(ids, _connection=None, page_size=100, page_number=0,
sort_by=enums.DEFAULT_SORT_BY, sort_order=enums.DEFAULT_SORT_ORDER):
"""
List all ... |
def drange(start, stop, step):
"""
A generator that yields successive samples from start (inclusive)
to stop (exclusive) in step intervals.
Parameters
----------
start : float
starting point
stop : float
stopping point
step : float
stepping interval
Yields
... | A generator that yields successive samples from start (inclusive)
to stop (exclusive) in step intervals.
Parameters
----------
start : float
starting point
stop : float
stopping point
step : float
stepping interval
Yields
------
x : float
next sampl... | Below is the the instruction that describes the task:
### Input:
A generator that yields successive samples from start (inclusive)
to stop (exclusive) in step intervals.
Parameters
----------
start : float
starting point
stop : float
stopping point
step : float
step... |
def js_exec(self, method: str, *args: Union[int, str, bool]) -> None:
"""Execute ``method`` in the related node on browser.
Other keyword arguments are passed to ``params`` attribute.
If this node is not in any document tree (namely, this node does not
have parent node), the ``method`` ... | Execute ``method`` in the related node on browser.
Other keyword arguments are passed to ``params`` attribute.
If this node is not in any document tree (namely, this node does not
have parent node), the ``method`` is not executed. | Below is the the instruction that describes the task:
### Input:
Execute ``method`` in the related node on browser.
Other keyword arguments are passed to ``params`` attribute.
If this node is not in any document tree (namely, this node does not
have parent node), the ``method`` is not execu... |
def nics_skip(name, nics, ipv6):
'''
Alias for :mod:`csf.nics_skipped <salt.states.csf.nics_skipped>`
'''
return nics_skipped(name, nics=nics, ipv6=ipv6) | Alias for :mod:`csf.nics_skipped <salt.states.csf.nics_skipped>` | Below is the the instruction that describes the task:
### Input:
Alias for :mod:`csf.nics_skipped <salt.states.csf.nics_skipped>`
### Response:
def nics_skip(name, nics, ipv6):
'''
Alias for :mod:`csf.nics_skipped <salt.states.csf.nics_skipped>`
'''
return nics_skipped(name, nics=nics, ipv6=ipv6) |
def nvmlUnitSetLedState(unit, color):
r"""
/**
* Set the LED state for the unit. The LED can be either green (0) or amber (1).
*
* For S-class products.
* Requires root/admin permissions.
*
* This operation takes effect immediately.
*
*
* <b>Current S-Class products ... | r"""
/**
* Set the LED state for the unit. The LED can be either green (0) or amber (1).
*
* For S-class products.
* Requires root/admin permissions.
*
* This operation takes effect immediately.
*
*
* <b>Current S-Class products don't provide unique LEDs for each unit. A... | Below is the the instruction that describes the task:
### Input:
r"""
/**
* Set the LED state for the unit. The LED can be either green (0) or amber (1).
*
* For S-class products.
* Requires root/admin permissions.
*
* This operation takes effect immediately.
*
*
* <... |
def tradeStatus(self, trade_id):
"""Return trade status.
:params trade_id: Trade id.
"""
method = 'GET'
url = 'trade/status'
if not isinstance(trade_id, (list, tuple)):
trade_id = (trade_id,)
trade_id = (str(i) for i in trade_id)
params = {'t... | Return trade status.
:params trade_id: Trade id. | Below is the the instruction that describes the task:
### Input:
Return trade status.
:params trade_id: Trade id.
### Response:
def tradeStatus(self, trade_id):
"""Return trade status.
:params trade_id: Trade id.
"""
method = 'GET'
url = 'trade/status'
if ... |
def _simsearch_to_simresult(self, sim_resp: Dict, method: SimAlgorithm) -> SimResult:
"""
Convert owlsim json to SimResult object
:param sim_resp: owlsim response from search_by_attribute_set()
:param method: SimAlgorithm
:return: SimResult object
"""
sim_ids = ... | Convert owlsim json to SimResult object
:param sim_resp: owlsim response from search_by_attribute_set()
:param method: SimAlgorithm
:return: SimResult object | Below is the the instruction that describes the task:
### Input:
Convert owlsim json to SimResult object
:param sim_resp: owlsim response from search_by_attribute_set()
:param method: SimAlgorithm
:return: SimResult object
### Response:
def _simsearch_to_simresult(self, sim_resp: Dict, met... |
def rule(ctx, rule):
""" [bookie] Show a specific rule
:param str bmg: Betting market id
"""
rule = Rule(rule, peerplays_instance=ctx.peerplays)
t = PrettyTable([
"id",
"name",
])
t.align = "l"
t.add_row([
rule["id"],
"\n".join(["{}: {}".format(v[0], ... | [bookie] Show a specific rule
:param str bmg: Betting market id | Below is the the instruction that describes the task:
### Input:
[bookie] Show a specific rule
:param str bmg: Betting market id
### Response:
def rule(ctx, rule):
""" [bookie] Show a specific rule
:param str bmg: Betting market id
"""
rule = Rule(rule, peerplays_instance=ctx.peerplay... |
def package_files(directory):
"""Get list of data files to add to the package."""
paths = []
for (path, _, file_names) in walk(directory):
for filename in file_names:
paths.append(join('..', path, filename))
return paths | Get list of data files to add to the package. | Below is the the instruction that describes the task:
### Input:
Get list of data files to add to the package.
### Response:
def package_files(directory):
"""Get list of data files to add to the package."""
paths = []
for (path, _, file_names) in walk(directory):
for filename in file_names:
... |
def rsdl_rn(self, AX, Y):
"""Compute primal residual normalisation term.
Overriding this method is required if methods :meth:`cnst_A`,
:meth:`cnst_AT`, :meth:`cnst_B`, and :meth:`cnst_c` are not
overridden.
"""
if not hasattr(self, '_cnst_nrm_c'):
self._cnst... | Compute primal residual normalisation term.
Overriding this method is required if methods :meth:`cnst_A`,
:meth:`cnst_AT`, :meth:`cnst_B`, and :meth:`cnst_c` are not
overridden. | Below is the the instruction that describes the task:
### Input:
Compute primal residual normalisation term.
Overriding this method is required if methods :meth:`cnst_A`,
:meth:`cnst_AT`, :meth:`cnst_B`, and :meth:`cnst_c` are not
overridden.
### Response:
def rsdl_rn(self, AX, Y):
... |
def get_stream_records(self, iterator_id):
"""Wraps :func:`boto3.DynamoDBStreams.Client.get_records`.
:param iterator_id: Iterator id. Usually :data:`Shard.iterator_id <bloop.stream.shard.Shard.iterator_id>`.
:return: Dict with "Records" list (may be empty) and "NextShardIterator" str (may not... | Wraps :func:`boto3.DynamoDBStreams.Client.get_records`.
:param iterator_id: Iterator id. Usually :data:`Shard.iterator_id <bloop.stream.shard.Shard.iterator_id>`.
:return: Dict with "Records" list (may be empty) and "NextShardIterator" str (may not exist).
:rtype: dict
:raises bloop.ex... | Below is the the instruction that describes the task:
### Input:
Wraps :func:`boto3.DynamoDBStreams.Client.get_records`.
:param iterator_id: Iterator id. Usually :data:`Shard.iterator_id <bloop.stream.shard.Shard.iterator_id>`.
:return: Dict with "Records" list (may be empty) and "NextShardIterato... |
def get_profile_configs(profile=None, use_cache=True):
"""
Returns upload configs for profile.
"""
if use_cache and profile in _profile_configs_cache:
return _profile_configs_cache[profile]
profile_conf = None
if profile is not None:
try:
profile_conf = dju_settings.D... | Returns upload configs for profile. | Below is the the instruction that describes the task:
### Input:
Returns upload configs for profile.
### Response:
def get_profile_configs(profile=None, use_cache=True):
"""
Returns upload configs for profile.
"""
if use_cache and profile in _profile_configs_cache:
return _profile_configs_c... |
def service_timeouts(self):
"""
run callbacks on all expired timers
Called from the event thread
:return: next end time, or None
"""
queue = self._queue
if self._new_timers:
new_timers = self._new_timers
while new_timers:
he... | run callbacks on all expired timers
Called from the event thread
:return: next end time, or None | Below is the the instruction that describes the task:
### Input:
run callbacks on all expired timers
Called from the event thread
:return: next end time, or None
### Response:
def service_timeouts(self):
"""
run callbacks on all expired timers
Called from the event thread
... |
def users_profile_get(self, **kwargs) -> SlackResponse:
"""Retrieves a user's profile information."""
self._validate_xoxp_token()
return self.api_call("users.profile.get", http_verb="GET", params=kwargs) | Retrieves a user's profile information. | Below is the the instruction that describes the task:
### Input:
Retrieves a user's profile information.
### Response:
def users_profile_get(self, **kwargs) -> SlackResponse:
"""Retrieves a user's profile information."""
self._validate_xoxp_token()
return self.api_call("users.profile.get", ... |
def p_delays_intnumber(self, p):
'delays : DELAY intnumber'
p[0] = DelayStatement(
IntConst(p[2], lineno=p.lineno(1)), lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | delays : DELAY intnumber | Below is the the instruction that describes the task:
### Input:
delays : DELAY intnumber
### Response:
def p_delays_intnumber(self, p):
'delays : DELAY intnumber'
p[0] = DelayStatement(
IntConst(p[2], lineno=p.lineno(1)), lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) |
def format_sizeof(num, suffix='bytes'):
'''Readable size format, courtesy of Sridhar Ratnakumar'''
for unit in ['','K','M','G','T','P','E','Z']:
if abs(num) < 1000.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1000.0
return "%.1f%s%s" % (num, 'Y', suffix) | Readable size format, courtesy of Sridhar Ratnakumar | Below is the the instruction that describes the task:
### Input:
Readable size format, courtesy of Sridhar Ratnakumar
### Response:
def format_sizeof(num, suffix='bytes'):
'''Readable size format, courtesy of Sridhar Ratnakumar'''
for unit in ['','K','M','G','T','P','E','Z']:
if abs(num) < 1000.0:
... |
def find_indentation(node):
"""Find the indentation of *node*."""
while node is not None:
if node.type == syms.suite and len(node.children) > 2:
indent = node.children[1]
if indent.type == token.INDENT:
return indent.value
node = node.parent
return u"" | Find the indentation of *node*. | Below is the the instruction that describes the task:
### Input:
Find the indentation of *node*.
### Response:
def find_indentation(node):
"""Find the indentation of *node*."""
while node is not None:
if node.type == syms.suite and len(node.children) > 2:
indent = node.children[1]
... |
def _repo_url_to_path(self, repo):
"""Convert a `repo` url to a file path for local storage."""
repo = repo.replace('http://', '')
repo = repo.replace('https://', '')
repo = repo.replace('/', '_')
return os.sep.join([self._data_directory, repo]) | Convert a `repo` url to a file path for local storage. | Below is the the instruction that describes the task:
### Input:
Convert a `repo` url to a file path for local storage.
### Response:
def _repo_url_to_path(self, repo):
"""Convert a `repo` url to a file path for local storage."""
repo = repo.replace('http://', '')
repo = repo.replace('https... |
def set_input_fields(self, input_fields):
"""Given a scalar or ordered list of strings generate JSONPaths
that describe how to access the values necessary for the Extractor """
if not (isinstance(input_fields, basestring) or
isinstance(input_fields, types.ListType)):
... | Given a scalar or ordered list of strings generate JSONPaths
that describe how to access the values necessary for the Extractor | Below is the the instruction that describes the task:
### Input:
Given a scalar or ordered list of strings generate JSONPaths
that describe how to access the values necessary for the Extractor
### Response:
def set_input_fields(self, input_fields):
"""Given a scalar or ordered list of strings gener... |
def merge(self, dict_=None):
"""not is use so far, see check()"""
if dict_ is None and hasattr(self, '__dict__'):
dict_ = self.__dict__
# doesn't work anymore as we have _lock attribute
if dict_ is None:
return self
self.update(dict_)
return ... | not is use so far, see check() | Below is the the instruction that describes the task:
### Input:
not is use so far, see check()
### Response:
def merge(self, dict_=None):
"""not is use so far, see check()"""
if dict_ is None and hasattr(self, '__dict__'):
dict_ = self.__dict__
# doesn't work anymore as w... |
def findall(self, obj, forced_type=None,
cls=anyconfig.models.processor.Processor):
"""
:param obj:
a file path, file, file-like object, pathlib.Path object or an
'anyconfig.globals.IOInfo' (namedtuple) object
:param forced_type: Forced processor type to f... | :param obj:
a file path, file, file-like object, pathlib.Path object or an
'anyconfig.globals.IOInfo' (namedtuple) object
:param forced_type: Forced processor type to find
:param cls: A class object to compare with 'ptype'
:return: A list of instances of processor classe... | Below is the the instruction that describes the task:
### Input:
:param obj:
a file path, file, file-like object, pathlib.Path object or an
'anyconfig.globals.IOInfo' (namedtuple) object
:param forced_type: Forced processor type to find
:param cls: A class object to compare w... |
def _populate_bookmarks_list(self):
"""Read the sqlite database and populate the bookmarks list.
If no bookmarks are found, the bookmarks radio button will be disabled
and the label will be shown indicating that the user should add
bookmarks in QGIS first.
Every bookmark are re... | Read the sqlite database and populate the bookmarks list.
If no bookmarks are found, the bookmarks radio button will be disabled
and the label will be shown indicating that the user should add
bookmarks in QGIS first.
Every bookmark are reprojected to mapcanvas crs. | Below is the the instruction that describes the task:
### Input:
Read the sqlite database and populate the bookmarks list.
If no bookmarks are found, the bookmarks radio button will be disabled
and the label will be shown indicating that the user should add
bookmarks in QGIS first.
... |
def import_obj(cls, i_datasource, import_time=None):
"""Imports the datasource from the object to the database.
Metrics and columns and datasource will be overrided if exists.
This function can be used to import/export dashboards between multiple
superset instances. Audit metadata is... | Imports the datasource from the object to the database.
Metrics and columns and datasource will be overrided if exists.
This function can be used to import/export dashboards between multiple
superset instances. Audit metadata isn't copies over. | Below is the the instruction that describes the task:
### Input:
Imports the datasource from the object to the database.
Metrics and columns and datasource will be overrided if exists.
This function can be used to import/export dashboards between multiple
superset instances. Audit metada... |
def stringify(*args):
"""
Joins args to build a string, unless there's one arg and it's a
function, then acts a decorator.
"""
if (len(args) == 1) and callable(args[0]):
func = args[0]
@wraps(func)
def _inner(*args, **kwargs):
return "".join([str(i) for i in func... | Joins args to build a string, unless there's one arg and it's a
function, then acts a decorator. | Below is the the instruction that describes the task:
### Input:
Joins args to build a string, unless there's one arg and it's a
function, then acts a decorator.
### Response:
def stringify(*args):
"""
Joins args to build a string, unless there's one arg and it's a
function, then acts a decorator.
... |
def deactivate_program(self, program):
"""
Called by program, when it is deactivated.
"""
self.logger.debug("deactivate_program %s", program)
with self._program_lock:
self.logger.debug("deactivate_program got through %s", program)
if program not in se... | Called by program, when it is deactivated. | Below is the the instruction that describes the task:
### Input:
Called by program, when it is deactivated.
### Response:
def deactivate_program(self, program):
"""
Called by program, when it is deactivated.
"""
self.logger.debug("deactivate_program %s", program)
with s... |
def taskotron_task(config, message, task=None):
""" Particular taskotron task
With this rule, you can limit messages to only those of particular
`taskotron <https://taskotron.fedoraproject.org/>`_ task.
You can specify several tasks by separating them with a comma ',',
i.e.: ``dist.depcheck,dist.r... | Particular taskotron task
With this rule, you can limit messages to only those of particular
`taskotron <https://taskotron.fedoraproject.org/>`_ task.
You can specify several tasks by separating them with a comma ',',
i.e.: ``dist.depcheck,dist.rpmlint``. | Below is the the instruction that describes the task:
### Input:
Particular taskotron task
With this rule, you can limit messages to only those of particular
`taskotron <https://taskotron.fedoraproject.org/>`_ task.
You can specify several tasks by separating them with a comma ',',
i.e.: ``dist.de... |
def match_examples(self, parse_fn, examples):
""" Given a parser instance and a dictionary mapping some label with
some malformed syntax examples, it'll return the label for the
example that bests matches the current error.
"""
assert self.state is not None, "Not supporte... | Given a parser instance and a dictionary mapping some label with
some malformed syntax examples, it'll return the label for the
example that bests matches the current error. | Below is the the instruction that describes the task:
### Input:
Given a parser instance and a dictionary mapping some label with
some malformed syntax examples, it'll return the label for the
example that bests matches the current error.
### Response:
def match_examples(self, parse_fn, exa... |
def history(self, user=None):
""" Return relevant who-did-what logs from the ticket history """
for event in self.changelog:
when, who, what, old, new, ignore = event
if (when >= self.options.since.date and
when <= self.options.until.date):
if ... | Return relevant who-did-what logs from the ticket history | Below is the the instruction that describes the task:
### Input:
Return relevant who-did-what logs from the ticket history
### Response:
def history(self, user=None):
""" Return relevant who-did-what logs from the ticket history """
for event in self.changelog:
when, who, what, old, new... |
def CreateDirectedEdges(self, points, gr, layer_width):
"""
Take each key (ie. point) in the graph and for that point
create an edge to every point downstream of it where the weight
of the edge is the tuple (distance, angle)
"""
for z0, x0, Q0 in points:
for z... | Take each key (ie. point) in the graph and for that point
create an edge to every point downstream of it where the weight
of the edge is the tuple (distance, angle) | Below is the the instruction that describes the task:
### Input:
Take each key (ie. point) in the graph and for that point
create an edge to every point downstream of it where the weight
of the edge is the tuple (distance, angle)
### Response:
def CreateDirectedEdges(self, points, gr, layer_width):... |
def child(self, number):
"""
:type number: int
:rtype: ProtocolTreeItem
"""
if number < self.childCount():
return self.__childItems[number]
else:
return False | :type number: int
:rtype: ProtocolTreeItem | Below is the the instruction that describes the task:
### Input:
:type number: int
:rtype: ProtocolTreeItem
### Response:
def child(self, number):
"""
:type number: int
:rtype: ProtocolTreeItem
"""
if number < self.childCount():
return self.__childItems[n... |
def _best_fit_font_size(self, family, max_size, bold, italic, font_file):
"""
Return the largest integer point size not greater than *max_size*
that allows all the text in this text frame to fit inside its extents
when rendered using the font described by *family*, *bold*, and
*i... | Return the largest integer point size not greater than *max_size*
that allows all the text in this text frame to fit inside its extents
when rendered using the font described by *family*, *bold*, and
*italic*. If *font_file* is specified, it is used to calculate the
fit, whether or not i... | Below is the the instruction that describes the task:
### Input:
Return the largest integer point size not greater than *max_size*
that allows all the text in this text frame to fit inside its extents
when rendered using the font described by *family*, *bold*, and
*italic*. If *font_file* is... |
def buildhtmlheader(self):
"""generate HTML header content"""
if self.drilldown_flag:
self.add_JSsource('http://code.highcharts.com/modules/drilldown.js')
if self.offline:
opener = urllib.request.build_opener()
opener.addheaders = [('User-Agent', '... | generate HTML header content | Below is the the instruction that describes the task:
### Input:
generate HTML header content
### Response:
def buildhtmlheader(self):
"""generate HTML header content"""
if self.drilldown_flag:
self.add_JSsource('http://code.highcharts.com/modules/drilldown.js')
if s... |
def write_points(self,
points,
time_precision=None,
database=None,
retention_policy=None,
tags=None,
batch_size=None,
protocol='json',
consistency=None
... | Write to multiple time series names.
:param points: the list of points to be written in the database
:type points: list of dictionaries, each dictionary represents a point
:type points: (if protocol is 'json') list of dicts, where each dict
represents... | Below is the the instruction that describes the task:
### Input:
Write to multiple time series names.
:param points: the list of points to be written in the database
:type points: list of dictionaries, each dictionary represents a point
:type points: (if protocol is 'json') list of dicts, w... |
def parse_broken_json(json_text: str) -> dict:
"""
Parses broken JSON that the standard Python JSON module cannot parse.
Ex: {success:true}
Keys do not contain quotes and the JSON cannot be parsed using the regular json encoder.
YAML happens to be a superset of JSON and can parse json without quot... | Parses broken JSON that the standard Python JSON module cannot parse.
Ex: {success:true}
Keys do not contain quotes and the JSON cannot be parsed using the regular json encoder.
YAML happens to be a superset of JSON and can parse json without quotes. | Below is the the instruction that describes the task:
### Input:
Parses broken JSON that the standard Python JSON module cannot parse.
Ex: {success:true}
Keys do not contain quotes and the JSON cannot be parsed using the regular json encoder.
YAML happens to be a superset of JSON and can parse json wi... |
def set_active_state(self, name, value):
"""Set active state."""
if name not in self.__active_states.keys():
raise ValueError("Can not set unknown state '" + name + "'")
if (isinstance(self.__active_states[name], int) and
isinstance(value, str)):
# we get... | Set active state. | Below is the the instruction that describes the task:
### Input:
Set active state.
### Response:
def set_active_state(self, name, value):
"""Set active state."""
if name not in self.__active_states.keys():
raise ValueError("Can not set unknown state '" + name + "'")
if (isinsta... |
def render_template_directory(deck, arguments):
"""Render a template directory"""
output_directory = dir_name_from_title(deck.title)
if os.path.exists(output_directory):
if sys.stdout.isatty():
if ask(
'%s already exists, shall I delete it?' % output_directory,
... | Render a template directory | Below is the the instruction that describes the task:
### Input:
Render a template directory
### Response:
def render_template_directory(deck, arguments):
"""Render a template directory"""
output_directory = dir_name_from_title(deck.title)
if os.path.exists(output_directory):
if sys.stdout.isa... |
def teardown_handles(self):
"""
If no custom update_handles method is supplied this method
is called to tear down any previous handles before replacing
them.
"""
if not isinstance(self.handles.get('artist'), GoogleTiles):
self.handles['artist'].remove() | If no custom update_handles method is supplied this method
is called to tear down any previous handles before replacing
them. | Below is the the instruction that describes the task:
### Input:
If no custom update_handles method is supplied this method
is called to tear down any previous handles before replacing
them.
### Response:
def teardown_handles(self):
"""
If no custom update_handles method is supplied... |
def status(name, sig=None):
'''
Return ``True`` if service is running
name
the service's name
sig
signature to identify with ps
CLI Example:
.. code-block:: bash
salt '*' runit.status <service name>
'''
if sig:
# usual way to do by others (debian_serv... | Return ``True`` if service is running
name
the service's name
sig
signature to identify with ps
CLI Example:
.. code-block:: bash
salt '*' runit.status <service name> | Below is the the instruction that describes the task:
### Input:
Return ``True`` if service is running
name
the service's name
sig
signature to identify with ps
CLI Example:
.. code-block:: bash
salt '*' runit.status <service name>
### Response:
def status(name, sig=Non... |
def trigger_create(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/chat/triggers#create-trigger"
api_path = "/api/v2/triggers"
return self.call(api_path, method="POST", data=data, **kwargs) | https://developer.zendesk.com/rest_api/docs/chat/triggers#create-trigger | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/chat/triggers#create-trigger
### Response:
def trigger_create(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/chat/triggers#create-trigger"
api_path = "/api/v2/triggers"
... |
def FlowProportions(
dem,
method = None,
exponent = None
):
"""Calculates flow proportions. A variety of methods are available.
Args:
dem (rdarray): An elevation model
method (str): Flow accumulation method to use. (See below.)
exponent (float): Some methods requi... | Calculates flow proportions. A variety of methods are available.
Args:
dem (rdarray): An elevation model
method (str): Flow accumulation method to use. (See below.)
exponent (float): Some methods require an exponent; refer to the
relevant publi... | Below is the the instruction that describes the task:
### Input:
Calculates flow proportions. A variety of methods are available.
Args:
dem (rdarray): An elevation model
method (str): Flow accumulation method to use. (See below.)
exponent (float): Some methods require a... |
def compile_bytecode(code: list) -> bytes:
"""
Compiles Pyte objects into a bytecode list.
:param code: A list of objects to compile.
:return: The computed bytecode.
"""
bc = b""
for i, op in enumerate(code):
try:
# Get the bytecode.
if isinstance(op, _PyteOp... | Compiles Pyte objects into a bytecode list.
:param code: A list of objects to compile.
:return: The computed bytecode. | Below is the the instruction that describes the task:
### Input:
Compiles Pyte objects into a bytecode list.
:param code: A list of objects to compile.
:return: The computed bytecode.
### Response:
def compile_bytecode(code: list) -> bytes:
"""
Compiles Pyte objects into a bytecode list.
:par... |
def AddAnalogShortIdRecordNoStatus(site_service, tag, time_value, value):
"""
This function will add an analog value to the specified eDNA service and
tag, without an associated point status.
:param site_service: The site.service where data will be pushed
:param tag: The eDNA tag to push data. Tag ... | This function will add an analog value to the specified eDNA service and
tag, without an associated point status.
:param site_service: The site.service where data will be pushed
:param tag: The eDNA tag to push data. Tag only (e.g. ADE1CA01)
:param time_value: The time of the point, which MUST be in UT... | Below is the the instruction that describes the task:
### Input:
This function will add an analog value to the specified eDNA service and
tag, without an associated point status.
:param site_service: The site.service where data will be pushed
:param tag: The eDNA tag to push data. Tag only (e.g. ADE1CA... |
def index():
"""List linked accounts."""
oauth = current_app.extensions['oauthlib.client']
services = []
service_map = {}
i = 0
for appid, conf in six.iteritems(
current_app.config['OAUTHCLIENT_REMOTE_APPS']):
if not conf.get('hide', False):
services.append(dict... | List linked accounts. | Below is the the instruction that describes the task:
### Input:
List linked accounts.
### Response:
def index():
"""List linked accounts."""
oauth = current_app.extensions['oauthlib.client']
services = []
service_map = {}
i = 0
for appid, conf in six.iteritems(
current_app.co... |
def update_payment_card_by_id(cls, payment_card_id, payment_card, **kwargs):
"""Update PaymentCard
Update attributes of PaymentCard
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_payme... | Update PaymentCard
Update attributes of PaymentCard
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_payment_card_by_id(payment_card_id, payment_card, async=True)
>>> result = thread.get... | Below is the the instruction that describes the task:
### Input:
Update PaymentCard
Update attributes of PaymentCard
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_payment_card_by_id(payme... |
def uninstall(self):
'''
Uninstall the module finder. If not installed, this will do nothing.
After uninstallation, none of the newly loaded modules will be
decorated (that is, everything will be back to normal).
'''
if self.installed:
sys.meta_path.remove(se... | Uninstall the module finder. If not installed, this will do nothing.
After uninstallation, none of the newly loaded modules will be
decorated (that is, everything will be back to normal). | Below is the the instruction that describes the task:
### Input:
Uninstall the module finder. If not installed, this will do nothing.
After uninstallation, none of the newly loaded modules will be
decorated (that is, everything will be back to normal).
### Response:
def uninstall(self):
'''... |
def Deserialize(self, reader):
"""
Deserialize full object.
Args:
reader (neocore.IO.BinaryReader):
"""
super(AssetState, self).Deserialize(reader)
self.AssetId = reader.ReadUInt256()
self.AssetType = reader.ReadByte()
self.Name = reader.ReadV... | Deserialize full object.
Args:
reader (neocore.IO.BinaryReader): | Below is the the instruction that describes the task:
### Input:
Deserialize full object.
Args:
reader (neocore.IO.BinaryReader):
### Response:
def Deserialize(self, reader):
"""
Deserialize full object.
Args:
reader (neocore.IO.BinaryReader):
"""
... |
def predict_compound_pairs_iterated(
reactions, formulas, prior=(1, 43), max_iterations=None,
element_weight=element_weight):
"""Predict reaction pairs using iterated method.
Returns a tuple containing a dictionary of predictions keyed by the
reaction IDs, and the final number of iterations... | Predict reaction pairs using iterated method.
Returns a tuple containing a dictionary of predictions keyed by the
reaction IDs, and the final number of iterations. Each reaction prediction
entry contains a tuple with a dictionary of transfers and a dictionary of
unbalanced compounds. The dictionary of ... | Below is the the instruction that describes the task:
### Input:
Predict reaction pairs using iterated method.
Returns a tuple containing a dictionary of predictions keyed by the
reaction IDs, and the final number of iterations. Each reaction prediction
entry contains a tuple with a dictionary of trans... |
def _meanprecision(D, tol=1e-7, maxiter=None):
'''Mean and precision alternating method for MLE of Dirichlet
distribution'''
N, K = D.shape
logp = log(D).mean(axis=0)
a0 = _init_a(D)
s0 = a0.sum()
if s0 < 0:
a0 = a0/s0
s0 = 1
elif s0 == 0:
a0 = ones(a.shape) / len... | Mean and precision alternating method for MLE of Dirichlet
distribution | Below is the the instruction that describes the task:
### Input:
Mean and precision alternating method for MLE of Dirichlet
distribution
### Response:
def _meanprecision(D, tol=1e-7, maxiter=None):
'''Mean and precision alternating method for MLE of Dirichlet
distribution'''
N, K = D.shape
logp... |
def run(self, args):
'''
Run the SPM command
'''
command = args[0]
try:
if command == 'install':
self._install(args)
elif command == 'local':
self._local(args)
elif command == 'repo':
self._repo(a... | Run the SPM command | Below is the the instruction that describes the task:
### Input:
Run the SPM command
### Response:
def run(self, args):
'''
Run the SPM command
'''
command = args[0]
try:
if command == 'install':
self._install(args)
elif command == 'lo... |
def fit(self, X, y=None):
"""
X : ANTsImage | string | list of ANTsImage types | list of strings
images to register to fixed image
y : string | list of strings
labels for images
"""
moving_images = X if isinstance(X, (list,tuple)) else [X]
moving_... | X : ANTsImage | string | list of ANTsImage types | list of strings
images to register to fixed image
y : string | list of strings
labels for images | Below is the the instruction that describes the task:
### Input:
X : ANTsImage | string | list of ANTsImage types | list of strings
images to register to fixed image
y : string | list of strings
labels for images
### Response:
def fit(self, X, y=None):
"""
X : ANTsI... |
def ToVM(self):
"""
Used for turning a ContractParameter item into somethnig consumable by the VM
Returns:
"""
if self.Type == ContractParameterType.String:
return str(self.Value).encode('utf-8').hex()
elif self.Type == ContractParameterType.Integer and isin... | Used for turning a ContractParameter item into somethnig consumable by the VM
Returns: | Below is the the instruction that describes the task:
### Input:
Used for turning a ContractParameter item into somethnig consumable by the VM
Returns:
### Response:
def ToVM(self):
"""
Used for turning a ContractParameter item into somethnig consumable by the VM
Returns:
... |
def _conglomerate_meshes(meshin, header):
"""Conglomerate meshes from several cores into one."""
meshout = {}
npc = header['nts'] // header['ncs']
shp = [val + 1 if val != 1 else 1 for val in header['nts']]
x_p = int(shp[0] != 1)
y_p = int(shp[1] != 1)
for coord in meshin[0]:
meshout... | Conglomerate meshes from several cores into one. | Below is the the instruction that describes the task:
### Input:
Conglomerate meshes from several cores into one.
### Response:
def _conglomerate_meshes(meshin, header):
"""Conglomerate meshes from several cores into one."""
meshout = {}
npc = header['nts'] // header['ncs']
shp = [val + 1 if val !=... |
def parse_timedelta(deltastr):
"""
Parse a string describing a period of time.
"""
matches = TIMEDELTA_REGEX.match(deltastr)
if not matches:
return None
components = {}
for name, value in matches.groupdict().items():
if value:
components[name] = int(value)
for... | Parse a string describing a period of time. | Below is the the instruction that describes the task:
### Input:
Parse a string describing a period of time.
### Response:
def parse_timedelta(deltastr):
"""
Parse a string describing a period of time.
"""
matches = TIMEDELTA_REGEX.match(deltastr)
if not matches:
return None
compone... |
def findall(lst, key, value):
"""
Find all items in lst where key matches value.
For example find all ``LAYER`` s in a ``MAP`` where ``GROUP`` equals ``VALUE``
Parameters
----------
list: list
A list of composite dictionaries e.g. ``layers``, ``classes``
key: string
The key... | Find all items in lst where key matches value.
For example find all ``LAYER`` s in a ``MAP`` where ``GROUP`` equals ``VALUE``
Parameters
----------
list: list
A list of composite dictionaries e.g. ``layers``, ``classes``
key: string
The key name to search each dictionary in the lis... | Below is the the instruction that describes the task:
### Input:
Find all items in lst where key matches value.
For example find all ``LAYER`` s in a ``MAP`` where ``GROUP`` equals ``VALUE``
Parameters
----------
list: list
A list of composite dictionaries e.g. ``layers``, ``classes``
... |
def register(model_or_iterable, **options):
"""
Registers the given model(s) with the given translation options.
The model(s) should be Model classes, not instances.
Fields declared for translation on a base class are inherited by
subclasses. If the model or one of its subclasses is already
re... | Registers the given model(s) with the given translation options.
The model(s) should be Model classes, not instances.
Fields declared for translation on a base class are inherited by
subclasses. If the model or one of its subclasses is already
registered for translation, this will raise an exception.
... | Below is the the instruction that describes the task:
### Input:
Registers the given model(s) with the given translation options.
The model(s) should be Model classes, not instances.
Fields declared for translation on a base class are inherited by
subclasses. If the model or one of its subclasses is a... |
def has_file(self, name: str):
'''
check whether this directory contains the file.
'''
return os.path.isfile(self._path / name) | check whether this directory contains the file. | Below is the the instruction that describes the task:
### Input:
check whether this directory contains the file.
### Response:
def has_file(self, name: str):
'''
check whether this directory contains the file.
'''
return os.path.isfile(self._path / name) |
def sort(self, key, *get_patterns,
by=None, offset=None, count=None,
asc=None, alpha=False, store=None):
"""Sort the elements in a list, set or sorted set."""
args = []
if by is not None:
args += [b'BY', by]
if offset is not None and count is not Non... | Sort the elements in a list, set or sorted set. | Below is the the instruction that describes the task:
### Input:
Sort the elements in a list, set or sorted set.
### Response:
def sort(self, key, *get_patterns,
by=None, offset=None, count=None,
asc=None, alpha=False, store=None):
"""Sort the elements in a list, set or sorted set... |
def next_unit_id(self) -> int:
"""
Returns: next free Unit ID
"""
ids: typing.Set[int] = set()
for unit in chain(self._blue_coa.units, self._red_coa.units): # type: ignore
id_ = unit.unit_id
if id_ in ids:
raise IndexError(unit.unit_name)... | Returns: next free Unit ID | Below is the the instruction that describes the task:
### Input:
Returns: next free Unit ID
### Response:
def next_unit_id(self) -> int:
"""
Returns: next free Unit ID
"""
ids: typing.Set[int] = set()
for unit in chain(self._blue_coa.units, self._red_coa.units): # type: ign... |
def _initial_broks(self, broker_name):
"""Get initial_broks from the scheduler
This is used by the brokers to prepare the initial status broks
This do not send broks, it only makes scheduler internal processing. Then the broker
must use the *_broks* API to get all the stuff
:p... | Get initial_broks from the scheduler
This is used by the brokers to prepare the initial status broks
This do not send broks, it only makes scheduler internal processing. Then the broker
must use the *_broks* API to get all the stuff
:param broker_name: broker name, used to filter brok... | Below is the the instruction that describes the task:
### Input:
Get initial_broks from the scheduler
This is used by the brokers to prepare the initial status broks
This do not send broks, it only makes scheduler internal processing. Then the broker
must use the *_broks* API to get all th... |
def restore(self):
"""Restore signal handlers to their original settings."""
signal.signal(signal.SIGINT, self.original_sigint)
signal.signal(signal.SIGTERM, self.original_sigterm)
if os.name == 'nt':
signal.signal(signal.SIGBREAK, self.original_sigbreak) | Restore signal handlers to their original settings. | Below is the the instruction that describes the task:
### Input:
Restore signal handlers to their original settings.
### Response:
def restore(self):
"""Restore signal handlers to their original settings."""
signal.signal(signal.SIGINT, self.original_sigint)
signal.signal(signal.SIGTERM, se... |
def receiver_blueprint_for(self, name):
""" Get a Flask blueprint for the named provider that handles incoming messages & status reports
Note: this requires Flask microframework.
:rtype: flask.blueprints.Blueprint
:returns: Flask Blueprint, fully functional
:rai... | Get a Flask blueprint for the named provider that handles incoming messages & status reports
Note: this requires Flask microframework.
:rtype: flask.blueprints.Blueprint
:returns: Flask Blueprint, fully functional
:raises KeyError: provider not found
:raises... | Below is the the instruction that describes the task:
### Input:
Get a Flask blueprint for the named provider that handles incoming messages & status reports
Note: this requires Flask microframework.
:rtype: flask.blueprints.Blueprint
:returns: Flask Blueprint, fully functional... |
def var(tensor_type, last_dim=0, test_shape=None):
"""
Wrap a Theano tensor into the variable for defining neural network.
:param last_dim: last dimension of tensor, 0 indicates that the last dimension is flexible
:rtype: deepy.core.neural_var.NeuralVariable
"""
# Create tensor
from deepy.co... | Wrap a Theano tensor into the variable for defining neural network.
:param last_dim: last dimension of tensor, 0 indicates that the last dimension is flexible
:rtype: deepy.core.neural_var.NeuralVariable | Below is the the instruction that describes the task:
### Input:
Wrap a Theano tensor into the variable for defining neural network.
:param last_dim: last dimension of tensor, 0 indicates that the last dimension is flexible
:rtype: deepy.core.neural_var.NeuralVariable
### Response:
def var(tensor_type, las... |
def read_struct_file(struct_file,return_type=GeoStruct):
"""read an existing PEST-type structure file into a GeoStruct instance
Parameters
----------
struct_file : (str)
existing pest-type structure file
return_type : (object)
the instance type to return. Default is GeoStruct
... | read an existing PEST-type structure file into a GeoStruct instance
Parameters
----------
struct_file : (str)
existing pest-type structure file
return_type : (object)
the instance type to return. Default is GeoStruct
Returns
-------
GeoStruct : list or GeoStruct
Note... | Below is the the instruction that describes the task:
### Input:
read an existing PEST-type structure file into a GeoStruct instance
Parameters
----------
struct_file : (str)
existing pest-type structure file
return_type : (object)
the instance type to return. Default is GeoStruct... |
def get_first_model_with_rest_name(cls, rest_name):
""" Get the first model corresponding to a rest_name
Args:
rest_name: the rest name
"""
models = cls.get_models_with_rest_name(rest_name)
if len(models) > 0:
return models[0]
return No... | Get the first model corresponding to a rest_name
Args:
rest_name: the rest name | Below is the the instruction that describes the task:
### Input:
Get the first model corresponding to a rest_name
Args:
rest_name: the rest name
### Response:
def get_first_model_with_rest_name(cls, rest_name):
""" Get the first model corresponding to a rest_name
A... |
def mousePressEvent(self, event):
"""
Creates the drag event for this item.
:param event | <QMousePressEvent>
"""
near_x, near_y = self.nearestPoint(event.pos())
data = self.dragData(x=near_x, y=near_y)
self.startDrag(data)
... | Creates the drag event for this item.
:param event | <QMousePressEvent> | Below is the the instruction that describes the task:
### Input:
Creates the drag event for this item.
:param event | <QMousePressEvent>
### Response:
def mousePressEvent(self, event):
"""
Creates the drag event for this item.
:param event | <QMouse... |
def refactor_move_module(self, new_name):
"""Move the current module."""
refactor = create_move(self.project, self.resource)
resource = path_to_resource(self.project, new_name)
return self._get_changes(refactor, resource) | Move the current module. | Below is the the instruction that describes the task:
### Input:
Move the current module.
### Response:
def refactor_move_module(self, new_name):
"""Move the current module."""
refactor = create_move(self.project, self.resource)
resource = path_to_resource(self.project, new_name)
re... |
def confusion_matrix(links_true, links_pred, total=None):
"""Compute the confusion matrix.
The confusion matrix is of the following form:
+----------------------+-----------------------+----------------------+
| | Predicted Positives | Predicted Negatives |
+===============... | Compute the confusion matrix.
The confusion matrix is of the following form:
+----------------------+-----------------------+----------------------+
| | Predicted Positives | Predicted Negatives |
+======================+=======================+======================+
| **T... | Below is the the instruction that describes the task:
### Input:
Compute the confusion matrix.
The confusion matrix is of the following form:
+----------------------+-----------------------+----------------------+
| | Predicted Positives | Predicted Negatives |
+===========... |
def rescue(device, start, end):
'''
Rescue a lost partition that was located somewhere between start and end.
If a partition is found, parted will ask if you want to create an
entry for it in the partition table.
CLI Example:
.. code-block:: bash
salt '*' partition.rescue /dev/sda 0 8... | Rescue a lost partition that was located somewhere between start and end.
If a partition is found, parted will ask if you want to create an
entry for it in the partition table.
CLI Example:
.. code-block:: bash
salt '*' partition.rescue /dev/sda 0 8056 | Below is the the instruction that describes the task:
### Input:
Rescue a lost partition that was located somewhere between start and end.
If a partition is found, parted will ask if you want to create an
entry for it in the partition table.
CLI Example:
.. code-block:: bash
salt '*' part... |
def get_syslog_config(host, username, password, protocol=None, port=None, esxi_hosts=None, credstore=None):
'''
Retrieve the syslog configuration.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used t... | Retrieve the syslog configuration.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optionally set to alternate protocol if the host is not using the default
... | Below is the the instruction that describes the task:
### Input:
Retrieve the syslog configuration.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
The password used to login to the host.
protocol
Optional... |
def _bdtr(k, n, p):
"""The binomial cumulative distribution function.
Args:
k: floating point `Tensor`.
n: floating point `Tensor`.
p: floating point `Tensor`.
Returns:
`sum_{j=0}^k p^j (1 - p)^(n - j)`.
"""
# Trick for getting safe backprop/gradients into n, k when
# betainc(a = 0, ..) ... | The binomial cumulative distribution function.
Args:
k: floating point `Tensor`.
n: floating point `Tensor`.
p: floating point `Tensor`.
Returns:
`sum_{j=0}^k p^j (1 - p)^(n - j)`. | Below is the the instruction that describes the task:
### Input:
The binomial cumulative distribution function.
Args:
k: floating point `Tensor`.
n: floating point `Tensor`.
p: floating point `Tensor`.
Returns:
`sum_{j=0}^k p^j (1 - p)^(n - j)`.
### Response:
def _bdtr(k, n, p):
"""The bino... |
def _group_range(records, method):
"""
Yield the range of all dates between the extrema of
a list of records, separated by a given time delta.
"""
start_date = records[0].datetime
end_date = records[-1].datetime
_fun = DATE_GROUPERS[method]
d = start_date
# Day and week use timede... | Yield the range of all dates between the extrema of
a list of records, separated by a given time delta. | Below is the the instruction that describes the task:
### Input:
Yield the range of all dates between the extrema of
a list of records, separated by a given time delta.
### Response:
def _group_range(records, method):
"""
Yield the range of all dates between the extrema of
a list of records, separa... |
def ite_burrowed(self):
"""
Returns an equivalent AST that "burrows" the ITE expressions as deep as possible into the ast, for simpler
printing.
"""
if self._burrowed is None:
self._burrowed = self._burrow_ite() # pylint:disable=attribute-defined-outside-init
... | Returns an equivalent AST that "burrows" the ITE expressions as deep as possible into the ast, for simpler
printing. | Below is the the instruction that describes the task:
### Input:
Returns an equivalent AST that "burrows" the ITE expressions as deep as possible into the ast, for simpler
printing.
### Response:
def ite_burrowed(self):
"""
Returns an equivalent AST that "burrows" the ITE expressions as dee... |
def get_parent_object(self):
"""
Lookup a parent object. If parent_field is None
this will return None. Otherwise this will try to
return that object.
The filter arguments are found by using the known url
parameters of the bundle, finding the value in the url keyword
... | Lookup a parent object. If parent_field is None
this will return None. Otherwise this will try to
return that object.
The filter arguments are found by using the known url
parameters of the bundle, finding the value in the url keyword
arguments and matching them with the argumen... | Below is the the instruction that describes the task:
### Input:
Lookup a parent object. If parent_field is None
this will return None. Otherwise this will try to
return that object.
The filter arguments are found by using the known url
parameters of the bundle, finding the value in... |
def _get_chart_info(df, vtype, cat, prep, callers):
"""Retrieve values for a specific variant type, category and prep method.
"""
maxval_raw = max(list(df["value.floor"]))
curdf = df[(df["variant.type"] == vtype) & (df["category"] == cat)
& (df["bamprep"] == prep)]
vals = []
label... | Retrieve values for a specific variant type, category and prep method. | Below is the the instruction that describes the task:
### Input:
Retrieve values for a specific variant type, category and prep method.
### Response:
def _get_chart_info(df, vtype, cat, prep, callers):
"""Retrieve values for a specific variant type, category and prep method.
"""
maxval_raw = max(list(d... |
def aptknt(tau, order):
"""Create an acceptable knot vector.
Minimal emulation of MATLAB's ``aptknt``.
The returned knot vector can be used to generate splines of desired `order`
that are suitable for interpolation to the collocation sites `tau`.
Note that this is only possible when ``len(tau)`` >= `order` + 1.
... | Create an acceptable knot vector.
Minimal emulation of MATLAB's ``aptknt``.
The returned knot vector can be used to generate splines of desired `order`
that are suitable for interpolation to the collocation sites `tau`.
Note that this is only possible when ``len(tau)`` >= `order` + 1.
When this condition does not h... | Below is the the instruction that describes the task:
### Input:
Create an acceptable knot vector.
Minimal emulation of MATLAB's ``aptknt``.
The returned knot vector can be used to generate splines of desired `order`
that are suitable for interpolation to the collocation sites `tau`.
Note that this is only possi... |
def check_jobs_status(self,
fail_running=False,
fail_pending=False):
"""Check the status of all the jobs run from this link
and return a status flag that summarizes that.
Parameters
----------
fail_running : `bool`
... | Check the status of all the jobs run from this link
and return a status flag that summarizes that.
Parameters
----------
fail_running : `bool`
If True, consider running jobs as failed
fail_pending : `bool`
If True, consider pending jobs as failed
... | Below is the the instruction that describes the task:
### Input:
Check the status of all the jobs run from this link
and return a status flag that summarizes that.
Parameters
----------
fail_running : `bool`
If True, consider running jobs as failed
fail_pending... |
def sanitize(string):
"""
Catch and replace invalid path chars
[replace, with]
"""
replace_chars = [
['\\', '-'], [':', '-'], ['/', '-'],
['?', ''], ['<', ''], ['>', ''],
['`', '`'], ['|', '-'], ['*', '`'],
['"', '\''], ['.', ''], ['&', 'and']
]
for ch in repl... | Catch and replace invalid path chars
[replace, with] | Below is the the instruction that describes the task:
### Input:
Catch and replace invalid path chars
[replace, with]
### Response:
def sanitize(string):
"""
Catch and replace invalid path chars
[replace, with]
"""
replace_chars = [
['\\', '-'], [':', '-'], ['/', '-'],
['?',... |
def to_simple(self, serializer=None):
""" Prepare to serialization.
:return dict: paginator params
"""
return dict(
count=self.paginator.count,
page=self.page_number,
num_pages=self.paginator.num_pages,
next=self.next_page,
pr... | Prepare to serialization.
:return dict: paginator params | Below is the the instruction that describes the task:
### Input:
Prepare to serialization.
:return dict: paginator params
### Response:
def to_simple(self, serializer=None):
""" Prepare to serialization.
:return dict: paginator params
"""
return dict(
count=se... |
def execute(self):
"""
Executes a new build on a project.
"""
if not self.config.pr:
raise NotPullRequestException
logger.debug('Using the following configuration:')
for name, value in self.config.as_dict().items():
logger.debug(' - {}={}'.format... | Executes a new build on a project. | Below is the the instruction that describes the task:
### Input:
Executes a new build on a project.
### Response:
def execute(self):
"""
Executes a new build on a project.
"""
if not self.config.pr:
raise NotPullRequestException
logger.debug('Using the following... |
def validate_model_specification_file(file_path: str) -> str:
"""Ensures the provided file is a yaml file"""
if not os.path.isfile(file_path):
raise ConfigurationError('If you provide a model specification file, it must be a file. '
f'You provided {file_path}')
exte... | Ensures the provided file is a yaml file | Below is the the instruction that describes the task:
### Input:
Ensures the provided file is a yaml file
### Response:
def validate_model_specification_file(file_path: str) -> str:
"""Ensures the provided file is a yaml file"""
if not os.path.isfile(file_path):
raise ConfigurationError('If you pro... |
def SCM(root_dir, repo=None): # pylint: disable=invalid-name
"""Returns SCM instance that corresponds to a repo at the specified
path.
Args:
root_dir (str): path to a root directory of the repo.
repo (dvc.repo.Repo): dvc repo instance that root_dir belongs to.
Returns:
dvc.scm... | Returns SCM instance that corresponds to a repo at the specified
path.
Args:
root_dir (str): path to a root directory of the repo.
repo (dvc.repo.Repo): dvc repo instance that root_dir belongs to.
Returns:
dvc.scm.base.Base: SCM instance. | Below is the the instruction that describes the task:
### Input:
Returns SCM instance that corresponds to a repo at the specified
path.
Args:
root_dir (str): path to a root directory of the repo.
repo (dvc.repo.Repo): dvc repo instance that root_dir belongs to.
Returns:
dvc.scm... |
def is_callable(self):
"""The fake can be called.
This is useful for when you stub out a function
as opposed to a class. For example::
>>> import fudge
>>> remove = Fake('os.remove').is_callable()
>>> remove('some/path')
"""
self._callable ... | The fake can be called.
This is useful for when you stub out a function
as opposed to a class. For example::
>>> import fudge
>>> remove = Fake('os.remove').is_callable()
>>> remove('some/path') | Below is the the instruction that describes the task:
### Input:
The fake can be called.
This is useful for when you stub out a function
as opposed to a class. For example::
>>> import fudge
>>> remove = Fake('os.remove').is_callable()
>>> remove('some/path')
#... |
def search(self, title=None, libtype=None, **kwargs):
""" Searching within a library section is much more powerful. It seems certain
attributes on the media objects can be targeted to filter this search down
a bit, but I havent found the documentation for it.
Example: "studi... | Searching within a library section is much more powerful. It seems certain
attributes on the media objects can be targeted to filter this search down
a bit, but I havent found the documentation for it.
Example: "studio=Comedy%20Central" or "year=1999" "title=Kung Fu" all work. Other... | Below is the the instruction that describes the task:
### Input:
Searching within a library section is much more powerful. It seems certain
attributes on the media objects can be targeted to filter this search down
a bit, but I havent found the documentation for it.
Example: "st... |
def get_release_number(name):
'''
Returns the release number of a given release code name in a
``<year>.<month>`` context.
If the release name has not been given an assigned release number, the
function returns a string. If the release cannot be found, it returns
``None``.
name
The... | Returns the release number of a given release code name in a
``<year>.<month>`` context.
If the release name has not been given an assigned release number, the
function returns a string. If the release cannot be found, it returns
``None``.
name
The release codename for which to find a rele... | Below is the the instruction that describes the task:
### Input:
Returns the release number of a given release code name in a
``<year>.<month>`` context.
If the release name has not been given an assigned release number, the
function returns a string. If the release cannot be found, it returns
``No... |
def forward(self, observations):
""" Model forward pass """
input_data = self.input_block(observations)
base_output = self.backbone(input_data)
log_histogram = self.q_head(base_output)
return log_histogram | Model forward pass | Below is the the instruction that describes the task:
### Input:
Model forward pass
### Response:
def forward(self, observations):
""" Model forward pass """
input_data = self.input_block(observations)
base_output = self.backbone(input_data)
log_histogram = self.q_head(base_output)
... |
def resolvePrefix(self):
""" extract prefix information into dict with the key of '_prefixstr'
"""
tmpstrlist = []
tmpstodict = {}
for line in self.file_lines:
if line.startswith('%'):
stolist = line.replace('%', '').split('sto')
rpnexp... | extract prefix information into dict with the key of '_prefixstr' | Below is the the instruction that describes the task:
### Input:
extract prefix information into dict with the key of '_prefixstr'
### Response:
def resolvePrefix(self):
""" extract prefix information into dict with the key of '_prefixstr'
"""
tmpstrlist = []
tmpstodict = {}
... |
def set_mode_apm(self, mode, custom_mode = 0, custom_sub_mode = 0):
'''enter arbitrary mode'''
if isinstance(mode, str):
mode_map = self.mode_mapping()
if mode_map is None or mode not in mode_map:
print("Unknown mode '%s'" % mode)
return
... | enter arbitrary mode | Below is the the instruction that describes the task:
### Input:
enter arbitrary mode
### Response:
def set_mode_apm(self, mode, custom_mode = 0, custom_sub_mode = 0):
'''enter arbitrary mode'''
if isinstance(mode, str):
mode_map = self.mode_mapping()
if mode_map is None or ... |
def initDeviceScan(self):
"""Initialize Key Stored Values."""
self.__isIphone = self.detectIphoneOrIpod()
self.__isAndroidPhone = self.detectAndroidPhone()
self.__isTierTablet = self.detectTierTablet()
self.__isTierIphone = self.detectTierIphone()
self.__isTierRichCss = s... | Initialize Key Stored Values. | Below is the the instruction that describes the task:
### Input:
Initialize Key Stored Values.
### Response:
def initDeviceScan(self):
"""Initialize Key Stored Values."""
self.__isIphone = self.detectIphoneOrIpod()
self.__isAndroidPhone = self.detectAndroidPhone()
self.__isTierTable... |
def exponential(data):
""" Creates a segment cost function for a time series with a
exponential distribution with changing mean
Args:
data (:obj:`list` of float): 1D time series data
Returns:
function: Function with signature
(int, int) -> float
where the fir... | Creates a segment cost function for a time series with a
exponential distribution with changing mean
Args:
data (:obj:`list` of float): 1D time series data
Returns:
function: Function with signature
(int, int) -> float
where the first arg is the starting index, a... | Below is the the instruction that describes the task:
### Input:
Creates a segment cost function for a time series with a
exponential distribution with changing mean
Args:
data (:obj:`list` of float): 1D time series data
Returns:
function: Function with signature
(int, i... |
def to_categorical(y, nb_classes, num_classes=None):
"""
Converts a class vector (integers) to binary class matrix.
This is adapted from the Keras function with the same name.
:param y: class vector to be converted into a matrix
(integers from 0 to nb_classes).
:param nb_classes: nb_classes: total... | Converts a class vector (integers) to binary class matrix.
This is adapted from the Keras function with the same name.
:param y: class vector to be converted into a matrix
(integers from 0 to nb_classes).
:param nb_classes: nb_classes: total number of classes.
:param num_classses: depricated version... | Below is the the instruction that describes the task:
### Input:
Converts a class vector (integers) to binary class matrix.
This is adapted from the Keras function with the same name.
:param y: class vector to be converted into a matrix
(integers from 0 to nb_classes).
:param nb_classes: nb_classe... |
def plot_spectrum(self, t=0, f_start=None, f_stop=None, logged=False, if_id=0, c=None, **kwargs):
""" Plot frequency spectrum of a given file
Args:
t (int): integration number to plot (0 -> len(data))
logged (bool): Plot in linear (False) or dB units (True)
if_id (in... | Plot frequency spectrum of a given file
Args:
t (int): integration number to plot (0 -> len(data))
logged (bool): Plot in linear (False) or dB units (True)
if_id (int): IF identification (if multiple IF signals in file)
c: color for line
kwargs: keywo... | Below is the the instruction that describes the task:
### Input:
Plot frequency spectrum of a given file
Args:
t (int): integration number to plot (0 -> len(data))
logged (bool): Plot in linear (False) or dB units (True)
if_id (int): IF identification (if multiple IF sig... |
def fetch(self, multithread=True, median_kernel=5, solar_diam=740):
"""
For all products in products, will call the correct fetch routine and download an image
:param multithread: if true will fetch the files simultaneously
:type multithread: bool
:param median_kernel: the size o... | For all products in products, will call the correct fetch routine and download an image
:param multithread: if true will fetch the files simultaneously
:type multithread: bool
:param median_kernel: the size of the kernel to smooth by
:type median_kernel: int >= 0
:return: a dicti... | Below is the the instruction that describes the task:
### Input:
For all products in products, will call the correct fetch routine and download an image
:param multithread: if true will fetch the files simultaneously
:type multithread: bool
:param median_kernel: the size of the kernel to smo... |
def objects_list(self, bucket, prefix=None, delimiter=None, projection='noAcl', versions=False,
max_results=0, page_token=None):
"""Issues a request to retrieve information about an object.
Args:
bucket: the name of the bucket.
prefix: an optional key prefix.
delimiter: an ... | Issues a request to retrieve information about an object.
Args:
bucket: the name of the bucket.
prefix: an optional key prefix.
delimiter: an optional key delimiter.
projection: the projection of the objects to retrieve.
versions: whether to list each version of a file as a distinct o... | Below is the the instruction that describes the task:
### Input:
Issues a request to retrieve information about an object.
Args:
bucket: the name of the bucket.
prefix: an optional key prefix.
delimiter: an optional key delimiter.
projection: the projection of the objects to retrieve.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.