text stringlengths 81 112k |
|---|
Create a ``DataSpec`` dict that applyies a client-side
``LinearColorMapper`` transformation to a ``ColumnDataSource`` column.
Args:
field_name (str) : a field name to configure ``DataSpec`` with
palette (seq[color]) : a list of colors to use for colormapping
low (float) : a minimum va... |
Create a ``DataSpec`` dict that applies a client-side ``LogColorMapper``
transformation to a ``ColumnDataSource`` column.
Args:
field_name (str) : a field name to configure ``DataSpec`` with
palette (seq[color]) : a list of colors to use for colormapping
low (float) : a minimum value ... |
Return a browser controller.
Args:
browser (str or None) : browser name, or ``None`` (default: ``None``)
If passed the string ``'none'``, a dummy web browser controller
is returned
Otherwise, use the value to select an appropriate controller using
the ``webb... |
Open a browser to view the specified location.
Args:
location (str) : Location to open
If location does not begin with "http:" it is assumed
to be a file path on the local filesystem.
browser (str or None) : what browser to use (default: None)
... |
Create a ``CustomJSFilter`` instance from a Python function. The
function is translated to JavaScript using PScript.
The ``func`` function namespace will contain the variable ``source``
at render time. This will be the data source associated with the ``CDSView``
that this filter is adde... |
Return streamlines of a vector flow.
* x and y are 1d arrays defining an *evenly spaced* grid.
* u and v are 2d arrays (shape [y,x]) giving velocities.
* density controls the closeness of the streamlines. For different
densities in each direction, use a tuple or list [densityx, densityy].
def stream... |
Function to build a suitable CustomJS to display the current event
in the div model.
def display_event(div, attributes=[]):
"""
Function to build a suitable CustomJS to display the current event
in the div model.
"""
style = 'float: left; clear: left; font-size: 10pt'
return CustomJS(args=d... |
Function that returns a Python callback to pretty print the events.
def print_event(attributes=[]):
"""
Function that returns a Python callback to pretty print the events.
"""
def python_callback(event):
cls_name = event.__class__.__name__
attrs = ', '.join(['{attr}={val}'.format(attr=a... |
Create a new Message instance for the given type.
Args:
msgtype (str) :
def create(self, msgtype, *args, **kwargs):
''' Create a new Message instance for the given type.
Args:
msgtype (str) :
'''
if msgtype not in self._messages:
raise Prot... |
Create a Message instance assembled from json fragments.
Args:
header_json (``JSON``) :
metadata_json (``JSON``) :
content_json (``JSON``) :
Returns:
message
def assemble(self, header_json, metadata_json, content_json):
''' Create a Message in... |
Attempt to combine a new event with a list of previous events.
The ``old_event`` will be scanned in reverse, and ``.combine(new_event)``
will be called on each. If a combination can be made, the function
will return immediately. Otherwise, ``new_event`` will be appended to
``old_events``.
Args:
... |
Add callback to be invoked once on the next tick of the event loop.
Args:
callback (callable) :
A callback function to execute on the next tick.
Returns:
NextTickCallback : can be used with ``remove_next_tick_callback``
.. note::
Next tick c... |
Add a callback to be invoked on a session periodically.
Args:
callback (callable) :
A callback function to execute periodically
period_milliseconds (int) :
Number of milliseconds between each callback execution.
Returns:
PeriodicCall... |
Add a model as a root of this Document.
Any changes to this model (including to other models referred to
by it) will trigger ``on_change`` callbacks registered on this
document.
Args:
model (Model) :
The model to add as a root of this document.
... |
Add callback to be invoked once, after a specified timeout passes.
Args:
callback (callable) :
A callback function to execute after timeout
timeout_milliseconds (int) :
Number of milliseconds before callback execution.
Returns:
Timeo... |
Apply a JSON patch object and process any resulting events.
Args:
patch (JSON-data) :
The JSON-object containing the patch to apply.
setter (ClientSession or ServerSession or None, optional) :
This is used to prevent "boomerang" updates to Bokeh apps.
... |
Remove all content from the document but do not reset title.
Returns:
None
def clear(self):
''' Remove all content from the document but do not reset title.
Returns:
None
'''
self._push_all_models_freeze()
try:
while len(self._roots... |
Clean up after any modules created by this Document when its session is
destroyed.
def delete_modules(self):
''' Clean up after any modules created by this Document when its session is
destroyed.
'''
from gc import get_referrers
from types import FrameType
log.... |
Load a document from JSON.
json (JSON-data) :
A JSON-encoded document to create a new Document from.
Returns:
Document :
def from_json(cls, json):
''' Load a document from JSON.
json (JSON-data) :
A JSON-encoded document to create a new Document fr... |
Activate a document hold.
While a hold is active, no model changes will be applied, or trigger
callbacks. Once ``unhold`` is called, the events collected during the
hold will be applied according to the hold policy.
Args:
hold ('combine' or 'collect', optional)
... |
Turn off any active document hold and apply any collected events.
Returns:
None
def unhold(self):
''' Turn off any active document hold and apply any collected events.
Returns:
None
'''
# no-op if we are already no holding
if self._hold is None... |
Provide callbacks to invoke if the document or any Model reachable
from its roots changes.
def on_change(self, *callbacks):
''' Provide callbacks to invoke if the document or any Model reachable
from its roots changes.
'''
for callback in callbacks:
if callback in ... |
Provide callbacks to invoke when the session serving the Document
is destroyed
def on_session_destroyed(self, *callbacks):
''' Provide callbacks to invoke when the session serving the Document
is destroyed
'''
for callback in callbacks:
_check_callback(callback, ('s... |
Remove a model as root model from this Document.
Changes to this model may still trigger ``on_change`` callbacks
on this document, if the model is still referred to by other
root models.
Args:
model (Model) :
The model to add as a root of this document.
... |
Overwrite everything in this document with the JSON-encoded
document.
json (JSON-data) :
A JSON-encoded document to overwrite this one.
Returns:
None
def replace_with_json(self, json):
''' Overwrite everything in this document with the JSON-encoded
docu... |
Query this document for objects that match the given selector.
Args:
selector (JSON-like query dictionary) : you can query by type or by
name, e.g. ``{"type": HoverTool}``, ``{"name": "mycircle"}``
Returns:
seq[Model]
def select(self, selector):
''' Que... |
Query this document for objects that match the given selector.
Raises an error if more than one object is found. Returns
single matching object, or None if nothing is found
Args:
selector (JSON-like query dictionary) : you can query by type or by
name, e.g. ``{"type... |
Convert the document to a JSON string.
Args:
indent (int or None, optional) : number of spaces to indent, or
None to suppress all newlines and indentation (default: None)
Returns:
str
def to_json_string(self, indent=None):
''' Convert the document to a ... |
Perform integrity checks on the modes in this document.
Returns:
None
def validate(self):
''' Perform integrity checks on the modes in this document.
Returns:
None
'''
for r in self.roots:
refs = r.references()
check_integrity(r... |
Internal implementation for adding session callbacks.
Args:
callback_obj (SessionCallback) :
A session callback object that wraps a callable and is
passed to ``trigger_on_change``.
callback (callable) :
A callable to execute when session ... |
Move all data in this doc to the dest_doc, leaving this doc empty.
Args:
dest_doc (Document) :
The Bokeh document to populate with data from this one
Returns:
None
def _destructively_move(self, dest_doc):
''' Move all data in this doc to the dest_doc, l... |
Called by Model when it changes
def _notify_change(self, model, attr, old, new, hint=None, setter=None, callback_invoker=None):
''' Called by Model when it changes
'''
# if name changes, update by-name index
if attr == 'name':
if old is not None:
self._all_m... |
Remove a callback added earlier with ``add_periodic_callback``,
``add_timeout_callback``, or ``add_next_tick_callback``.
Returns:
None
Raises:
KeyError, if the callback was never added
def _remove_session_callback(self, callback_obj, originator):
''' Remove a c... |
Bokeh-internal function to check callback signature
def _check_callback(callback, fargs, what="Callback functions"):
'''Bokeh-internal function to check callback signature'''
sig = signature(callback)
formatted_args = format_signature(sig)
error_msg = what + " must have signature func(%s), got func%s"
... |
Add a callback on this object to trigger when ``attr`` changes.
Args:
attr (str) : an attribute name on this object
callback (callable) : a callback function to register
Returns:
None
def on_change(self, attr, *callbacks):
''' Add a callback on this object ... |
Remove a callback from this object
def remove_on_change(self, attr, *callbacks):
''' Remove a callback from this object '''
if len(callbacks) == 0:
raise ValueError("remove_on_change takes an attribute name and one or more callbacks, got only one parameter")
_callbacks = self._callb... |
Trigger callbacks for ``attr`` on this object.
Args:
attr (str) :
old (object) :
new (object) :
Returns:
None
def trigger(self, attr, old, new, hint=None, setter=None):
''' Trigger callbacks for ``attr`` on this object.
Args:
... |
Download larger data sets for various Bokeh examples.
def download(progress=True):
''' Download larger data sets for various Bokeh examples.
'''
data_dir = external_data_dir(create=True)
print("Using data directory: %s" % data_dir)
s3 = 'https://bokeh-sampledata.s3.amazonaws.com'
files = [
... |
Execute the Bokeh command.
Args:
argv (seq[str]) : a list of command line arguments to process
Returns:
None
The first item in ``argv`` is typically "bokeh", and the second should
be the name of one of the available subcommands:
* :ref:`html <bokeh.command.subcommands.html>`
... |
Immediately display a Bokeh object or application.
:func:`show` may be called multiple times in a single Jupyter notebook
cell to display multiple objects. The objects are displayed in order.
Args:
obj (LayoutDOM or Application or callable) :
A Bokeh object to display.
... |
Render an HTML page from a template and Bokeh render items.
Args:
bundle (tuple):
a tuple containing (bokehjs, bokehcss)
docs_json (JSON-like):
Serialized Bokeh Document
render_items (RenderItems)
Specific items to render from the document and where
... |
Downloads, then extracts a zip file.
def extract_hosted_zip(data_url, save_dir, exclude_term=None):
"""Downloads, then extracts a zip file."""
zip_name = os.path.join(save_dir, 'temp.zip')
# get the zip file
try:
print('Downloading %r to %r' % (data_url, zip_name))
zip_name, hdrs = ur... |
Extracts a zip file to its containing directory.
def extract_zip(zip_name, exclude_term=None):
"""Extracts a zip file to its containing directory."""
zip_dir = os.path.dirname(os.path.abspath(zip_name))
try:
with zipfile.ZipFile(zip_name) as z:
# write each zipped file out if it isn'... |
Convenience property to retrieve the value tuple as a tuple of
datetime objects.
def value_as_datetime(self):
''' Convenience property to retrieve the value tuple as a tuple of
datetime objects.
'''
if self.value is None:
return None
v1, v2 = self.value
... |
Convenience property to retrieve the value tuple as a tuple of
date objects.
Added in version 1.1
def value_as_date(self):
''' Convenience property to retrieve the value tuple as a tuple of
date objects.
Added in version 1.1
'''
if self.value is None:
... |
Execute the configured ``main.py`` or ``main.ipynb`` to modify the
document.
This method will also search the app directory for any theme or
template files, and automatically configure the document with them
if they are found.
def modify_document(self, doc):
''' Execute the con... |
Prints a list of valid marker types for scatter()
Returns:
None
def markers():
''' Prints a list of valid marker types for scatter()
Returns:
None
'''
print("Available markers: \n\n - " + "\n - ".join(list(MarkerType)))
print()
print("Shortcuts: \n\n" + "\n".join(" %r: %s"... |
Creates a scatter plot of the given x and y items.
Args:
x (str or seq[float]) : values or field names of center x coordinates
y (str or seq[float]) : values or field names of center y coordinates
size (str or list[float]) : values or field names of sizes in screen units
... |
Perform a simple equal-weight hexagonal binning.
A :class:`~bokeh.models._glyphs.HexTile` glyph will be added to display
the binning. The :class:`~bokeh.models.sources.ColumnDataSource` for
the glyph will have columns ``q``, ``r``, and ``count``, where ``q``
and ``r`` are `axial coordin... |
Generate multiple ``HArea`` renderers for levels stacked left
to right.
Args:
stackers (seq[str]) : a list of data source field names to stack
successively for ``x1`` and ``x2`` harea coordinates.
Additionally, the ``name`` of the renderer will be set to
... |
Generate multiple ``HBar`` renderers for levels stacked left to right.
Args:
stackers (seq[str]) : a list of data source field names to stack
successively for ``left`` and ``right`` bar coordinates.
Additionally, the ``name`` of the renderer will be set to
... |
Generate multiple ``Line`` renderers for lines stacked vertically
or horizontally.
Args:
x (seq[str]) :
y (seq[str]) :
Additionally, the ``name`` of the renderer will be set to
the value of each successive stacker (this is useful with the
special hover ... |
Generate multiple ``VArea`` renderers for levels stacked bottom
to top.
Args:
stackers (seq[str]) : a list of data source field names to stack
successively for ``y1`` and ``y1`` varea coordinates.
Additionally, the ``name`` of the renderer will be set to
... |
Generate multiple ``VBar`` renderers for levels stacked bottom
to top.
Args:
stackers (seq[str]) : a list of data source field names to stack
successively for ``left`` and ``right`` bar coordinates.
Additionally, the ``name`` of the renderer will be set to
... |
Creates a network graph using the given node, edge and layout provider.
Args:
node_source (:class:`~bokeh.models.sources.ColumnDataSource`) : a user-supplied data source
for the graph nodes. An attempt will be made to convert the object to
:class:`~bokeh.models.sourc... |
Convert an ``ws(s)`` URL for a Bokeh server into the appropriate
``http(s)`` URL for the websocket endpoint.
Args:
url (str):
An ``ws(s)`` URL ending in ``/ws``
Returns:
str:
The corresponding ``http(s)`` URL.
Raises:
ValueError:
If the inpu... |
Convert an ``http(s)`` URL for a Bokeh server websocket endpoint into
the appropriate ``ws(s)`` URL
Args:
url (str):
An ``http(s)`` URL
Returns:
str:
The corresponding ``ws(s)`` URL ending in ``/ws``
Raises:
ValueError:
If the input URL is n... |
Turn off property validation during update callbacks
Example:
.. code-block:: python
@without_property_validation
def update(attr, old, new):
# do things without validation
See Also:
:class:`~bokeh.core.properties.validate`: context mangager for more fi... |
Get the correct Jinja2 Environment, also for frozen scripts.
def get_env():
''' Get the correct Jinja2 Environment, also for frozen scripts.
'''
if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
# PyInstaller uses _MEIPASS and only works with jinja2.FileSystemLoader
templates_p... |
From a dataframe create a parallel coordinate plot
def parallel_plot(df, color=None, palette=None):
"""From a dataframe create a parallel coordinate plot
"""
npts = df.shape[0]
ndims = len(df.columns)
if color is None:
color = np.ones(npts)
if palette is None:
palette = ['#ff00... |
Delegate a received message to the appropriate handler.
Args:
message (Message) :
The message that was receive that needs to be handled
connection (ServerConnection) :
The connection that received this message
Raises:
ProtocolError
... |
Decorator that adds the necessary locking and post-processing
to manipulate the session's document. Expects to decorate a
method on ServerSession and transforms it into a coroutine
if it wasn't already.
def _needs_document_lock(func):
'''Decorator that adds the necessary locking and post-proce... |
This should only be called by ``ServerConnection.unsubscribe_session`` or our book-keeping will be broken
def unsubscribe(self, connection):
"""This should only be called by ``ServerConnection.unsubscribe_session`` or our book-keeping will be broken"""
self._subscribed_connections.discard(connection)
... |
Set shell current working directory.
def set_cwd(self, dirname):
"""Set shell current working directory."""
# Replace single for double backslashes on Windows
if os.name == 'nt':
dirname = dirname.replace(u"\\", u"\\\\")
if not self.external_kernel:
code = u"get... |
Set color scheme for matched parentheses.
def set_bracket_matcher_color_scheme(self, color_scheme):
"""Set color scheme for matched parentheses."""
bsh = sh.BaseSH(parent=self, color_scheme=color_scheme)
mpcolor = bsh.get_matched_p_color()
self._bracket_matcher.format.setBackground(mpco... |
Set color scheme of the shell.
def set_color_scheme(self, color_scheme, reset=True):
"""Set color scheme of the shell."""
self.set_bracket_matcher_color_scheme(color_scheme)
self.style_sheet, dark_color = create_qss_style(color_scheme)
self.syntax_style = color_scheme
self._styl... |
Banner for IPython widgets with pylab message
def long_banner(self):
"""Banner for IPython widgets with pylab message"""
# Default banner
try:
from IPython.core.usage import quick_guide
except Exception:
quick_guide = ''
banner_parts = [
'Pyth... |
Reset the namespace by removing all names defined by the user.
def reset_namespace(self, warning=False, message=False):
"""Reset the namespace by removing all names defined by the user."""
reset_str = _("Remove all variables")
warn_str = _("All user-defined variables will be removed. "
... |
Create shortcuts for ipyconsole.
def create_shortcuts(self):
"""Create shortcuts for ipyconsole."""
inspect = config_shortcut(self._control.inspect_current_object,
context='Console',
name='Inspect current object', parent=self)
... |
Execute code in the kernel without increasing the prompt
def silent_execute(self, code):
"""Execute code in the kernel without increasing the prompt"""
try:
self.kernel_client.execute(to_text_string(code), silent=True)
except AttributeError:
pass |
Silently execute a kernel method and save its reply
The methods passed here **don't** involve getting the value
of a variable but instead replies that can be handled by
ast.literal_eval.
To get a value see `get_value`
Parameters
----------
code : string
... |
Handle data returned by silent executions of kernel methods
This is based on the _handle_exec_callback of RichJupyterWidget.
Therefore this is licensed BSD.
def handle_exec_method(self, msg):
"""
Handle data returned by silent executions of kernel methods
This is based on the ... |
Mayavi plots require the Qt backend, so we try to detect if one is
generated to change backends
def set_backend_for_mayavi(self, command):
"""
Mayavi plots require the Qt backend, so we try to detect if one is
generated to change backends
"""
calling_mayavi = False
... |
If the user is trying to change Matplotlib backends with
%matplotlib, send the same command again to the kernel to
correctly change it.
Fixes issue 4002
def change_mpl_backend(self, command):
"""
If the user is trying to change Matplotlib backends with
%matplotlib, send... |
Reimplement the IPython context menu
def _context_menu_make(self, pos):
"""Reimplement the IPython context menu"""
menu = super(ShellWidget, self)._context_menu_make(pos)
return self.ipyclient.add_actions_to_context_menu(menu) |
Reimplement banner creation to let the user decide if he wants a
banner or not
def _banner_default(self):
"""
Reimplement banner creation to let the user decide if he wants a
banner or not
"""
# Don't change banner for external kernels
if self.external_kernel:
... |
Refresh the highlighting with the current syntax style by class.
def _syntax_style_changed(self):
"""Refresh the highlighting with the current syntax style by class."""
if self._highlighter is None:
# ignore premature calls
return
if self.syntax_style:
self._... |
Emit a signal when the prompt is ready.
def _prompt_started_hook(self):
"""Emit a signal when the prompt is ready."""
if not self._reading:
self._highlighter.highlighting_on = True
self.sig_prompt_ready.emit() |
Reimplement Qt method to send focus change notification
def focusInEvent(self, event):
"""Reimplement Qt method to send focus change notification"""
self.focus_changed.emit()
return super(ShellWidget, self).focusInEvent(event) |
Reimplement Qt method to send focus change notification
def focusOutEvent(self, event):
"""Reimplement Qt method to send focus change notification"""
self.focus_changed.emit()
return super(ShellWidget, self).focusOutEvent(event) |
Installs a panel on the editor.
:param panel: Panel to install
:param position: Position where the panel must be installed.
:return: The installed panel
def register(self, panel, position=Panel.Position.LEFT):
"""
Installs a panel on the editor.
:param panel: Panel to ... |
Removes the specified panel.
:param name_or_klass: Name or class of the panel to remove.
:return: The removed panel
def remove(self, name_or_klass):
"""
Removes the specified panel.
:param name_or_klass: Name or class of the panel to remove.
:return: The removed panel
... |
Removes all panel from the CodeEditor.
def clear(self):
"""Removes all panel from the CodeEditor."""
for i in range(4):
while len(self._panels[i]):
key = sorted(list(self._panels[i].keys()))[0]
panel = self.remove(key)
panel.setParent(None)
... |
Gets a specific panel instance.
:param name_or_klass: Name or class of the panel to retrieve.
:return: The specified panel instance.
def get(self, name_or_klass):
"""
Gets a specific panel instance.
:param name_or_klass: Name or class of the panel to retrieve.
:return:... |
Refreshes the editor panels (resize and update margins).
def refresh(self):
"""Refreshes the editor panels (resize and update margins)."""
logger.debug('Refresh panels')
self.resize()
self._update(self.editor.contentsRect(), 0,
force_update_margins=True) |
Resizes panels.
def resize(self):
"""Resizes panels."""
crect = self.editor.contentsRect()
view_crect = self.editor.viewport().contentsRect()
s_bottom, s_left, s_right, s_top = self._compute_zones_sizes()
tw = s_left + s_right
th = s_bottom + s_top
w_offset = cre... |
Update foating panels.
def update_floating_panels(self):
"""Update foating panels."""
crect = self.editor.contentsRect()
panels = self.panels_for_zone(Panel.Position.FLOATING)
for panel in panels:
if not panel.isVisible():
continue
panel.set_geome... |
Update viewport margins.
def _update_viewport_margins(self):
"""Update viewport margins."""
top = 0
left = 0
right = 0
bottom = 0
for panel in self.panels_for_zone(Panel.Position.LEFT):
if panel.isVisible():
width = panel.sizeHint().width()
... |
Compute panel zone sizes.
def _compute_zones_sizes(self):
"""Compute panel zone sizes."""
# Left panels
left = 0
for panel in self.panels_for_zone(Panel.Position.LEFT):
if not panel.isVisible():
continue
size_hint = panel.sizeHint()
le... |
Locate a module path based on an import line in an python-like file
import_line is the line of source code containing the import
alt_path specifies an alternate base path for the module
stop_token specifies the desired name to stop on
This is used to a find the path to python-like modules
(... |
Find the definition of an object within a source closest to a given line
def get_definition_with_regex(source, token, start_line=-1):
"""
Find the definition of an object within a source closest to a given line
"""
if not token:
return None
if DEBUG_EDITOR:
t0 = time.time()
... |
Return a list of all python-like extensions
def python_like_exts():
"""Return a list of all python-like extensions"""
exts = []
for lang in languages.PYTHON_LIKE_LANGUAGES:
exts.extend(list(languages.ALL_LANGUAGES[lang]))
return ['.' + ext for ext in exts] |
Return a list of all editable extensions
def all_editable_exts():
"""Return a list of all editable extensions"""
exts = []
for (language, extensions) in languages.ALL_LANGUAGES.items():
exts.extend(list(extensions))
return ['.' + ext for ext in exts] |
Perform completion of filesystem path.
https://stackoverflow.com/questions/5637124/tab-completion-in-pythons-raw-input
def _complete_path(path=None):
"""Perform completion of filesystem path.
https://stackoverflow.com/questions/5637124/tab-completion-in-pythons-raw-input
"""
if not path:
... |
Return a list of (completion, type) tuples
Simple completion based on python-like identifiers and whitespace
def get_completions(self, info):
"""Return a list of (completion, type) tuples
Simple completion based on python-like identifiers and whitespace
"""
if not info[... |
Find the definition for an object within a set of source code
This is used to find the path of python-like modules
(e.g. cython and enaml) for a goto definition
def get_definition(self, info):
"""
Find the definition for an object within a set of source code
This is use... |
Get a formatted calltip and docstring from Fallback
def get_info(self, info):
"""Get a formatted calltip and docstring from Fallback"""
if info['docstring']:
if info['filename']:
filename = os.path.basename(info['filename'])
filename = os.path.splitext(f... |
Creates the editor dialog and returns a tuple (dialog, func) where func
is the function to be called with the dialog instance as argument, after
quitting the dialog box
The role of this intermediate function is to allow easy monkey-patching.
(uschmitt suggested this indirection here so that h... |
Edit the object 'obj' in a GUI-based editor and return the edited copy
(if Cancel is pressed, return None)
The object 'obj' is a container
Supported container types:
dict, list, set, tuple, str/unicode or numpy.array
(instantiate a new QApplication if necessary,
so it can be ... |
Return a sorted list of all the children items of 'item'.
def get_item_children(item):
"""Return a sorted list of all the children items of 'item'."""
children = [item.child(index) for index in range(item.childCount())]
for child in children[:]:
others = get_item_children(child)
if oth... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.