code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def log_writer():
'''log writing thread'''
while True:
mpstate.logfile_raw.write(bytearray(mpstate.logqueue_raw.get()))
timeout = time.time() + 10
while not mpstate.logqueue_raw.empty() and time.time() < timeout:
mpstate.logfile_raw.write(mpstate.logqueue_raw.get())
w... | log writing thread | Below is the the instruction that describes the task:
### Input:
log writing thread
### Response:
def log_writer():
'''log writing thread'''
while True:
mpstate.logfile_raw.write(bytearray(mpstate.logqueue_raw.get()))
timeout = time.time() + 10
while not mpstate.logqueue_raw.empty()... |
def delay(sig):
""" Simple feedforward delay effect """
smix = Streamix()
sig = thub(sig, 3) # Auto-copy 3 times (remove this line if using feedback)
smix.add(0, sig)
# To get a feedback delay, use "smix.copy()" below instead of both "sig"
smix.add(280 * ms, .1 * sig) # You can also try other constants
sm... | Simple feedforward delay effect | Below is the the instruction that describes the task:
### Input:
Simple feedforward delay effect
### Response:
def delay(sig):
""" Simple feedforward delay effect """
smix = Streamix()
sig = thub(sig, 3) # Auto-copy 3 times (remove this line if using feedback)
smix.add(0, sig)
# To get a feedback delay, ... |
def create_app():
""" Flask application factory """
# Setup Flask app and app.config
app = Flask(__name__)
app.config.from_object(__name__ + '.ConfigClass')
# Initialize Flask extensions
db = Flywheel(app) # Initialize Flask-Flywheel
mail = Mail(app) # Initialize Flask-Mail
# Define... | Flask application factory | Below is the the instruction that describes the task:
### Input:
Flask application factory
### Response:
def create_app():
""" Flask application factory """
# Setup Flask app and app.config
app = Flask(__name__)
app.config.from_object(__name__ + '.ConfigClass')
# Initialize Flask extensions
... |
def sysinit(systype, conf, project):
"""Outputs configuration for system initialization subsystem."""
click.secho(get_config(
systype,
conf=ConfModule(conf).configurations[0],
conf_path=conf,
project_name=project,
)) | Outputs configuration for system initialization subsystem. | Below is the the instruction that describes the task:
### Input:
Outputs configuration for system initialization subsystem.
### Response:
def sysinit(systype, conf, project):
"""Outputs configuration for system initialization subsystem."""
click.secho(get_config(
systype,
conf=ConfModule(c... |
def chain_frames(self):
"""Chains the frames. Requires ctypes or the speedups extension."""
prev_tb = None
for tb in self.frames:
if prev_tb is not None:
prev_tb.tb_next = tb
prev_tb = tb
prev_tb.tb_next = None | Chains the frames. Requires ctypes or the speedups extension. | Below is the the instruction that describes the task:
### Input:
Chains the frames. Requires ctypes or the speedups extension.
### Response:
def chain_frames(self):
"""Chains the frames. Requires ctypes or the speedups extension."""
prev_tb = None
for tb in self.frames:
if pre... |
def update(self, sid, **kwargs):
"""
Add attribute value assertion to a special session
:param sid: Session ID
:param kwargs:
"""
item = self[sid]
for attribute, value in kwargs.items():
item[attribute] = value
self[sid] = item | Add attribute value assertion to a special session
:param sid: Session ID
:param kwargs: | Below is the the instruction that describes the task:
### Input:
Add attribute value assertion to a special session
:param sid: Session ID
:param kwargs:
### Response:
def update(self, sid, **kwargs):
"""
Add attribute value assertion to a special session
:param sid: Sessi... |
def LaplaceCentreWeight(self):
"""Centre weighting matrix for TV Laplacian."""
sz = [1,] * self.S.ndim
for ax in self.axes:
sz[ax] = self.S.shape[ax]
lcw = 2*len(self.axes)*np.ones(sz, dtype=self.dtype)
for ax in self.axes:
lcw[(slice(None),)*ax + ([0, -1... | Centre weighting matrix for TV Laplacian. | Below is the the instruction that describes the task:
### Input:
Centre weighting matrix for TV Laplacian.
### Response:
def LaplaceCentreWeight(self):
"""Centre weighting matrix for TV Laplacian."""
sz = [1,] * self.S.ndim
for ax in self.axes:
sz[ax] = self.S.shape[ax]
... |
def bundle(self, bundle_id, channel=None):
'''Get the default data for a bundle.
@param bundle_id The bundle's id.
@param channel Optional channel name.
'''
return self.entity(bundle_id, get_files=True, channel=channel) | Get the default data for a bundle.
@param bundle_id The bundle's id.
@param channel Optional channel name. | Below is the the instruction that describes the task:
### Input:
Get the default data for a bundle.
@param bundle_id The bundle's id.
@param channel Optional channel name.
### Response:
def bundle(self, bundle_id, channel=None):
'''Get the default data for a bundle.
@param bundle_... |
def sys(**kwargs):
''' Manage system configuration. '''
output, err = cli_syncthing_adapter.sys(**kwargs)
if output:
click.echo("%s" % output, err=err)
else:
if not kwargs['init']:
click.echo(click.get_current_context().get_help()) | Manage system configuration. | Below is the the instruction that describes the task:
### Input:
Manage system configuration.
### Response:
def sys(**kwargs):
''' Manage system configuration. '''
output, err = cli_syncthing_adapter.sys(**kwargs)
if output:
click.echo("%s" % output, err=err)
else:
if not kwargs['init']:
... |
def _log_likelihood_per_sample(X, means, covars):
"""
Theta = (theta_1, theta_2, ... theta_M)
Likelihood of mixture parameters given data: L(Theta | X) = product_i P(x_i | Theta)
log likelihood: log L(Theta | X) = sum_i log(P(x_i | Theta))
and note that p(x_i | Theta) = sum_j prior_j * p(x_... | Theta = (theta_1, theta_2, ... theta_M)
Likelihood of mixture parameters given data: L(Theta | X) = product_i P(x_i | Theta)
log likelihood: log L(Theta | X) = sum_i log(P(x_i | Theta))
and note that p(x_i | Theta) = sum_j prior_j * p(x_i | theta_j)
Probability of sample x being generated fro... | Below is the the instruction that describes the task:
### Input:
Theta = (theta_1, theta_2, ... theta_M)
Likelihood of mixture parameters given data: L(Theta | X) = product_i P(x_i | Theta)
log likelihood: log L(Theta | X) = sum_i log(P(x_i | Theta))
and note that p(x_i | Theta) = sum_j prior_j *... |
def is_connected(self, other):
"""
Returns ``True`` if there exists a (possibly empty) range which is
enclosed by both this range and other.
Examples:
* [1, 3] and [5, 7] are not connected
* [5, 7] and [1, 3] are not connected
* [2, 4) and [3, 5) are connected, ... | Returns ``True`` if there exists a (possibly empty) range which is
enclosed by both this range and other.
Examples:
* [1, 3] and [5, 7] are not connected
* [5, 7] and [1, 3] are not connected
* [2, 4) and [3, 5) are connected, because both enclose [3, 4)
* [1, 3) and [3... | Below is the the instruction that describes the task:
### Input:
Returns ``True`` if there exists a (possibly empty) range which is
enclosed by both this range and other.
Examples:
* [1, 3] and [5, 7] are not connected
* [5, 7] and [1, 3] are not connected
* [2, 4) and [3, ... |
def _convert_2_0_0_alpha(topo, topo_path):
"""
Convert topologies from GNS3 2.0.0 alpha to 2.0.0 final.
Changes:
* No more serial console
* No more option for VMware / VirtualBox remote console (always use telnet)
"""
topo["revision"] = 6
for node in topo.get("topology", {}).get("node... | Convert topologies from GNS3 2.0.0 alpha to 2.0.0 final.
Changes:
* No more serial console
* No more option for VMware / VirtualBox remote console (always use telnet) | Below is the the instruction that describes the task:
### Input:
Convert topologies from GNS3 2.0.0 alpha to 2.0.0 final.
Changes:
* No more serial console
* No more option for VMware / VirtualBox remote console (always use telnet)
### Response:
def _convert_2_0_0_alpha(topo, topo_path):
"""
... |
def next(self):
"""Returns the next row of the reader’s iterable object."""
row = self.reader.next()
return [s.decode("utf-8") for s in row] | Returns the next row of the reader’s iterable object. | Below is the the instruction that describes the task:
### Input:
Returns the next row of the reader’s iterable object.
### Response:
def next(self):
"""Returns the next row of the reader’s iterable object."""
row = self.reader.next()
return [s.decode("utf-8") for s in row] |
def map_recursive(function, iterable):
"""
Apply function recursively to every item or value of iterable and returns a
new iterable object with the results.
"""
if isiterable(iterable):
dataOut = iterable.__class__()
for i in iterable:
if isinstance(dataOut, dict):
... | Apply function recursively to every item or value of iterable and returns a
new iterable object with the results. | Below is the the instruction that describes the task:
### Input:
Apply function recursively to every item or value of iterable and returns a
new iterable object with the results.
### Response:
def map_recursive(function, iterable):
"""
Apply function recursively to every item or value of iterable and r... |
def _format_line(self, data, column=0, rel_line=1):
'Formats a line from the data to be the appropriate length'
line_length = len(data)
if line_length > 140:
if rel_line == 0:
# Trim from the beginning
data = '... %s' % data[-140:]
elif re... | Formats a line from the data to be the appropriate length | Below is the the instruction that describes the task:
### Input:
Formats a line from the data to be the appropriate length
### Response:
def _format_line(self, data, column=0, rel_line=1):
'Formats a line from the data to be the appropriate length'
line_length = len(data)
if line_length > ... |
def _Fierz_to_EOS_V(Fsbuu,Fsbdd,Fsbcc,Fsbss,Fsbbb,parameters):
p = parameters
V = ckmutil.ckm.ckm_tree(p["Vus"], p["Vub"], p["Vcb"], p["delta"])
Vtb = V[2,2]
Vts = V[2,1]
"""From Fierz to the EOS basis for b -> s transitions.
The arguments are dictionaries of the corresponding Fierz bases """
... | From Fierz to the EOS basis for b -> s transitions.
The arguments are dictionaries of the corresponding Fierz bases | Below is the the instruction that describes the task:
### Input:
From Fierz to the EOS basis for b -> s transitions.
The arguments are dictionaries of the corresponding Fierz bases
### Response:
def _Fierz_to_EOS_V(Fsbuu,Fsbdd,Fsbcc,Fsbss,Fsbbb,parameters):
p = parameters
V = ckmutil.ckm.ckm_tree(p["Vu... |
def scan(self, data, dlen=None):
'''
Scan a data block for matching signatures.
@data - A string of data to scan.
@dlen - If specified, signatures at offsets larger than dlen will be ignored.
Returns a list of SignatureResult objects.
'''
results = []
ma... | Scan a data block for matching signatures.
@data - A string of data to scan.
@dlen - If specified, signatures at offsets larger than dlen will be ignored.
Returns a list of SignatureResult objects. | Below is the the instruction that describes the task:
### Input:
Scan a data block for matching signatures.
@data - A string of data to scan.
@dlen - If specified, signatures at offsets larger than dlen will be ignored.
Returns a list of SignatureResult objects.
### Response:
def scan(sel... |
def load(self, **kwargs):
"""Override load to retrieve object based on exists above."""
tmos_v = self._meta_data['bigip']._meta_data['tmos_version']
if self._check_existence_by_collection(
self._meta_data['container'], kwargs['name']):
if LooseVersion(tmos_v) == Loose... | Override load to retrieve object based on exists above. | Below is the the instruction that describes the task:
### Input:
Override load to retrieve object based on exists above.
### Response:
def load(self, **kwargs):
"""Override load to retrieve object based on exists above."""
tmos_v = self._meta_data['bigip']._meta_data['tmos_version']
if self... |
def get_app_list(site, request):
"""
Returns a sorted list of all the installed apps that have been
registered in this site.
"""
app_dict = _build_app_dict(site, request)
# Sort the apps alphabetically.
app_list = sorted(app_dict.values(), key=lambda x: x['name'].lower())
# Sort the mo... | Returns a sorted list of all the installed apps that have been
registered in this site. | Below is the the instruction that describes the task:
### Input:
Returns a sorted list of all the installed apps that have been
registered in this site.
### Response:
def get_app_list(site, request):
"""
Returns a sorted list of all the installed apps that have been
registered in this site.
"""... |
def get_imports(filename):
"""Get all the imports in a file.
Each import is a tuple of:
(name, alias, is_from, is_star, source_file)
"""
with open(filename, "rb") as f:
src = f.read()
finder = ImportFinder()
finder.visit(ast.parse(src, filename=filename))
imports = []
for ... | Get all the imports in a file.
Each import is a tuple of:
(name, alias, is_from, is_star, source_file) | Below is the the instruction that describes the task:
### Input:
Get all the imports in a file.
Each import is a tuple of:
(name, alias, is_from, is_star, source_file)
### Response:
def get_imports(filename):
"""Get all the imports in a file.
Each import is a tuple of:
(name, alias, is_fr... |
def _check_and_apply_deprecations(self, scope, values):
"""Checks whether a ScopeInfo has options specified in a deprecated scope.
There are two related cases here. Either:
1) The ScopeInfo has an associated deprecated_scope that was replaced with a non-deprecated
scope, meaning that the options... | Checks whether a ScopeInfo has options specified in a deprecated scope.
There are two related cases here. Either:
1) The ScopeInfo has an associated deprecated_scope that was replaced with a non-deprecated
scope, meaning that the options temporarily live in two locations.
2) The entire ScopeIn... | Below is the the instruction that describes the task:
### Input:
Checks whether a ScopeInfo has options specified in a deprecated scope.
There are two related cases here. Either:
1) The ScopeInfo has an associated deprecated_scope that was replaced with a non-deprecated
scope, meaning that the o... |
async def on_isupport_targmax(self, value):
""" The maximum number of targets certain types of commands can affect. """
if not value:
return
for entry in value.split(','):
command, limit = entry.split(':', 1)
if not limit:
continue
... | The maximum number of targets certain types of commands can affect. | Below is the the instruction that describes the task:
### Input:
The maximum number of targets certain types of commands can affect.
### Response:
async def on_isupport_targmax(self, value):
""" The maximum number of targets certain types of commands can affect. """
if not value:
return... |
def _estimate_p_values(self):
"""estimate the p-values for all features
"""
if not self._is_fitted:
raise AttributeError('GAM has not been fitted. Call fit first.')
p_values = []
for term_i in range(len(self.terms)):
p_values.append(self._compute_p_value(... | estimate the p-values for all features | Below is the the instruction that describes the task:
### Input:
estimate the p-values for all features
### Response:
def _estimate_p_values(self):
"""estimate the p-values for all features
"""
if not self._is_fitted:
raise AttributeError('GAM has not been fitted. Call fit first... |
def _fit(self, col):
"""Create a map of the empirical probability for each category.
Args:
col(pandas.DataFrame): Data to transform.
"""
column = col[self.col_name].replace({np.nan: np.inf})
frequencies = column.groupby(column).count().rename({np.inf: None}).to_dict... | Create a map of the empirical probability for each category.
Args:
col(pandas.DataFrame): Data to transform. | Below is the the instruction that describes the task:
### Input:
Create a map of the empirical probability for each category.
Args:
col(pandas.DataFrame): Data to transform.
### Response:
def _fit(self, col):
"""Create a map of the empirical probability for each category.
Args... |
def _calculate_adjustment(
lcm, choosers, alternatives, alt_segmenter,
clip_change_low, clip_change_high, multiplier_func=None):
"""
Calculate adjustments to prices to compensate for
supply and demand effects.
Parameters
----------
lcm : LocationChoiceModel
Used to calcu... | Calculate adjustments to prices to compensate for
supply and demand effects.
Parameters
----------
lcm : LocationChoiceModel
Used to calculate the probability of agents choosing among
alternatives. Must be fully configured and fitted.
choosers : pandas.DataFrame
alternatives : p... | Below is the the instruction that describes the task:
### Input:
Calculate adjustments to prices to compensate for
supply and demand effects.
Parameters
----------
lcm : LocationChoiceModel
Used to calculate the probability of agents choosing among
alternatives. Must be fully config... |
def restart_service(service):
""" restarts a service """
with settings(hide('running', 'stdout'), warn_only=True):
log_yellow('stoping service %s' % service)
sudo('service %s stop' % service)
log_yellow('starting service %s' % service)
sudo('service %s start' % service) | restarts a service | Below is the the instruction that describes the task:
### Input:
restarts a service
### Response:
def restart_service(service):
""" restarts a service """
with settings(hide('running', 'stdout'), warn_only=True):
log_yellow('stoping service %s' % service)
sudo('service %s stop' % service)
... |
def write(self, records=None, path=None, fields=None, append=False,
gzip=None):
"""
Write the table to disk.
The basic usage has no arguments and writes the table's data
to the attached file. The parameters accommodate a variety of
use cases, such as using *fields*... | Write the table to disk.
The basic usage has no arguments and writes the table's data
to the attached file. The parameters accommodate a variety of
use cases, such as using *fields* to refresh a table to a
new schema or *records* and *append* to incrementally build a
table.
... | Below is the the instruction that describes the task:
### Input:
Write the table to disk.
The basic usage has no arguments and writes the table's data
to the attached file. The parameters accommodate a variety of
use cases, such as using *fields* to refresh a table to a
new schema o... |
def checkscript(self, content):
"""Check whether a script is valid
See MANAGESIEVE specifications, section 2.12
:param name: script's content
:rtype: boolean
"""
if "VERSION" not in self.__capabilities:
raise NotImplementedError(
"server does... | Check whether a script is valid
See MANAGESIEVE specifications, section 2.12
:param name: script's content
:rtype: boolean | Below is the the instruction that describes the task:
### Input:
Check whether a script is valid
See MANAGESIEVE specifications, section 2.12
:param name: script's content
:rtype: boolean
### Response:
def checkscript(self, content):
"""Check whether a script is valid
See... |
def submit_job(
self,
project_id,
region,
job,
request_id=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Submits a job to a cluster.
Example:
... | Submits a job to a cluster.
Example:
>>> from google.cloud import dataproc_v1beta2
>>>
>>> client = dataproc_v1beta2.JobControllerClient()
>>>
>>> # TODO: Initialize `project_id`:
>>> project_id = ''
>>>
>>> # TODO:... | Below is the the instruction that describes the task:
### Input:
Submits a job to a cluster.
Example:
>>> from google.cloud import dataproc_v1beta2
>>>
>>> client = dataproc_v1beta2.JobControllerClient()
>>>
>>> # TODO: Initialize `project_id`:
... |
def path(self, which=None):
"""Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
bulk_resume
/foreman_tasks/api/tasks/bulk_resume
bulk_search
/foreman_tasks/api/tasks/bulk_search
summary
... | Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
bulk_resume
/foreman_tasks/api/tasks/bulk_resume
bulk_search
/foreman_tasks/api/tasks/bulk_search
summary
/foreman_tasks/api/tasks/summar... | Below is the the instruction that describes the task:
### Input:
Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
bulk_resume
/foreman_tasks/api/tasks/bulk_resume
bulk_search
/foreman_tasks/api/tasks/bu... |
def get_description(self):
"""Get the description of a GObject."""
vo = ffi.cast('VipsObject *', self.pointer)
return _to_string(vips_lib.vips_object_get_description(vo)) | Get the description of a GObject. | Below is the the instruction that describes the task:
### Input:
Get the description of a GObject.
### Response:
def get_description(self):
"""Get the description of a GObject."""
vo = ffi.cast('VipsObject *', self.pointer)
return _to_string(vips_lib.vips_object_get_description(vo)) |
def md(self, text=TEXT, float_format="%.2g"):
""" Generate Markdown from the table data. """
cols = self._data.columns
hl = pd.DataFrame([["---"] * len(cols)], index=["---"], columns=cols)
df = pd.concat([hl, self._data])
return df.to_csv(sep='|', index=True, float_format=float_f... | Generate Markdown from the table data. | Below is the the instruction that describes the task:
### Input:
Generate Markdown from the table data.
### Response:
def md(self, text=TEXT, float_format="%.2g"):
""" Generate Markdown from the table data. """
cols = self._data.columns
hl = pd.DataFrame([["---"] * len(cols)], index=["---"]... |
def _register_stements(self, statements: List["HdlStatement"],
target: List["HdlStatement"]):
"""
Append statements to this container under conditions specified
by condSet
"""
for stm in flatten(statements):
assert stm.parentStm is None, stm... | Append statements to this container under conditions specified
by condSet | Below is the the instruction that describes the task:
### Input:
Append statements to this container under conditions specified
by condSet
### Response:
def _register_stements(self, statements: List["HdlStatement"],
target: List["HdlStatement"]):
"""
Append statem... |
def call(self):
'''show a value dialog'''
from wx_loader import wx
dlg = wx.TextEntryDialog(None, self.title, self.title, defaultValue=str(self.default))
if dlg.ShowModal() != wx.ID_OK:
return None
return dlg.GetValue() | show a value dialog | Below is the the instruction that describes the task:
### Input:
show a value dialog
### Response:
def call(self):
'''show a value dialog'''
from wx_loader import wx
dlg = wx.TextEntryDialog(None, self.title, self.title, defaultValue=str(self.default))
if dlg.ShowModal() != wx.ID_O... |
def get_timestamp_at(time_in=None, time_at=None):
'''
Computes the timestamp for a future event that may occur in ``time_in`` time
or at ``time_at``.
'''
if time_in:
if isinstance(time_in, int):
hours = 0
minutes = time_in
else:
time_in = time_in.r... | Computes the timestamp for a future event that may occur in ``time_in`` time
or at ``time_at``. | Below is the the instruction that describes the task:
### Input:
Computes the timestamp for a future event that may occur in ``time_in`` time
or at ``time_at``.
### Response:
def get_timestamp_at(time_in=None, time_at=None):
'''
Computes the timestamp for a future event that may occur in ``time_in`` ti... |
def _unparse_material(material):
"""
Turn a trimesh material into a COLLADA material.
"""
# TODO EXPORT TEXTURES
if isinstance(material, visual.texture.PBRMaterial):
diffuse = material.baseColorFactor
if diffuse is not None:
diffuse = list(diffuse)
emission = mat... | Turn a trimesh material into a COLLADA material. | Below is the the instruction that describes the task:
### Input:
Turn a trimesh material into a COLLADA material.
### Response:
def _unparse_material(material):
"""
Turn a trimesh material into a COLLADA material.
"""
# TODO EXPORT TEXTURES
if isinstance(material, visual.texture.PBRMaterial):
... |
def db010(self, value=None):
""" Corresponds to IDD Field `db010`
Dry-bulb temperature corresponding to 1.0% annual cumulative frequency of occurrence (warm conditions)
Args:
value (float): value for IDD Field `db010`
Unit: C
if `value` is None it wi... | Corresponds to IDD Field `db010`
Dry-bulb temperature corresponding to 1.0% annual cumulative frequency of occurrence (warm conditions)
Args:
value (float): value for IDD Field `db010`
Unit: C
if `value` is None it will not be checked against the
... | Below is the the instruction that describes the task:
### Input:
Corresponds to IDD Field `db010`
Dry-bulb temperature corresponding to 1.0% annual cumulative frequency of occurrence (warm conditions)
Args:
value (float): value for IDD Field `db010`
Unit: C
... |
def setup(self, interval):
"""Prepares the tests for execution, interval in ms"""
self.trace_counter = 0
self._halt = False
self.interval = interval | Prepares the tests for execution, interval in ms | Below is the the instruction that describes the task:
### Input:
Prepares the tests for execution, interval in ms
### Response:
def setup(self, interval):
"""Prepares the tests for execution, interval in ms"""
self.trace_counter = 0
self._halt = False
self.interval = interval |
def schedule(self, task: Schedulable, *args, **kwargs):
"""Schedule a job to be executed as soon as possible.
:arg task: the task or its name to execute in the background
:arg args: args to be passed to the task function
:arg kwargs: kwargs to be passed to the task function
Thi... | Schedule a job to be executed as soon as possible.
:arg task: the task or its name to execute in the background
:arg args: args to be passed to the task function
:arg kwargs: kwargs to be passed to the task function
This method can only be used once tasks have been attached to a
... | Below is the the instruction that describes the task:
### Input:
Schedule a job to be executed as soon as possible.
:arg task: the task or its name to execute in the background
:arg args: args to be passed to the task function
:arg kwargs: kwargs to be passed to the task function
T... |
def send(self, message, callback=None):
"""Add message to write queue."""
assert isinstance(message, velbus.Message)
self._write_queue.put_nowait((message, callback)) | Add message to write queue. | Below is the the instruction that describes the task:
### Input:
Add message to write queue.
### Response:
def send(self, message, callback=None):
"""Add message to write queue."""
assert isinstance(message, velbus.Message)
self._write_queue.put_nowait((message, callback)) |
def valid(cls, data, context=None):
"""Shortcut to create a VALID Token."""
return cls(cls.TagType.VALID, data, context) | Shortcut to create a VALID Token. | Below is the the instruction that describes the task:
### Input:
Shortcut to create a VALID Token.
### Response:
def valid(cls, data, context=None):
"""Shortcut to create a VALID Token."""
return cls(cls.TagType.VALID, data, context) |
def _make_stream_item(entry):
"""Given a single spinn3r feed entry, produce a single StreamItem.
Returns 'None' if a complete item can't be constructed.
"""
# get standard metadata, assuming it's present...
if not hasattr(entry, 'permalink_entry'):
return None
pe = entry.permalink_entr... | Given a single spinn3r feed entry, produce a single StreamItem.
Returns 'None' if a complete item can't be constructed. | Below is the the instruction that describes the task:
### Input:
Given a single spinn3r feed entry, produce a single StreamItem.
Returns 'None' if a complete item can't be constructed.
### Response:
def _make_stream_item(entry):
"""Given a single spinn3r feed entry, produce a single StreamItem.
Retur... |
def UpdateOsLogin(self, oslogin_desired, two_factor_desired=False):
"""Update whether OS Login is enabled and update NSS cache if necessary.
Args:
oslogin_desired: bool, enable OS Login if True, disable if False.
two_factor_desired: bool, enable two factor if True, disable if False.
Returns:
... | Update whether OS Login is enabled and update NSS cache if necessary.
Args:
oslogin_desired: bool, enable OS Login if True, disable if False.
two_factor_desired: bool, enable two factor if True, disable if False.
Returns:
int, the return code from updating OS Login, or None if not present. | Below is the the instruction that describes the task:
### Input:
Update whether OS Login is enabled and update NSS cache if necessary.
Args:
oslogin_desired: bool, enable OS Login if True, disable if False.
two_factor_desired: bool, enable two factor if True, disable if False.
Returns:
i... |
def spd_inv(W, epsilon=1e-10, method='QR'):
"""
Compute matrix inverse of symmetric positive-definite matrix :math:`W`.
by first reducing W to a low-rank approximation that is truly spd
(Moore-Penrose inverse).
Parameters
----------
W : ndarray((m,m), dtype=float)
Symmetric positiv... | Compute matrix inverse of symmetric positive-definite matrix :math:`W`.
by first reducing W to a low-rank approximation that is truly spd
(Moore-Penrose inverse).
Parameters
----------
W : ndarray((m,m), dtype=float)
Symmetric positive-definite (spd) matrix.
epsilon : float
Tru... | Below is the the instruction that describes the task:
### Input:
Compute matrix inverse of symmetric positive-definite matrix :math:`W`.
by first reducing W to a low-rank approximation that is truly spd
(Moore-Penrose inverse).
Parameters
----------
W : ndarray((m,m), dtype=float)
Symm... |
def DirectoryFixmatFactory(directory, categories = None, glob_str = '*.mat', var_name = 'fixmat'):
"""
Concatenates all fixmats in dir and returns the resulting single
fixmat.
Parameters:
directory : string
Path from which the fixmats should be loaded
categories : instan... | Concatenates all fixmats in dir and returns the resulting single
fixmat.
Parameters:
directory : string
Path from which the fixmats should be loaded
categories : instance of stimuli.Categories, optional
If given, the resulting fixmat provides direct access
... | Below is the the instruction that describes the task:
### Input:
Concatenates all fixmats in dir and returns the resulting single
fixmat.
Parameters:
directory : string
Path from which the fixmats should be loaded
categories : instance of stimuli.Categories, optional
... |
def logout(self):
"""
Logs the user out of all clients and removes the expires_in,
expires_datetime, id_token, refresh_token, access_token, and token_type
attributes
:return:
"""
self.client.global_sign_out(
AccessToken=self.access_token
)
... | Logs the user out of all clients and removes the expires_in,
expires_datetime, id_token, refresh_token, access_token, and token_type
attributes
:return: | Below is the the instruction that describes the task:
### Input:
Logs the user out of all clients and removes the expires_in,
expires_datetime, id_token, refresh_token, access_token, and token_type
attributes
:return:
### Response:
def logout(self):
"""
Logs the user out of ... |
def fcoe_get_interface_output_fcoe_intf_list_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_get_interface = ET.Element("fcoe_get_interface")
config = fcoe_get_interface
output = ET.SubElement(fcoe_get_interface, "output")
... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def fcoe_get_interface_output_fcoe_intf_list_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_get_interface = ET.Element("fcoe_get_interfac... |
def get_ip(self, access='public', addr_family=None, strict=None):
"""
Return the server's IP address.
Params:
- addr_family: IPv4, IPv6 or None. None prefers IPv4 but will
return IPv6 if IPv4 addr was not available.
- access: 'public' or 'private'
... | Return the server's IP address.
Params:
- addr_family: IPv4, IPv6 or None. None prefers IPv4 but will
return IPv6 if IPv4 addr was not available.
- access: 'public' or 'private' | Below is the the instruction that describes the task:
### Input:
Return the server's IP address.
Params:
- addr_family: IPv4, IPv6 or None. None prefers IPv4 but will
return IPv6 if IPv4 addr was not available.
- access: 'public' or 'private'
### Response:
def get_ip... |
def add_deps(self, deps):
"""
Add a list of dependencies to the :class:`Node`.
Args:
deps: List of :class:`Dependency` objects specifying the dependencies of the node.
or dictionary mapping nodes to file extensions e.g. {task: "DEN"}
"""
if isinstan... | Add a list of dependencies to the :class:`Node`.
Args:
deps: List of :class:`Dependency` objects specifying the dependencies of the node.
or dictionary mapping nodes to file extensions e.g. {task: "DEN"} | Below is the the instruction that describes the task:
### Input:
Add a list of dependencies to the :class:`Node`.
Args:
deps: List of :class:`Dependency` objects specifying the dependencies of the node.
or dictionary mapping nodes to file extensions e.g. {task: "DEN"}
### Resp... |
def crypto_box(message, nonce, pk, sk):
"""
Encrypts and returns a message ``message`` using the secret key ``sk``,
public key ``pk``, and the nonce ``nonce``.
:param message: bytes
:param nonce: bytes
:param pk: bytes
:param sk: bytes
:rtype: bytes
"""
if len(nonce) != crypto_b... | Encrypts and returns a message ``message`` using the secret key ``sk``,
public key ``pk``, and the nonce ``nonce``.
:param message: bytes
:param nonce: bytes
:param pk: bytes
:param sk: bytes
:rtype: bytes | Below is the the instruction that describes the task:
### Input:
Encrypts and returns a message ``message`` using the secret key ``sk``,
public key ``pk``, and the nonce ``nonce``.
:param message: bytes
:param nonce: bytes
:param pk: bytes
:param sk: bytes
:rtype: bytes
### Response:
def c... |
def sendEmoji(
self,
emoji=None,
size=EmojiSize.SMALL,
thread_id=None,
thread_type=ThreadType.USER,
):
"""
Deprecated. Use :func:`fbchat.Client.send` instead
"""
return self.send(
Message(text=emoji, emoji_size=size),
th... | Deprecated. Use :func:`fbchat.Client.send` instead | Below is the the instruction that describes the task:
### Input:
Deprecated. Use :func:`fbchat.Client.send` instead
### Response:
def sendEmoji(
self,
emoji=None,
size=EmojiSize.SMALL,
thread_id=None,
thread_type=ThreadType.USER,
):
"""
Deprecated. Use :f... |
def getoutput(cmd):
"""Return standard output of executing cmd in a shell.
Accepts the same arguments as os.system().
Parameters
----------
cmd : str
A command to be executed in the system shell.
Returns
-------
stdout : str
"""
out = process_handler(cmd, lambda p: p.co... | Return standard output of executing cmd in a shell.
Accepts the same arguments as os.system().
Parameters
----------
cmd : str
A command to be executed in the system shell.
Returns
-------
stdout : str | Below is the the instruction that describes the task:
### Input:
Return standard output of executing cmd in a shell.
Accepts the same arguments as os.system().
Parameters
----------
cmd : str
A command to be executed in the system shell.
Returns
-------
stdout : str
### Response... |
def getcolslicenp(self, columnname, nparray, blc, trc, inc=[],
startrow=0, nrow=-1, rowincr=1):
"""Get a slice from a table column into the given numpy array.
The numpy array has to be C-contiguous with a shape matching the
shape of the column (slice). Data type coercion w... | Get a slice from a table column into the given numpy array.
The numpy array has to be C-contiguous with a shape matching the
shape of the column (slice). Data type coercion will be done as needed.
The slice in each array is given by blc, trc, and inc
(as in getcellslice).
The c... | Below is the the instruction that describes the task:
### Input:
Get a slice from a table column into the given numpy array.
The numpy array has to be C-contiguous with a shape matching the
shape of the column (slice). Data type coercion will be done as needed.
The slice in each array is g... |
def cmp(self, other_service):
"""
Compare with an instance of this object. Returns None if the object
is not comparable, False is relevant attributes don't match and True
if they do.
"""
if not isinstance(other_service, HttpService):
return None
for att i... | Compare with an instance of this object. Returns None if the object
is not comparable, False is relevant attributes don't match and True
if they do. | Below is the the instruction that describes the task:
### Input:
Compare with an instance of this object. Returns None if the object
is not comparable, False is relevant attributes don't match and True
if they do.
### Response:
def cmp(self, other_service):
"""
Compare with an inst... |
def processPayment(self, amount, fees, paidOnline=True, methodName=None, methodTxn=None, submissionUser=None, collectedByUser=None, forceFinalize=False, status=None, notify=None):
'''
When a payment processor makes a successful payment against an invoice, it can call this method
which handles st... | When a payment processor makes a successful payment against an invoice, it can call this method
which handles status updates, the creation of a final registration object (if applicable), and
the firing of appropriate registration-related signals. | Below is the the instruction that describes the task:
### Input:
When a payment processor makes a successful payment against an invoice, it can call this method
which handles status updates, the creation of a final registration object (if applicable), and
the firing of appropriate registration-relat... |
def get_user_agent():
'''User-Agent Header. Sends library identification to Azure endpoint.
'''
version = pkg_resources.require("azurerm")[0].version
user_agent = "python/{} ({}) requests/{} azurerm/{}".format(
platform.python_version(),
platform.platform(),
requests.__version__,... | User-Agent Header. Sends library identification to Azure endpoint. | Below is the the instruction that describes the task:
### Input:
User-Agent Header. Sends library identification to Azure endpoint.
### Response:
def get_user_agent():
'''User-Agent Header. Sends library identification to Azure endpoint.
'''
version = pkg_resources.require("azurerm")[0].version
use... |
async def send_schema(self, schema_data_json: str) -> str:
"""
Send schema to ledger, then retrieve it as written to the ledger and return it.
Raise BadLedgerTxn on failure. Raise BadAttribute for attribute name with spaces or
reserved for indy-sdk.
If schema already exists on l... | Send schema to ledger, then retrieve it as written to the ledger and return it.
Raise BadLedgerTxn on failure. Raise BadAttribute for attribute name with spaces or
reserved for indy-sdk.
If schema already exists on ledger, log error and return schema.
:param schema_data_json: schema da... | Below is the the instruction that describes the task:
### Input:
Send schema to ledger, then retrieve it as written to the ledger and return it.
Raise BadLedgerTxn on failure. Raise BadAttribute for attribute name with spaces or
reserved for indy-sdk.
If schema already exists on ledger, log... |
def inquire(self):
"""Maps to fortran CDF_Inquire.
Assigns parameters returned by CDF_Inquire
to pysatCDF instance. Not intended
for regular direct use by user.
"""
name = copy.deepcopy(self.fname)
stats = fortran_cdf.inquire(name)
# break out fortran ... | Maps to fortran CDF_Inquire.
Assigns parameters returned by CDF_Inquire
to pysatCDF instance. Not intended
for regular direct use by user. | Below is the the instruction that describes the task:
### Input:
Maps to fortran CDF_Inquire.
Assigns parameters returned by CDF_Inquire
to pysatCDF instance. Not intended
for regular direct use by user.
### Response:
def inquire(self):
"""Maps to fortran CDF_Inquire.
Assi... |
def truncatechars(value, num, end_text="..."):
"""Truncate string on character boundary.
.. note::
Django ticket `5025 <http://code.djangoproject.com/ticket/5025>`_ has a
patch for a more extensible and robust truncate characters tag filter.
Example::
{{ my_variable|truncatechars:... | Truncate string on character boundary.
.. note::
Django ticket `5025 <http://code.djangoproject.com/ticket/5025>`_ has a
patch for a more extensible and robust truncate characters tag filter.
Example::
{{ my_variable|truncatechars:22 }}
:param value: Value to truncate.
:type ... | Below is the the instruction that describes the task:
### Input:
Truncate string on character boundary.
.. note::
Django ticket `5025 <http://code.djangoproject.com/ticket/5025>`_ has a
patch for a more extensible and robust truncate characters tag filter.
Example::
{{ my_variable... |
def record_messages(self):
"""Records all messages. Use in unit tests for example::
with mail.record_messages() as outbox:
response = app.test_client.get("/email-sending-view/")
assert len(outbox) == 1
assert outbox[0].subject == "testing"
Yo... | Records all messages. Use in unit tests for example::
with mail.record_messages() as outbox:
response = app.test_client.get("/email-sending-view/")
assert len(outbox) == 1
assert outbox[0].subject == "testing"
You must have blinker installed in order... | Below is the the instruction that describes the task:
### Input:
Records all messages. Use in unit tests for example::
with mail.record_messages() as outbox:
response = app.test_client.get("/email-sending-view/")
assert len(outbox) == 1
assert outbox[0].s... |
def _setup_task_manager(self):
"""instantiate the threaded task manager to run the producer/consumer
queue that is the heart of the processor."""
self.config.logger.info('installing signal handers')
# set up the signal handler for dealing with SIGTERM. the target should
# be this... | instantiate the threaded task manager to run the producer/consumer
queue that is the heart of the processor. | Below is the the instruction that describes the task:
### Input:
instantiate the threaded task manager to run the producer/consumer
queue that is the heart of the processor.
### Response:
def _setup_task_manager(self):
"""instantiate the threaded task manager to run the producer/consumer
qu... |
async def reset_config(self, to_default):
"""
Restore application config to default values.
:param list to_default: A list of config options to be reset to their
default value.
"""
app_facade = client.ApplicationFacade.from_connection(self.connection)
log.debug(... | Restore application config to default values.
:param list to_default: A list of config options to be reset to their
default value. | Below is the the instruction that describes the task:
### Input:
Restore application config to default values.
:param list to_default: A list of config options to be reset to their
default value.
### Response:
async def reset_config(self, to_default):
"""
Restore application config... |
def copy_item(self, erase_original=False):
"""Copy item"""
indexes = self.selectedIndexes()
if not indexes:
return
idx_rows = unsorted_unique([idx.row() for idx in indexes])
if len(idx_rows) > 1 or not indexes[0].isValid():
return
orig_key ... | Copy item | Below is the the instruction that describes the task:
### Input:
Copy item
### Response:
def copy_item(self, erase_original=False):
"""Copy item"""
indexes = self.selectedIndexes()
if not indexes:
return
idx_rows = unsorted_unique([idx.row() for idx in indexes])
... |
def run(align_bams, items, ref_file, assoc_files, region, out_file):
"""Run strelka2 variant calling, either paired tumor/normal or germline calling.
region can be a single region or list of multiple regions for multicore calling.
"""
call_file = "%s-raw.vcf.gz" % utils.splitext_plus(out_file)[0]
s... | Run strelka2 variant calling, either paired tumor/normal or germline calling.
region can be a single region or list of multiple regions for multicore calling. | Below is the the instruction that describes the task:
### Input:
Run strelka2 variant calling, either paired tumor/normal or germline calling.
region can be a single region or list of multiple regions for multicore calling.
### Response:
def run(align_bams, items, ref_file, assoc_files, region, out_file):
... |
def change_sample(self, old_samp_name, new_samp_name, new_site_name=None,
new_er_data=None, new_pmag_data=None, replace_data=False):
"""
Find actual data objects for sample and site.
Then call Sample class change method to update sample name and data..
"""
s... | Find actual data objects for sample and site.
Then call Sample class change method to update sample name and data.. | Below is the the instruction that describes the task:
### Input:
Find actual data objects for sample and site.
Then call Sample class change method to update sample name and data..
### Response:
def change_sample(self, old_samp_name, new_samp_name, new_site_name=None,
new_er_data=None... |
def transform(function):
"""Return a processor for a style's "transform" function.
"""
def transform_fn(_, result):
if isinstance(result, Nothing):
return result
lgr.debug("Transforming %r with %r", result, function)
try:
retur... | Return a processor for a style's "transform" function. | Below is the the instruction that describes the task:
### Input:
Return a processor for a style's "transform" function.
### Response:
def transform(function):
"""Return a processor for a style's "transform" function.
"""
def transform_fn(_, result):
if isinstance(result, Nothing... |
def follow_logs(instance_log_id, sleep_duration=1):
"""
Follow the logs until Job termination.
"""
cur_idx = 0
job_terminated = False
while not job_terminated:
# Get the logs in a loop and log the new lines
log_file_contents = ResourceClient().get_content(instance_log_id)
... | Follow the logs until Job termination. | Below is the the instruction that describes the task:
### Input:
Follow the logs until Job termination.
### Response:
def follow_logs(instance_log_id, sleep_duration=1):
"""
Follow the logs until Job termination.
"""
cur_idx = 0
job_terminated = False
while not job_terminated:
# Ge... |
def export_handle(self, directory):
"""Get a filehandle for exporting"""
filename = getattr(self, 'filename')
dest_file = "%s/%s" % (directory, filename)
dest_dir = os.path.dirname(dest_file)
if not os.path.isdir(dest_dir):
os.mkdir(dest_dir, 0o700)
return op... | Get a filehandle for exporting | Below is the the instruction that describes the task:
### Input:
Get a filehandle for exporting
### Response:
def export_handle(self, directory):
"""Get a filehandle for exporting"""
filename = getattr(self, 'filename')
dest_file = "%s/%s" % (directory, filename)
dest_dir = os.path.... |
def compare(self, a, b):
r"""
Compare two sequences of lines; generate the resulting delta.
Each sequence must contain individual single-line strings ending with
newlines. Such sequences can be obtained from the `readlines()` method
of file-like objects. The delta generated als... | r"""
Compare two sequences of lines; generate the resulting delta.
Each sequence must contain individual single-line strings ending with
newlines. Such sequences can be obtained from the `readlines()` method
of file-like objects. The delta generated also consists of newline-
te... | Below is the the instruction that describes the task:
### Input:
r"""
Compare two sequences of lines; generate the resulting delta.
Each sequence must contain individual single-line strings ending with
newlines. Such sequences can be obtained from the `readlines()` method
of file-li... |
def moveToPoint(self, xxx_todo_changeme):
"""
Moves the rect to the point x,y
"""
(x,y) = xxx_todo_changeme
self.set_x(float(self.get_x()) + float(x))
self.set_y(float(self.get_y()) + float(y)) | Moves the rect to the point x,y | Below is the the instruction that describes the task:
### Input:
Moves the rect to the point x,y
### Response:
def moveToPoint(self, xxx_todo_changeme):
"""
Moves the rect to the point x,y
"""
(x,y) = xxx_todo_changeme
self.set_x(float(self.get_x()) + float(x))
self.... |
def recode(self, table: pd.DataFrame, validate=False) -> pd.DataFrame:
"""Pass the appropriate columns through each recoder function sequentially and return the final result.
Args:
table (pd.DataFrame): A dataframe on which to apply recoding logic.
validate (bool): If ``True``, ... | Pass the appropriate columns through each recoder function sequentially and return the final result.
Args:
table (pd.DataFrame): A dataframe on which to apply recoding logic.
validate (bool): If ``True``, recoded table must pass validation tests. | Below is the the instruction that describes the task:
### Input:
Pass the appropriate columns through each recoder function sequentially and return the final result.
Args:
table (pd.DataFrame): A dataframe on which to apply recoding logic.
validate (bool): If ``True``, recoded table... |
def update(self, storagemodel:object, modeldefinition = None, hide = 0) -> StorageQueueModel:
""" update the message in queue """
if (storagemodel.id != '') and (storagemodel.pop_receipt != '') and (not storagemodel.id is None) and (not storagemodel.pop_receipt is None):
try:
... | update the message in queue | Below is the the instruction that describes the task:
### Input:
update the message in queue
### Response:
def update(self, storagemodel:object, modeldefinition = None, hide = 0) -> StorageQueueModel:
""" update the message in queue """
if (storagemodel.id != '') and (storagemodel.pop_receipt != '... |
def send_ready(self):
"""
Returns true if data can be written to this channel without blocking.
This means the channel is either closed (so any write attempt would
return immediately) or there is at least one byte of space in the
outbound buffer. If there is at least one byte of ... | Returns true if data can be written to this channel without blocking.
This means the channel is either closed (so any write attempt would
return immediately) or there is at least one byte of space in the
outbound buffer. If there is at least one byte of space in the
outbound buffer, a `s... | Below is the the instruction that describes the task:
### Input:
Returns true if data can be written to this channel without blocking.
This means the channel is either closed (so any write attempt would
return immediately) or there is at least one byte of space in the
outbound buffer. If the... |
def get_map_values(self, lons, lats, ibin=None):
"""Return the indices in the flat array corresponding to a set of coordinates
Parameters
----------
lons : array-like
'Longitudes' (RA or GLON)
lats : array-like
'Latitidues' (DEC or GLAT)
ibin : ... | Return the indices in the flat array corresponding to a set of coordinates
Parameters
----------
lons : array-like
'Longitudes' (RA or GLON)
lats : array-like
'Latitidues' (DEC or GLAT)
ibin : int or array-like
Extract data only for a given e... | Below is the the instruction that describes the task:
### Input:
Return the indices in the flat array corresponding to a set of coordinates
Parameters
----------
lons : array-like
'Longitudes' (RA or GLON)
lats : array-like
'Latitidues' (DEC or GLAT)
... |
def _is_latin_letter(cls, letter):
"""Helper method to determine if a character is a Latin-script letter
or not. For our purposes, combining marks should also return True
since we assume they have been added to a preceding Latin character."""
# Combining marks are a subset of non-spacing... | Helper method to determine if a character is a Latin-script letter
or not. For our purposes, combining marks should also return True
since we assume they have been added to a preceding Latin character. | Below is the the instruction that describes the task:
### Input:
Helper method to determine if a character is a Latin-script letter
or not. For our purposes, combining marks should also return True
since we assume they have been added to a preceding Latin character.
### Response:
def _is_latin_lett... |
def init_app(self, app):
"""Flask application initialization."""
app.before_request(verify_token)
self.init_config(app)
state = _AppState(app=app)
app.extensions['zenodo-accessrequests'] = state | Flask application initialization. | Below is the the instruction that describes the task:
### Input:
Flask application initialization.
### Response:
def init_app(self, app):
"""Flask application initialization."""
app.before_request(verify_token)
self.init_config(app)
state = _AppState(app=app)
app.extensions[... |
def parse_links(self, markup):
""" Returns a list of internal Wikipedia links in the markup.
# A Wikipedia link looks like:
# [[List of operating systems#Embedded | List of embedded operating systems]]
# It does not contain a colon, this indicates images, users, languages, etc.... | Returns a list of internal Wikipedia links in the markup.
# A Wikipedia link looks like:
# [[List of operating systems#Embedded | List of embedded operating systems]]
# It does not contain a colon, this indicates images, users, languages, etc.
The return value is a list contain... | Below is the the instruction that describes the task:
### Input:
Returns a list of internal Wikipedia links in the markup.
# A Wikipedia link looks like:
# [[List of operating systems#Embedded | List of embedded operating systems]]
# It does not contain a colon, this indicates images, users... |
def get_gradebook_column_admin_session(self):
"""Gets the ``OsidSession`` associated with the gradebook column administration service.
return: (osid.grading.GradebookColumnAdminSession) - a
``GradebookColumnAdminSession``
raise: OperationFailed - unable to complete request
... | Gets the ``OsidSession`` associated with the gradebook column administration service.
return: (osid.grading.GradebookColumnAdminSession) - a
``GradebookColumnAdminSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_gradebook_column_a... | Below is the the instruction that describes the task:
### Input:
Gets the ``OsidSession`` associated with the gradebook column administration service.
return: (osid.grading.GradebookColumnAdminSession) - a
``GradebookColumnAdminSession``
raise: OperationFailed - unable to complete ... |
def coerce_to_list(items, preprocess=None):
"""Given an instance or list, coerce to list.
With optional preprocessing.
"""
if not isinstance(items, list):
items = [items]
if preprocess:
items = list(map(preprocess, items))
return items | Given an instance or list, coerce to list.
With optional preprocessing. | Below is the the instruction that describes the task:
### Input:
Given an instance or list, coerce to list.
With optional preprocessing.
### Response:
def coerce_to_list(items, preprocess=None):
"""Given an instance or list, coerce to list.
With optional preprocessing.
"""
if not isinstance(i... |
def docx_process_table(table: DOCX_TABLE_TYPE,
config: TextProcessingConfig) -> str:
"""
Converts a DOCX table to text.
Structure representing a DOCX table:
.. code-block:: none
table
.rows[]
.cells[]
.paragraphs[]
... | Converts a DOCX table to text.
Structure representing a DOCX table:
.. code-block:: none
table
.rows[]
.cells[]
.paragraphs[]
.text
That's the structure of a :class:`docx.table.Table` object, but also of our
homebrew cre... | Below is the the instruction that describes the task:
### Input:
Converts a DOCX table to text.
Structure representing a DOCX table:
.. code-block:: none
table
.rows[]
.cells[]
.paragraphs[]
.text
That's the structure of... |
def Baroczy(x, rhol, rhog, mul, mug):
r'''Calculates void fraction in two-phase flow according to the model of
[1]_ as given in [2]_, [3]_, and [4]_.
.. math::
\alpha = \left[1 + \left(\frac{1-x}{x}\right)^{0.74}\left(\frac{\rho_g}
{\rho_l}\right)^{0.65}\left(\frac{\mu_l}{\mu_g}\right)^{0.... | r'''Calculates void fraction in two-phase flow according to the model of
[1]_ as given in [2]_, [3]_, and [4]_.
.. math::
\alpha = \left[1 + \left(\frac{1-x}{x}\right)^{0.74}\left(\frac{\rho_g}
{\rho_l}\right)^{0.65}\left(\frac{\mu_l}{\mu_g}\right)^{0.13}
\right]^{-1}
Para... | Below is the the instruction that describes the task:
### Input:
r'''Calculates void fraction in two-phase flow according to the model of
[1]_ as given in [2]_, [3]_, and [4]_.
.. math::
\alpha = \left[1 + \left(\frac{1-x}{x}\right)^{0.74}\left(\frac{\rho_g}
{\rho_l}\right)^{0.65}\left(\fr... |
async def save(self):
"""Save the machine in MAAS."""
orig_owner_data = self._orig_data['owner_data']
new_owner_data = dict(self._data['owner_data'])
self._changed_data.pop('owner_data', None)
await super(Machine, self).save()
params_diff = calculate_dict_diff(orig_owner_... | Save the machine in MAAS. | Below is the the instruction that describes the task:
### Input:
Save the machine in MAAS.
### Response:
async def save(self):
"""Save the machine in MAAS."""
orig_owner_data = self._orig_data['owner_data']
new_owner_data = dict(self._data['owner_data'])
self._changed_data.pop('owne... |
def ising_energy(sample, h, J, offset=0.0):
"""Calculate the energy for the specified sample of an Ising model.
Energy of a sample for a binary quadratic model is defined as a sum, offset
by the constant energy offset associated with the model, of
the sample multipled by the linear bias of the variable... | Calculate the energy for the specified sample of an Ising model.
Energy of a sample for a binary quadratic model is defined as a sum, offset
by the constant energy offset associated with the model, of
the sample multipled by the linear bias of the variable and
all its interactions. For an Ising model,
... | Below is the the instruction that describes the task:
### Input:
Calculate the energy for the specified sample of an Ising model.
Energy of a sample for a binary quadratic model is defined as a sum, offset
by the constant energy offset associated with the model, of
the sample multipled by the linear bi... |
def track_metric(self, name: str, value: float, type: TelemetryDataPointType =None,
count: int =None, min: float=None, max: float=None, std_dev: float=None,
properties: Dict[str, object]=None) -> NotImplemented:
"""
Send information about a single metric data poi... | Send information about a single metric data point that was captured for the application.
:param name: The name of the metric that was captured.
:param value: The value of the metric that was captured.
:param type: The type of the metric. (defaults to: TelemetryDataPointType.aggregation`)
... | Below is the the instruction that describes the task:
### Input:
Send information about a single metric data point that was captured for the application.
:param name: The name of the metric that was captured.
:param value: The value of the metric that was captured.
:param type: The type of t... |
def scrypt_mcf_check(scrypt, mcf, password):
"""Returns True if the password matches the given MCF hash
Supports both the libscrypt $s1$ format and the $7$ format.
"""
if not isinstance(mcf, bytes):
raise TypeError('MCF must be a byte string')
if isinstance(password, unicode):
passw... | Returns True if the password matches the given MCF hash
Supports both the libscrypt $s1$ format and the $7$ format. | Below is the the instruction that describes the task:
### Input:
Returns True if the password matches the given MCF hash
Supports both the libscrypt $s1$ format and the $7$ format.
### Response:
def scrypt_mcf_check(scrypt, mcf, password):
"""Returns True if the password matches the given MCF hash
Su... |
def update_log(self, log_form):
"""Updates an existing log.
arg: log_form (osid.logging.LogForm): the form containing the
elements to be updated
raise: IllegalState - ``log_form`` already used in an update
transaction
raise: InvalidArgument - the for... | Updates an existing log.
arg: log_form (osid.logging.LogForm): the form containing the
elements to be updated
raise: IllegalState - ``log_form`` already used in an update
transaction
raise: InvalidArgument - the form contains an invalid value
raise: ... | Below is the the instruction that describes the task:
### Input:
Updates an existing log.
arg: log_form (osid.logging.LogForm): the form containing the
elements to be updated
raise: IllegalState - ``log_form`` already used in an update
transaction
raise: ... |
def parse_cmdline(argv=None):
"""Parse command line options.
@param argv: List of command line arguments. If None, get list from system.
@return: Tuple of Option List and Argument List.
"""
parser = optparse.OptionParser()
parser.add_option('-c', '--conf', help='Configuration file ... | Parse command line options.
@param argv: List of command line arguments. If None, get list from system.
@return: Tuple of Option List and Argument List. | Below is the the instruction that describes the task:
### Input:
Parse command line options.
@param argv: List of command line arguments. If None, get list from system.
@return: Tuple of Option List and Argument List.
### Response:
def parse_cmdline(argv=None):
"""Parse command line options.
... |
def broadcast_long(self):
"""
Broadcast address, as long.
>>> localnet = Network('127.0.0.1/8')
>>> print(localnet.broadcast_long())
2147483647
"""
if self.version() == 4:
return self.network_long() | (MAX_IPV4 - self.netmask_long())
else:
... | Broadcast address, as long.
>>> localnet = Network('127.0.0.1/8')
>>> print(localnet.broadcast_long())
2147483647 | Below is the the instruction that describes the task:
### Input:
Broadcast address, as long.
>>> localnet = Network('127.0.0.1/8')
>>> print(localnet.broadcast_long())
2147483647
### Response:
def broadcast_long(self):
"""
Broadcast address, as long.
>>> localnet =... |
def getEntitiesByRegexp(data = None, listRegexp = None, verbosity=1, logFolder="./logs"):
"""
Method to obtain entities by Regexp.
Args:
-----
data: text where the entities will be looked for.
listRegexp: list of selected regular expressions to be looked for. If
None was pro... | Method to obtain entities by Regexp.
Args:
-----
data: text where the entities will be looked for.
listRegexp: list of selected regular expressions to be looked for. If
None was provided, all the available will be chosen instead.
verbosity: the verbosity level.
logFo... | Below is the the instruction that describes the task:
### Input:
Method to obtain entities by Regexp.
Args:
-----
data: text where the entities will be looked for.
listRegexp: list of selected regular expressions to be looked for. If
None was provided, all the available will be ... |
def insert(self, i, arg):
r"""Insert whitespace, an unparsed argument string, or an argument
object.
:param int i: Index to insert argument into
:param Arg arg: Argument to insert
>>> arguments = TexArgs(['\n', RArg('arg0'), '[arg2]'])
>>> arguments.insert(1, '[arg1]')
... | r"""Insert whitespace, an unparsed argument string, or an argument
object.
:param int i: Index to insert argument into
:param Arg arg: Argument to insert
>>> arguments = TexArgs(['\n', RArg('arg0'), '[arg2]'])
>>> arguments.insert(1, '[arg1]')
>>> len(arguments)
... | Below is the the instruction that describes the task:
### Input:
r"""Insert whitespace, an unparsed argument string, or an argument
object.
:param int i: Index to insert argument into
:param Arg arg: Argument to insert
>>> arguments = TexArgs(['\n', RArg('arg0'), '[arg2]'])
... |
def offsetToZero(requestContext, seriesList):
"""
Offsets a metric or wildcard seriesList by subtracting the minimum
value in the series from each datapoint.
Useful to compare different series where the values in each series
may be higher or lower on average but you're only interested in the
re... | Offsets a metric or wildcard seriesList by subtracting the minimum
value in the series from each datapoint.
Useful to compare different series where the values in each series
may be higher or lower on average but you're only interested in the
relative difference.
An example use case is for compari... | Below is the the instruction that describes the task:
### Input:
Offsets a metric or wildcard seriesList by subtracting the minimum
value in the series from each datapoint.
Useful to compare different series where the values in each series
may be higher or lower on average but you're only interested in... |
def execute(self, peer_jid, command_name):
"""
Start execution of a command with a peer.
:param peer_jid: JID of the peer to start the command at.
:type peer_jid: :class:`~aioxmpp.JID`
:param command_name: Node name of the command to execute.
:type command_name: :class:`... | Start execution of a command with a peer.
:param peer_jid: JID of the peer to start the command at.
:type peer_jid: :class:`~aioxmpp.JID`
:param command_name: Node name of the command to execute.
:type command_name: :class:`str`
:rtype: :class:`~.adhoc.service.ClientSession`
... | Below is the the instruction that describes the task:
### Input:
Start execution of a command with a peer.
:param peer_jid: JID of the peer to start the command at.
:type peer_jid: :class:`~aioxmpp.JID`
:param command_name: Node name of the command to execute.
:type command_name: :c... |
def _strptime(self, time_str):
"""Convert an ISO 8601 formatted string in UTC into a
timezone-aware datetime object."""
if time_str:
# Parse UTC string into naive datetime, then add timezone
dt = datetime.strptime(time_str, __timeformat__)
return dt.replace(tz... | Convert an ISO 8601 formatted string in UTC into a
timezone-aware datetime object. | Below is the the instruction that describes the task:
### Input:
Convert an ISO 8601 formatted string in UTC into a
timezone-aware datetime object.
### Response:
def _strptime(self, time_str):
"""Convert an ISO 8601 formatted string in UTC into a
timezone-aware datetime object."""
i... |
def controlMsg(self, requestType, request, buffer, value = 0, index = 0, timeout = 100):
r"""Perform a control request to the default control pipe on a device.
Arguments:
requestType: specifies the direction of data flow, the type
of request, and the recipient.
... | r"""Perform a control request to the default control pipe on a device.
Arguments:
requestType: specifies the direction of data flow, the type
of request, and the recipient.
request: specifies the request.
buffer: if the transfer is a write transfer, ... | Below is the the instruction that describes the task:
### Input:
r"""Perform a control request to the default control pipe on a device.
Arguments:
requestType: specifies the direction of data flow, the type
of request, and the recipient.
request: specifies t... |
def add(self, document_data, document_id=None):
"""Create a document in the Firestore database with the provided data.
Args:
document_data (dict): Property names and values to use for
creating the document.
document_id (Optional[str]): The document identifier wit... | Create a document in the Firestore database with the provided data.
Args:
document_data (dict): Property names and values to use for
creating the document.
document_id (Optional[str]): The document identifier within the
current collection. If not provided... | Below is the the instruction that describes the task:
### Input:
Create a document in the Firestore database with the provided data.
Args:
document_data (dict): Property names and values to use for
creating the document.
document_id (Optional[str]): The document iden... |
def gaussian_square(times: np.ndarray, amp: complex, center: float, width: float,
sigma: float, zeroed_width: Union[None, float] = None) -> np.ndarray:
r"""Continuous gaussian square pulse.
Args:
times: Times to output pulse for.
amp: Pulse amplitude.
center: Center ... | r"""Continuous gaussian square pulse.
Args:
times: Times to output pulse for.
amp: Pulse amplitude.
center: Center of the square pulse component.
width: Width of the square pulse component.
sigma: Width (standard deviation) of gaussian rise/fall portion of the pulse.
... | Below is the the instruction that describes the task:
### Input:
r"""Continuous gaussian square pulse.
Args:
times: Times to output pulse for.
amp: Pulse amplitude.
center: Center of the square pulse component.
width: Width of the square pulse component.
sigma: Width (st... |
def remove_entry(self, offset, length):
# type: (int, int) -> None
'''
Given an offset and length, find and remove the entry in this block
that corresponds.
Parameters:
offset - The offset of the entry to look for.
length - The length of the entry to look for.
... | Given an offset and length, find and remove the entry in this block
that corresponds.
Parameters:
offset - The offset of the entry to look for.
length - The length of the entry to look for.
Returns:
Nothing. | Below is the the instruction that describes the task:
### Input:
Given an offset and length, find and remove the entry in this block
that corresponds.
Parameters:
offset - The offset of the entry to look for.
length - The length of the entry to look for.
Returns:
... |
def parse_keys(self, sn: "DataNode") -> Dict[InstanceName, ScalarValue]:
"""Parse key dictionary in the context of a schema node.
Args:
sn: Schema node corresponding to a list.
"""
res = {}
for k in self.keys:
knod = sn.get_data_child(*k)
if k... | Parse key dictionary in the context of a schema node.
Args:
sn: Schema node corresponding to a list. | Below is the the instruction that describes the task:
### Input:
Parse key dictionary in the context of a schema node.
Args:
sn: Schema node corresponding to a list.
### Response:
def parse_keys(self, sn: "DataNode") -> Dict[InstanceName, ScalarValue]:
"""Parse key dictionary in the co... |
def _infer_mutants_handler(self, request):
"""Returns JSON for the `vz-line-chart`s for a feature.
Args:
request: A request that should contain 'feature_name', 'example_index',
'inference_address', 'model_name', 'model_type', 'model_version', and
'model_signature'.
Returns:
A... | Returns JSON for the `vz-line-chart`s for a feature.
Args:
request: A request that should contain 'feature_name', 'example_index',
'inference_address', 'model_name', 'model_type', 'model_version', and
'model_signature'.
Returns:
A list of JSON objects, one for each chart. | Below is the the instruction that describes the task:
### Input:
Returns JSON for the `vz-line-chart`s for a feature.
Args:
request: A request that should contain 'feature_name', 'example_index',
'inference_address', 'model_name', 'model_type', 'model_version', and
'model_signature'.
... |
def get_credentials_for_url(url, opts, force_user=None):
"""Lookup credentials for a given target in keyring and .netrc.
Optionally prompts for credentials if not found.
Returns:
2-tuple (username, password) or None
"""
creds = None
verbose = int(opts.get("verbose"))
force_prompt =... | Lookup credentials for a given target in keyring and .netrc.
Optionally prompts for credentials if not found.
Returns:
2-tuple (username, password) or None | Below is the the instruction that describes the task:
### Input:
Lookup credentials for a given target in keyring and .netrc.
Optionally prompts for credentials if not found.
Returns:
2-tuple (username, password) or None
### Response:
def get_credentials_for_url(url, opts, force_user=None):
"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.