INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Delete given device model or instance. | def delete(ctx, resource, id):
"""Delete given device model or instance.
"""
session, api_url, project_id = build_client_from_context(ctx)
url = '/'.join([api_url, resource, id])
r = session.delete(url)
if r.status_code != 200:
raise failed_request_exception('failed to delete resource', ... |
Initiates or continues a conversation with the embedded assistant service. Each call performs one round - trip sending an audio request to the service and receiving the audio response. Uses bidirectional streaming to receive results such as the END_OF_UTTERANCE event while sending audio. | def Converse(self, request_iterator, context):
"""Initiates or continues a conversation with the embedded assistant service.
Each call performs one round-trip, sending an audio request to the service
and receiving the audio response. Uses bidirectional streaming to receive
results, such as the `END_OF_U... |
Log AssistRequest fields without audio data. | def log_assist_request_without_audio(assist_request):
"""Log AssistRequest fields without audio data."""
if logging.getLogger().isEnabledFor(logging.DEBUG):
resp_copy = embedded_assistant_pb2.AssistRequest()
resp_copy.CopyFrom(assist_request)
if len(resp_copy.audio_in) > 0:
s... |
Log AssistResponse fields without audio data. | def log_assist_response_without_audio(assist_response):
"""Log AssistResponse fields without audio data."""
if logging.getLogger().isEnabledFor(logging.DEBUG):
resp_copy = embedded_assistant_pb2.AssistResponse()
resp_copy.CopyFrom(assist_response)
has_audio_data = (resp_copy.HasField('au... |
Register a device action handlers. | def command(self, intent):
"""Register a device action handlers."""
def decorator(fn):
self.handlers[intent] = fn
return decorator |
Submit device command executions. | def submit_commands(self, devices, execution):
"""Submit device command executions.
Returns: a list of concurrent.futures for scheduled executions.
"""
fs = []
for device in devices:
if device[key_id_] != self.device_id:
logging.warning('Ignoring comm... |
Dispatch device commands to the appropriate handler. | def dispatch_command(self, command, params=None):
"""Dispatch device commands to the appropriate handler."""
try:
if command in self.handlers:
self.handlers[command](**params)
else:
logging.warning('Unsupported command: %s: %s',
... |
Adjusts the loudness of the audio data in the given buffer. | def normalize_audio_buffer(buf, volume_percentage, sample_width=2):
"""Adjusts the loudness of the audio data in the given buffer.
Volume normalization is done by scaling the amplitude of the audio
in the buffer by a scale factor of 2^(volume_percentage/100)-1.
For example, 50% volume scales the amplit... |
In case of buffer size not aligned to sample_width pad it with 0s | def align_buf(buf, sample_width):
"""In case of buffer size not aligned to sample_width pad it with 0s"""
remainder = len(buf) % sample_width
if remainder != 0:
buf += b'\0' * (sample_width - remainder)
return buf |
Helper command to test audio stream processing. | def main(record_time, audio_sample_rate, audio_sample_width,
audio_iter_size, audio_block_size, audio_flush_size):
"""Helper command to test audio stream processing.
- Record 5 seconds of 16-bit samples at 16khz.
- Playback the recorded samples.
"""
end_time = time.time() + record_time
... |
Read bytes from the stream and block until sample rate is achieved. | def read(self, size):
"""Read bytes from the stream and block until sample rate is achieved.
Args:
size: number of bytes to read from the stream.
"""
now = time.time()
missing_dt = self._sleep_until - now
if missing_dt > 0:
time.sleep(missing_dt)
... |
Close the underlying stream. | def close(self):
"""Close the underlying stream."""
if self._wavep:
self._wavep.close()
self._fp.close() |
Read bytes from the stream. | def read(self, size):
"""Read bytes from the stream."""
buf, overflow = self._audio_stream.read(size)
if overflow:
logging.warning('SoundDeviceStream read overflow (%d, %d)',
size, len(buf))
return bytes(buf) |
Write bytes to the stream. | def write(self, buf):
"""Write bytes to the stream."""
underflow = self._audio_stream.write(buf)
if underflow:
logging.warning('SoundDeviceStream write underflow (size: %d)',
len(buf))
return len(buf) |
Close the underlying stream and audio interface. | def close(self):
"""Close the underlying stream and audio interface."""
if self._audio_stream:
self.stop()
self._audio_stream.close()
self._audio_stream = None |
Start recording from the audio source. | def start_recording(self):
"""Start recording from the audio source."""
self._recording = True
self._stop_recording.clear()
self._source.start() |
Stop recording from the audio source. | def stop_recording(self):
"""Stop recording from the audio source."""
self._stop_recording.set()
with self._source_lock:
self._source.stop()
self._recording = False |
Stop playback from the audio sink. | def stop_playback(self):
"""Stop playback from the audio sink."""
self._sink.flush()
self._sink.stop()
self._playing = False |
Write bytes to the sink ( if currently playing ). | def write(self, buf):
"""Write bytes to the sink (if currently playing).
"""
buf = align_buf(buf, self._sample_width)
buf = normalize_audio_buffer(buf, self.volume_percentage)
return self._sink.write(buf) |
Send a text request to the Assistant and playback the response. | def assist(self, text_query):
"""Send a text request to the Assistant and playback the response.
"""
def iter_assist_requests():
config = embedded_assistant_pb2.AssistConfig(
audio_out_config=embedded_assistant_pb2.AudioOutConfig(
encoding='LINEAR1... |
Samples for the Google Assistant API. | def main(api_endpoint, credentials, project_id,
device_model_id, device_id, device_config,
lang, display, verbose,
input_audio_file, output_audio_file,
audio_sample_rate, audio_sample_width,
audio_iter_size, audio_block_size, audio_flush_size,
grpc_deadline, once, *... |
Send a voice request to the Assistant and playback the response. | def assist(self):
"""Send a voice request to the Assistant and playback the response.
Returns: True if conversation should continue.
"""
continue_conversation = False
device_actions_futures = []
self.conversation_stream.start_recording()
logging.info('Recording ... |
Yields: AssistRequest messages to send to the API. | def gen_assist_requests(self):
"""Yields: AssistRequest messages to send to the API."""
config = embedded_assistant_pb2.AssistConfig(
audio_in_config=embedded_assistant_pb2.AudioInConfig(
encoding='LINEAR16',
sample_rate_hertz=self.conversation_stream.sample_... |
Returns reconstructed X from low - rank thresholded SVD and the rank achieved. | def _svd_step(self, X, shrinkage_value, max_rank=None):
"""
Returns reconstructed X from low-rank thresholded SVD and
the rank achieved.
"""
if max_rank:
# if we have a max rank then perform the faster randomized SVD
(U, s, V) = randomized_svd(
... |
Parameters ---------- X: np. array Data array containing NaN entries | def fill(
self,
X,
missing_mask,
fill_method=None,
inplace=False):
"""
Parameters
----------
X : np.array
Data array containing NaN entries
missing_mask : np.array
Boolean array indicating where ... |
Check to make sure that the input matrix and its mask of missing values are valid. Returns X and missing mask. | def prepare_input_data(self, X):
"""
Check to make sure that the input matrix and its mask of missing
values are valid. Returns X and missing mask.
"""
X = check_array(X, force_all_finite=False)
if X.dtype != "f" and X.dtype != "d":
X = X.astype(float)
... |
Clip values to fall within any global or column - wise min/ max constraints | def clip(self, X):
"""
Clip values to fall within any global or column-wise min/max constraints
"""
X = np.asarray(X)
if self.min_value is not None:
X[X < self.min_value] = self.min_value
if self.max_value is not None:
X[X > self.max_value] = self.... |
First undo normalization and then clip to the user - specified min/ max range. | def project_result(self, X):
"""
First undo normalization and then clip to the user-specified min/max
range.
"""
X = np.asarray(X)
if self.normalizer is not None:
X = self.normalizer.inverse_transform(X)
return self.clip(X) |
Fit the imputer and then transform input X | def fit_transform(self, X, y=None):
"""
Fit the imputer and then transform input `X`
Note: all imputations should have a `fit_transform` method,
but only some (like IterativeImputer) also support inductive mode
using `fit` or `fit_transform` on `X_train` and then `transform`
... |
Transform input X. | def transform(self, X, y=None):
"""
Transform input `X`.
Note: all imputations should have a `fit_transform` method,
but only some (like IterativeImputer) also support inductive mode
using `fit` or `fit_transform` on `X_train` and then `transform`
on new `X_test`.
... |
Rescale the range of values in images to be between [ 0 1 ] | def rescale_pixel_values(images, order="C"):
"""
Rescale the range of values in images to be between [0, 1]
"""
images = np.asarray(images, order=order).astype("float32")
images -= images.min()
images /= images.max()
return images |
Generator for ( rank name MSE MAE ) sorted by increasing MAE | def sorted_errors(self):
"""
Generator for (rank, name, MSE, MAE) sorted by increasing MAE
"""
for i, (name, mae) in enumerate(
sorted(self.mae_dict.items(), key=lambda x: x[1])):
yield(i + 1, name, self.mse_dict[name], self.mae_dict[name],) |
Tests if x is NaN This function is meant to overcome the issue that np. isnan does not allow non - numerical types as input and that np. nan is not np. float ( nan ). Parameters ---------- x: any type Returns ------- boolean Examples -------- >>> is_scalar_nan ( np. nan ) True >>> is_scalar_nan ( float ( nan )) True >>... | def is_scalar_nan(x):
"""Tests if x is NaN
This function is meant to overcome the issue that np.isnan does not allow
non-numerical types as input, and that np.nan is not np.float('nan').
Parameters
----------
x : any type
Returns
-------
boolean
Examples
--------
>>> is_s... |
Compute the boolean mask X == missing_values. | def _get_mask(X, value_to_mask):
"""Compute the boolean mask X == missing_values."""
if is_scalar_nan(value_to_mask):
if X.dtype.kind == "f":
return np.isnan(X)
elif X.dtype.kind in ("i", "u"):
# can't have NaNs in integer array.
return np.zeros(X.shape, dtype... |
Compute the most frequent value in a 1d array extended with [ extra_value ] * n_repeat where extra_value is assumed to be not part of the array. | def _most_frequent(array, extra_value, n_repeat):
"""Compute the most frequent value in a 1d array extended with
[extra_value] * n_repeat, where extra_value is assumed to be not part
of the array."""
# Compute the most frequent value in array only
if array.size > 0:
with warnings.catch... |
Fit the imputer on X. | def fit(self, X, y=None):
"""Fit the imputer on X.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Input data, where ``n_samples`` is the number of samples and
``n_features`` is the number of features.
Returns
... |
Fit the transformer on sparse data. | def _sparse_fit(self, X, strategy, missing_values, fill_value):
"""Fit the transformer on sparse data."""
mask_data = _get_mask(X.data, missing_values)
n_implicit_zeros = X.shape[0] - np.diff(X.indptr)
statistics = np.empty(X.shape[1])
if strategy == "constant":
# f... |
Fit the transformer on dense data. | def _dense_fit(self, X, strategy, missing_values, fill_value):
"""Fit the transformer on dense data."""
mask = _get_mask(X, missing_values)
masked_X = ma.masked_array(X, mask=mask)
# Mean
if strategy == "mean":
mean_masked = np.ma.mean(masked_X, axis=0)
#... |
Impute all missing values in X. | def transform(self, X):
"""Impute all missing values in X.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
The input data to complete.
"""
check_is_fitted(self, 'statistics_')
X = self._validate_input(X)
... |
Impute a single feature from the others provided. | def _impute_one_feature(self,
X_filled,
mask_missing_values,
feat_idx,
neighbor_feat_idx,
predictor=None,
fit_mode=True):
"""Impute a single fea... |
Get a list of other features to predict feat_idx. | def _get_neighbor_feat_idx(self,
n_features,
feat_idx,
abs_corr_mat):
"""Get a list of other features to predict ``feat_idx``.
If self.n_nearest_features is less than or equal to the total
number of fea... |
Decide in what order we will update the features. | def _get_ordered_idx(self, mask_missing_values):
"""Decide in what order we will update the features.
As a homage to the MICE R package, we will have 4 main options of
how to order the updates, and use a random order if anything else
is specified.
Also, this function skips feat... |
Get absolute correlation matrix between features. | def _get_abs_corr_mat(self, X_filled, tolerance=1e-6):
"""Get absolute correlation matrix between features.
Parameters
----------
X_filled : ndarray, shape (n_samples, n_features)
Input data with the most recent imputations.
tolerance : float, optional (default=1e-6... |
Perform initial imputation for input X. | def _initial_imputation(self, X):
"""Perform initial imputation for input X.
Parameters
----------
X : ndarray, shape (n_samples, n_features)
Input data, where "n_samples" is the number of samples and
"n_features" is the number of features.
Returns
... |
Fits the imputer on X and return the transformed X. | def fit_transform(self, X, y=None):
"""Fits the imputer on X and return the transformed X.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Input data, where "n_samples" is the number of samples and
"n_features" is the number of features.
... |
Imputes all missing values in X. | def transform(self, X):
"""Imputes all missing values in X.
Note that this is stochastic, and that if random_state is not fixed,
repeated calls, or permuted input, will yield different results.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
... |
Parameters ---------- X: np. array Data matrix with missing values filled in | def _constraints(self, X, missing_mask, S, error_tolerance):
"""
Parameters
----------
X : np.array
Data matrix with missing values filled in
missing_mask : np.array
Boolean array indicating where missing values were
S : cvxpy.Variable
... |
Parameters ---------- m n: int Dimensions that of solution matrix Returns the objective function and a variable representing the solution to the convex optimization problem. | def _create_objective(self, m, n):
"""
Parameters
----------
m, n : int
Dimensions that of solution matrix
Returns the objective function and a variable representing the
solution to the convex optimization problem.
"""
# S is the completed matr... |
usage example: grid = import_from ( sklearn. model_selection GridSearchCV ) is equivalent to: from sklearn. model_selection import GridSearchV as grid | def import_from(module, name):
'''
usage example:
grid = import_from('sklearn.model_selection', 'GridSearchCV')
is equivalent to:
from sklearn.model_selection import GridSearchV as grid
'''
module = importlib.import_module(module)
return getattr(module, name) |
It s tricky to pick a single matrix out of all the candidate solutions with differing shrinkage thresholds. Our heuristic is to pick the matrix whose percentiles match best between the missing and observed data. | def choose_solution_using_percentiles(
X_original,
solutions,
parameters=None,
verbose=False,
percentiles=list(range(10, 100, 10))):
"""
It's tricky to pick a single matrix out of all the candidate
solutions with differing shrinkage thresholds.
Our heuristic is to... |
row_center [ i ] = sum { j in observed [ i: ] } { ( 1/ column_scale [ j ] ) * ( X [ i j ] - column_center [ j ] ) } ------------------------------------------------------------ sum { j in observed [ i: ] } { 1/ column_scale [ j ] } | def estimate_row_means(
self,
X,
observed,
column_means,
column_scales):
"""
row_center[i] =
sum{j in observed[i, :]}{
(1 / column_scale[j]) * (X[i, j] - column_center[j])
}
----------------------------------... |
column_center [ j ] = sum { i in observed [: j ] } { ( 1/ row_scale [ i ] ) * ( X [ i j ] ) - row_center [ i ] ) } ------------------------------------------------------------ sum { i in observed [: j ] } { 1/ row_scale [ i ] } | def estimate_column_means(
self,
X,
observed,
row_means,
row_scales):
"""
column_center[j] =
sum{i in observed[:, j]}{
(1 / row_scale[i]) * (X[i, j]) - row_center[i])
}
---------------------------------------... |
row_scale [ i ] ** 2 = mean { j in observed [ i: ] } { ( X [ i j ] - row_center [ i ] - column_center [ j ] ) ** 2 -------------------------------------------------- column_scale [ j ] ** 2 } | def estimate_row_scales(
self,
X_centered,
column_scales):
"""
row_scale[i]**2 =
mean{j in observed[i, :]}{
(X[i, j] - row_center[i] - column_center[j]) ** 2
--------------------------------------------------
col... |
column_scale [ j ] ** 2 = mean { i in observed [: j ] } { ( X [ i j ] - row_center [ i ] - column_center [ j ] ) ** 2 ------------------------------------------------- row_scale [ i ] ** 2 } | def estimate_column_scales(
self,
X_centered,
row_scales):
"""
column_scale[j] ** 2 =
mean{i in observed[:, j]}{
(X[i, j] - row_center[i] - column_center[j]) ** 2
-------------------------------------------------
... |
Compute the continuous Jacard similarity between all pairs of keys in dictionary - of - dictionaries given as an input. | def jacard_similarity_from_nested_dicts(self, nested_dictionaries):
"""
Compute the continuous Jacard similarity between all pairs
of keys in dictionary-of-dictionaries given as an input.
Returns three element tuple:
- similarity dictionary: (key, key) -> float
-... |
Keys of nested dictionaries can be arbitrary objects. | def complete_dict(
self,
values_dict):
"""
Keys of nested dictionaries can be arbitrary objects.
"""
if self.orientation != "rows":
values_dict = transpose_nested_dictionary(values_dict)
row_keys, column_keys = collect_nested_keys(values_dict)... |
Give an ordering to the outer and inner keys used in a dictionary that maps to dictionaries. | def nested_key_indices(nested_dict):
"""
Give an ordering to the outer and inner keys used in a dictionary that
maps to dictionaries.
"""
outer_keys, inner_keys = collect_nested_keys(nested_dict)
outer_key_indices = {k: i for (i, k) in enumerate(outer_keys)}
inner_key_indices = {k: i for (i,... |
Combine the outer and inner keys of nested dictionaries into a single ordering. | def flattened_nested_key_indices(nested_dict):
"""
Combine the outer and inner keys of nested dictionaries into a single
ordering.
"""
outer_keys, inner_keys = collect_nested_keys(nested_dict)
combined_keys = list(sorted(set(outer_keys + inner_keys)))
return {k: i for (i, k) in enumerate(com... |
Parameters ---------- nested_dict: dict Dictionary which contains dictionaries | def array_from_nested_dictionary(
nested_dict,
array_fn,
dtype="float32",
square_result=False):
"""
Parameters
----------
nested_dict : dict
Dictionary which contains dictionaries
array_fn : function
Takes shape and dtype as arguments, returns empty a... |
X: numpy. ndarray | def matrix_to_pair_dictionary(
X, row_keys=None, column_keys=None, filter_fn=None):
"""
X : numpy.ndarray
row_keys : dict
Dictionary mapping indices to row names. If omitted then maps each
number to its string representation, such as 1 -> "1".
column_keys : dict
If omit... |
Transform dictionary from pairs of keys to dict - > dict - > float | def curry_pair_dictionary(key_pair_dict, default_value=0.0):
"""
Transform dictionary from pairs of keys to dict -> dict -> float
"""
result = defaultdict(dict)
for (a, b), value in key_pair_dict.items():
result[a][b] = value
return result |
Transform dictionary from ( key_a - > key_b - > float ) to ( key_a key_b ) - > float | def uncurry_nested_dictionary(curried_dict):
"""
Transform dictionary from (key_a -> key_b -> float) to
(key_a, key_b) -> float
"""
result = {}
for a, a_dict in curried_dict.items():
for b, value in a_dict.items():
result[(a, b)] = value
return result |
Convert a dictionary whose keys are pairs ( k1 k2 ) into a sparse or incomplete array. | def array_from_pair_dictionary(
pair_dict,
array_fn,
dtype="float32",
square_result=False):
"""
Convert a dictionary whose keys are pairs (k1, k2) into a sparse
or incomplete array.
Parameters
----------
pair_dict : dict
Dictionary from pairs of keys to v... |
Given a nested dictionary from k1 - > k2 > value transpose its outer and inner keys so it maps k2 - > k1 - > value. | def transpose_nested_dictionary(nested_dict):
"""
Given a nested dictionary from k1 -> k2 > value
transpose its outer and inner keys so it maps
k2 -> k1 -> value.
"""
result = defaultdict(dict)
for k1, d in nested_dict.items():
for k2, v in d.items():
result[k2][k1] = v
... |
Create reverse - lookup dictionary mapping each row key to a list of triplets: [ ( column key value )... ] | def reverse_lookup_from_nested_dict(values_dict):
"""
Create reverse-lookup dictionary mapping each row key to a list of triplets:
[(column key, value), ...]
Parameters
----------
nested_values_dict : dict
column_key -> row_key -> value
weights_dict : dict
column_key -> row... |
Yield all cells in an nbformat - insensitive manner | def _cells(nb):
"""Yield all cells in an nbformat-insensitive manner"""
if nb.nbformat < 4:
for ws in nb.worksheets:
for cell in ws.cells:
yield cell
else:
for cell in nb.cells:
yield cell |
strip the outputs from a notebook object | def strip_output(nb):
"""strip the outputs from a notebook object"""
nb.metadata.pop('signature', None)
nb.metadata.pop('widgets', None)
for cell in _cells(nb):
if 'outputs' in cell:
cell['outputs'] = []
if 'prompt_number' in cell:
cell['prompt_number'] = None
... |
Enforce min < = value < = max | def _validate_min(self, proposal):
"""Enforce min <= value <= max"""
min = proposal['value']
if min > self.max:
raise TraitError('Setting min > max')
if min > self.value:
self.value = min
return min |
Enforce min < = value < = max | def _validate_max(self, proposal):
"""Enforce min <= value <= max"""
max = proposal['value']
if max < self.min:
raise TraitError('setting max < min')
if max < self.value:
self.value = max
return max |
Cap and floor value | def _validate_value(self, proposal):
"""Cap and floor value"""
value = proposal['value']
if self.base ** self.min > value or self.base ** self.max < value:
value = min(max(value, self.base ** self.min), self.base ** self.max)
return value |
Show matplotlib plots immediately if using the inline backend. | def show_inline_matplotlib_plots():
"""Show matplotlib plots immediately if using the inline backend.
With ipywidgets 6.0, matplotlib plots don't work well with interact when
using the inline backend that comes with ipykernel. Basically, the inline
backend only shows the plot after the entire cell exec... |
Connect widget controls to a function. | def interactive_output(f, controls):
"""Connect widget controls to a function.
This function does not generate a user interface for the widgets (unlike `interact`).
This enables customisation of the widget user interface layout.
The user interface layout must be defined and displayed manually.
"""
... |
Match a pattern of types in a sequence. | def _matches(o, pattern):
"""Match a pattern of types in a sequence."""
if not len(o) == len(pattern):
return False
comps = zip(o,pattern)
return all(isinstance(obj,kind) for obj,kind in comps) |
Return min max value given input values with possible None. | def _get_min_max_value(min, max, value=None, step=None):
"""Return min, max, value given input values with possible None."""
# Either min and max need to be given, or value needs to be given
if value is None:
if min is None or max is None:
raise ValueError('unable to infer range, value f... |
Get an abbreviation for a function parameter. | def _yield_abbreviations_for_parameter(param, kwargs):
"""Get an abbreviation for a function parameter."""
name = param.name
kind = param.kind
ann = param.annotation
default = param.default
not_found = (name, empty, empty)
if kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY):... |
Call the interact function and update the output widget with the result of the function call. | def update(self, *args):
"""
Call the interact function and update the output widget with
the result of the function call.
Parameters
----------
*args : ignored
Required for this method to be used as traitlets callback.
"""
self.kwargs = {}
... |
Find the abbreviations for the given function and kwargs. Return ( name abbrev default ) tuples. | def find_abbreviations(self, kwargs):
"""Find the abbreviations for the given function and kwargs.
Return (name, abbrev, default) tuples.
"""
new_kwargs = []
try:
sig = self.signature()
except (ValueError, TypeError):
# can't inspect, no info from ... |
Given a sequence of ( name abbrev default ) tuples return a sequence of Widgets. | def widgets_from_abbreviations(self, seq):
"""Given a sequence of (name, abbrev, default) tuples, return a sequence of Widgets."""
result = []
for name, abbrev, default in seq:
widget = self.widget_from_abbrev(abbrev, default)
if not (isinstance(widget, ValueWidget) or is... |
Build a ValueWidget instance given an abbreviation or Widget. | def widget_from_abbrev(cls, abbrev, default=empty):
"""Build a ValueWidget instance given an abbreviation or Widget."""
if isinstance(abbrev, ValueWidget) or isinstance(abbrev, fixed):
return abbrev
if isinstance(abbrev, tuple):
widget = cls.widget_from_tuple(abbrev)
... |
Make widgets from single values which can be used as parameter defaults. | def widget_from_single_value(o):
"""Make widgets from single values, which can be used as parameter defaults."""
if isinstance(o, string_types):
return Text(value=unicode_type(o))
elif isinstance(o, bool):
return Checkbox(value=o)
elif isinstance(o, Integral):
... |
Make widgets from a tuple abbreviation. | def widget_from_tuple(o):
"""Make widgets from a tuple abbreviation."""
if _matches(o, (Real, Real)):
min, max, value = _get_min_max_value(o[0], o[1])
if all(isinstance(_, Integral) for _ in o):
cls = IntSlider
else:
cls = FloatSlider
... |
Make widgets from an iterable. This should not be done for a string or tuple. | def widget_from_iterable(o):
"""Make widgets from an iterable. This should not be done for
a string or tuple."""
# Dropdown expects a dict or list, so we convert an arbitrary
# iterable to either of those.
if isinstance(o, (list, dict)):
return Dropdown(options=o)
... |
Return an interactive function widget for the given function. | def widget(self, f):
"""
Return an interactive function widget for the given function.
The widget is only constructed, not displayed nor attached to
the function.
Returns
-------
An instance of ``self.cls`` (typically :class:`interactive`).
Parameters
... |
Change options for interactive functions. | def options(self, **kwds):
"""
Change options for interactive functions.
Returns
-------
A new :class:`_InteractFactory` which will apply the
options when called.
"""
opts = dict(self.opts)
for k in kwds:
try:
# Ensure ... |
Sets the title of a container page. | def set_title(self, index, title):
"""Sets the title of a container page.
Parameters
----------
index : int
Index of the container page
title : unicode
New title
"""
# JSON dictionaries have string keys, so we convert index to a string
... |
Gets the title of a container pages. | def get_title(self, index):
"""Gets the title of a container pages.
Parameters
----------
index : int
Index of the container page
"""
# JSON dictionaries have string keys, so we convert index to a string
index = unicode_type(int(index))
if ind... |
Runs a bash script in the local directory | def bash(filename):
"""Runs a bash script in the local directory"""
sys.stdout.flush()
subprocess.call("bash {}".format(filename), shell=True) |
The inverse of _remove_buffers except here we modify the existing dict/ lists. Modifying should be fine since this is used when state comes from the wire. | def _put_buffers(state, buffer_paths, buffers):
"""The inverse of _remove_buffers, except here we modify the existing dict/lists.
Modifying should be fine, since this is used when state comes from the wire.
"""
for buffer_path, buffer in zip(buffer_paths, buffers):
# we'd like to set say sync_da... |
For internal see _remove_buffers | def _separate_buffers(substate, path, buffer_paths, buffers):
"""For internal, see _remove_buffers"""
# remove binary types from dicts and lists, but keep track of their paths
# any part of the dict/list that needs modification will be cloned, so the original stays untouched
# e.g. {'x': {'ar': ar}, 'y'... |
Return ( state_without_buffers buffer_paths buffers ) for binary message parts | def _remove_buffers(state):
"""Return (state_without_buffers, buffer_paths, buffers) for binary message parts
A binary message part is a memoryview, bytearray, or python 3 bytes object.
As an example:
>>> state = {'plain': [0, 'text'], 'x': {'ar': memoryview(ar1)}, 'y': {'shape': (10,10), 'data': memo... |
Compare two lists of buffers for equality. | def _buffer_list_equal(a, b):
"""Compare two lists of buffers for equality.
Used to decide whether two sequences of buffers (memoryviews,
bytearrays, or python 3 bytes) differ, such that a sync is needed.
Returns True if equal, False if unequal
"""
if len(a) != len(b):
return False
... |
decorator for showing tracebacks in IPython | def _show_traceback(method):
"""decorator for showing tracebacks in IPython"""
def m(self, *args, **kwargs):
try:
return(method(self, *args, **kwargs))
except Exception as e:
ip = get_ipython()
if ip is None:
self.log.warning("Exception in widg... |
For backwards compatibility we support | def register(name=''):
"For backwards compatibility, we support @register(name) syntax."
def reg(widget):
"""A decorator registering a widget class in the widget registry."""
w = widget.class_traits()
Widget.widget_types.register(w['_model_module'].default_value,
... |
( Un ) Register a callback | def register_callback(self, callback, remove=False):
"""(Un)Register a callback
Parameters
----------
callback: method handle
Method to be registered or unregistered.
remove=False: bool
Whether to unregister the callback."""
# (Un)Register the ca... |
Register a value | def register(self, model_module, model_module_version_range, model_name, view_module, view_module_version_range, view_name, klass):
"""Register a value"""
model_module = self._registry.setdefault(model_module, {})
model_version = model_module.setdefault(model_module_version_range, {})
mo... |
Get a value | def get(self, model_module, model_module_version, model_name, view_module, view_module_version, view_name):
"""Get a value"""
module_versions = self._registry[model_module]
# The python semver module doesn't work well, for example, it can't do match('3', '*')
# so we just take the first ... |
Static method called when a widget is constructed. | def _call_widget_constructed(widget):
"""Static method, called when a widget is constructed."""
if Widget._widget_construction_callback is not None and callable(Widget._widget_construction_callback):
Widget._widget_construction_callback(widget) |
Static method called when a widget is constructed. | def handle_comm_opened(comm, msg):
"""Static method, called when a widget is constructed."""
version = msg.get('metadata', {}).get('version', '')
if version.split('.')[0] != PROTOCOL_VERSION_MAJOR:
raise ValueError("Incompatible widget protocol versions: received version %r, expected... |
Returns the full state for a widget manager for embedding | def get_manager_state(drop_defaults=False, widgets=None):
"""Returns the full state for a widget manager for embedding
:param drop_defaults: when True, it will not include default value
:param widgets: list with widgets to include in the state (or all widgets when None)
:return:
... |
Open a comm to the frontend if one isn t already open. | def open(self):
"""Open a comm to the frontend if one isn't already open."""
if self.comm is None:
state, buffer_paths, buffers = _remove_buffers(self.get_state())
args = dict(target_name='jupyter.widget',
data={'state': state, 'buffer_paths': buffer_path... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.