id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
30,300 | bokeh/bokeh | bokeh/util/serialization.py | transform_column_source_data | def transform_column_source_data(data, buffers=None, cols=None):
''' Transform ``ColumnSourceData`` data to a serialized format
Args:
data (dict) : the mapping of names to data columns to transform
buffers (set, optional) :
If binary buffers are desired, the buffers parameter may be
provided, and any columns that may be sent as binary buffers
will be added to the set. If None, then only base64 encoding
will be used (default: None)
**This is an "out" parameter**. The values it contains will be
modified in-place.
cols (list[str], optional) :
Optional list of subset of columns to transform. If None, all
columns will be transformed (default: None)
Returns:
JSON compatible dict
'''
to_transform = set(data) if cols is None else set(cols)
data_copy = {}
for key in to_transform:
if pd and isinstance(data[key], (pd.Series, pd.Index)):
data_copy[key] = transform_series(data[key], buffers=buffers)
elif isinstance(data[key], np.ndarray):
data_copy[key] = transform_array(data[key], buffers=buffers)
else:
data_copy[key] = traverse_data(data[key], buffers=buffers)
return data_copy | python | def transform_column_source_data(data, buffers=None, cols=None):
''' Transform ``ColumnSourceData`` data to a serialized format
Args:
data (dict) : the mapping of names to data columns to transform
buffers (set, optional) :
If binary buffers are desired, the buffers parameter may be
provided, and any columns that may be sent as binary buffers
will be added to the set. If None, then only base64 encoding
will be used (default: None)
**This is an "out" parameter**. The values it contains will be
modified in-place.
cols (list[str], optional) :
Optional list of subset of columns to transform. If None, all
columns will be transformed (default: None)
Returns:
JSON compatible dict
'''
to_transform = set(data) if cols is None else set(cols)
data_copy = {}
for key in to_transform:
if pd and isinstance(data[key], (pd.Series, pd.Index)):
data_copy[key] = transform_series(data[key], buffers=buffers)
elif isinstance(data[key], np.ndarray):
data_copy[key] = transform_array(data[key], buffers=buffers)
else:
data_copy[key] = traverse_data(data[key], buffers=buffers)
return data_copy | [
"def",
"transform_column_source_data",
"(",
"data",
",",
"buffers",
"=",
"None",
",",
"cols",
"=",
"None",
")",
":",
"to_transform",
"=",
"set",
"(",
"data",
")",
"if",
"cols",
"is",
"None",
"else",
"set",
"(",
"cols",
")",
"data_copy",
"=",
"{",
"}",
... | Transform ``ColumnSourceData`` data to a serialized format
Args:
data (dict) : the mapping of names to data columns to transform
buffers (set, optional) :
If binary buffers are desired, the buffers parameter may be
provided, and any columns that may be sent as binary buffers
will be added to the set. If None, then only base64 encoding
will be used (default: None)
**This is an "out" parameter**. The values it contains will be
modified in-place.
cols (list[str], optional) :
Optional list of subset of columns to transform. If None, all
columns will be transformed (default: None)
Returns:
JSON compatible dict | [
"Transform",
"ColumnSourceData",
"data",
"to",
"a",
"serialized",
"format"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/serialization.py#L458-L492 |
30,301 | bokeh/bokeh | bokeh/util/serialization.py | encode_binary_dict | def encode_binary_dict(array, buffers):
''' Send a numpy array as an unencoded binary buffer
The encoded format is a dict with the following structure:
.. code:: python
{
'__buffer__' : << an ID to locate the buffer >>,
'shape' : << array shape >>,
'dtype' : << dtype name >>,
'order' : << byte order at origin (little or big)>>
}
Args:
array (np.ndarray) : an array to encode
buffers (set) :
Set to add buffers to
**This is an "out" parameter**. The values it contains will be
modified in-place.
Returns:
dict
'''
buffer_id = make_id()
buf = (dict(id=buffer_id), array.tobytes())
buffers.append(buf)
return {
'__buffer__' : buffer_id,
'shape' : array.shape,
'dtype' : array.dtype.name,
'order' : sys.byteorder
} | python | def encode_binary_dict(array, buffers):
''' Send a numpy array as an unencoded binary buffer
The encoded format is a dict with the following structure:
.. code:: python
{
'__buffer__' : << an ID to locate the buffer >>,
'shape' : << array shape >>,
'dtype' : << dtype name >>,
'order' : << byte order at origin (little or big)>>
}
Args:
array (np.ndarray) : an array to encode
buffers (set) :
Set to add buffers to
**This is an "out" parameter**. The values it contains will be
modified in-place.
Returns:
dict
'''
buffer_id = make_id()
buf = (dict(id=buffer_id), array.tobytes())
buffers.append(buf)
return {
'__buffer__' : buffer_id,
'shape' : array.shape,
'dtype' : array.dtype.name,
'order' : sys.byteorder
} | [
"def",
"encode_binary_dict",
"(",
"array",
",",
"buffers",
")",
":",
"buffer_id",
"=",
"make_id",
"(",
")",
"buf",
"=",
"(",
"dict",
"(",
"id",
"=",
"buffer_id",
")",
",",
"array",
".",
"tobytes",
"(",
")",
")",
"buffers",
".",
"append",
"(",
"buf",
... | Send a numpy array as an unencoded binary buffer
The encoded format is a dict with the following structure:
.. code:: python
{
'__buffer__' : << an ID to locate the buffer >>,
'shape' : << array shape >>,
'dtype' : << dtype name >>,
'order' : << byte order at origin (little or big)>>
}
Args:
array (np.ndarray) : an array to encode
buffers (set) :
Set to add buffers to
**This is an "out" parameter**. The values it contains will be
modified in-place.
Returns:
dict | [
"Send",
"a",
"numpy",
"array",
"as",
"an",
"unencoded",
"binary",
"buffer"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/serialization.py#L494-L530 |
30,302 | bokeh/bokeh | bokeh/util/serialization.py | decode_base64_dict | def decode_base64_dict(data):
''' Decode a base64 encoded array into a NumPy array.
Args:
data (dict) : encoded array data to decode
Data should have the format encoded by :func:`encode_base64_dict`.
Returns:
np.ndarray
'''
b64 = base64.b64decode(data['__ndarray__'])
array = np.copy(np.frombuffer(b64, dtype=data['dtype']))
if len(data['shape']) > 1:
array = array.reshape(data['shape'])
return array | python | def decode_base64_dict(data):
''' Decode a base64 encoded array into a NumPy array.
Args:
data (dict) : encoded array data to decode
Data should have the format encoded by :func:`encode_base64_dict`.
Returns:
np.ndarray
'''
b64 = base64.b64decode(data['__ndarray__'])
array = np.copy(np.frombuffer(b64, dtype=data['dtype']))
if len(data['shape']) > 1:
array = array.reshape(data['shape'])
return array | [
"def",
"decode_base64_dict",
"(",
"data",
")",
":",
"b64",
"=",
"base64",
".",
"b64decode",
"(",
"data",
"[",
"'__ndarray__'",
"]",
")",
"array",
"=",
"np",
".",
"copy",
"(",
"np",
".",
"frombuffer",
"(",
"b64",
",",
"dtype",
"=",
"data",
"[",
"'dtyp... | Decode a base64 encoded array into a NumPy array.
Args:
data (dict) : encoded array data to decode
Data should have the format encoded by :func:`encode_base64_dict`.
Returns:
np.ndarray | [
"Decode",
"a",
"base64",
"encoded",
"array",
"into",
"a",
"NumPy",
"array",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/serialization.py#L559-L575 |
30,303 | bokeh/bokeh | bokeh/models/tools.py | CustomJSHover.from_py_func | def from_py_func(cls, code):
''' Create a ``CustomJSHover`` instance from a Python functions. The
function is translated to JavaScript using PScript.
The python functions must have no positional arguments. It is
possible to pass Bokeh models (e.g. a ``ColumnDataSource``) as keyword
arguments to the functions.
The ``code`` function namespace will contain the variable ``value``
(the untransformed value) at render time as well as ``format`` and
``special_vars`` as described in the class description.
Args:
code (function) : a scalar function to transform a single ``value``
Returns:
CustomJSHover
'''
from bokeh.util.deprecation import deprecated
deprecated("'from_py_func' is deprecated and will be removed in an eventual 2.0 release. "
"Use CustomJSHover directly instead.")
if not isinstance(code, FunctionType):
raise ValueError('CustomJSHover.from_py_func only accepts function objects.')
pscript = import_required('pscript',
'To use Python functions for CustomJSHover, you need PScript ' +
'("conda install -c conda-forge pscript" or "pip install pscript")')
def pscript_compile(code):
sig = signature(code)
all_names, default_values = get_param_info(sig)
if len(all_names) - len(default_values) != 0:
raise ValueError("Function may only contain keyword arguments.")
if default_values and not any(isinstance(value, Model) for value in default_values):
raise ValueError("Default value must be a Bokeh Model.")
func_kwargs = dict(zip(all_names, default_values))
# Wrap the code attr in a function named `code` and call it
# with arguments that match the `args` attr
code = pscript.py2js(code, 'transformer') + 'return transformer(%s);\n' % ', '.join(all_names)
return code, func_kwargs
jsfunc, func_kwargs = pscript_compile(code)
return cls(code=jsfunc, args=func_kwargs) | python | def from_py_func(cls, code):
''' Create a ``CustomJSHover`` instance from a Python functions. The
function is translated to JavaScript using PScript.
The python functions must have no positional arguments. It is
possible to pass Bokeh models (e.g. a ``ColumnDataSource``) as keyword
arguments to the functions.
The ``code`` function namespace will contain the variable ``value``
(the untransformed value) at render time as well as ``format`` and
``special_vars`` as described in the class description.
Args:
code (function) : a scalar function to transform a single ``value``
Returns:
CustomJSHover
'''
from bokeh.util.deprecation import deprecated
deprecated("'from_py_func' is deprecated and will be removed in an eventual 2.0 release. "
"Use CustomJSHover directly instead.")
if not isinstance(code, FunctionType):
raise ValueError('CustomJSHover.from_py_func only accepts function objects.')
pscript = import_required('pscript',
'To use Python functions for CustomJSHover, you need PScript ' +
'("conda install -c conda-forge pscript" or "pip install pscript")')
def pscript_compile(code):
sig = signature(code)
all_names, default_values = get_param_info(sig)
if len(all_names) - len(default_values) != 0:
raise ValueError("Function may only contain keyword arguments.")
if default_values and not any(isinstance(value, Model) for value in default_values):
raise ValueError("Default value must be a Bokeh Model.")
func_kwargs = dict(zip(all_names, default_values))
# Wrap the code attr in a function named `code` and call it
# with arguments that match the `args` attr
code = pscript.py2js(code, 'transformer') + 'return transformer(%s);\n' % ', '.join(all_names)
return code, func_kwargs
jsfunc, func_kwargs = pscript_compile(code)
return cls(code=jsfunc, args=func_kwargs) | [
"def",
"from_py_func",
"(",
"cls",
",",
"code",
")",
":",
"from",
"bokeh",
".",
"util",
".",
"deprecation",
"import",
"deprecated",
"deprecated",
"(",
"\"'from_py_func' is deprecated and will be removed in an eventual 2.0 release. \"",
"\"Use CustomJSHover directly instead.\"",... | Create a ``CustomJSHover`` instance from a Python functions. The
function is translated to JavaScript using PScript.
The python functions must have no positional arguments. It is
possible to pass Bokeh models (e.g. a ``ColumnDataSource``) as keyword
arguments to the functions.
The ``code`` function namespace will contain the variable ``value``
(the untransformed value) at render time as well as ``format`` and
``special_vars`` as described in the class description.
Args:
code (function) : a scalar function to transform a single ``value``
Returns:
CustomJSHover | [
"Create",
"a",
"CustomJSHover",
"instance",
"from",
"a",
"Python",
"functions",
".",
"The",
"function",
"is",
"translated",
"to",
"JavaScript",
"using",
"PScript",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/tools.py#L882-L932 |
30,304 | bokeh/bokeh | bokeh/models/tools.py | CustomJSHover.from_coffeescript | def from_coffeescript(cls, code, args={}):
''' Create a CustomJSHover instance from a CoffeeScript snippet. The
function bodies are translated to JavaScript functions using node and
therefore require return statements.
The ``code`` snippet namespace will contain the variable ``value`` (the
untransformed value) at render time as well as ``special_vars`` and
``format`` as described in the class description.
Example:
.. code-block:: coffeescript
formatter = CustomJSHover.from_coffeescript("return value + " total")
Args:
code (str) :
A coffeescript snippet to transform a single ``value`` value
Returns:
CustomJSHover
'''
compiled = nodejs_compile(code, lang="coffeescript", file="???")
if "error" in compiled:
raise CompilationError(compiled.error)
return cls(code=compiled.code, args=args) | python | def from_coffeescript(cls, code, args={}):
''' Create a CustomJSHover instance from a CoffeeScript snippet. The
function bodies are translated to JavaScript functions using node and
therefore require return statements.
The ``code`` snippet namespace will contain the variable ``value`` (the
untransformed value) at render time as well as ``special_vars`` and
``format`` as described in the class description.
Example:
.. code-block:: coffeescript
formatter = CustomJSHover.from_coffeescript("return value + " total")
Args:
code (str) :
A coffeescript snippet to transform a single ``value`` value
Returns:
CustomJSHover
'''
compiled = nodejs_compile(code, lang="coffeescript", file="???")
if "error" in compiled:
raise CompilationError(compiled.error)
return cls(code=compiled.code, args=args) | [
"def",
"from_coffeescript",
"(",
"cls",
",",
"code",
",",
"args",
"=",
"{",
"}",
")",
":",
"compiled",
"=",
"nodejs_compile",
"(",
"code",
",",
"lang",
"=",
"\"coffeescript\"",
",",
"file",
"=",
"\"???\"",
")",
"if",
"\"error\"",
"in",
"compiled",
":",
... | Create a CustomJSHover instance from a CoffeeScript snippet. The
function bodies are translated to JavaScript functions using node and
therefore require return statements.
The ``code`` snippet namespace will contain the variable ``value`` (the
untransformed value) at render time as well as ``special_vars`` and
``format`` as described in the class description.
Example:
.. code-block:: coffeescript
formatter = CustomJSHover.from_coffeescript("return value + " total")
Args:
code (str) :
A coffeescript snippet to transform a single ``value`` value
Returns:
CustomJSHover | [
"Create",
"a",
"CustomJSHover",
"instance",
"from",
"a",
"CoffeeScript",
"snippet",
".",
"The",
"function",
"bodies",
"are",
"translated",
"to",
"JavaScript",
"functions",
"using",
"node",
"and",
"therefore",
"require",
"return",
"statements",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/tools.py#L935-L962 |
30,305 | bokeh/bokeh | bokeh/sphinxext/bokehjs_content.py | BokehJSContent.get_codeblock_node | def get_codeblock_node(self, code, language):
"""this is copied from sphinx.directives.code.CodeBlock.run
it has been changed to accept code and language as an arguments instead
of reading from self
"""
# type: () -> List[nodes.Node]
document = self.state.document
location = self.state_machine.get_source_and_line(self.lineno)
linespec = self.options.get('emphasize-lines')
if linespec:
try:
nlines = len(code.split('\n'))
hl_lines = parselinenos(linespec, nlines)
if any(i >= nlines for i in hl_lines):
log.warning(__('line number spec is out of range(1-%d): %r') %
(nlines, self.options['emphasize-lines']),
location=location)
hl_lines = [x + 1 for x in hl_lines if x < nlines]
except ValueError as err:
return [document.reporter.warning(str(err), line=self.lineno)]
else:
hl_lines = None
if 'dedent' in self.options:
location = self.state_machine.get_source_and_line(self.lineno)
lines = code.split('\n')
lines = dedent_lines(lines, self.options['dedent'], location=location)
code = '\n'.join(lines)
literal = nodes.literal_block(code, code)
literal['language'] = language
literal['linenos'] = 'linenos' in self.options or \
'lineno-start' in self.options
literal['classes'] += self.options.get('class', [])
extra_args = literal['highlight_args'] = {}
if hl_lines is not None:
extra_args['hl_lines'] = hl_lines
if 'lineno-start' in self.options:
extra_args['linenostart'] = self.options['lineno-start']
set_source_info(self, literal)
caption = self.options.get('caption')
if caption:
try:
literal = container_wrapper(self, literal, caption)
except ValueError as exc:
return [document.reporter.warning(text_type(exc), line=self.lineno)]
# literal will be note_implicit_target that is linked from caption and numref.
# when options['name'] is provided, it should be primary ID.
self.add_name(literal)
return [literal] | python | def get_codeblock_node(self, code, language):
"""this is copied from sphinx.directives.code.CodeBlock.run
it has been changed to accept code and language as an arguments instead
of reading from self
"""
# type: () -> List[nodes.Node]
document = self.state.document
location = self.state_machine.get_source_and_line(self.lineno)
linespec = self.options.get('emphasize-lines')
if linespec:
try:
nlines = len(code.split('\n'))
hl_lines = parselinenos(linespec, nlines)
if any(i >= nlines for i in hl_lines):
log.warning(__('line number spec is out of range(1-%d): %r') %
(nlines, self.options['emphasize-lines']),
location=location)
hl_lines = [x + 1 for x in hl_lines if x < nlines]
except ValueError as err:
return [document.reporter.warning(str(err), line=self.lineno)]
else:
hl_lines = None
if 'dedent' in self.options:
location = self.state_machine.get_source_and_line(self.lineno)
lines = code.split('\n')
lines = dedent_lines(lines, self.options['dedent'], location=location)
code = '\n'.join(lines)
literal = nodes.literal_block(code, code)
literal['language'] = language
literal['linenos'] = 'linenos' in self.options or \
'lineno-start' in self.options
literal['classes'] += self.options.get('class', [])
extra_args = literal['highlight_args'] = {}
if hl_lines is not None:
extra_args['hl_lines'] = hl_lines
if 'lineno-start' in self.options:
extra_args['linenostart'] = self.options['lineno-start']
set_source_info(self, literal)
caption = self.options.get('caption')
if caption:
try:
literal = container_wrapper(self, literal, caption)
except ValueError as exc:
return [document.reporter.warning(text_type(exc), line=self.lineno)]
# literal will be note_implicit_target that is linked from caption and numref.
# when options['name'] is provided, it should be primary ID.
self.add_name(literal)
return [literal] | [
"def",
"get_codeblock_node",
"(",
"self",
",",
"code",
",",
"language",
")",
":",
"# type: () -> List[nodes.Node]",
"document",
"=",
"self",
".",
"state",
".",
"document",
"location",
"=",
"self",
".",
"state_machine",
".",
"get_source_and_line",
"(",
"self",
".... | this is copied from sphinx.directives.code.CodeBlock.run
it has been changed to accept code and language as an arguments instead
of reading from self | [
"this",
"is",
"copied",
"from",
"sphinx",
".",
"directives",
".",
"code",
".",
"CodeBlock",
".",
"run"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/sphinxext/bokehjs_content.py#L117-L174 |
30,306 | bokeh/bokeh | bokeh/sphinxext/bokehjs_content.py | BokehJSContent.get_code_language | def get_code_language(self):
"""
This is largely copied from bokeh.sphinxext.bokeh_plot.run
"""
js_source = self.get_js_source()
if self.options.get("include_html", False):
resources = get_sphinx_resources(include_bokehjs_api=True)
html_source = BJS_HTML.render(
css_files=resources.css_files,
js_files=resources.js_files,
bjs_script=js_source)
return [html_source, "html"]
else:
return [js_source, "javascript"] | python | def get_code_language(self):
"""
This is largely copied from bokeh.sphinxext.bokeh_plot.run
"""
js_source = self.get_js_source()
if self.options.get("include_html", False):
resources = get_sphinx_resources(include_bokehjs_api=True)
html_source = BJS_HTML.render(
css_files=resources.css_files,
js_files=resources.js_files,
bjs_script=js_source)
return [html_source, "html"]
else:
return [js_source, "javascript"] | [
"def",
"get_code_language",
"(",
"self",
")",
":",
"js_source",
"=",
"self",
".",
"get_js_source",
"(",
")",
"if",
"self",
".",
"options",
".",
"get",
"(",
"\"include_html\"",
",",
"False",
")",
":",
"resources",
"=",
"get_sphinx_resources",
"(",
"include_bo... | This is largely copied from bokeh.sphinxext.bokeh_plot.run | [
"This",
"is",
"largely",
"copied",
"from",
"bokeh",
".",
"sphinxext",
".",
"bokeh_plot",
".",
"run"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/sphinxext/bokehjs_content.py#L196-L209 |
30,307 | bokeh/bokeh | bokeh/embed/standalone.py | autoload_static | def autoload_static(model, resources, script_path):
''' Return JavaScript code and a script tag that can be used to embed
Bokeh Plots.
The data for the plot is stored directly in the returned JavaScript code.
Args:
model (Model or Document) :
resources (Resources) :
script_path (str) :
Returns:
(js, tag) :
JavaScript code to be saved at ``script_path`` and a ``<script>``
tag to load it
Raises:
ValueError
'''
# TODO: maybe warn that it's not exactly useful, but technically possible
# if resources.mode == 'inline':
# raise ValueError("autoload_static() requires non-inline resources")
if isinstance(model, Model):
models = [model]
elif isinstance (model, Document):
models = model.roots
else:
raise ValueError("autoload_static expects a single Model or Document")
with OutputDocumentFor(models):
(docs_json, [render_item]) = standalone_docs_json_and_render_items([model])
bundle = bundle_all_models() or ""
script = script_for_render_items(docs_json, [render_item])
(modelid, elementid) = list(render_item.roots.to_json().items())[0]
js = wrap_in_onload(AUTOLOAD_JS.render(
js_urls = resources.js_files,
css_urls = resources.css_files,
js_raw = resources.js_raw + [bundle, script],
css_raw = resources.css_raw_str,
elementid = elementid,
))
tag = AUTOLOAD_TAG.render(
src_path = script_path,
elementid = elementid,
)
return encode_utf8(js), encode_utf8(tag) | python | def autoload_static(model, resources, script_path):
''' Return JavaScript code and a script tag that can be used to embed
Bokeh Plots.
The data for the plot is stored directly in the returned JavaScript code.
Args:
model (Model or Document) :
resources (Resources) :
script_path (str) :
Returns:
(js, tag) :
JavaScript code to be saved at ``script_path`` and a ``<script>``
tag to load it
Raises:
ValueError
'''
# TODO: maybe warn that it's not exactly useful, but technically possible
# if resources.mode == 'inline':
# raise ValueError("autoload_static() requires non-inline resources")
if isinstance(model, Model):
models = [model]
elif isinstance (model, Document):
models = model.roots
else:
raise ValueError("autoload_static expects a single Model or Document")
with OutputDocumentFor(models):
(docs_json, [render_item]) = standalone_docs_json_and_render_items([model])
bundle = bundle_all_models() or ""
script = script_for_render_items(docs_json, [render_item])
(modelid, elementid) = list(render_item.roots.to_json().items())[0]
js = wrap_in_onload(AUTOLOAD_JS.render(
js_urls = resources.js_files,
css_urls = resources.css_files,
js_raw = resources.js_raw + [bundle, script],
css_raw = resources.css_raw_str,
elementid = elementid,
))
tag = AUTOLOAD_TAG.render(
src_path = script_path,
elementid = elementid,
)
return encode_utf8(js), encode_utf8(tag) | [
"def",
"autoload_static",
"(",
"model",
",",
"resources",
",",
"script_path",
")",
":",
"# TODO: maybe warn that it's not exactly useful, but technically possible",
"# if resources.mode == 'inline':",
"# raise ValueError(\"autoload_static() requires non-inline resources\")",
"if",
"i... | Return JavaScript code and a script tag that can be used to embed
Bokeh Plots.
The data for the plot is stored directly in the returned JavaScript code.
Args:
model (Model or Document) :
resources (Resources) :
script_path (str) :
Returns:
(js, tag) :
JavaScript code to be saved at ``script_path`` and a ``<script>``
tag to load it
Raises:
ValueError | [
"Return",
"JavaScript",
"code",
"and",
"a",
"script",
"tag",
"that",
"can",
"be",
"used",
"to",
"embed",
"Bokeh",
"Plots",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/standalone.py#L55-L109 |
30,308 | bokeh/bokeh | bokeh/embed/standalone.py | components | def components(models, wrap_script=True, wrap_plot_info=True, theme=FromCurdoc):
''' Return HTML components to embed a Bokeh plot. The data for the plot is
stored directly in the returned HTML.
An example can be found in examples/embed/embed_multiple.py
The returned components assume that BokehJS resources are **already loaded**.
The html template in which they will be embedded needs to include the following
links and scripts tags. The widgets and tables resources are only necessary if
the components make use of widgets and tables.
.. code-block:: html
<link
href="http://cdn.pydata.org/bokeh/release/bokeh-x.y.z.min.css"
rel="stylesheet" type="text/css">
<link
href="http://cdn.pydata.org/bokeh/release/bokeh-widgets-x.y.z.min.css"
rel="stylesheet" type="text/css">
<link
href="http://cdn.pydata.org/bokeh/release/bokeh-tables-x.y.z.min.css"
rel="stylesheet" type="text/css">
<script src="http://cdn.pydata.org/bokeh/release/bokeh-x.y.z.min.js"></script>
<script src="http://cdn.pydata.org/bokeh/release/bokeh-widgets-x.y.z.min.js"></script>
<script src="http://cdn.pydata.org/bokeh/release/bokeh-tables-x.y.z.min.js"></script>
Note that in Jupyter Notebooks, it is not possible to use components and show in
the same notebook cell.
Args:
models (Model|list|dict|tuple) :
A single Model, a list/tuple of Models, or a dictionary of keys and Models.
wrap_script (boolean, optional) :
If True, the returned javascript is wrapped in a script tag.
(default: True)
wrap_plot_info (boolean, optional) : If True, returns ``<div>`` strings.
Otherwise, return dicts that can be used to build your own divs.
(default: True)
If False, the returned dictionary contains the following information:
.. code-block:: python
{
'modelid': 'The model ID, used with Document.get_model_by_id',
'elementid': 'The css identifier the BokehJS will look for to target the plot',
'docid': 'Used by Bokeh to find the doc embedded in the returned script',
}
theme (Theme, optional) :
Defaults to the ``Theme`` instance in the current document.
Setting this to ``None`` uses the default theme or the theme
already specified in the document. Any other value must be an
instance of the ``Theme`` class.
Returns:
UTF-8 encoded *(script, div[s])* or *(raw_script, plot_info[s])*
Examples:
With default wrapping parameter values:
.. code-block:: python
components(plot)
# => (script, plot_div)
components((plot1, plot2))
# => (script, (plot1_div, plot2_div))
components({"Plot 1": plot1, "Plot 2": plot2})
# => (script, {"Plot 1": plot1_div, "Plot 2": plot2_div})
Examples:
With wrapping parameters set to ``False``:
.. code-block:: python
components(plot, wrap_script=False, wrap_plot_info=False)
# => (javascript, plot_dict)
components((plot1, plot2), wrap_script=False, wrap_plot_info=False)
# => (javascript, (plot1_dict, plot2_dict))
components({"Plot 1": plot1, "Plot 2": plot2}, wrap_script=False, wrap_plot_info=False)
# => (javascript, {"Plot 1": plot1_dict, "Plot 2": plot2_dict})
'''
# 1) Convert single items and dicts into list
was_single_object = isinstance(models, Model) or isinstance(models, Document)
models = _check_models_or_docs(models)
# now convert dict to list, saving keys in the same order
model_keys = None
dict_type = None
if isinstance(models, dict):
model_keys = models.keys()
dict_type = models.__class__
values = []
# don't just use .values() to ensure we are in the same order as key list
for k in model_keys:
values.append(models[k])
models = values
# 2) Append models to one document. Either pre-existing or new and render
with OutputDocumentFor(models, apply_theme=theme):
(docs_json, [render_item]) = standalone_docs_json_and_render_items(models)
script = bundle_all_models() or ""
script += script_for_render_items(docs_json, [render_item])
if wrap_script:
script = wrap_in_script_tag(script)
script = encode_utf8(script)
def div_for_root(root):
return ROOT_DIV.render(root=root, macros=MACROS)
if wrap_plot_info:
results = list(div_for_root(root) for root in render_item.roots)
else:
results = render_item.roots
# 3) convert back to the input shape
if was_single_object:
result = results[0]
elif model_keys is not None:
result = dict_type(zip(model_keys, results))
else:
result = tuple(results)
return script, result | python | def components(models, wrap_script=True, wrap_plot_info=True, theme=FromCurdoc):
''' Return HTML components to embed a Bokeh plot. The data for the plot is
stored directly in the returned HTML.
An example can be found in examples/embed/embed_multiple.py
The returned components assume that BokehJS resources are **already loaded**.
The html template in which they will be embedded needs to include the following
links and scripts tags. The widgets and tables resources are only necessary if
the components make use of widgets and tables.
.. code-block:: html
<link
href="http://cdn.pydata.org/bokeh/release/bokeh-x.y.z.min.css"
rel="stylesheet" type="text/css">
<link
href="http://cdn.pydata.org/bokeh/release/bokeh-widgets-x.y.z.min.css"
rel="stylesheet" type="text/css">
<link
href="http://cdn.pydata.org/bokeh/release/bokeh-tables-x.y.z.min.css"
rel="stylesheet" type="text/css">
<script src="http://cdn.pydata.org/bokeh/release/bokeh-x.y.z.min.js"></script>
<script src="http://cdn.pydata.org/bokeh/release/bokeh-widgets-x.y.z.min.js"></script>
<script src="http://cdn.pydata.org/bokeh/release/bokeh-tables-x.y.z.min.js"></script>
Note that in Jupyter Notebooks, it is not possible to use components and show in
the same notebook cell.
Args:
models (Model|list|dict|tuple) :
A single Model, a list/tuple of Models, or a dictionary of keys and Models.
wrap_script (boolean, optional) :
If True, the returned javascript is wrapped in a script tag.
(default: True)
wrap_plot_info (boolean, optional) : If True, returns ``<div>`` strings.
Otherwise, return dicts that can be used to build your own divs.
(default: True)
If False, the returned dictionary contains the following information:
.. code-block:: python
{
'modelid': 'The model ID, used with Document.get_model_by_id',
'elementid': 'The css identifier the BokehJS will look for to target the plot',
'docid': 'Used by Bokeh to find the doc embedded in the returned script',
}
theme (Theme, optional) :
Defaults to the ``Theme`` instance in the current document.
Setting this to ``None`` uses the default theme or the theme
already specified in the document. Any other value must be an
instance of the ``Theme`` class.
Returns:
UTF-8 encoded *(script, div[s])* or *(raw_script, plot_info[s])*
Examples:
With default wrapping parameter values:
.. code-block:: python
components(plot)
# => (script, plot_div)
components((plot1, plot2))
# => (script, (plot1_div, plot2_div))
components({"Plot 1": plot1, "Plot 2": plot2})
# => (script, {"Plot 1": plot1_div, "Plot 2": plot2_div})
Examples:
With wrapping parameters set to ``False``:
.. code-block:: python
components(plot, wrap_script=False, wrap_plot_info=False)
# => (javascript, plot_dict)
components((plot1, plot2), wrap_script=False, wrap_plot_info=False)
# => (javascript, (plot1_dict, plot2_dict))
components({"Plot 1": plot1, "Plot 2": plot2}, wrap_script=False, wrap_plot_info=False)
# => (javascript, {"Plot 1": plot1_dict, "Plot 2": plot2_dict})
'''
# 1) Convert single items and dicts into list
was_single_object = isinstance(models, Model) or isinstance(models, Document)
models = _check_models_or_docs(models)
# now convert dict to list, saving keys in the same order
model_keys = None
dict_type = None
if isinstance(models, dict):
model_keys = models.keys()
dict_type = models.__class__
values = []
# don't just use .values() to ensure we are in the same order as key list
for k in model_keys:
values.append(models[k])
models = values
# 2) Append models to one document. Either pre-existing or new and render
with OutputDocumentFor(models, apply_theme=theme):
(docs_json, [render_item]) = standalone_docs_json_and_render_items(models)
script = bundle_all_models() or ""
script += script_for_render_items(docs_json, [render_item])
if wrap_script:
script = wrap_in_script_tag(script)
script = encode_utf8(script)
def div_for_root(root):
return ROOT_DIV.render(root=root, macros=MACROS)
if wrap_plot_info:
results = list(div_for_root(root) for root in render_item.roots)
else:
results = render_item.roots
# 3) convert back to the input shape
if was_single_object:
result = results[0]
elif model_keys is not None:
result = dict_type(zip(model_keys, results))
else:
result = tuple(results)
return script, result | [
"def",
"components",
"(",
"models",
",",
"wrap_script",
"=",
"True",
",",
"wrap_plot_info",
"=",
"True",
",",
"theme",
"=",
"FromCurdoc",
")",
":",
"# 1) Convert single items and dicts into list",
"was_single_object",
"=",
"isinstance",
"(",
"models",
",",
"Model",
... | Return HTML components to embed a Bokeh plot. The data for the plot is
stored directly in the returned HTML.
An example can be found in examples/embed/embed_multiple.py
The returned components assume that BokehJS resources are **already loaded**.
The html template in which they will be embedded needs to include the following
links and scripts tags. The widgets and tables resources are only necessary if
the components make use of widgets and tables.
.. code-block:: html
<link
href="http://cdn.pydata.org/bokeh/release/bokeh-x.y.z.min.css"
rel="stylesheet" type="text/css">
<link
href="http://cdn.pydata.org/bokeh/release/bokeh-widgets-x.y.z.min.css"
rel="stylesheet" type="text/css">
<link
href="http://cdn.pydata.org/bokeh/release/bokeh-tables-x.y.z.min.css"
rel="stylesheet" type="text/css">
<script src="http://cdn.pydata.org/bokeh/release/bokeh-x.y.z.min.js"></script>
<script src="http://cdn.pydata.org/bokeh/release/bokeh-widgets-x.y.z.min.js"></script>
<script src="http://cdn.pydata.org/bokeh/release/bokeh-tables-x.y.z.min.js"></script>
Note that in Jupyter Notebooks, it is not possible to use components and show in
the same notebook cell.
Args:
models (Model|list|dict|tuple) :
A single Model, a list/tuple of Models, or a dictionary of keys and Models.
wrap_script (boolean, optional) :
If True, the returned javascript is wrapped in a script tag.
(default: True)
wrap_plot_info (boolean, optional) : If True, returns ``<div>`` strings.
Otherwise, return dicts that can be used to build your own divs.
(default: True)
If False, the returned dictionary contains the following information:
.. code-block:: python
{
'modelid': 'The model ID, used with Document.get_model_by_id',
'elementid': 'The css identifier the BokehJS will look for to target the plot',
'docid': 'Used by Bokeh to find the doc embedded in the returned script',
}
theme (Theme, optional) :
Defaults to the ``Theme`` instance in the current document.
Setting this to ``None`` uses the default theme or the theme
already specified in the document. Any other value must be an
instance of the ``Theme`` class.
Returns:
UTF-8 encoded *(script, div[s])* or *(raw_script, plot_info[s])*
Examples:
With default wrapping parameter values:
.. code-block:: python
components(plot)
# => (script, plot_div)
components((plot1, plot2))
# => (script, (plot1_div, plot2_div))
components({"Plot 1": plot1, "Plot 2": plot2})
# => (script, {"Plot 1": plot1_div, "Plot 2": plot2_div})
Examples:
With wrapping parameters set to ``False``:
.. code-block:: python
components(plot, wrap_script=False, wrap_plot_info=False)
# => (javascript, plot_dict)
components((plot1, plot2), wrap_script=False, wrap_plot_info=False)
# => (javascript, (plot1_dict, plot2_dict))
components({"Plot 1": plot1, "Plot 2": plot2}, wrap_script=False, wrap_plot_info=False)
# => (javascript, {"Plot 1": plot1_dict, "Plot 2": plot2_dict}) | [
"Return",
"HTML",
"components",
"to",
"embed",
"a",
"Bokeh",
"plot",
".",
"The",
"data",
"for",
"the",
"plot",
"is",
"stored",
"directly",
"in",
"the",
"returned",
"HTML",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/standalone.py#L111-L248 |
30,309 | bokeh/bokeh | bokeh/embed/standalone.py | file_html | def file_html(models,
resources,
title=None,
template=FILE,
template_variables={},
theme=FromCurdoc,
suppress_callback_warning=False,
_always_new=False):
''' Return an HTML document that embeds Bokeh Model or Document objects.
The data for the plot is stored directly in the returned HTML, with
support for customizing the JS/CSS resources independently and
customizing the jinja2 template.
Args:
models (Model or Document or seq[Model]) : Bokeh object or objects to render
typically a Model or Document
resources (Resources or tuple(JSResources or None, CSSResources or None)) :
A resource configuration for Bokeh JS & CSS assets.
title (str, optional) :
A title for the HTML document ``<title>`` tags or None. (default: None)
If None, attempt to automatically find the Document title from the given
plot objects.
template (Template, optional) : HTML document template (default: FILE)
A Jinja2 Template, see bokeh.core.templates.FILE for the required
template parameters
template_variables (dict, optional) : variables to be used in the Jinja2
template. If used, the following variable names will be overwritten:
title, bokeh_js, bokeh_css, plot_script, plot_div
theme (Theme, optional) :
Defaults to the ``Theme`` instance in the current document.
Setting this to ``None`` uses the default theme or the theme
already specified in the document. Any other value must be an
instance of the ``Theme`` class.
suppress_callback_warning (bool, optional) :
Normally generating standalone HTML from a Bokeh Document that has
Python callbacks will result in a warning stating that the callbacks
cannot function. However, this warning can be suppressed by setting
this value to True (default: False)
Returns:
UTF-8 encoded HTML
'''
if isinstance(models, Model):
models = [models]
if isinstance(models, Document):
models = models.roots
with OutputDocumentFor(models, apply_theme=theme, always_new=_always_new) as doc:
(docs_json, render_items) = standalone_docs_json_and_render_items(models, suppress_callback_warning=suppress_callback_warning)
title = _title_from_models(models, title)
bundle = bundle_for_objs_and_resources([doc], resources)
return html_page_for_render_items(bundle, docs_json, render_items, title=title,
template=template, template_variables=template_variables) | python | def file_html(models,
resources,
title=None,
template=FILE,
template_variables={},
theme=FromCurdoc,
suppress_callback_warning=False,
_always_new=False):
''' Return an HTML document that embeds Bokeh Model or Document objects.
The data for the plot is stored directly in the returned HTML, with
support for customizing the JS/CSS resources independently and
customizing the jinja2 template.
Args:
models (Model or Document or seq[Model]) : Bokeh object or objects to render
typically a Model or Document
resources (Resources or tuple(JSResources or None, CSSResources or None)) :
A resource configuration for Bokeh JS & CSS assets.
title (str, optional) :
A title for the HTML document ``<title>`` tags or None. (default: None)
If None, attempt to automatically find the Document title from the given
plot objects.
template (Template, optional) : HTML document template (default: FILE)
A Jinja2 Template, see bokeh.core.templates.FILE for the required
template parameters
template_variables (dict, optional) : variables to be used in the Jinja2
template. If used, the following variable names will be overwritten:
title, bokeh_js, bokeh_css, plot_script, plot_div
theme (Theme, optional) :
Defaults to the ``Theme`` instance in the current document.
Setting this to ``None`` uses the default theme or the theme
already specified in the document. Any other value must be an
instance of the ``Theme`` class.
suppress_callback_warning (bool, optional) :
Normally generating standalone HTML from a Bokeh Document that has
Python callbacks will result in a warning stating that the callbacks
cannot function. However, this warning can be suppressed by setting
this value to True (default: False)
Returns:
UTF-8 encoded HTML
'''
if isinstance(models, Model):
models = [models]
if isinstance(models, Document):
models = models.roots
with OutputDocumentFor(models, apply_theme=theme, always_new=_always_new) as doc:
(docs_json, render_items) = standalone_docs_json_and_render_items(models, suppress_callback_warning=suppress_callback_warning)
title = _title_from_models(models, title)
bundle = bundle_for_objs_and_resources([doc], resources)
return html_page_for_render_items(bundle, docs_json, render_items, title=title,
template=template, template_variables=template_variables) | [
"def",
"file_html",
"(",
"models",
",",
"resources",
",",
"title",
"=",
"None",
",",
"template",
"=",
"FILE",
",",
"template_variables",
"=",
"{",
"}",
",",
"theme",
"=",
"FromCurdoc",
",",
"suppress_callback_warning",
"=",
"False",
",",
"_always_new",
"=",
... | Return an HTML document that embeds Bokeh Model or Document objects.
The data for the plot is stored directly in the returned HTML, with
support for customizing the JS/CSS resources independently and
customizing the jinja2 template.
Args:
models (Model or Document or seq[Model]) : Bokeh object or objects to render
typically a Model or Document
resources (Resources or tuple(JSResources or None, CSSResources or None)) :
A resource configuration for Bokeh JS & CSS assets.
title (str, optional) :
A title for the HTML document ``<title>`` tags or None. (default: None)
If None, attempt to automatically find the Document title from the given
plot objects.
template (Template, optional) : HTML document template (default: FILE)
A Jinja2 Template, see bokeh.core.templates.FILE for the required
template parameters
template_variables (dict, optional) : variables to be used in the Jinja2
template. If used, the following variable names will be overwritten:
title, bokeh_js, bokeh_css, plot_script, plot_div
theme (Theme, optional) :
Defaults to the ``Theme`` instance in the current document.
Setting this to ``None`` uses the default theme or the theme
already specified in the document. Any other value must be an
instance of the ``Theme`` class.
suppress_callback_warning (bool, optional) :
Normally generating standalone HTML from a Bokeh Document that has
Python callbacks will result in a warning stating that the callbacks
cannot function. However, this warning can be suppressed by setting
this value to True (default: False)
Returns:
UTF-8 encoded HTML | [
"Return",
"an",
"HTML",
"document",
"that",
"embeds",
"Bokeh",
"Model",
"or",
"Document",
"objects",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/standalone.py#L250-L312 |
30,310 | bokeh/bokeh | bokeh/embed/standalone.py | json_item | def json_item(model, target=None, theme=FromCurdoc):
''' Return a JSON block that can be used to embed standalone Bokeh content.
Args:
model (Model) :
The Bokeh object to embed
target (string, optional)
A div id to embed the model into. If None, the target id must
be supplied in the JavaScript call.
theme (Theme, optional) :
Defaults to the ``Theme`` instance in the current document.
Setting this to ``None`` uses the default theme or the theme
already specified in the document. Any other value must be an
instance of the ``Theme`` class.
Returns:
JSON-like
This function returns a JSON block that can be consumed by the BokehJS
function ``Bokeh.embed.embed_item``. As an example, a Flask endpoint for
``/plot`` might return the following content to embed a Bokeh plot into
a div with id *"myplot"*:
.. code-block:: python
@app.route('/plot')
def plot():
p = make_plot('petal_width', 'petal_length')
return json.dumps(json_item(p, "myplot"))
Then a web page can retrieve this JSON and embed the plot by calling
``Bokeh.embed.embed_item``:
.. code-block:: html
<script>
fetch('/plot')
.then(function(response) { return response.json(); })
.then(function(item) { Bokeh.embed.embed_item(item); })
</script>
Alternatively, if is more convenient to supply the target div id directly
in the page source, that is also possible. If `target_id` is omitted in the
call to this function:
.. code-block:: python
return json.dumps(json_item(p))
Then the value passed to ``embed_item`` is used:
.. code-block:: javascript
Bokeh.embed.embed_item(item, "myplot");
'''
with OutputDocumentFor([model], apply_theme=theme) as doc:
doc.title = ""
docs_json = standalone_docs_json([model])
doc = list(docs_json.values())[0]
root_id = doc['roots']['root_ids'][0]
return {
'target_id' : target,
'root_id' : root_id,
'doc' : doc,
} | python | def json_item(model, target=None, theme=FromCurdoc):
''' Return a JSON block that can be used to embed standalone Bokeh content.
Args:
model (Model) :
The Bokeh object to embed
target (string, optional)
A div id to embed the model into. If None, the target id must
be supplied in the JavaScript call.
theme (Theme, optional) :
Defaults to the ``Theme`` instance in the current document.
Setting this to ``None`` uses the default theme or the theme
already specified in the document. Any other value must be an
instance of the ``Theme`` class.
Returns:
JSON-like
This function returns a JSON block that can be consumed by the BokehJS
function ``Bokeh.embed.embed_item``. As an example, a Flask endpoint for
``/plot`` might return the following content to embed a Bokeh plot into
a div with id *"myplot"*:
.. code-block:: python
@app.route('/plot')
def plot():
p = make_plot('petal_width', 'petal_length')
return json.dumps(json_item(p, "myplot"))
Then a web page can retrieve this JSON and embed the plot by calling
``Bokeh.embed.embed_item``:
.. code-block:: html
<script>
fetch('/plot')
.then(function(response) { return response.json(); })
.then(function(item) { Bokeh.embed.embed_item(item); })
</script>
Alternatively, if is more convenient to supply the target div id directly
in the page source, that is also possible. If `target_id` is omitted in the
call to this function:
.. code-block:: python
return json.dumps(json_item(p))
Then the value passed to ``embed_item`` is used:
.. code-block:: javascript
Bokeh.embed.embed_item(item, "myplot");
'''
with OutputDocumentFor([model], apply_theme=theme) as doc:
doc.title = ""
docs_json = standalone_docs_json([model])
doc = list(docs_json.values())[0]
root_id = doc['roots']['root_ids'][0]
return {
'target_id' : target,
'root_id' : root_id,
'doc' : doc,
} | [
"def",
"json_item",
"(",
"model",
",",
"target",
"=",
"None",
",",
"theme",
"=",
"FromCurdoc",
")",
":",
"with",
"OutputDocumentFor",
"(",
"[",
"model",
"]",
",",
"apply_theme",
"=",
"theme",
")",
"as",
"doc",
":",
"doc",
".",
"title",
"=",
"\"\"",
"... | Return a JSON block that can be used to embed standalone Bokeh content.
Args:
model (Model) :
The Bokeh object to embed
target (string, optional)
A div id to embed the model into. If None, the target id must
be supplied in the JavaScript call.
theme (Theme, optional) :
Defaults to the ``Theme`` instance in the current document.
Setting this to ``None`` uses the default theme or the theme
already specified in the document. Any other value must be an
instance of the ``Theme`` class.
Returns:
JSON-like
This function returns a JSON block that can be consumed by the BokehJS
function ``Bokeh.embed.embed_item``. As an example, a Flask endpoint for
``/plot`` might return the following content to embed a Bokeh plot into
a div with id *"myplot"*:
.. code-block:: python
@app.route('/plot')
def plot():
p = make_plot('petal_width', 'petal_length')
return json.dumps(json_item(p, "myplot"))
Then a web page can retrieve this JSON and embed the plot by calling
``Bokeh.embed.embed_item``:
.. code-block:: html
<script>
fetch('/plot')
.then(function(response) { return response.json(); })
.then(function(item) { Bokeh.embed.embed_item(item); })
</script>
Alternatively, if is more convenient to supply the target div id directly
in the page source, that is also possible. If `target_id` is omitted in the
call to this function:
.. code-block:: python
return json.dumps(json_item(p))
Then the value passed to ``embed_item`` is used:
.. code-block:: javascript
Bokeh.embed.embed_item(item, "myplot"); | [
"Return",
"a",
"JSON",
"block",
"that",
"can",
"be",
"used",
"to",
"embed",
"standalone",
"Bokeh",
"content",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/standalone.py#L314-L383 |
30,311 | bokeh/bokeh | bokeh/protocol/messages/patch_doc.py | process_document_events | def process_document_events(events, use_buffers=True):
''' Create a JSON string describing a patch to be applied as well as
any optional buffers.
Args:
events : list of events to be translated into patches
Returns:
str, list :
JSON string which can be applied to make the given updates to obj
as well as any optional buffers
'''
json_events = []
references = set()
buffers = [] if use_buffers else None
for event in events:
json_events.append(event.generate(references, buffers))
json = {
'events' : json_events,
'references' : references_json(references),
}
return serialize_json(json), buffers if use_buffers else [] | python | def process_document_events(events, use_buffers=True):
''' Create a JSON string describing a patch to be applied as well as
any optional buffers.
Args:
events : list of events to be translated into patches
Returns:
str, list :
JSON string which can be applied to make the given updates to obj
as well as any optional buffers
'''
json_events = []
references = set()
buffers = [] if use_buffers else None
for event in events:
json_events.append(event.generate(references, buffers))
json = {
'events' : json_events,
'references' : references_json(references),
}
return serialize_json(json), buffers if use_buffers else [] | [
"def",
"process_document_events",
"(",
"events",
",",
"use_buffers",
"=",
"True",
")",
":",
"json_events",
"=",
"[",
"]",
"references",
"=",
"set",
"(",
")",
"buffers",
"=",
"[",
"]",
"if",
"use_buffers",
"else",
"None",
"for",
"event",
"in",
"events",
"... | Create a JSON string describing a patch to be applied as well as
any optional buffers.
Args:
events : list of events to be translated into patches
Returns:
str, list :
JSON string which can be applied to make the given updates to obj
as well as any optional buffers | [
"Create",
"a",
"JSON",
"string",
"describing",
"a",
"patch",
"to",
"be",
"applied",
"as",
"well",
"as",
"any",
"optional",
"buffers",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/protocol/messages/patch_doc.py#L109-L136 |
30,312 | bokeh/bokeh | bokeh/util/compiler.py | calc_cache_key | def calc_cache_key(custom_models):
''' Generate a key to cache a custom extension implementation with.
There is no metadata other than the Model classes, so this is the only
base to generate a cache key.
We build the model keys from the list of ``model.full_name``. This is
not ideal but possibly a better solution can be found found later.
'''
model_names = {model.full_name for model in custom_models.values()}
encoded_names = ",".join(sorted(model_names)).encode('utf-8')
return hashlib.sha256(encoded_names).hexdigest() | python | def calc_cache_key(custom_models):
''' Generate a key to cache a custom extension implementation with.
There is no metadata other than the Model classes, so this is the only
base to generate a cache key.
We build the model keys from the list of ``model.full_name``. This is
not ideal but possibly a better solution can be found found later.
'''
model_names = {model.full_name for model in custom_models.values()}
encoded_names = ",".join(sorted(model_names)).encode('utf-8')
return hashlib.sha256(encoded_names).hexdigest() | [
"def",
"calc_cache_key",
"(",
"custom_models",
")",
":",
"model_names",
"=",
"{",
"model",
".",
"full_name",
"for",
"model",
"in",
"custom_models",
".",
"values",
"(",
")",
"}",
"encoded_names",
"=",
"\",\"",
".",
"join",
"(",
"sorted",
"(",
"model_names",
... | Generate a key to cache a custom extension implementation with.
There is no metadata other than the Model classes, so this is the only
base to generate a cache key.
We build the model keys from the list of ``model.full_name``. This is
not ideal but possibly a better solution can be found found later. | [
"Generate",
"a",
"key",
"to",
"cache",
"a",
"custom",
"extension",
"implementation",
"with",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/compiler.py#L312-L324 |
30,313 | bokeh/bokeh | bokeh/util/compiler.py | bundle_models | def bundle_models(models):
"""Create a bundle of selected `models`. """
custom_models = _get_custom_models(models)
if custom_models is None:
return None
key = calc_cache_key(custom_models)
bundle = _bundle_cache.get(key, None)
if bundle is None:
try:
_bundle_cache[key] = bundle = _bundle_models(custom_models)
except CompilationError as error:
print("Compilation failed:", file=sys.stderr)
print(str(error), file=sys.stderr)
sys.exit(1)
return bundle | python | def bundle_models(models):
"""Create a bundle of selected `models`. """
custom_models = _get_custom_models(models)
if custom_models is None:
return None
key = calc_cache_key(custom_models)
bundle = _bundle_cache.get(key, None)
if bundle is None:
try:
_bundle_cache[key] = bundle = _bundle_models(custom_models)
except CompilationError as error:
print("Compilation failed:", file=sys.stderr)
print(str(error), file=sys.stderr)
sys.exit(1)
return bundle | [
"def",
"bundle_models",
"(",
"models",
")",
":",
"custom_models",
"=",
"_get_custom_models",
"(",
"models",
")",
"if",
"custom_models",
"is",
"None",
":",
"return",
"None",
"key",
"=",
"calc_cache_key",
"(",
"custom_models",
")",
"bundle",
"=",
"_bundle_cache",
... | Create a bundle of selected `models`. | [
"Create",
"a",
"bundle",
"of",
"selected",
"models",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/compiler.py#L328-L343 |
30,314 | bokeh/bokeh | bokeh/util/compiler.py | _compile_models | def _compile_models(custom_models):
"""Returns the compiled implementation of supplied `models`. """
ordered_models = sorted(custom_models.values(), key=lambda model: model.full_name)
custom_impls = {}
dependencies = []
for model in ordered_models:
dependencies.extend(list(model.dependencies.items()))
if dependencies:
dependencies = sorted(dependencies, key=lambda name_version: name_version[0])
_run_npmjs(["install", "--no-progress"] + [ name + "@" + version for (name, version) in dependencies ])
for model in ordered_models:
impl = model.implementation
compiled = _CACHING_IMPLEMENTATION(model, impl)
if compiled is None:
compiled = nodejs_compile(impl.code, lang=impl.lang, file=impl.file)
if "error" in compiled:
raise CompilationError(compiled.error)
custom_impls[model.full_name] = compiled
return custom_impls | python | def _compile_models(custom_models):
"""Returns the compiled implementation of supplied `models`. """
ordered_models = sorted(custom_models.values(), key=lambda model: model.full_name)
custom_impls = {}
dependencies = []
for model in ordered_models:
dependencies.extend(list(model.dependencies.items()))
if dependencies:
dependencies = sorted(dependencies, key=lambda name_version: name_version[0])
_run_npmjs(["install", "--no-progress"] + [ name + "@" + version for (name, version) in dependencies ])
for model in ordered_models:
impl = model.implementation
compiled = _CACHING_IMPLEMENTATION(model, impl)
if compiled is None:
compiled = nodejs_compile(impl.code, lang=impl.lang, file=impl.file)
if "error" in compiled:
raise CompilationError(compiled.error)
custom_impls[model.full_name] = compiled
return custom_impls | [
"def",
"_compile_models",
"(",
"custom_models",
")",
":",
"ordered_models",
"=",
"sorted",
"(",
"custom_models",
".",
"values",
"(",
")",
",",
"key",
"=",
"lambda",
"model",
":",
"model",
".",
"full_name",
")",
"custom_impls",
"=",
"{",
"}",
"dependencies",
... | Returns the compiled implementation of supplied `models`. | [
"Returns",
"the",
"compiled",
"implementation",
"of",
"supplied",
"models",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/compiler.py#L518-L542 |
30,315 | bokeh/bokeh | bokeh/command/util.py | build_single_handler_application | def build_single_handler_application(path, argv=None):
''' Return a Bokeh application built using a single handler for a script,
notebook, or directory.
In general a Bokeh :class:`~bokeh.application.application.Application` may
have any number of handlers to initialize :class:`~bokeh.document.Document`
objects for new client sessions. However, in many cases only a single
handler is needed. This function examines the ``path`` provided, and
returns an ``Application`` initialized with one of the following handlers:
* :class:`~bokeh.application.handlers.script.ScriptHandler` when ``path``
is to a ``.py`` script.
* :class:`~bokeh.application.handlers.notebook.NotebookHandler` when
``path`` is to an ``.ipynb`` Jupyter notebook.
* :class:`~bokeh.application.handlers.directory.DirectoryHandler` when
``path`` is to a directory containing a ``main.py`` script.
Args:
path (str) : path to a file or directory for creating a Bokeh
application.
argv (seq[str], optional) : command line arguments to pass to the
application handler
Returns:
:class:`~bokeh.application.application.Application`
Raises:
RuntimeError
Notes:
If ``path`` ends with a file ``main.py`` then a warning will be printed
regarding running directory-style apps by passing the directory instead.
'''
argv = argv or []
path = os.path.abspath(path)
# There are certainly race conditions here if the file/directory is deleted
# in between the isdir/isfile tests and subsequent code. But it would be a
# failure if they were not there to begin with, too (just a different error)
if os.path.isdir(path):
handler = DirectoryHandler(filename=path, argv=argv)
elif os.path.isfile(path):
if path.endswith(".ipynb"):
handler = NotebookHandler(filename=path, argv=argv)
elif path.endswith(".py"):
if path.endswith("main.py"):
warnings.warn(DIRSTYLE_MAIN_WARNING)
handler = ScriptHandler(filename=path, argv=argv)
else:
raise ValueError("Expected a '.py' script or '.ipynb' notebook, got: '%s'" % path)
else:
raise ValueError("Path for Bokeh server application does not exist: %s" % path)
if handler.failed:
raise RuntimeError("Error loading %s:\n\n%s\n%s " % (path, handler.error, handler.error_detail))
application = Application(handler)
return application | python | def build_single_handler_application(path, argv=None):
''' Return a Bokeh application built using a single handler for a script,
notebook, or directory.
In general a Bokeh :class:`~bokeh.application.application.Application` may
have any number of handlers to initialize :class:`~bokeh.document.Document`
objects for new client sessions. However, in many cases only a single
handler is needed. This function examines the ``path`` provided, and
returns an ``Application`` initialized with one of the following handlers:
* :class:`~bokeh.application.handlers.script.ScriptHandler` when ``path``
is to a ``.py`` script.
* :class:`~bokeh.application.handlers.notebook.NotebookHandler` when
``path`` is to an ``.ipynb`` Jupyter notebook.
* :class:`~bokeh.application.handlers.directory.DirectoryHandler` when
``path`` is to a directory containing a ``main.py`` script.
Args:
path (str) : path to a file or directory for creating a Bokeh
application.
argv (seq[str], optional) : command line arguments to pass to the
application handler
Returns:
:class:`~bokeh.application.application.Application`
Raises:
RuntimeError
Notes:
If ``path`` ends with a file ``main.py`` then a warning will be printed
regarding running directory-style apps by passing the directory instead.
'''
argv = argv or []
path = os.path.abspath(path)
# There are certainly race conditions here if the file/directory is deleted
# in between the isdir/isfile tests and subsequent code. But it would be a
# failure if they were not there to begin with, too (just a different error)
if os.path.isdir(path):
handler = DirectoryHandler(filename=path, argv=argv)
elif os.path.isfile(path):
if path.endswith(".ipynb"):
handler = NotebookHandler(filename=path, argv=argv)
elif path.endswith(".py"):
if path.endswith("main.py"):
warnings.warn(DIRSTYLE_MAIN_WARNING)
handler = ScriptHandler(filename=path, argv=argv)
else:
raise ValueError("Expected a '.py' script or '.ipynb' notebook, got: '%s'" % path)
else:
raise ValueError("Path for Bokeh server application does not exist: %s" % path)
if handler.failed:
raise RuntimeError("Error loading %s:\n\n%s\n%s " % (path, handler.error, handler.error_detail))
application = Application(handler)
return application | [
"def",
"build_single_handler_application",
"(",
"path",
",",
"argv",
"=",
"None",
")",
":",
"argv",
"=",
"argv",
"or",
"[",
"]",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
"# There are certainly race conditions here if the file/directory is ... | Return a Bokeh application built using a single handler for a script,
notebook, or directory.
In general a Bokeh :class:`~bokeh.application.application.Application` may
have any number of handlers to initialize :class:`~bokeh.document.Document`
objects for new client sessions. However, in many cases only a single
handler is needed. This function examines the ``path`` provided, and
returns an ``Application`` initialized with one of the following handlers:
* :class:`~bokeh.application.handlers.script.ScriptHandler` when ``path``
is to a ``.py`` script.
* :class:`~bokeh.application.handlers.notebook.NotebookHandler` when
``path`` is to an ``.ipynb`` Jupyter notebook.
* :class:`~bokeh.application.handlers.directory.DirectoryHandler` when
``path`` is to a directory containing a ``main.py`` script.
Args:
path (str) : path to a file or directory for creating a Bokeh
application.
argv (seq[str], optional) : command line arguments to pass to the
application handler
Returns:
:class:`~bokeh.application.application.Application`
Raises:
RuntimeError
Notes:
If ``path`` ends with a file ``main.py`` then a warning will be printed
regarding running directory-style apps by passing the directory instead. | [
"Return",
"a",
"Bokeh",
"application",
"built",
"using",
"a",
"single",
"handler",
"for",
"a",
"script",
"notebook",
"or",
"directory",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/command/util.py#L77-L139 |
30,316 | bokeh/bokeh | bokeh/command/util.py | build_single_handler_applications | def build_single_handler_applications(paths, argvs=None):
''' Return a dictionary mapping routes to Bokeh applications built using
single handlers, for specified files or directories.
This function iterates over ``paths`` and ``argvs`` and calls
:func:`~bokeh.command.util.build_single_handler_application` on each
to generate the mapping.
Args:
path (seq[str]) : paths to files or directories for creating Bokeh
applications.
argvs (dict[str, list[str]], optional) : mapping of paths to command
line arguments to pass to the handler for each path
Returns:
dict[str, Application]
Raises:
RuntimeError
'''
applications = {}
argvs = {} or argvs
for path in paths:
application = build_single_handler_application(path, argvs.get(path, []))
route = application.handlers[0].url_path()
if not route:
if '/' in applications:
raise RuntimeError("Don't know the URL path to use for %s" % (path))
route = '/'
applications[route] = application
return applications | python | def build_single_handler_applications(paths, argvs=None):
''' Return a dictionary mapping routes to Bokeh applications built using
single handlers, for specified files or directories.
This function iterates over ``paths`` and ``argvs`` and calls
:func:`~bokeh.command.util.build_single_handler_application` on each
to generate the mapping.
Args:
path (seq[str]) : paths to files or directories for creating Bokeh
applications.
argvs (dict[str, list[str]], optional) : mapping of paths to command
line arguments to pass to the handler for each path
Returns:
dict[str, Application]
Raises:
RuntimeError
'''
applications = {}
argvs = {} or argvs
for path in paths:
application = build_single_handler_application(path, argvs.get(path, []))
route = application.handlers[0].url_path()
if not route:
if '/' in applications:
raise RuntimeError("Don't know the URL path to use for %s" % (path))
route = '/'
applications[route] = application
return applications | [
"def",
"build_single_handler_applications",
"(",
"paths",
",",
"argvs",
"=",
"None",
")",
":",
"applications",
"=",
"{",
"}",
"argvs",
"=",
"{",
"}",
"or",
"argvs",
"for",
"path",
"in",
"paths",
":",
"application",
"=",
"build_single_handler_application",
"(",... | Return a dictionary mapping routes to Bokeh applications built using
single handlers, for specified files or directories.
This function iterates over ``paths`` and ``argvs`` and calls
:func:`~bokeh.command.util.build_single_handler_application` on each
to generate the mapping.
Args:
path (seq[str]) : paths to files or directories for creating Bokeh
applications.
argvs (dict[str, list[str]], optional) : mapping of paths to command
line arguments to pass to the handler for each path
Returns:
dict[str, Application]
Raises:
RuntimeError | [
"Return",
"a",
"dictionary",
"mapping",
"routes",
"to",
"Bokeh",
"applications",
"built",
"using",
"single",
"handlers",
"for",
"specified",
"files",
"or",
"directories",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/command/util.py#L141-L177 |
30,317 | bokeh/bokeh | bokeh/command/util.py | report_server_init_errors | def report_server_init_errors(address=None, port=None, **kwargs):
''' A context manager to help print more informative error messages when a
``Server`` cannot be started due to a network problem.
Args:
address (str) : network address that the server will be listening on
port (int) : network address that the server will be listening on
Example:
.. code-block:: python
with report_server_init_errors(**server_kwargs):
server = Server(applications, **server_kwargs)
If there are any errors (e.g. port or address in already in use) then a
critical error will be logged and the process will terminate with a
call to ``sys.exit(1)``
'''
try:
yield
except EnvironmentError as e:
if e.errno == errno.EADDRINUSE:
log.critical("Cannot start Bokeh server, port %s is already in use", port)
elif e.errno == errno.EADDRNOTAVAIL:
log.critical("Cannot start Bokeh server, address '%s' not available", address)
else:
codename = errno.errorcode[e.errno]
log.critical("Cannot start Bokeh server [%s]: %r", codename, e)
sys.exit(1) | python | def report_server_init_errors(address=None, port=None, **kwargs):
''' A context manager to help print more informative error messages when a
``Server`` cannot be started due to a network problem.
Args:
address (str) : network address that the server will be listening on
port (int) : network address that the server will be listening on
Example:
.. code-block:: python
with report_server_init_errors(**server_kwargs):
server = Server(applications, **server_kwargs)
If there are any errors (e.g. port or address in already in use) then a
critical error will be logged and the process will terminate with a
call to ``sys.exit(1)``
'''
try:
yield
except EnvironmentError as e:
if e.errno == errno.EADDRINUSE:
log.critical("Cannot start Bokeh server, port %s is already in use", port)
elif e.errno == errno.EADDRNOTAVAIL:
log.critical("Cannot start Bokeh server, address '%s' not available", address)
else:
codename = errno.errorcode[e.errno]
log.critical("Cannot start Bokeh server [%s]: %r", codename, e)
sys.exit(1) | [
"def",
"report_server_init_errors",
"(",
"address",
"=",
"None",
",",
"port",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"yield",
"except",
"EnvironmentError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"EADDRINUSE",
... | A context manager to help print more informative error messages when a
``Server`` cannot be started due to a network problem.
Args:
address (str) : network address that the server will be listening on
port (int) : network address that the server will be listening on
Example:
.. code-block:: python
with report_server_init_errors(**server_kwargs):
server = Server(applications, **server_kwargs)
If there are any errors (e.g. port or address in already in use) then a
critical error will be logged and the process will terminate with a
call to ``sys.exit(1)`` | [
"A",
"context",
"manager",
"to",
"help",
"print",
"more",
"informative",
"error",
"messages",
"when",
"a",
"Server",
"cannot",
"be",
"started",
"due",
"to",
"a",
"network",
"problem",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/command/util.py#L181-L212 |
30,318 | bokeh/bokeh | bokeh/server/util.py | bind_sockets | def bind_sockets(address, port):
''' Bind a socket to a port on an address.
Args:
address (str) :
An address to bind a port on, e.g. ``"localhost"``
port (int) :
A port number to bind.
Pass 0 to have the OS automatically choose a free port.
This function returns a 2-tuple with the new socket as the first element,
and the port that was bound as the second. (Useful when passing 0 as a port
number to bind any free port.)
Returns:
(socket, port)
'''
ss = netutil.bind_sockets(port=port or 0, address=address)
assert len(ss)
ports = {s.getsockname()[1] for s in ss}
assert len(ports) == 1, "Multiple ports assigned??"
actual_port = ports.pop()
if port:
assert actual_port == port
return ss, actual_port | python | def bind_sockets(address, port):
''' Bind a socket to a port on an address.
Args:
address (str) :
An address to bind a port on, e.g. ``"localhost"``
port (int) :
A port number to bind.
Pass 0 to have the OS automatically choose a free port.
This function returns a 2-tuple with the new socket as the first element,
and the port that was bound as the second. (Useful when passing 0 as a port
number to bind any free port.)
Returns:
(socket, port)
'''
ss = netutil.bind_sockets(port=port or 0, address=address)
assert len(ss)
ports = {s.getsockname()[1] for s in ss}
assert len(ports) == 1, "Multiple ports assigned??"
actual_port = ports.pop()
if port:
assert actual_port == port
return ss, actual_port | [
"def",
"bind_sockets",
"(",
"address",
",",
"port",
")",
":",
"ss",
"=",
"netutil",
".",
"bind_sockets",
"(",
"port",
"=",
"port",
"or",
"0",
",",
"address",
"=",
"address",
")",
"assert",
"len",
"(",
"ss",
")",
"ports",
"=",
"{",
"s",
".",
"getsoc... | Bind a socket to a port on an address.
Args:
address (str) :
An address to bind a port on, e.g. ``"localhost"``
port (int) :
A port number to bind.
Pass 0 to have the OS automatically choose a free port.
This function returns a 2-tuple with the new socket as the first element,
and the port that was bound as the second. (Useful when passing 0 as a port
number to bind any free port.)
Returns:
(socket, port) | [
"Bind",
"a",
"socket",
"to",
"a",
"port",
"on",
"an",
"address",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/util.py#L46-L73 |
30,319 | bokeh/bokeh | bokeh/server/util.py | check_whitelist | def check_whitelist(host, whitelist):
''' Check a given request host against a whitelist.
Args:
host (str) :
A host string to compare against a whitelist.
If the host does not specify a port, then ``":80"`` is implicitly
assumed.
whitelist (seq[str]) :
A list of host patterns to match against
Returns:
``True``, if ``host`` matches any pattern in ``whitelist``, otherwise
``False``
'''
if ':' not in host:
host = host + ':80'
if host in whitelist:
return True
return any(match_host(host, pattern) for pattern in whitelist) | python | def check_whitelist(host, whitelist):
''' Check a given request host against a whitelist.
Args:
host (str) :
A host string to compare against a whitelist.
If the host does not specify a port, then ``":80"`` is implicitly
assumed.
whitelist (seq[str]) :
A list of host patterns to match against
Returns:
``True``, if ``host`` matches any pattern in ``whitelist``, otherwise
``False``
'''
if ':' not in host:
host = host + ':80'
if host in whitelist:
return True
return any(match_host(host, pattern) for pattern in whitelist) | [
"def",
"check_whitelist",
"(",
"host",
",",
"whitelist",
")",
":",
"if",
"':'",
"not",
"in",
"host",
":",
"host",
"=",
"host",
"+",
"':80'",
"if",
"host",
"in",
"whitelist",
":",
"return",
"True",
"return",
"any",
"(",
"match_host",
"(",
"host",
",",
... | Check a given request host against a whitelist.
Args:
host (str) :
A host string to compare against a whitelist.
If the host does not specify a port, then ``":80"`` is implicitly
assumed.
whitelist (seq[str]) :
A list of host patterns to match against
Returns:
``True``, if ``host`` matches any pattern in ``whitelist``, otherwise
``False`` | [
"Check",
"a",
"given",
"request",
"host",
"against",
"a",
"whitelist",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/util.py#L75-L99 |
30,320 | bokeh/bokeh | bokeh/server/util.py | match_host | def match_host(host, pattern):
''' Match a host string against a pattern
Args:
host (str)
A hostname to compare to the given pattern
pattern (str)
A string representing a hostname pattern, possibly including
wildcards for ip address octets or ports.
This function will return ``True`` if the hostname matches the pattern,
including any wildcards. If the pattern contains a port, the host string
must also contain a matching port.
Returns:
bool
Examples:
>>> match_host('192.168.0.1:80', '192.168.0.1:80')
True
>>> match_host('192.168.0.1:80', '192.168.0.1')
True
>>> match_host('192.168.0.1:80', '192.168.0.1:8080')
False
>>> match_host('192.168.0.1', '192.168.0.2')
False
>>> match_host('192.168.0.1', '192.168.*.*')
True
>>> match_host('alice', 'alice')
True
>>> match_host('alice:80', 'alice')
True
>>> match_host('alice', 'bob')
False
>>> match_host('foo.example.com', 'foo.example.com.net')
False
>>> match_host('alice', '*')
True
>>> match_host('alice', '*:*')
True
>>> match_host('alice:80', '*')
True
>>> match_host('alice:80', '*:80')
True
>>> match_host('alice:8080', '*:80')
False
'''
if ':' in host:
host, host_port = host.rsplit(':', 1)
else:
host_port = None
if ':' in pattern:
pattern, pattern_port = pattern.rsplit(':', 1)
if pattern_port == '*':
pattern_port = None
else:
pattern_port = None
if pattern_port is not None and host_port != pattern_port:
return False
host = host.split('.')
pattern = pattern.split('.')
if len(pattern) > len(host):
return False
for h, p in zip(host, pattern):
if h == p or p == '*':
continue
else:
return False
return True | python | def match_host(host, pattern):
''' Match a host string against a pattern
Args:
host (str)
A hostname to compare to the given pattern
pattern (str)
A string representing a hostname pattern, possibly including
wildcards for ip address octets or ports.
This function will return ``True`` if the hostname matches the pattern,
including any wildcards. If the pattern contains a port, the host string
must also contain a matching port.
Returns:
bool
Examples:
>>> match_host('192.168.0.1:80', '192.168.0.1:80')
True
>>> match_host('192.168.0.1:80', '192.168.0.1')
True
>>> match_host('192.168.0.1:80', '192.168.0.1:8080')
False
>>> match_host('192.168.0.1', '192.168.0.2')
False
>>> match_host('192.168.0.1', '192.168.*.*')
True
>>> match_host('alice', 'alice')
True
>>> match_host('alice:80', 'alice')
True
>>> match_host('alice', 'bob')
False
>>> match_host('foo.example.com', 'foo.example.com.net')
False
>>> match_host('alice', '*')
True
>>> match_host('alice', '*:*')
True
>>> match_host('alice:80', '*')
True
>>> match_host('alice:80', '*:80')
True
>>> match_host('alice:8080', '*:80')
False
'''
if ':' in host:
host, host_port = host.rsplit(':', 1)
else:
host_port = None
if ':' in pattern:
pattern, pattern_port = pattern.rsplit(':', 1)
if pattern_port == '*':
pattern_port = None
else:
pattern_port = None
if pattern_port is not None and host_port != pattern_port:
return False
host = host.split('.')
pattern = pattern.split('.')
if len(pattern) > len(host):
return False
for h, p in zip(host, pattern):
if h == p or p == '*':
continue
else:
return False
return True | [
"def",
"match_host",
"(",
"host",
",",
"pattern",
")",
":",
"if",
"':'",
"in",
"host",
":",
"host",
",",
"host_port",
"=",
"host",
".",
"rsplit",
"(",
"':'",
",",
"1",
")",
"else",
":",
"host_port",
"=",
"None",
"if",
"':'",
"in",
"pattern",
":",
... | Match a host string against a pattern
Args:
host (str)
A hostname to compare to the given pattern
pattern (str)
A string representing a hostname pattern, possibly including
wildcards for ip address octets or ports.
This function will return ``True`` if the hostname matches the pattern,
including any wildcards. If the pattern contains a port, the host string
must also contain a matching port.
Returns:
bool
Examples:
>>> match_host('192.168.0.1:80', '192.168.0.1:80')
True
>>> match_host('192.168.0.1:80', '192.168.0.1')
True
>>> match_host('192.168.0.1:80', '192.168.0.1:8080')
False
>>> match_host('192.168.0.1', '192.168.0.2')
False
>>> match_host('192.168.0.1', '192.168.*.*')
True
>>> match_host('alice', 'alice')
True
>>> match_host('alice:80', 'alice')
True
>>> match_host('alice', 'bob')
False
>>> match_host('foo.example.com', 'foo.example.com.net')
False
>>> match_host('alice', '*')
True
>>> match_host('alice', '*:*')
True
>>> match_host('alice:80', '*')
True
>>> match_host('alice:80', '*:80')
True
>>> match_host('alice:8080', '*:80')
False | [
"Match",
"a",
"host",
"string",
"against",
"a",
"pattern"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/util.py#L164-L240 |
30,321 | bokeh/bokeh | bokeh/io/state.py | State.notebook_type | def notebook_type(self, notebook_type):
''' Notebook type, acceptable values are 'jupyter' as well as any names
defined by external notebook hooks that have been installed.
'''
if notebook_type is None or not isinstance(notebook_type, string_types):
raise ValueError("Notebook type must be a string")
self._notebook_type = notebook_type.lower() | python | def notebook_type(self, notebook_type):
''' Notebook type, acceptable values are 'jupyter' as well as any names
defined by external notebook hooks that have been installed.
'''
if notebook_type is None or not isinstance(notebook_type, string_types):
raise ValueError("Notebook type must be a string")
self._notebook_type = notebook_type.lower() | [
"def",
"notebook_type",
"(",
"self",
",",
"notebook_type",
")",
":",
"if",
"notebook_type",
"is",
"None",
"or",
"not",
"isinstance",
"(",
"notebook_type",
",",
"string_types",
")",
":",
"raise",
"ValueError",
"(",
"\"Notebook type must be a string\"",
")",
"self",... | Notebook type, acceptable values are 'jupyter' as well as any names
defined by external notebook hooks that have been installed. | [
"Notebook",
"type",
"acceptable",
"values",
"are",
"jupyter",
"as",
"well",
"as",
"any",
"names",
"defined",
"by",
"external",
"notebook",
"hooks",
"that",
"have",
"been",
"installed",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/state.py#L124-L131 |
30,322 | bokeh/bokeh | bokeh/io/state.py | State.output_file | def output_file(self, filename, title="Bokeh Plot", mode="cdn", root_dir=None):
''' Configure output to a standalone HTML file.
Calling ``output_file`` not clear the effects of any other calls to
``output_notebook``, etc. It adds an additional output destination
(publishing to HTML files). Any other active output modes continue
to be active.
Args:
filename (str) : a filename for saving the HTML document
title (str, optional) : a title for the HTML document
mode (str, optional) : how to include BokehJS (default: ``'cdn'``)
One of: ``'inline'``, ``'cdn'``, ``'relative(-dev)'`` or
``'absolute(-dev)'``. See :class:`~bokeh.resources.Resources`
for more details.
root_dir (str, optional) : root dir to use for absolute resources
(default: None)
This value is ignored for other resource types, e.g. ``INLINE`` or ``CDN``.
.. warning::
The specified output file will be overwritten on every save, e.g.,
every time ``show()`` or ``save()`` is called.
'''
self._file = {
'filename' : filename,
'resources' : Resources(mode=mode, root_dir=root_dir),
'title' : title
}
if os.path.isfile(filename):
log.info("Session output file '%s' already exists, will be overwritten." % filename) | python | def output_file(self, filename, title="Bokeh Plot", mode="cdn", root_dir=None):
''' Configure output to a standalone HTML file.
Calling ``output_file`` not clear the effects of any other calls to
``output_notebook``, etc. It adds an additional output destination
(publishing to HTML files). Any other active output modes continue
to be active.
Args:
filename (str) : a filename for saving the HTML document
title (str, optional) : a title for the HTML document
mode (str, optional) : how to include BokehJS (default: ``'cdn'``)
One of: ``'inline'``, ``'cdn'``, ``'relative(-dev)'`` or
``'absolute(-dev)'``. See :class:`~bokeh.resources.Resources`
for more details.
root_dir (str, optional) : root dir to use for absolute resources
(default: None)
This value is ignored for other resource types, e.g. ``INLINE`` or ``CDN``.
.. warning::
The specified output file will be overwritten on every save, e.g.,
every time ``show()`` or ``save()`` is called.
'''
self._file = {
'filename' : filename,
'resources' : Resources(mode=mode, root_dir=root_dir),
'title' : title
}
if os.path.isfile(filename):
log.info("Session output file '%s' already exists, will be overwritten." % filename) | [
"def",
"output_file",
"(",
"self",
",",
"filename",
",",
"title",
"=",
"\"Bokeh Plot\"",
",",
"mode",
"=",
"\"cdn\"",
",",
"root_dir",
"=",
"None",
")",
":",
"self",
".",
"_file",
"=",
"{",
"'filename'",
":",
"filename",
",",
"'resources'",
":",
"Resourc... | Configure output to a standalone HTML file.
Calling ``output_file`` not clear the effects of any other calls to
``output_notebook``, etc. It adds an additional output destination
(publishing to HTML files). Any other active output modes continue
to be active.
Args:
filename (str) : a filename for saving the HTML document
title (str, optional) : a title for the HTML document
mode (str, optional) : how to include BokehJS (default: ``'cdn'``)
One of: ``'inline'``, ``'cdn'``, ``'relative(-dev)'`` or
``'absolute(-dev)'``. See :class:`~bokeh.resources.Resources`
for more details.
root_dir (str, optional) : root dir to use for absolute resources
(default: None)
This value is ignored for other resource types, e.g. ``INLINE`` or ``CDN``.
.. warning::
The specified output file will be overwritten on every save, e.g.,
every time ``show()`` or ``save()`` is called. | [
"Configure",
"output",
"to",
"a",
"standalone",
"HTML",
"file",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/state.py#L135-L171 |
30,323 | bokeh/bokeh | bokeh/io/saving.py | save | def save(obj, filename=None, resources=None, title=None, template=None, state=None, **kwargs):
''' Save an HTML file with the data for the current document.
Will fall back to the default output state (or an explicitly provided
:class:`State` object) for ``filename``, ``resources``, or ``title`` if they
are not provided. If the filename is not given and not provided via output state,
it is derived from the script name (e.g. ``/foo/myplot.py`` will create
``/foo/myplot.html``)
Args:
obj (LayoutDOM object) : a Layout (Row/Column), Plot or Widget object to display
filename (str, optional) : filename to save document under (default: None)
If None, use the default state configuration.
resources (Resources, optional) : A Resources config to use (default: None)
If None, use the default state configuration, if there is one.
otherwise use ``resources.INLINE``.
title (str, optional) : a title for the HTML document (default: None)
If None, use the default state title value, if there is one.
Otherwise, use "Bokeh Plot"
state (State, optional) :
A :class:`State` object. If None, then the current default
implicit state is used. (default: None).
Returns:
str: the filename where the HTML file is saved.
'''
if state is None:
state = curstate()
filename, resources, title = _get_save_args(state, filename, resources, title)
_save_helper(obj, filename, resources, title, template)
return abspath(filename) | python | def save(obj, filename=None, resources=None, title=None, template=None, state=None, **kwargs):
''' Save an HTML file with the data for the current document.
Will fall back to the default output state (or an explicitly provided
:class:`State` object) for ``filename``, ``resources``, or ``title`` if they
are not provided. If the filename is not given and not provided via output state,
it is derived from the script name (e.g. ``/foo/myplot.py`` will create
``/foo/myplot.html``)
Args:
obj (LayoutDOM object) : a Layout (Row/Column), Plot or Widget object to display
filename (str, optional) : filename to save document under (default: None)
If None, use the default state configuration.
resources (Resources, optional) : A Resources config to use (default: None)
If None, use the default state configuration, if there is one.
otherwise use ``resources.INLINE``.
title (str, optional) : a title for the HTML document (default: None)
If None, use the default state title value, if there is one.
Otherwise, use "Bokeh Plot"
state (State, optional) :
A :class:`State` object. If None, then the current default
implicit state is used. (default: None).
Returns:
str: the filename where the HTML file is saved.
'''
if state is None:
state = curstate()
filename, resources, title = _get_save_args(state, filename, resources, title)
_save_helper(obj, filename, resources, title, template)
return abspath(filename) | [
"def",
"save",
"(",
"obj",
",",
"filename",
"=",
"None",
",",
"resources",
"=",
"None",
",",
"title",
"=",
"None",
",",
"template",
"=",
"None",
",",
"state",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"state",
"is",
"None",
":",
"stat... | Save an HTML file with the data for the current document.
Will fall back to the default output state (or an explicitly provided
:class:`State` object) for ``filename``, ``resources``, or ``title`` if they
are not provided. If the filename is not given and not provided via output state,
it is derived from the script name (e.g. ``/foo/myplot.py`` will create
``/foo/myplot.html``)
Args:
obj (LayoutDOM object) : a Layout (Row/Column), Plot or Widget object to display
filename (str, optional) : filename to save document under (default: None)
If None, use the default state configuration.
resources (Resources, optional) : A Resources config to use (default: None)
If None, use the default state configuration, if there is one.
otherwise use ``resources.INLINE``.
title (str, optional) : a title for the HTML document (default: None)
If None, use the default state title value, if there is one.
Otherwise, use "Bokeh Plot"
state (State, optional) :
A :class:`State` object. If None, then the current default
implicit state is used. (default: None).
Returns:
str: the filename where the HTML file is saved. | [
"Save",
"an",
"HTML",
"file",
"with",
"the",
"data",
"for",
"the",
"current",
"document",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/saving.py#L50-L87 |
30,324 | bokeh/bokeh | bokeh/sphinxext/bokeh_sitemap.py | html_page_context | def html_page_context(app, pagename, templatename, context, doctree):
''' Collect page names for the sitemap as HTML pages are built.
'''
site = context['SITEMAP_BASE_URL']
version = context['version']
app.sitemap_links.add(site + version + '/' + pagename + ".html") | python | def html_page_context(app, pagename, templatename, context, doctree):
''' Collect page names for the sitemap as HTML pages are built.
'''
site = context['SITEMAP_BASE_URL']
version = context['version']
app.sitemap_links.add(site + version + '/' + pagename + ".html") | [
"def",
"html_page_context",
"(",
"app",
",",
"pagename",
",",
"templatename",
",",
"context",
",",
"doctree",
")",
":",
"site",
"=",
"context",
"[",
"'SITEMAP_BASE_URL'",
"]",
"version",
"=",
"context",
"[",
"'version'",
"]",
"app",
".",
"sitemap_links",
"."... | Collect page names for the sitemap as HTML pages are built. | [
"Collect",
"page",
"names",
"for",
"the",
"sitemap",
"as",
"HTML",
"pages",
"are",
"built",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/sphinxext/bokeh_sitemap.py#L58-L64 |
30,325 | bokeh/bokeh | bokeh/sphinxext/bokeh_sitemap.py | build_finished | def build_finished(app, exception):
''' Generate a ``sitemap.txt`` from the collected HTML page links.
'''
filename = join(app.outdir, "sitemap.txt")
links_iter = status_iterator(sorted(app.sitemap_links),
'adding links to sitemap... ',
'brown',
len(app.sitemap_links),
app.verbosity)
try:
with open(filename, 'w') as f:
for link in links_iter:
f.write("%s\n" % link)
except OSError as e:
raise SphinxError('cannot write sitemap.txt, reason: %s' % e) | python | def build_finished(app, exception):
''' Generate a ``sitemap.txt`` from the collected HTML page links.
'''
filename = join(app.outdir, "sitemap.txt")
links_iter = status_iterator(sorted(app.sitemap_links),
'adding links to sitemap... ',
'brown',
len(app.sitemap_links),
app.verbosity)
try:
with open(filename, 'w') as f:
for link in links_iter:
f.write("%s\n" % link)
except OSError as e:
raise SphinxError('cannot write sitemap.txt, reason: %s' % e) | [
"def",
"build_finished",
"(",
"app",
",",
"exception",
")",
":",
"filename",
"=",
"join",
"(",
"app",
".",
"outdir",
",",
"\"sitemap.txt\"",
")",
"links_iter",
"=",
"status_iterator",
"(",
"sorted",
"(",
"app",
".",
"sitemap_links",
")",
",",
"'adding links ... | Generate a ``sitemap.txt`` from the collected HTML page links. | [
"Generate",
"a",
"sitemap",
".",
"txt",
"from",
"the",
"collected",
"HTML",
"page",
"links",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/sphinxext/bokeh_sitemap.py#L66-L83 |
30,326 | bokeh/bokeh | bokeh/server/tornado.py | BokehTornado.initialize | def initialize(self, io_loop):
''' Start a Bokeh Server Tornado Application on a given Tornado IOLoop.
'''
self._loop = io_loop
for app_context in self._applications.values():
app_context._loop = self._loop
self._clients = set()
self._stats_job = PeriodicCallback(self._log_stats,
self._stats_log_frequency_milliseconds)
if self._mem_log_frequency_milliseconds > 0:
self._mem_job = PeriodicCallback(self._log_mem,
self._mem_log_frequency_milliseconds)
else:
self._mem_job = None
self._cleanup_job = PeriodicCallback(self._cleanup_sessions,
self._check_unused_sessions_milliseconds)
if self._keep_alive_milliseconds > 0:
self._ping_job = PeriodicCallback(self._keep_alive, self._keep_alive_milliseconds)
else:
self._ping_job = None | python | def initialize(self, io_loop):
''' Start a Bokeh Server Tornado Application on a given Tornado IOLoop.
'''
self._loop = io_loop
for app_context in self._applications.values():
app_context._loop = self._loop
self._clients = set()
self._stats_job = PeriodicCallback(self._log_stats,
self._stats_log_frequency_milliseconds)
if self._mem_log_frequency_milliseconds > 0:
self._mem_job = PeriodicCallback(self._log_mem,
self._mem_log_frequency_milliseconds)
else:
self._mem_job = None
self._cleanup_job = PeriodicCallback(self._cleanup_sessions,
self._check_unused_sessions_milliseconds)
if self._keep_alive_milliseconds > 0:
self._ping_job = PeriodicCallback(self._keep_alive, self._keep_alive_milliseconds)
else:
self._ping_job = None | [
"def",
"initialize",
"(",
"self",
",",
"io_loop",
")",
":",
"self",
".",
"_loop",
"=",
"io_loop",
"for",
"app_context",
"in",
"self",
".",
"_applications",
".",
"values",
"(",
")",
":",
"app_context",
".",
"_loop",
"=",
"self",
".",
"_loop",
"self",
".... | Start a Bokeh Server Tornado Application on a given Tornado IOLoop. | [
"Start",
"a",
"Bokeh",
"Server",
"Tornado",
"Application",
"on",
"a",
"given",
"Tornado",
"IOLoop",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/tornado.py#L319-L346 |
30,327 | bokeh/bokeh | bokeh/server/tornado.py | BokehTornado.start | def start(self):
''' Start the Bokeh Server application.
Starting the Bokeh Server Tornado application will run periodic
callbacks for stats logging, cleanup, pinging, etc. Additionally, any
startup hooks defined by the configured Bokeh applications will be run.
'''
self._stats_job.start()
if self._mem_job is not None:
self._mem_job.start()
self._cleanup_job.start()
if self._ping_job is not None:
self._ping_job.start()
for context in self._applications.values():
context.run_load_hook() | python | def start(self):
''' Start the Bokeh Server application.
Starting the Bokeh Server Tornado application will run periodic
callbacks for stats logging, cleanup, pinging, etc. Additionally, any
startup hooks defined by the configured Bokeh applications will be run.
'''
self._stats_job.start()
if self._mem_job is not None:
self._mem_job.start()
self._cleanup_job.start()
if self._ping_job is not None:
self._ping_job.start()
for context in self._applications.values():
context.run_load_hook() | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_stats_job",
".",
"start",
"(",
")",
"if",
"self",
".",
"_mem_job",
"is",
"not",
"None",
":",
"self",
".",
"_mem_job",
".",
"start",
"(",
")",
"self",
".",
"_cleanup_job",
".",
"start",
"(",
")",... | Start the Bokeh Server application.
Starting the Bokeh Server Tornado application will run periodic
callbacks for stats logging, cleanup, pinging, etc. Additionally, any
startup hooks defined by the configured Bokeh applications will be run. | [
"Start",
"the",
"Bokeh",
"Server",
"application",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/tornado.py#L425-L441 |
30,328 | bokeh/bokeh | bokeh/server/tornado.py | BokehTornado.stop | def stop(self, wait=True):
''' Stop the Bokeh Server application.
Args:
wait (bool): whether to wait for orderly cleanup (default: True)
Returns:
None
'''
# TODO should probably close all connections and shut down all sessions here
for context in self._applications.values():
context.run_unload_hook()
self._stats_job.stop()
if self._mem_job is not None:
self._mem_job.stop()
self._cleanup_job.stop()
if self._ping_job is not None:
self._ping_job.stop()
self._clients.clear() | python | def stop(self, wait=True):
''' Stop the Bokeh Server application.
Args:
wait (bool): whether to wait for orderly cleanup (default: True)
Returns:
None
'''
# TODO should probably close all connections and shut down all sessions here
for context in self._applications.values():
context.run_unload_hook()
self._stats_job.stop()
if self._mem_job is not None:
self._mem_job.stop()
self._cleanup_job.stop()
if self._ping_job is not None:
self._ping_job.stop()
self._clients.clear() | [
"def",
"stop",
"(",
"self",
",",
"wait",
"=",
"True",
")",
":",
"# TODO should probably close all connections and shut down all sessions here",
"for",
"context",
"in",
"self",
".",
"_applications",
".",
"values",
"(",
")",
":",
"context",
".",
"run_unload_hook",
"("... | Stop the Bokeh Server application.
Args:
wait (bool): whether to wait for orderly cleanup (default: True)
Returns:
None | [
"Stop",
"the",
"Bokeh",
"Server",
"application",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/tornado.py#L443-L465 |
30,329 | bokeh/bokeh | bokeh/server/tornado.py | BokehTornado.get_session | def get_session(self, app_path, session_id):
''' Get an active a session by name application path and session ID.
Args:
app_path (str) :
The configured application path for the application to return
a session for.
session_id (str) :
The session ID of the session to retrieve.
Returns:
ServerSession
'''
if app_path not in self._applications:
raise ValueError("Application %s does not exist on this server" % app_path)
return self._applications[app_path].get_session(session_id) | python | def get_session(self, app_path, session_id):
''' Get an active a session by name application path and session ID.
Args:
app_path (str) :
The configured application path for the application to return
a session for.
session_id (str) :
The session ID of the session to retrieve.
Returns:
ServerSession
'''
if app_path not in self._applications:
raise ValueError("Application %s does not exist on this server" % app_path)
return self._applications[app_path].get_session(session_id) | [
"def",
"get_session",
"(",
"self",
",",
"app_path",
",",
"session_id",
")",
":",
"if",
"app_path",
"not",
"in",
"self",
".",
"_applications",
":",
"raise",
"ValueError",
"(",
"\"Application %s does not exist on this server\"",
"%",
"app_path",
")",
"return",
"self... | Get an active a session by name application path and session ID.
Args:
app_path (str) :
The configured application path for the application to return
a session for.
session_id (str) :
The session ID of the session to retrieve.
Returns:
ServerSession | [
"Get",
"an",
"active",
"a",
"session",
"by",
"name",
"application",
"path",
"and",
"session",
"ID",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/tornado.py#L476-L493 |
30,330 | bokeh/bokeh | bokeh/server/tornado.py | BokehTornado.get_sessions | def get_sessions(self, app_path):
''' Gets all currently active sessions for an application.
Args:
app_path (str) :
The configured application path for the application to return
sessions for.
Returns:
list[ServerSession]
'''
if app_path not in self._applications:
raise ValueError("Application %s does not exist on this server" % app_path)
return list(self._applications[app_path].sessions) | python | def get_sessions(self, app_path):
''' Gets all currently active sessions for an application.
Args:
app_path (str) :
The configured application path for the application to return
sessions for.
Returns:
list[ServerSession]
'''
if app_path not in self._applications:
raise ValueError("Application %s does not exist on this server" % app_path)
return list(self._applications[app_path].sessions) | [
"def",
"get_sessions",
"(",
"self",
",",
"app_path",
")",
":",
"if",
"app_path",
"not",
"in",
"self",
".",
"_applications",
":",
"raise",
"ValueError",
"(",
"\"Application %s does not exist on this server\"",
"%",
"app_path",
")",
"return",
"list",
"(",
"self",
... | Gets all currently active sessions for an application.
Args:
app_path (str) :
The configured application path for the application to return
sessions for.
Returns:
list[ServerSession] | [
"Gets",
"all",
"currently",
"active",
"sessions",
"for",
"an",
"application",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/tornado.py#L495-L509 |
30,331 | bokeh/bokeh | bokeh/core/validation/decorators.py | _validator | def _validator(code_or_name, validator_type):
''' Internal shared implementation to handle both error and warning
validation checks.
Args:
code code_or_name (int or str) : a defined error code or custom message
validator_type (str) : either "error" or "warning"
Returns:
validation decorator
'''
if validator_type == "error":
from .errors import codes
from .errors import EXT
elif validator_type == "warning":
from .warnings import codes
from .warnings import EXT
else:
pass # TODO (bev) ValueError?
def decorator(func):
def wrapper(*args, **kw):
extra = func(*args, **kw)
if extra is None: return []
if isinstance(code_or_name, string_types):
code = EXT
name = codes[code][0] + ":" + code_or_name
else:
code = code_or_name
name = codes[code][0]
text = codes[code][1]
return [(code, name, text, extra)]
wrapper.validator_type = validator_type
return wrapper
return decorator | python | def _validator(code_or_name, validator_type):
''' Internal shared implementation to handle both error and warning
validation checks.
Args:
code code_or_name (int or str) : a defined error code or custom message
validator_type (str) : either "error" or "warning"
Returns:
validation decorator
'''
if validator_type == "error":
from .errors import codes
from .errors import EXT
elif validator_type == "warning":
from .warnings import codes
from .warnings import EXT
else:
pass # TODO (bev) ValueError?
def decorator(func):
def wrapper(*args, **kw):
extra = func(*args, **kw)
if extra is None: return []
if isinstance(code_or_name, string_types):
code = EXT
name = codes[code][0] + ":" + code_or_name
else:
code = code_or_name
name = codes[code][0]
text = codes[code][1]
return [(code, name, text, extra)]
wrapper.validator_type = validator_type
return wrapper
return decorator | [
"def",
"_validator",
"(",
"code_or_name",
",",
"validator_type",
")",
":",
"if",
"validator_type",
"==",
"\"error\"",
":",
"from",
".",
"errors",
"import",
"codes",
"from",
".",
"errors",
"import",
"EXT",
"elif",
"validator_type",
"==",
"\"warning\"",
":",
"fr... | Internal shared implementation to handle both error and warning
validation checks.
Args:
code code_or_name (int or str) : a defined error code or custom message
validator_type (str) : either "error" or "warning"
Returns:
validation decorator | [
"Internal",
"shared",
"implementation",
"to",
"handle",
"both",
"error",
"and",
"warning",
"validation",
"checks",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/validation/decorators.py#L44-L80 |
30,332 | bokeh/bokeh | bokeh/core/query.py | find | def find(objs, selector, context=None):
''' Query a collection of Bokeh models and yield any that match the
a selector.
Args:
obj (Model) : object to test
selector (JSON-like) : query selector
context (dict) : kwargs to supply callable query attributes
Yields:
Model : objects that match the query
Queries are specified as selectors similar to MongoDB style query
selectors, as described for :func:`~bokeh.core.query.match`.
Examples:
.. code-block:: python
# find all objects with type Grid
find(p.references(), {'type': Grid})
# find all objects with type Grid or Axis
find(p.references(), {OR: [
{'type': Grid}, {'type': Axis}
]})
# same query, using IN operator
find(p.references(), {'type': {IN: [Grid, Axis]}})
# find all plot objects on the 'left' layout of the Plot
# here layout is a method that takes a plot as context
find(p.references(), {'layout': 'left'}, {'plot': p})
'''
return (obj for obj in objs if match(obj, selector, context)) | python | def find(objs, selector, context=None):
''' Query a collection of Bokeh models and yield any that match the
a selector.
Args:
obj (Model) : object to test
selector (JSON-like) : query selector
context (dict) : kwargs to supply callable query attributes
Yields:
Model : objects that match the query
Queries are specified as selectors similar to MongoDB style query
selectors, as described for :func:`~bokeh.core.query.match`.
Examples:
.. code-block:: python
# find all objects with type Grid
find(p.references(), {'type': Grid})
# find all objects with type Grid or Axis
find(p.references(), {OR: [
{'type': Grid}, {'type': Axis}
]})
# same query, using IN operator
find(p.references(), {'type': {IN: [Grid, Axis]}})
# find all plot objects on the 'left' layout of the Plot
# here layout is a method that takes a plot as context
find(p.references(), {'layout': 'left'}, {'plot': p})
'''
return (obj for obj in objs if match(obj, selector, context)) | [
"def",
"find",
"(",
"objs",
",",
"selector",
",",
"context",
"=",
"None",
")",
":",
"return",
"(",
"obj",
"for",
"obj",
"in",
"objs",
"if",
"match",
"(",
"obj",
",",
"selector",
",",
"context",
")",
")"
] | Query a collection of Bokeh models and yield any that match the
a selector.
Args:
obj (Model) : object to test
selector (JSON-like) : query selector
context (dict) : kwargs to supply callable query attributes
Yields:
Model : objects that match the query
Queries are specified as selectors similar to MongoDB style query
selectors, as described for :func:`~bokeh.core.query.match`.
Examples:
.. code-block:: python
# find all objects with type Grid
find(p.references(), {'type': Grid})
# find all objects with type Grid or Axis
find(p.references(), {OR: [
{'type': Grid}, {'type': Axis}
]})
# same query, using IN operator
find(p.references(), {'type': {IN: [Grid, Axis]}})
# find all plot objects on the 'left' layout of the Plot
# here layout is a method that takes a plot as context
find(p.references(), {'layout': 'left'}, {'plot': p}) | [
"Query",
"a",
"collection",
"of",
"Bokeh",
"models",
"and",
"yield",
"any",
"that",
"match",
"the",
"a",
"selector",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/query.py#L52-L87 |
30,333 | bokeh/bokeh | bokeh/core/query.py | match | def match(obj, selector, context=None):
''' Test whether a given Bokeh model matches a given selector.
Args:
obj (Model) : object to test
selector (JSON-like) : query selector
context (dict) : kwargs to supply callable query attributes
Returns:
bool : True if the object matches, False otherwise
In general, the selectors have the form:
.. code-block:: python
{ attrname : predicate }
Where a predicate is constructed from the operators ``EQ``, ``GT``, etc.
and is used to compare against values of model attributes named
``attrname``.
For example:
.. code-block:: python
>>> from bokeh.plotting import figure
>>> p = figure(plot_width=400)
>>> match(p, {'plot_width': {EQ: 400}})
True
>>> match(p, {'plot_width': {GT: 500}})
False
There are two selector keys that are handled especially. The first
is 'type', which will do an isinstance check:
.. code-block:: python
>>> from bokeh.plotting import figure
>>> from bokeh.models import Axis
>>> p = figure()
>>> match(p.xaxis[0], {'type': Axis})
True
>>> match(p.title, {'type': Axis})
False
There is also a ``'tags'`` attribute that ``Model`` objects have, that
is a list of user-supplied values. The ``'tags'`` selector key can be
used to query against this list of tags. An object matches if any of the
tags in the selector match any of the tags on the object:
.. code-block:: python
>>> from bokeh.plotting import figure
>>> p = figure(tags = ["my plot", 10])
>>> match(p, {'tags': "my plot"})
True
>>> match(p, {'tags': ["my plot", 10]})
True
>>> match(p, {'tags': ["foo"]})
False
'''
context = context or {}
for key, val in selector.items():
# test attributes
if isinstance(key, string_types):
# special case 'type'
if key == "type":
# type supports IN, check for that first
if isinstance(val, dict) and list(val.keys()) == [IN]:
if not any(isinstance(obj, x) for x in val[IN]): return False
# otherwise just check the type of the object against val
elif not isinstance(obj, val): return False
# special case 'tag'
elif key == 'tags':
if isinstance(val, string_types):
if val not in obj.tags: return False
else:
try:
if not set(val) & set(obj.tags): return False
except TypeError:
if val not in obj.tags: return False
# if the object doesn't have the attr, it doesn't match
elif not hasattr(obj, key): return False
# if the value to check is a dict, recurse
else:
attr = getattr(obj, key)
if callable(attr):
try:
if not attr(val, **context): return False
except:
return False
elif isinstance(val, dict):
if not match(attr, val, context): return False
else:
if attr != val: return False
# test OR conditionals
elif key is OR:
if not _or(obj, val): return False
# test operands
elif key in _operators:
if not _operators[key](obj, val): return False
else:
raise ValueError("malformed query selector")
return True | python | def match(obj, selector, context=None):
''' Test whether a given Bokeh model matches a given selector.
Args:
obj (Model) : object to test
selector (JSON-like) : query selector
context (dict) : kwargs to supply callable query attributes
Returns:
bool : True if the object matches, False otherwise
In general, the selectors have the form:
.. code-block:: python
{ attrname : predicate }
Where a predicate is constructed from the operators ``EQ``, ``GT``, etc.
and is used to compare against values of model attributes named
``attrname``.
For example:
.. code-block:: python
>>> from bokeh.plotting import figure
>>> p = figure(plot_width=400)
>>> match(p, {'plot_width': {EQ: 400}})
True
>>> match(p, {'plot_width': {GT: 500}})
False
There are two selector keys that are handled especially. The first
is 'type', which will do an isinstance check:
.. code-block:: python
>>> from bokeh.plotting import figure
>>> from bokeh.models import Axis
>>> p = figure()
>>> match(p.xaxis[0], {'type': Axis})
True
>>> match(p.title, {'type': Axis})
False
There is also a ``'tags'`` attribute that ``Model`` objects have, that
is a list of user-supplied values. The ``'tags'`` selector key can be
used to query against this list of tags. An object matches if any of the
tags in the selector match any of the tags on the object:
.. code-block:: python
>>> from bokeh.plotting import figure
>>> p = figure(tags = ["my plot", 10])
>>> match(p, {'tags': "my plot"})
True
>>> match(p, {'tags': ["my plot", 10]})
True
>>> match(p, {'tags': ["foo"]})
False
'''
context = context or {}
for key, val in selector.items():
# test attributes
if isinstance(key, string_types):
# special case 'type'
if key == "type":
# type supports IN, check for that first
if isinstance(val, dict) and list(val.keys()) == [IN]:
if not any(isinstance(obj, x) for x in val[IN]): return False
# otherwise just check the type of the object against val
elif not isinstance(obj, val): return False
# special case 'tag'
elif key == 'tags':
if isinstance(val, string_types):
if val not in obj.tags: return False
else:
try:
if not set(val) & set(obj.tags): return False
except TypeError:
if val not in obj.tags: return False
# if the object doesn't have the attr, it doesn't match
elif not hasattr(obj, key): return False
# if the value to check is a dict, recurse
else:
attr = getattr(obj, key)
if callable(attr):
try:
if not attr(val, **context): return False
except:
return False
elif isinstance(val, dict):
if not match(attr, val, context): return False
else:
if attr != val: return False
# test OR conditionals
elif key is OR:
if not _or(obj, val): return False
# test operands
elif key in _operators:
if not _operators[key](obj, val): return False
else:
raise ValueError("malformed query selector")
return True | [
"def",
"match",
"(",
"obj",
",",
"selector",
",",
"context",
"=",
"None",
")",
":",
"context",
"=",
"context",
"or",
"{",
"}",
"for",
"key",
",",
"val",
"in",
"selector",
".",
"items",
"(",
")",
":",
"# test attributes",
"if",
"isinstance",
"(",
"key... | Test whether a given Bokeh model matches a given selector.
Args:
obj (Model) : object to test
selector (JSON-like) : query selector
context (dict) : kwargs to supply callable query attributes
Returns:
bool : True if the object matches, False otherwise
In general, the selectors have the form:
.. code-block:: python
{ attrname : predicate }
Where a predicate is constructed from the operators ``EQ``, ``GT``, etc.
and is used to compare against values of model attributes named
``attrname``.
For example:
.. code-block:: python
>>> from bokeh.plotting import figure
>>> p = figure(plot_width=400)
>>> match(p, {'plot_width': {EQ: 400}})
True
>>> match(p, {'plot_width': {GT: 500}})
False
There are two selector keys that are handled especially. The first
is 'type', which will do an isinstance check:
.. code-block:: python
>>> from bokeh.plotting import figure
>>> from bokeh.models import Axis
>>> p = figure()
>>> match(p.xaxis[0], {'type': Axis})
True
>>> match(p.title, {'type': Axis})
False
There is also a ``'tags'`` attribute that ``Model`` objects have, that
is a list of user-supplied values. The ``'tags'`` selector key can be
used to query against this list of tags. An object matches if any of the
tags in the selector match any of the tags on the object:
.. code-block:: python
>>> from bokeh.plotting import figure
>>> p = figure(tags = ["my plot", 10])
>>> match(p, {'tags': "my plot"})
True
>>> match(p, {'tags': ["my plot", 10]})
True
>>> match(p, {'tags': ["foo"]})
False | [
"Test",
"whether",
"a",
"given",
"Bokeh",
"model",
"matches",
"a",
"given",
"selector",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/query.py#L89-L211 |
30,334 | bokeh/bokeh | bokeh/io/util.py | default_filename | def default_filename(ext):
''' Generate a default filename with a given extension, attempting to use
the filename of the currently running process, if possible.
If the filename of the current process is not available (or would not be
writable), then a temporary file with the given extension is returned.
Args:
ext (str) : the desired extension for the filename
Returns:
str
Raises:
RuntimeError
If the extensions requested is ".py"
'''
if ext == "py":
raise RuntimeError("asked for a default filename with 'py' extension")
filename = detect_current_filename()
if filename is None:
return temp_filename(ext)
basedir = dirname(filename) or getcwd()
if _no_access(basedir) or _shares_exec_prefix(basedir):
return temp_filename(ext)
name, _ = splitext(basename(filename))
return join(basedir, name + "." + ext) | python | def default_filename(ext):
''' Generate a default filename with a given extension, attempting to use
the filename of the currently running process, if possible.
If the filename of the current process is not available (or would not be
writable), then a temporary file with the given extension is returned.
Args:
ext (str) : the desired extension for the filename
Returns:
str
Raises:
RuntimeError
If the extensions requested is ".py"
'''
if ext == "py":
raise RuntimeError("asked for a default filename with 'py' extension")
filename = detect_current_filename()
if filename is None:
return temp_filename(ext)
basedir = dirname(filename) or getcwd()
if _no_access(basedir) or _shares_exec_prefix(basedir):
return temp_filename(ext)
name, _ = splitext(basename(filename))
return join(basedir, name + "." + ext) | [
"def",
"default_filename",
"(",
"ext",
")",
":",
"if",
"ext",
"==",
"\"py\"",
":",
"raise",
"RuntimeError",
"(",
"\"asked for a default filename with 'py' extension\"",
")",
"filename",
"=",
"detect_current_filename",
"(",
")",
"if",
"filename",
"is",
"None",
":",
... | Generate a default filename with a given extension, attempting to use
the filename of the currently running process, if possible.
If the filename of the current process is not available (or would not be
writable), then a temporary file with the given extension is returned.
Args:
ext (str) : the desired extension for the filename
Returns:
str
Raises:
RuntimeError
If the extensions requested is ".py" | [
"Generate",
"a",
"default",
"filename",
"with",
"a",
"given",
"extension",
"attempting",
"to",
"use",
"the",
"filename",
"of",
"the",
"currently",
"running",
"process",
"if",
"possible",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/util.py#L50-L82 |
30,335 | bokeh/bokeh | bokeh/io/util.py | detect_current_filename | def detect_current_filename():
''' Attempt to return the filename of the currently running Python process
Returns None if the filename cannot be detected.
'''
import inspect
filename = None
frame = inspect.currentframe()
try:
while frame.f_back and frame.f_globals.get('name') != '__main__':
frame = frame.f_back
filename = frame.f_globals.get('__file__')
finally:
del frame
return filename | python | def detect_current_filename():
''' Attempt to return the filename of the currently running Python process
Returns None if the filename cannot be detected.
'''
import inspect
filename = None
frame = inspect.currentframe()
try:
while frame.f_back and frame.f_globals.get('name') != '__main__':
frame = frame.f_back
filename = frame.f_globals.get('__file__')
finally:
del frame
return filename | [
"def",
"detect_current_filename",
"(",
")",
":",
"import",
"inspect",
"filename",
"=",
"None",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"try",
":",
"while",
"frame",
".",
"f_back",
"and",
"frame",
".",
"f_globals",
".",
"get",
"(",
"'name'",... | Attempt to return the filename of the currently running Python process
Returns None if the filename cannot be detected. | [
"Attempt",
"to",
"return",
"the",
"filename",
"of",
"the",
"currently",
"running",
"Python",
"process"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/util.py#L84-L101 |
30,336 | bokeh/bokeh | bokeh/io/util.py | _no_access | def _no_access(basedir):
''' Return True if the given base dir is not accessible or writeable
'''
import os
return not os.access(basedir, os.W_OK | os.X_OK) | python | def _no_access(basedir):
''' Return True if the given base dir is not accessible or writeable
'''
import os
return not os.access(basedir, os.W_OK | os.X_OK) | [
"def",
"_no_access",
"(",
"basedir",
")",
":",
"import",
"os",
"return",
"not",
"os",
".",
"access",
"(",
"basedir",
",",
"os",
".",
"W_OK",
"|",
"os",
".",
"X_OK",
")"
] | Return True if the given base dir is not accessible or writeable | [
"Return",
"True",
"if",
"the",
"given",
"base",
"dir",
"is",
"not",
"accessible",
"or",
"writeable"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/util.py#L113-L118 |
30,337 | bokeh/bokeh | bokeh/io/util.py | _shares_exec_prefix | def _shares_exec_prefix(basedir):
''' Whether a give base directory is on the system exex prefix
'''
import sys
prefix = sys.exec_prefix
return (prefix is not None and basedir.startswith(prefix)) | python | def _shares_exec_prefix(basedir):
''' Whether a give base directory is on the system exex prefix
'''
import sys
prefix = sys.exec_prefix
return (prefix is not None and basedir.startswith(prefix)) | [
"def",
"_shares_exec_prefix",
"(",
"basedir",
")",
":",
"import",
"sys",
"prefix",
"=",
"sys",
".",
"exec_prefix",
"return",
"(",
"prefix",
"is",
"not",
"None",
"and",
"basedir",
".",
"startswith",
"(",
"prefix",
")",
")"
] | Whether a give base directory is on the system exex prefix | [
"Whether",
"a",
"give",
"base",
"directory",
"is",
"on",
"the",
"system",
"exex",
"prefix"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/util.py#L120-L126 |
30,338 | bokeh/bokeh | bokeh/plotting/helpers.py | _pop_colors_and_alpha | def _pop_colors_and_alpha(glyphclass, kwargs, prefix="", default_alpha=1.0):
"""
Given a kwargs dict, a prefix, and a default value, looks for different
color and alpha fields of the given prefix, and fills in the default value
if it doesn't exist.
"""
result = dict()
# TODO: The need to do this and the complexity of managing this kind of
# thing throughout the codebase really suggests that we need to have
# a real stylesheet class, where defaults and Types can declaratively
# substitute for this kind of imperative logic.
color = kwargs.pop(prefix + "color", get_default_color())
for argname in ("fill_color", "line_color"):
if argname not in glyphclass.properties():
continue
result[argname] = kwargs.pop(prefix + argname, color)
# NOTE: text fill color should really always default to black, hard coding
# this here now until the stylesheet solution exists
if "text_color" in glyphclass.properties():
result["text_color"] = kwargs.pop(prefix + "text_color", "black")
alpha = kwargs.pop(prefix + "alpha", default_alpha)
for argname in ("fill_alpha", "line_alpha", "text_alpha"):
if argname not in glyphclass.properties():
continue
result[argname] = kwargs.pop(prefix + argname, alpha)
return result | python | def _pop_colors_and_alpha(glyphclass, kwargs, prefix="", default_alpha=1.0):
"""
Given a kwargs dict, a prefix, and a default value, looks for different
color and alpha fields of the given prefix, and fills in the default value
if it doesn't exist.
"""
result = dict()
# TODO: The need to do this and the complexity of managing this kind of
# thing throughout the codebase really suggests that we need to have
# a real stylesheet class, where defaults and Types can declaratively
# substitute for this kind of imperative logic.
color = kwargs.pop(prefix + "color", get_default_color())
for argname in ("fill_color", "line_color"):
if argname not in glyphclass.properties():
continue
result[argname] = kwargs.pop(prefix + argname, color)
# NOTE: text fill color should really always default to black, hard coding
# this here now until the stylesheet solution exists
if "text_color" in glyphclass.properties():
result["text_color"] = kwargs.pop(prefix + "text_color", "black")
alpha = kwargs.pop(prefix + "alpha", default_alpha)
for argname in ("fill_alpha", "line_alpha", "text_alpha"):
if argname not in glyphclass.properties():
continue
result[argname] = kwargs.pop(prefix + argname, alpha)
return result | [
"def",
"_pop_colors_and_alpha",
"(",
"glyphclass",
",",
"kwargs",
",",
"prefix",
"=",
"\"\"",
",",
"default_alpha",
"=",
"1.0",
")",
":",
"result",
"=",
"dict",
"(",
")",
"# TODO: The need to do this and the complexity of managing this kind of",
"# thing throughout the co... | Given a kwargs dict, a prefix, and a default value, looks for different
color and alpha fields of the given prefix, and fills in the default value
if it doesn't exist. | [
"Given",
"a",
"kwargs",
"dict",
"a",
"prefix",
"and",
"a",
"default",
"value",
"looks",
"for",
"different",
"color",
"and",
"alpha",
"fields",
"of",
"the",
"given",
"prefix",
"and",
"fills",
"in",
"the",
"default",
"value",
"if",
"it",
"doesn",
"t",
"exi... | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/plotting/helpers.py#L286-L315 |
30,339 | bokeh/bokeh | bokeh/plotting/helpers.py | _tool_from_string | def _tool_from_string(name):
""" Takes a string and returns a corresponding `Tool` instance. """
known_tools = sorted(_known_tools.keys())
if name in known_tools:
tool_fn = _known_tools[name]
if isinstance(tool_fn, string_types):
tool_fn = _known_tools[tool_fn]
return tool_fn()
else:
matches, text = difflib.get_close_matches(name.lower(), known_tools), "similar"
if not matches:
matches, text = known_tools, "possible"
raise ValueError("unexpected tool name '%s', %s tools are %s" % (name, text, nice_join(matches))) | python | def _tool_from_string(name):
""" Takes a string and returns a corresponding `Tool` instance. """
known_tools = sorted(_known_tools.keys())
if name in known_tools:
tool_fn = _known_tools[name]
if isinstance(tool_fn, string_types):
tool_fn = _known_tools[tool_fn]
return tool_fn()
else:
matches, text = difflib.get_close_matches(name.lower(), known_tools), "similar"
if not matches:
matches, text = known_tools, "possible"
raise ValueError("unexpected tool name '%s', %s tools are %s" % (name, text, nice_join(matches))) | [
"def",
"_tool_from_string",
"(",
"name",
")",
":",
"known_tools",
"=",
"sorted",
"(",
"_known_tools",
".",
"keys",
"(",
")",
")",
"if",
"name",
"in",
"known_tools",
":",
"tool_fn",
"=",
"_known_tools",
"[",
"name",
"]",
"if",
"isinstance",
"(",
"tool_fn",
... | Takes a string and returns a corresponding `Tool` instance. | [
"Takes",
"a",
"string",
"and",
"returns",
"a",
"corresponding",
"Tool",
"instance",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/plotting/helpers.py#L544-L561 |
30,340 | bokeh/bokeh | bokeh/models/callbacks.py | CustomJS.from_py_func | def from_py_func(cls, func):
""" Create a ``CustomJS`` instance from a Python function. The
function is translated to JavaScript using PScript.
"""
from bokeh.util.deprecation import deprecated
deprecated("'from_py_func' is deprecated and will be removed in an eventual 2.0 release. "
"Use CustomJS directly instead.")
if not isinstance(func, FunctionType):
raise ValueError('CustomJS.from_py_func needs function object.')
pscript = import_required('pscript',
'To use Python functions for CustomJS, you need PScript ' +
'("conda install -c conda-forge pscript" or "pip install pscript")')
# Collect default values
default_values = func.__defaults__ # Python 2.6+
default_names = func.__code__.co_varnames[:len(default_values)]
args = dict(zip(default_names, default_values))
args.pop('window', None) # Clear window, so we use the global window object
# Get JS code, we could rip out the function def, or just
# call the function. We do the latter.
code = pscript.py2js(func, 'cb') + 'cb(%s);\n' % ', '.join(default_names)
return cls(code=code, args=args) | python | def from_py_func(cls, func):
""" Create a ``CustomJS`` instance from a Python function. The
function is translated to JavaScript using PScript.
"""
from bokeh.util.deprecation import deprecated
deprecated("'from_py_func' is deprecated and will be removed in an eventual 2.0 release. "
"Use CustomJS directly instead.")
if not isinstance(func, FunctionType):
raise ValueError('CustomJS.from_py_func needs function object.')
pscript = import_required('pscript',
'To use Python functions for CustomJS, you need PScript ' +
'("conda install -c conda-forge pscript" or "pip install pscript")')
# Collect default values
default_values = func.__defaults__ # Python 2.6+
default_names = func.__code__.co_varnames[:len(default_values)]
args = dict(zip(default_names, default_values))
args.pop('window', None) # Clear window, so we use the global window object
# Get JS code, we could rip out the function def, or just
# call the function. We do the latter.
code = pscript.py2js(func, 'cb') + 'cb(%s);\n' % ', '.join(default_names)
return cls(code=code, args=args) | [
"def",
"from_py_func",
"(",
"cls",
",",
"func",
")",
":",
"from",
"bokeh",
".",
"util",
".",
"deprecation",
"import",
"deprecated",
"deprecated",
"(",
"\"'from_py_func' is deprecated and will be removed in an eventual 2.0 release. \"",
"\"Use CustomJS directly instead.\"",
")... | Create a ``CustomJS`` instance from a Python function. The
function is translated to JavaScript using PScript. | [
"Create",
"a",
"CustomJS",
"instance",
"from",
"a",
"Python",
"function",
".",
"The",
"function",
"is",
"translated",
"to",
"JavaScript",
"using",
"PScript",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/callbacks.py#L85-L106 |
30,341 | bokeh/bokeh | bokeh/client/websocket.py | WebSocketClientConnectionWrapper.write_message | def write_message(self, message, binary=False, locked=True):
''' Write a message to the websocket after obtaining the appropriate
Bokeh Document lock.
'''
def write_message_unlocked():
if self._socket.protocol is None:
# Tornado is maybe supposed to do this, but in fact it
# tries to do _socket.protocol.write_message when protocol
# is None and throws AttributeError or something. So avoid
# trying to write to the closed socket. There doesn't seem
# to be an obvious public function to check if the socket
# is closed.
raise WebSocketError("Connection to the server has been closed")
future = self._socket.write_message(message, binary)
# don't yield this future or we're blocking on ourselves!
raise gen.Return(future)
if locked:
with (yield self.write_lock.acquire()):
write_message_unlocked()
else:
write_message_unlocked() | python | def write_message(self, message, binary=False, locked=True):
''' Write a message to the websocket after obtaining the appropriate
Bokeh Document lock.
'''
def write_message_unlocked():
if self._socket.protocol is None:
# Tornado is maybe supposed to do this, but in fact it
# tries to do _socket.protocol.write_message when protocol
# is None and throws AttributeError or something. So avoid
# trying to write to the closed socket. There doesn't seem
# to be an obvious public function to check if the socket
# is closed.
raise WebSocketError("Connection to the server has been closed")
future = self._socket.write_message(message, binary)
# don't yield this future or we're blocking on ourselves!
raise gen.Return(future)
if locked:
with (yield self.write_lock.acquire()):
write_message_unlocked()
else:
write_message_unlocked() | [
"def",
"write_message",
"(",
"self",
",",
"message",
",",
"binary",
"=",
"False",
",",
"locked",
"=",
"True",
")",
":",
"def",
"write_message_unlocked",
"(",
")",
":",
"if",
"self",
".",
"_socket",
".",
"protocol",
"is",
"None",
":",
"# Tornado is maybe su... | Write a message to the websocket after obtaining the appropriate
Bokeh Document lock. | [
"Write",
"a",
"message",
"to",
"the",
"websocket",
"after",
"obtaining",
"the",
"appropriate",
"Bokeh",
"Document",
"lock",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/client/websocket.py#L62-L86 |
30,342 | bokeh/bokeh | bokeh/resources.py | BaseResources._collect_external_resources | def _collect_external_resources(self, resource_attr):
""" Collect external resources set on resource_attr attribute of all models."""
external_resources = []
for _, cls in sorted(Model.model_class_reverse_map.items(), key=lambda arg: arg[0]):
external = getattr(cls, resource_attr, None)
if isinstance(external, string_types):
if external not in external_resources:
external_resources.append(external)
elif isinstance(external, list):
for e in external:
if e not in external_resources:
external_resources.append(e)
return external_resources | python | def _collect_external_resources(self, resource_attr):
""" Collect external resources set on resource_attr attribute of all models."""
external_resources = []
for _, cls in sorted(Model.model_class_reverse_map.items(), key=lambda arg: arg[0]):
external = getattr(cls, resource_attr, None)
if isinstance(external, string_types):
if external not in external_resources:
external_resources.append(external)
elif isinstance(external, list):
for e in external:
if e not in external_resources:
external_resources.append(e)
return external_resources | [
"def",
"_collect_external_resources",
"(",
"self",
",",
"resource_attr",
")",
":",
"external_resources",
"=",
"[",
"]",
"for",
"_",
",",
"cls",
"in",
"sorted",
"(",
"Model",
".",
"model_class_reverse_map",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
... | Collect external resources set on resource_attr attribute of all models. | [
"Collect",
"external",
"resources",
"set",
"on",
"resource_attr",
"attribute",
"of",
"all",
"models",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/resources.py#L155-L171 |
30,343 | bokeh/bokeh | bokeh/settings.py | _Settings.py_log_level | def py_log_level(self, default='none'):
''' Set the log level for python Bokeh code.
'''
level = self._get_str("PY_LOG_LEVEL", default, "debug")
LEVELS = {'trace': logging.TRACE,
'debug': logging.DEBUG,
'info' : logging.INFO,
'warn' : logging.WARNING,
'error': logging.ERROR,
'fatal': logging.CRITICAL,
'none' : None}
return LEVELS[level] | python | def py_log_level(self, default='none'):
''' Set the log level for python Bokeh code.
'''
level = self._get_str("PY_LOG_LEVEL", default, "debug")
LEVELS = {'trace': logging.TRACE,
'debug': logging.DEBUG,
'info' : logging.INFO,
'warn' : logging.WARNING,
'error': logging.ERROR,
'fatal': logging.CRITICAL,
'none' : None}
return LEVELS[level] | [
"def",
"py_log_level",
"(",
"self",
",",
"default",
"=",
"'none'",
")",
":",
"level",
"=",
"self",
".",
"_get_str",
"(",
"\"PY_LOG_LEVEL\"",
",",
"default",
",",
"\"debug\"",
")",
"LEVELS",
"=",
"{",
"'trace'",
":",
"logging",
".",
"TRACE",
",",
"'debug'... | Set the log level for python Bokeh code. | [
"Set",
"the",
"log",
"level",
"for",
"python",
"Bokeh",
"code",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/settings.py#L275-L287 |
30,344 | bokeh/bokeh | bokeh/settings.py | _Settings.secret_key_bytes | def secret_key_bytes(self):
''' Return the secret_key, converted to bytes and cached.
'''
if not hasattr(self, '_secret_key_bytes'):
key = self.secret_key()
if key is None:
self._secret_key_bytes = None
else:
self._secret_key_bytes = codecs.encode(key, "utf-8")
return self._secret_key_bytes | python | def secret_key_bytes(self):
''' Return the secret_key, converted to bytes and cached.
'''
if not hasattr(self, '_secret_key_bytes'):
key = self.secret_key()
if key is None:
self._secret_key_bytes = None
else:
self._secret_key_bytes = codecs.encode(key, "utf-8")
return self._secret_key_bytes | [
"def",
"secret_key_bytes",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_secret_key_bytes'",
")",
":",
"key",
"=",
"self",
".",
"secret_key",
"(",
")",
"if",
"key",
"is",
"None",
":",
"self",
".",
"_secret_key_bytes",
"=",
"None",
... | Return the secret_key, converted to bytes and cached. | [
"Return",
"the",
"secret_key",
"converted",
"to",
"bytes",
"and",
"cached",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/settings.py#L315-L325 |
30,345 | bokeh/bokeh | bokeh/settings.py | _Settings.bokehjssrcdir | def bokehjssrcdir(self):
''' The absolute path of the BokehJS source code in the installed
Bokeh source tree.
'''
if self._is_dev or self.debugjs:
bokehjssrcdir = abspath(join(ROOT_DIR, '..', 'bokehjs', 'src'))
if isdir(bokehjssrcdir):
return bokehjssrcdir
return None | python | def bokehjssrcdir(self):
''' The absolute path of the BokehJS source code in the installed
Bokeh source tree.
'''
if self._is_dev or self.debugjs:
bokehjssrcdir = abspath(join(ROOT_DIR, '..', 'bokehjs', 'src'))
if isdir(bokehjssrcdir):
return bokehjssrcdir
return None | [
"def",
"bokehjssrcdir",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_dev",
"or",
"self",
".",
"debugjs",
":",
"bokehjssrcdir",
"=",
"abspath",
"(",
"join",
"(",
"ROOT_DIR",
",",
"'..'",
",",
"'bokehjs'",
",",
"'src'",
")",
")",
"if",
"isdir",
"(",
... | The absolute path of the BokehJS source code in the installed
Bokeh source tree. | [
"The",
"absolute",
"path",
"of",
"the",
"BokehJS",
"source",
"code",
"in",
"the",
"installed",
"Bokeh",
"source",
"tree",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/settings.py#L344-L355 |
30,346 | bokeh/bokeh | bokeh/settings.py | _Settings.css_files | def css_files(self):
''' The CSS files in the BokehJS directory.
'''
bokehjsdir = self.bokehjsdir()
js_files = []
for root, dirnames, files in os.walk(bokehjsdir):
for fname in files:
if fname.endswith(".css"):
js_files.append(join(root, fname))
return js_files | python | def css_files(self):
''' The CSS files in the BokehJS directory.
'''
bokehjsdir = self.bokehjsdir()
js_files = []
for root, dirnames, files in os.walk(bokehjsdir):
for fname in files:
if fname.endswith(".css"):
js_files.append(join(root, fname))
return js_files | [
"def",
"css_files",
"(",
"self",
")",
":",
"bokehjsdir",
"=",
"self",
".",
"bokehjsdir",
"(",
")",
"js_files",
"=",
"[",
"]",
"for",
"root",
",",
"dirnames",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"bokehjsdir",
")",
":",
"for",
"fname",
"in",
... | The CSS files in the BokehJS directory. | [
"The",
"CSS",
"files",
"in",
"the",
"BokehJS",
"directory",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/settings.py#L375-L385 |
30,347 | bokeh/bokeh | bokeh/core/json_encoder.py | serialize_json | def serialize_json(obj, pretty=None, indent=None, **kwargs):
''' Return a serialized JSON representation of objects, suitable to
send to BokehJS.
This function is typically used to serialize single python objects in
the manner expected by BokehJS. In particular, many datetime values are
automatically normalized to an expected format. Some Bokeh objects can
also be passed, but note that Bokeh models are typically properly
serialized in the context of an entire Bokeh document.
The resulting JSON always has sorted keys. By default. the output is
as compact as possible unless pretty output or indentation is requested.
Args:
obj (obj) : the object to serialize to JSON format
pretty (bool, optional) :
Whether to generate prettified output. If ``True``, spaces are
added after added after separators, and indentation and newlines
are applied. (default: False)
Pretty output can also be enabled with the environment variable
``BOKEH_PRETTY``, which overrides this argument, if set.
indent (int or None, optional) :
Amount of indentation to use in generated JSON output. If ``None``
then no indentation is used, unless pretty output is enabled,
in which case two spaces are used. (default: None)
Any additional keyword arguments are passed to ``json.dumps``, except for
some that are computed internally, and cannot be overridden:
* allow_nan
* indent
* separators
* sort_keys
Examples:
.. code-block:: python
>>> data = dict(b=np.datetime64('2017-01-01'), a = np.arange(3))
>>>print(serialize_json(data))
{"a":[0,1,2],"b":1483228800000.0}
>>> print(serialize_json(data, pretty=True))
{
"a": [
0,
1,
2
],
"b": 1483228800000.0
}
'''
# these args to json.dumps are computed internally and should not be passed along
for name in ['allow_nan', 'separators', 'sort_keys']:
if name in kwargs:
raise ValueError("The value of %r is computed internally, overriding is not permissable." % name)
if pretty is None:
pretty = settings.pretty(False)
if pretty:
separators=(",", ": ")
else:
separators=(",", ":")
if pretty and indent is None:
indent = 2
return json.dumps(obj, cls=BokehJSONEncoder, allow_nan=False, indent=indent, separators=separators, sort_keys=True, **kwargs) | python | def serialize_json(obj, pretty=None, indent=None, **kwargs):
''' Return a serialized JSON representation of objects, suitable to
send to BokehJS.
This function is typically used to serialize single python objects in
the manner expected by BokehJS. In particular, many datetime values are
automatically normalized to an expected format. Some Bokeh objects can
also be passed, but note that Bokeh models are typically properly
serialized in the context of an entire Bokeh document.
The resulting JSON always has sorted keys. By default. the output is
as compact as possible unless pretty output or indentation is requested.
Args:
obj (obj) : the object to serialize to JSON format
pretty (bool, optional) :
Whether to generate prettified output. If ``True``, spaces are
added after added after separators, and indentation and newlines
are applied. (default: False)
Pretty output can also be enabled with the environment variable
``BOKEH_PRETTY``, which overrides this argument, if set.
indent (int or None, optional) :
Amount of indentation to use in generated JSON output. If ``None``
then no indentation is used, unless pretty output is enabled,
in which case two spaces are used. (default: None)
Any additional keyword arguments are passed to ``json.dumps``, except for
some that are computed internally, and cannot be overridden:
* allow_nan
* indent
* separators
* sort_keys
Examples:
.. code-block:: python
>>> data = dict(b=np.datetime64('2017-01-01'), a = np.arange(3))
>>>print(serialize_json(data))
{"a":[0,1,2],"b":1483228800000.0}
>>> print(serialize_json(data, pretty=True))
{
"a": [
0,
1,
2
],
"b": 1483228800000.0
}
'''
# these args to json.dumps are computed internally and should not be passed along
for name in ['allow_nan', 'separators', 'sort_keys']:
if name in kwargs:
raise ValueError("The value of %r is computed internally, overriding is not permissable." % name)
if pretty is None:
pretty = settings.pretty(False)
if pretty:
separators=(",", ": ")
else:
separators=(",", ":")
if pretty and indent is None:
indent = 2
return json.dumps(obj, cls=BokehJSONEncoder, allow_nan=False, indent=indent, separators=separators, sort_keys=True, **kwargs) | [
"def",
"serialize_json",
"(",
"obj",
",",
"pretty",
"=",
"None",
",",
"indent",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# these args to json.dumps are computed internally and should not be passed along",
"for",
"name",
"in",
"[",
"'allow_nan'",
",",
"'separ... | Return a serialized JSON representation of objects, suitable to
send to BokehJS.
This function is typically used to serialize single python objects in
the manner expected by BokehJS. In particular, many datetime values are
automatically normalized to an expected format. Some Bokeh objects can
also be passed, but note that Bokeh models are typically properly
serialized in the context of an entire Bokeh document.
The resulting JSON always has sorted keys. By default. the output is
as compact as possible unless pretty output or indentation is requested.
Args:
obj (obj) : the object to serialize to JSON format
pretty (bool, optional) :
Whether to generate prettified output. If ``True``, spaces are
added after added after separators, and indentation and newlines
are applied. (default: False)
Pretty output can also be enabled with the environment variable
``BOKEH_PRETTY``, which overrides this argument, if set.
indent (int or None, optional) :
Amount of indentation to use in generated JSON output. If ``None``
then no indentation is used, unless pretty output is enabled,
in which case two spaces are used. (default: None)
Any additional keyword arguments are passed to ``json.dumps``, except for
some that are computed internally, and cannot be overridden:
* allow_nan
* indent
* separators
* sort_keys
Examples:
.. code-block:: python
>>> data = dict(b=np.datetime64('2017-01-01'), a = np.arange(3))
>>>print(serialize_json(data))
{"a":[0,1,2],"b":1483228800000.0}
>>> print(serialize_json(data, pretty=True))
{
"a": [
0,
1,
2
],
"b": 1483228800000.0
} | [
"Return",
"a",
"serialized",
"JSON",
"representation",
"of",
"objects",
"suitable",
"to",
"send",
"to",
"BokehJS",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/json_encoder.py#L85-L161 |
30,348 | bokeh/bokeh | bokeh/core/json_encoder.py | BokehJSONEncoder.default | def default(self, obj):
''' The required ``default`` method for ``JSONEncoder`` subclasses.
Args:
obj (obj) :
The object to encode. Anything not specifically handled in
this method is passed on to the default system JSON encoder.
'''
from ..model import Model
from ..colors import Color
from .has_props import HasProps
# array types -- use force_list here, only binary
# encoding CDS columns for now
if pd and isinstance(obj, (pd.Series, pd.Index)):
return transform_series(obj, force_list=True)
elif isinstance(obj, np.ndarray):
return transform_array(obj, force_list=True)
elif isinstance(obj, collections.deque):
return list(map(self.default, obj))
elif isinstance(obj, Model):
return obj.ref
elif isinstance(obj, HasProps):
return obj.properties_with_values(include_defaults=False)
elif isinstance(obj, Color):
return obj.to_css()
else:
return self.transform_python_types(obj) | python | def default(self, obj):
''' The required ``default`` method for ``JSONEncoder`` subclasses.
Args:
obj (obj) :
The object to encode. Anything not specifically handled in
this method is passed on to the default system JSON encoder.
'''
from ..model import Model
from ..colors import Color
from .has_props import HasProps
# array types -- use force_list here, only binary
# encoding CDS columns for now
if pd and isinstance(obj, (pd.Series, pd.Index)):
return transform_series(obj, force_list=True)
elif isinstance(obj, np.ndarray):
return transform_array(obj, force_list=True)
elif isinstance(obj, collections.deque):
return list(map(self.default, obj))
elif isinstance(obj, Model):
return obj.ref
elif isinstance(obj, HasProps):
return obj.properties_with_values(include_defaults=False)
elif isinstance(obj, Color):
return obj.to_css()
else:
return self.transform_python_types(obj) | [
"def",
"default",
"(",
"self",
",",
"obj",
")",
":",
"from",
".",
".",
"model",
"import",
"Model",
"from",
".",
".",
"colors",
"import",
"Color",
"from",
".",
"has_props",
"import",
"HasProps",
"# array types -- use force_list here, only binary",
"# encoding CDS c... | The required ``default`` method for ``JSONEncoder`` subclasses.
Args:
obj (obj) :
The object to encode. Anything not specifically handled in
this method is passed on to the default system JSON encoder. | [
"The",
"required",
"default",
"method",
"for",
"JSONEncoder",
"subclasses",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/json_encoder.py#L221-L252 |
30,349 | bokeh/bokeh | bokeh/application/application.py | Application.add | def add(self, handler):
''' Add a handler to the pipeline used to initialize new documents.
Args:
handler (Handler) : a handler for this Application to use to
process Documents
'''
self._handlers.append(handler)
# make sure there is at most one static path
static_paths = set(h.static_path() for h in self.handlers)
static_paths.discard(None)
if len(static_paths) > 1:
raise RuntimeError("More than one static path requested for app: %r" % list(static_paths))
elif len(static_paths) == 1:
self._static_path = static_paths.pop()
else:
self._static_path = None | python | def add(self, handler):
''' Add a handler to the pipeline used to initialize new documents.
Args:
handler (Handler) : a handler for this Application to use to
process Documents
'''
self._handlers.append(handler)
# make sure there is at most one static path
static_paths = set(h.static_path() for h in self.handlers)
static_paths.discard(None)
if len(static_paths) > 1:
raise RuntimeError("More than one static path requested for app: %r" % list(static_paths))
elif len(static_paths) == 1:
self._static_path = static_paths.pop()
else:
self._static_path = None | [
"def",
"add",
"(",
"self",
",",
"handler",
")",
":",
"self",
".",
"_handlers",
".",
"append",
"(",
"handler",
")",
"# make sure there is at most one static path",
"static_paths",
"=",
"set",
"(",
"h",
".",
"static_path",
"(",
")",
"for",
"h",
"in",
"self",
... | Add a handler to the pipeline used to initialize new documents.
Args:
handler (Handler) : a handler for this Application to use to
process Documents | [
"Add",
"a",
"handler",
"to",
"the",
"pipeline",
"used",
"to",
"initialize",
"new",
"documents",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/application/application.py#L142-L160 |
30,350 | bokeh/bokeh | bokeh/application/application.py | Application.initialize_document | def initialize_document(self, doc):
''' Fills in a new document using the Application's handlers.
'''
for h in self._handlers:
# TODO (havocp) we need to check the 'failed' flag on each handler
# and build a composite error display. In develop mode, we want to
# somehow get these errors to the client.
h.modify_document(doc)
if h.failed:
log.error("Error running application handler %r: %s %s ", h, h.error, h.error_detail)
if settings.perform_document_validation():
doc.validate() | python | def initialize_document(self, doc):
''' Fills in a new document using the Application's handlers.
'''
for h in self._handlers:
# TODO (havocp) we need to check the 'failed' flag on each handler
# and build a composite error display. In develop mode, we want to
# somehow get these errors to the client.
h.modify_document(doc)
if h.failed:
log.error("Error running application handler %r: %s %s ", h, h.error, h.error_detail)
if settings.perform_document_validation():
doc.validate() | [
"def",
"initialize_document",
"(",
"self",
",",
"doc",
")",
":",
"for",
"h",
"in",
"self",
".",
"_handlers",
":",
"# TODO (havocp) we need to check the 'failed' flag on each handler",
"# and build a composite error display. In develop mode, we want to",
"# somehow get these errors ... | Fills in a new document using the Application's handlers. | [
"Fills",
"in",
"a",
"new",
"document",
"using",
"the",
"Application",
"s",
"handlers",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/application/application.py#L170-L183 |
30,351 | bokeh/bokeh | bokeh/application/application.py | Application.on_session_created | def on_session_created(self, session_context):
''' Invoked to execute code when a new session is created.
This method calls ``on_session_created`` on each handler, in order,
with the session context passed as the only argument.
May return a ``Future`` which will delay session creation until the
``Future`` completes.
'''
for h in self._handlers:
result = h.on_session_created(session_context)
yield yield_for_all_futures(result)
raise gen.Return(None) | python | def on_session_created(self, session_context):
''' Invoked to execute code when a new session is created.
This method calls ``on_session_created`` on each handler, in order,
with the session context passed as the only argument.
May return a ``Future`` which will delay session creation until the
``Future`` completes.
'''
for h in self._handlers:
result = h.on_session_created(session_context)
yield yield_for_all_futures(result)
raise gen.Return(None) | [
"def",
"on_session_created",
"(",
"self",
",",
"session_context",
")",
":",
"for",
"h",
"in",
"self",
".",
"_handlers",
":",
"result",
"=",
"h",
".",
"on_session_created",
"(",
"session_context",
")",
"yield",
"yield_for_all_futures",
"(",
"result",
")",
"rais... | Invoked to execute code when a new session is created.
This method calls ``on_session_created`` on each handler, in order,
with the session context passed as the only argument.
May return a ``Future`` which will delay session creation until the
``Future`` completes. | [
"Invoked",
"to",
"execute",
"code",
"when",
"a",
"new",
"session",
"is",
"created",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/application/application.py#L211-L224 |
30,352 | bokeh/bokeh | bokeh/models/plots.py | _select_helper | def _select_helper(args, kwargs):
""" Allow flexible selector syntax.
Returns:
dict
"""
if len(args) > 1:
raise TypeError("select accepts at most ONE positional argument.")
if len(args) > 0 and len(kwargs) > 0:
raise TypeError("select accepts EITHER a positional argument, OR keyword arguments (not both).")
if len(args) == 0 and len(kwargs) == 0:
raise TypeError("select requires EITHER a positional argument, OR keyword arguments.")
if args:
arg = args[0]
if isinstance(arg, dict):
selector = arg
elif isinstance(arg, string_types):
selector = dict(name=arg)
elif isinstance(arg, type) and issubclass(arg, Model):
selector = {"type": arg}
else:
raise TypeError("selector must be a dictionary, string or plot object.")
elif 'selector' in kwargs:
if len(kwargs) == 1:
selector = kwargs['selector']
else:
raise TypeError("when passing 'selector' keyword arg, not other keyword args may be present")
else:
selector = kwargs
return selector | python | def _select_helper(args, kwargs):
""" Allow flexible selector syntax.
Returns:
dict
"""
if len(args) > 1:
raise TypeError("select accepts at most ONE positional argument.")
if len(args) > 0 and len(kwargs) > 0:
raise TypeError("select accepts EITHER a positional argument, OR keyword arguments (not both).")
if len(args) == 0 and len(kwargs) == 0:
raise TypeError("select requires EITHER a positional argument, OR keyword arguments.")
if args:
arg = args[0]
if isinstance(arg, dict):
selector = arg
elif isinstance(arg, string_types):
selector = dict(name=arg)
elif isinstance(arg, type) and issubclass(arg, Model):
selector = {"type": arg}
else:
raise TypeError("selector must be a dictionary, string or plot object.")
elif 'selector' in kwargs:
if len(kwargs) == 1:
selector = kwargs['selector']
else:
raise TypeError("when passing 'selector' keyword arg, not other keyword args may be present")
else:
selector = kwargs
return selector | [
"def",
"_select_helper",
"(",
"args",
",",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
">",
"1",
":",
"raise",
"TypeError",
"(",
"\"select accepts at most ONE positional argument.\"",
")",
"if",
"len",
"(",
"args",
")",
">",
"0",
"and",
"len",
"(",
... | Allow flexible selector syntax.
Returns:
dict | [
"Allow",
"flexible",
"selector",
"syntax",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/plots.py#L759-L795 |
30,353 | bokeh/bokeh | bokeh/models/plots.py | Plot.select | def select(self, *args, **kwargs):
''' Query this object and all of its references for objects that
match the given selector.
There are a few different ways to call the ``select`` method.
The most general is to supply a JSON-like query dictionary as the
single argument or as keyword arguments:
Args:
selector (JSON-like) : some sample text
Keyword Arguments:
kwargs : query dict key/values as keyword arguments
Additionally, for compatibility with ``Model.select``, a selector
dict may be passed as ``selector`` keyword argument, in which case
the value of ``kwargs['selector']`` is used for the query.
For convenience, queries on just names can be made by supplying
the ``name`` string as the single parameter:
Args:
name (str) : the name to query on
Also queries on just type can be made simply by supplying the
``Model`` subclass as the single parameter:
Args:
type (Model) : the type to query on
Returns:
seq[Model]
Examples:
.. code-block:: python
# These three are equivalent
p.select(selector={"type": HoverTool})
p.select({"type": HoverTool})
p.select(HoverTool)
# These two are also equivalent
p.select({"name": "mycircle"})
p.select("mycircle")
# Keyword arguments can be supplied in place of selector dict
p.select({"name": "foo", "type": HoverTool})
p.select(name="foo", type=HoverTool)
'''
selector = _select_helper(args, kwargs)
# Want to pass selector that is a dictionary
return _list_attr_splat(find(self.references(), selector, {'plot': self})) | python | def select(self, *args, **kwargs):
''' Query this object and all of its references for objects that
match the given selector.
There are a few different ways to call the ``select`` method.
The most general is to supply a JSON-like query dictionary as the
single argument or as keyword arguments:
Args:
selector (JSON-like) : some sample text
Keyword Arguments:
kwargs : query dict key/values as keyword arguments
Additionally, for compatibility with ``Model.select``, a selector
dict may be passed as ``selector`` keyword argument, in which case
the value of ``kwargs['selector']`` is used for the query.
For convenience, queries on just names can be made by supplying
the ``name`` string as the single parameter:
Args:
name (str) : the name to query on
Also queries on just type can be made simply by supplying the
``Model`` subclass as the single parameter:
Args:
type (Model) : the type to query on
Returns:
seq[Model]
Examples:
.. code-block:: python
# These three are equivalent
p.select(selector={"type": HoverTool})
p.select({"type": HoverTool})
p.select(HoverTool)
# These two are also equivalent
p.select({"name": "mycircle"})
p.select("mycircle")
# Keyword arguments can be supplied in place of selector dict
p.select({"name": "foo", "type": HoverTool})
p.select(name="foo", type=HoverTool)
'''
selector = _select_helper(args, kwargs)
# Want to pass selector that is a dictionary
return _list_attr_splat(find(self.references(), selector, {'plot': self})) | [
"def",
"select",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"selector",
"=",
"_select_helper",
"(",
"args",
",",
"kwargs",
")",
"# Want to pass selector that is a dictionary",
"return",
"_list_attr_splat",
"(",
"find",
"(",
"self",
".",
... | Query this object and all of its references for objects that
match the given selector.
There are a few different ways to call the ``select`` method.
The most general is to supply a JSON-like query dictionary as the
single argument or as keyword arguments:
Args:
selector (JSON-like) : some sample text
Keyword Arguments:
kwargs : query dict key/values as keyword arguments
Additionally, for compatibility with ``Model.select``, a selector
dict may be passed as ``selector`` keyword argument, in which case
the value of ``kwargs['selector']`` is used for the query.
For convenience, queries on just names can be made by supplying
the ``name`` string as the single parameter:
Args:
name (str) : the name to query on
Also queries on just type can be made simply by supplying the
``Model`` subclass as the single parameter:
Args:
type (Model) : the type to query on
Returns:
seq[Model]
Examples:
.. code-block:: python
# These three are equivalent
p.select(selector={"type": HoverTool})
p.select({"type": HoverTool})
p.select(HoverTool)
# These two are also equivalent
p.select({"name": "mycircle"})
p.select("mycircle")
# Keyword arguments can be supplied in place of selector dict
p.select({"name": "foo", "type": HoverTool})
p.select(name="foo", type=HoverTool) | [
"Query",
"this",
"object",
"and",
"all",
"of",
"its",
"references",
"for",
"objects",
"that",
"match",
"the",
"given",
"selector",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/plots.py#L69-L124 |
30,354 | bokeh/bokeh | bokeh/models/plots.py | Plot.add_layout | def add_layout(self, obj, place='center'):
''' Adds an object to the plot in a specified place.
Args:
obj (Renderer) : the object to add to the Plot
place (str, optional) : where to add the object (default: 'center')
Valid places are: 'left', 'right', 'above', 'below', 'center'.
Returns:
None
'''
valid_places = ['left', 'right', 'above', 'below', 'center']
if place not in valid_places:
raise ValueError(
"Invalid place '%s' specified. Valid place values are: %s" % (place, nice_join(valid_places))
)
getattr(self, place).append(obj) | python | def add_layout(self, obj, place='center'):
''' Adds an object to the plot in a specified place.
Args:
obj (Renderer) : the object to add to the Plot
place (str, optional) : where to add the object (default: 'center')
Valid places are: 'left', 'right', 'above', 'below', 'center'.
Returns:
None
'''
valid_places = ['left', 'right', 'above', 'below', 'center']
if place not in valid_places:
raise ValueError(
"Invalid place '%s' specified. Valid place values are: %s" % (place, nice_join(valid_places))
)
getattr(self, place).append(obj) | [
"def",
"add_layout",
"(",
"self",
",",
"obj",
",",
"place",
"=",
"'center'",
")",
":",
"valid_places",
"=",
"[",
"'left'",
",",
"'right'",
",",
"'above'",
",",
"'below'",
",",
"'center'",
"]",
"if",
"place",
"not",
"in",
"valid_places",
":",
"raise",
"... | Adds an object to the plot in a specified place.
Args:
obj (Renderer) : the object to add to the Plot
place (str, optional) : where to add the object (default: 'center')
Valid places are: 'left', 'right', 'above', 'below', 'center'.
Returns:
None | [
"Adds",
"an",
"object",
"to",
"the",
"plot",
"in",
"a",
"specified",
"place",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/plots.py#L230-L248 |
30,355 | bokeh/bokeh | bokeh/models/plots.py | Plot.add_tools | def add_tools(self, *tools):
''' Adds tools to the plot.
Args:
*tools (Tool) : the tools to add to the Plot
Returns:
None
'''
for tool in tools:
if not isinstance(tool, Tool):
raise ValueError("All arguments to add_tool must be Tool subclasses.")
self.toolbar.tools.append(tool) | python | def add_tools(self, *tools):
''' Adds tools to the plot.
Args:
*tools (Tool) : the tools to add to the Plot
Returns:
None
'''
for tool in tools:
if not isinstance(tool, Tool):
raise ValueError("All arguments to add_tool must be Tool subclasses.")
self.toolbar.tools.append(tool) | [
"def",
"add_tools",
"(",
"self",
",",
"*",
"tools",
")",
":",
"for",
"tool",
"in",
"tools",
":",
"if",
"not",
"isinstance",
"(",
"tool",
",",
"Tool",
")",
":",
"raise",
"ValueError",
"(",
"\"All arguments to add_tool must be Tool subclasses.\"",
")",
"self",
... | Adds tools to the plot.
Args:
*tools (Tool) : the tools to add to the Plot
Returns:
None | [
"Adds",
"tools",
"to",
"the",
"plot",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/plots.py#L250-L264 |
30,356 | bokeh/bokeh | bokeh/models/plots.py | Plot.add_glyph | def add_glyph(self, source_or_glyph, glyph=None, **kw):
''' Adds a glyph to the plot with associated data sources and ranges.
This function will take care of creating and configuring a Glyph object,
and then add it to the plot's list of renderers.
Args:
source (DataSource) : a data source for the glyphs to all use
glyph (Glyph) : the glyph to add to the Plot
Keyword Arguments:
Any additional keyword arguments are passed on as-is to the
Glyph initializer.
Returns:
GlyphRenderer
'''
if glyph is not None:
source = source_or_glyph
else:
source, glyph = ColumnDataSource(), source_or_glyph
if not isinstance(source, DataSource):
raise ValueError("'source' argument to add_glyph() must be DataSource subclass")
if not isinstance(glyph, Glyph):
raise ValueError("'glyph' argument to add_glyph() must be Glyph subclass")
g = GlyphRenderer(data_source=source, glyph=glyph, **kw)
self.renderers.append(g)
return g | python | def add_glyph(self, source_or_glyph, glyph=None, **kw):
''' Adds a glyph to the plot with associated data sources and ranges.
This function will take care of creating and configuring a Glyph object,
and then add it to the plot's list of renderers.
Args:
source (DataSource) : a data source for the glyphs to all use
glyph (Glyph) : the glyph to add to the Plot
Keyword Arguments:
Any additional keyword arguments are passed on as-is to the
Glyph initializer.
Returns:
GlyphRenderer
'''
if glyph is not None:
source = source_or_glyph
else:
source, glyph = ColumnDataSource(), source_or_glyph
if not isinstance(source, DataSource):
raise ValueError("'source' argument to add_glyph() must be DataSource subclass")
if not isinstance(glyph, Glyph):
raise ValueError("'glyph' argument to add_glyph() must be Glyph subclass")
g = GlyphRenderer(data_source=source, glyph=glyph, **kw)
self.renderers.append(g)
return g | [
"def",
"add_glyph",
"(",
"self",
",",
"source_or_glyph",
",",
"glyph",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"if",
"glyph",
"is",
"not",
"None",
":",
"source",
"=",
"source_or_glyph",
"else",
":",
"source",
",",
"glyph",
"=",
"ColumnDataSource",
... | Adds a glyph to the plot with associated data sources and ranges.
This function will take care of creating and configuring a Glyph object,
and then add it to the plot's list of renderers.
Args:
source (DataSource) : a data source for the glyphs to all use
glyph (Glyph) : the glyph to add to the Plot
Keyword Arguments:
Any additional keyword arguments are passed on as-is to the
Glyph initializer.
Returns:
GlyphRenderer | [
"Adds",
"a",
"glyph",
"to",
"the",
"plot",
"with",
"associated",
"data",
"sources",
"and",
"ranges",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/plots.py#L266-L298 |
30,357 | bokeh/bokeh | bokeh/models/plots.py | Plot.add_tile | def add_tile(self, tile_source, **kw):
''' Adds new ``TileRenderer`` into ``Plot.renderers``
Args:
tile_source (TileSource) : a tile source instance which contain tileset configuration
Keyword Arguments:
Additional keyword arguments are passed on as-is to the tile renderer
Returns:
TileRenderer : TileRenderer
'''
tile_renderer = TileRenderer(tile_source=tile_source, **kw)
self.renderers.append(tile_renderer)
return tile_renderer | python | def add_tile(self, tile_source, **kw):
''' Adds new ``TileRenderer`` into ``Plot.renderers``
Args:
tile_source (TileSource) : a tile source instance which contain tileset configuration
Keyword Arguments:
Additional keyword arguments are passed on as-is to the tile renderer
Returns:
TileRenderer : TileRenderer
'''
tile_renderer = TileRenderer(tile_source=tile_source, **kw)
self.renderers.append(tile_renderer)
return tile_renderer | [
"def",
"add_tile",
"(",
"self",
",",
"tile_source",
",",
"*",
"*",
"kw",
")",
":",
"tile_renderer",
"=",
"TileRenderer",
"(",
"tile_source",
"=",
"tile_source",
",",
"*",
"*",
"kw",
")",
"self",
".",
"renderers",
".",
"append",
"(",
"tile_renderer",
")",... | Adds new ``TileRenderer`` into ``Plot.renderers``
Args:
tile_source (TileSource) : a tile source instance which contain tileset configuration
Keyword Arguments:
Additional keyword arguments are passed on as-is to the tile renderer
Returns:
TileRenderer : TileRenderer | [
"Adds",
"new",
"TileRenderer",
"into",
"Plot",
".",
"renderers"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/plots.py#L300-L315 |
30,358 | bokeh/bokeh | bokeh/layouts.py | layout | def layout(*args, **kwargs):
""" Create a grid-based arrangement of Bokeh Layout objects.
Args:
children (list of lists of :class:`~bokeh.models.layouts.LayoutDOM` ): A list of lists of instances
for a grid layout. Can be any of the following - :class:`~bokeh.models.plots.Plot`,
:class:`~bokeh.models.widgets.widget.Widget`,
:class:`~bokeh.models.layouts.Row`,
:class:`~bokeh.models.layouts.Column`,
:class:`~bokeh.models.tools.ToolbarBox`,
:class:`~bokeh.models.layouts.Spacer`.
sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How
will the items in the layout resize to fill the available space.
Default is ``"fixed"``. For more information on the different
modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode`
description on :class:`~bokeh.models.layouts.LayoutDOM`.
Returns:
Column: A column of ``Row`` layouts of the children, all with the same sizing_mode.
Examples:
>>> layout([[plot_1, plot_2], [plot_3, plot_4]])
>>> layout(
children=[
[widget_1, plot_1],
[slider],
[widget_2, plot_2, plot_3]
],
sizing_mode='fixed',
)
"""
sizing_mode = kwargs.pop('sizing_mode', None)
children = kwargs.pop('children', None)
children = _handle_children(*args, children=children)
# Make the grid
return _create_grid(children, sizing_mode) | python | def layout(*args, **kwargs):
""" Create a grid-based arrangement of Bokeh Layout objects.
Args:
children (list of lists of :class:`~bokeh.models.layouts.LayoutDOM` ): A list of lists of instances
for a grid layout. Can be any of the following - :class:`~bokeh.models.plots.Plot`,
:class:`~bokeh.models.widgets.widget.Widget`,
:class:`~bokeh.models.layouts.Row`,
:class:`~bokeh.models.layouts.Column`,
:class:`~bokeh.models.tools.ToolbarBox`,
:class:`~bokeh.models.layouts.Spacer`.
sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How
will the items in the layout resize to fill the available space.
Default is ``"fixed"``. For more information on the different
modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode`
description on :class:`~bokeh.models.layouts.LayoutDOM`.
Returns:
Column: A column of ``Row`` layouts of the children, all with the same sizing_mode.
Examples:
>>> layout([[plot_1, plot_2], [plot_3, plot_4]])
>>> layout(
children=[
[widget_1, plot_1],
[slider],
[widget_2, plot_2, plot_3]
],
sizing_mode='fixed',
)
"""
sizing_mode = kwargs.pop('sizing_mode', None)
children = kwargs.pop('children', None)
children = _handle_children(*args, children=children)
# Make the grid
return _create_grid(children, sizing_mode) | [
"def",
"layout",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"sizing_mode",
"=",
"kwargs",
".",
"pop",
"(",
"'sizing_mode'",
",",
"None",
")",
"children",
"=",
"kwargs",
".",
"pop",
"(",
"'children'",
",",
"None",
")",
"children",
"=",
"_han... | Create a grid-based arrangement of Bokeh Layout objects.
Args:
children (list of lists of :class:`~bokeh.models.layouts.LayoutDOM` ): A list of lists of instances
for a grid layout. Can be any of the following - :class:`~bokeh.models.plots.Plot`,
:class:`~bokeh.models.widgets.widget.Widget`,
:class:`~bokeh.models.layouts.Row`,
:class:`~bokeh.models.layouts.Column`,
:class:`~bokeh.models.tools.ToolbarBox`,
:class:`~bokeh.models.layouts.Spacer`.
sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How
will the items in the layout resize to fill the available space.
Default is ``"fixed"``. For more information on the different
modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode`
description on :class:`~bokeh.models.layouts.LayoutDOM`.
Returns:
Column: A column of ``Row`` layouts of the children, all with the same sizing_mode.
Examples:
>>> layout([[plot_1, plot_2], [plot_3, plot_4]])
>>> layout(
children=[
[widget_1, plot_1],
[slider],
[widget_2, plot_2, plot_3]
],
sizing_mode='fixed',
) | [
"Create",
"a",
"grid",
"-",
"based",
"arrangement",
"of",
"Bokeh",
"Layout",
"objects",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/layouts.py#L182-L222 |
30,359 | bokeh/bokeh | bokeh/layouts.py | gridplot | def gridplot(children, sizing_mode=None, toolbar_location='above', ncols=None,
plot_width=None, plot_height=None, toolbar_options=None, merge_tools=True):
''' Create a grid of plots rendered on separate canvases.
The ``gridplot`` function builds a single toolbar for all the plots in the
grid. ``gridplot`` is designed to layout a set of plots. For general
grid layout, use the :func:`~bokeh.layouts.layout` function.
Args:
children (list of lists of :class:`~bokeh.models.plots.Plot` ): An
array of plots to display in a grid, given as a list of lists of Plot
objects. To leave a position in the grid empty, pass None for that
position in the children list. OR list of :class:`~bokeh.models.plots.Plot` if called with
ncols. OR an instance of GridSpec.
sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How
will the items in the layout resize to fill the available space.
Default is ``"fixed"``. For more information on the different
modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode`
description on :class:`~bokeh.models.layouts.LayoutDOM`.
toolbar_location (``above``, ``below``, ``left``, ``right`` ): Where the
toolbar will be located, with respect to the grid. Default is
``above``. If set to None, no toolbar will be attached to the grid.
ncols (int, optional): Specify the number of columns you would like in your grid.
You must only pass an un-nested list of plots (as opposed to a list of lists of plots)
when using ncols.
plot_width (int, optional): The width you would like all your plots to be
plot_height (int, optional): The height you would like all your plots to be.
toolbar_options (dict, optional) : A dictionary of options that will be
used to construct the grid's toolbar (an instance of
:class:`~bokeh.models.tools.ToolbarBox`). If none is supplied,
ToolbarBox's defaults will be used.
merge_tools (``True``, ``False``): Combine tools from all child plots into
a single toolbar.
Returns:
Row or Column: A row or column containing the grid toolbar and the grid
of plots (depending on whether the toolbar is left/right or
above/below. The grid is always a Column of Rows of plots.
Examples:
>>> gridplot([[plot_1, plot_2], [plot_3, plot_4]])
>>> gridplot([plot_1, plot_2, plot_3, plot_4], ncols=2, plot_width=200, plot_height=100)
>>> gridplot(
children=[[plot_1, plot_2], [None, plot_3]],
toolbar_location='right'
sizing_mode='fixed',
toolbar_options=dict(logo='gray')
)
'''
if toolbar_options is None:
toolbar_options = {}
if toolbar_location:
if not hasattr(Location, toolbar_location):
raise ValueError("Invalid value of toolbar_location: %s" % toolbar_location)
children = _handle_children(children=children)
if ncols:
if any(isinstance(child, list) for child in children):
raise ValueError("Cannot provide a nested list when using ncols")
children = list(_chunks(children, ncols))
# Additional children set-up for grid plot
if not children:
children = []
# Make the grid
tools = []
items = []
for y, row in enumerate(children):
for x, item in enumerate(row):
if item is None:
continue
elif isinstance(item, LayoutDOM):
if merge_tools:
for plot in item.select(dict(type=Plot)):
tools += plot.toolbar.tools
plot.toolbar_location = None
if isinstance(item, Plot):
if plot_width is not None:
item.plot_width = plot_width
if plot_height is not None:
item.plot_height = plot_height
if sizing_mode is not None and _has_auto_sizing(item):
item.sizing_mode = sizing_mode
items.append((item, y, x))
else:
raise ValueError("Only LayoutDOM items can be inserted into a grid")
if not merge_tools or not toolbar_location:
return GridBox(children=items, sizing_mode=sizing_mode)
grid = GridBox(children=items)
proxy = ProxyToolbar(tools=tools, **toolbar_options)
toolbar = ToolbarBox(toolbar=proxy, toolbar_location=toolbar_location)
if toolbar_location == 'above':
return Column(children=[toolbar, grid], sizing_mode=sizing_mode)
elif toolbar_location == 'below':
return Column(children=[grid, toolbar], sizing_mode=sizing_mode)
elif toolbar_location == 'left':
return Row(children=[toolbar, grid], sizing_mode=sizing_mode)
elif toolbar_location == 'right':
return Row(children=[grid, toolbar], sizing_mode=sizing_mode) | python | def gridplot(children, sizing_mode=None, toolbar_location='above', ncols=None,
plot_width=None, plot_height=None, toolbar_options=None, merge_tools=True):
''' Create a grid of plots rendered on separate canvases.
The ``gridplot`` function builds a single toolbar for all the plots in the
grid. ``gridplot`` is designed to layout a set of plots. For general
grid layout, use the :func:`~bokeh.layouts.layout` function.
Args:
children (list of lists of :class:`~bokeh.models.plots.Plot` ): An
array of plots to display in a grid, given as a list of lists of Plot
objects. To leave a position in the grid empty, pass None for that
position in the children list. OR list of :class:`~bokeh.models.plots.Plot` if called with
ncols. OR an instance of GridSpec.
sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How
will the items in the layout resize to fill the available space.
Default is ``"fixed"``. For more information on the different
modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode`
description on :class:`~bokeh.models.layouts.LayoutDOM`.
toolbar_location (``above``, ``below``, ``left``, ``right`` ): Where the
toolbar will be located, with respect to the grid. Default is
``above``. If set to None, no toolbar will be attached to the grid.
ncols (int, optional): Specify the number of columns you would like in your grid.
You must only pass an un-nested list of plots (as opposed to a list of lists of plots)
when using ncols.
plot_width (int, optional): The width you would like all your plots to be
plot_height (int, optional): The height you would like all your plots to be.
toolbar_options (dict, optional) : A dictionary of options that will be
used to construct the grid's toolbar (an instance of
:class:`~bokeh.models.tools.ToolbarBox`). If none is supplied,
ToolbarBox's defaults will be used.
merge_tools (``True``, ``False``): Combine tools from all child plots into
a single toolbar.
Returns:
Row or Column: A row or column containing the grid toolbar and the grid
of plots (depending on whether the toolbar is left/right or
above/below. The grid is always a Column of Rows of plots.
Examples:
>>> gridplot([[plot_1, plot_2], [plot_3, plot_4]])
>>> gridplot([plot_1, plot_2, plot_3, plot_4], ncols=2, plot_width=200, plot_height=100)
>>> gridplot(
children=[[plot_1, plot_2], [None, plot_3]],
toolbar_location='right'
sizing_mode='fixed',
toolbar_options=dict(logo='gray')
)
'''
if toolbar_options is None:
toolbar_options = {}
if toolbar_location:
if not hasattr(Location, toolbar_location):
raise ValueError("Invalid value of toolbar_location: %s" % toolbar_location)
children = _handle_children(children=children)
if ncols:
if any(isinstance(child, list) for child in children):
raise ValueError("Cannot provide a nested list when using ncols")
children = list(_chunks(children, ncols))
# Additional children set-up for grid plot
if not children:
children = []
# Make the grid
tools = []
items = []
for y, row in enumerate(children):
for x, item in enumerate(row):
if item is None:
continue
elif isinstance(item, LayoutDOM):
if merge_tools:
for plot in item.select(dict(type=Plot)):
tools += plot.toolbar.tools
plot.toolbar_location = None
if isinstance(item, Plot):
if plot_width is not None:
item.plot_width = plot_width
if plot_height is not None:
item.plot_height = plot_height
if sizing_mode is not None and _has_auto_sizing(item):
item.sizing_mode = sizing_mode
items.append((item, y, x))
else:
raise ValueError("Only LayoutDOM items can be inserted into a grid")
if not merge_tools or not toolbar_location:
return GridBox(children=items, sizing_mode=sizing_mode)
grid = GridBox(children=items)
proxy = ProxyToolbar(tools=tools, **toolbar_options)
toolbar = ToolbarBox(toolbar=proxy, toolbar_location=toolbar_location)
if toolbar_location == 'above':
return Column(children=[toolbar, grid], sizing_mode=sizing_mode)
elif toolbar_location == 'below':
return Column(children=[grid, toolbar], sizing_mode=sizing_mode)
elif toolbar_location == 'left':
return Row(children=[toolbar, grid], sizing_mode=sizing_mode)
elif toolbar_location == 'right':
return Row(children=[grid, toolbar], sizing_mode=sizing_mode) | [
"def",
"gridplot",
"(",
"children",
",",
"sizing_mode",
"=",
"None",
",",
"toolbar_location",
"=",
"'above'",
",",
"ncols",
"=",
"None",
",",
"plot_width",
"=",
"None",
",",
"plot_height",
"=",
"None",
",",
"toolbar_options",
"=",
"None",
",",
"merge_tools",... | Create a grid of plots rendered on separate canvases.
The ``gridplot`` function builds a single toolbar for all the plots in the
grid. ``gridplot`` is designed to layout a set of plots. For general
grid layout, use the :func:`~bokeh.layouts.layout` function.
Args:
children (list of lists of :class:`~bokeh.models.plots.Plot` ): An
array of plots to display in a grid, given as a list of lists of Plot
objects. To leave a position in the grid empty, pass None for that
position in the children list. OR list of :class:`~bokeh.models.plots.Plot` if called with
ncols. OR an instance of GridSpec.
sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How
will the items in the layout resize to fill the available space.
Default is ``"fixed"``. For more information on the different
modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode`
description on :class:`~bokeh.models.layouts.LayoutDOM`.
toolbar_location (``above``, ``below``, ``left``, ``right`` ): Where the
toolbar will be located, with respect to the grid. Default is
``above``. If set to None, no toolbar will be attached to the grid.
ncols (int, optional): Specify the number of columns you would like in your grid.
You must only pass an un-nested list of plots (as opposed to a list of lists of plots)
when using ncols.
plot_width (int, optional): The width you would like all your plots to be
plot_height (int, optional): The height you would like all your plots to be.
toolbar_options (dict, optional) : A dictionary of options that will be
used to construct the grid's toolbar (an instance of
:class:`~bokeh.models.tools.ToolbarBox`). If none is supplied,
ToolbarBox's defaults will be used.
merge_tools (``True``, ``False``): Combine tools from all child plots into
a single toolbar.
Returns:
Row or Column: A row or column containing the grid toolbar and the grid
of plots (depending on whether the toolbar is left/right or
above/below. The grid is always a Column of Rows of plots.
Examples:
>>> gridplot([[plot_1, plot_2], [plot_3, plot_4]])
>>> gridplot([plot_1, plot_2, plot_3, plot_4], ncols=2, plot_width=200, plot_height=100)
>>> gridplot(
children=[[plot_1, plot_2], [None, plot_3]],
toolbar_location='right'
sizing_mode='fixed',
toolbar_options=dict(logo='gray')
) | [
"Create",
"a",
"grid",
"of",
"plots",
"rendered",
"on",
"separate",
"canvases",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/layouts.py#L224-L340 |
30,360 | bokeh/bokeh | bokeh/layouts.py | _chunks | def _chunks(l, ncols):
"""Yield successive n-sized chunks from list, l."""
assert isinstance(ncols, int), "ncols must be an integer"
for i in range(0, len(l), ncols):
yield l[i: i+ncols] | python | def _chunks(l, ncols):
"""Yield successive n-sized chunks from list, l."""
assert isinstance(ncols, int), "ncols must be an integer"
for i in range(0, len(l), ncols):
yield l[i: i+ncols] | [
"def",
"_chunks",
"(",
"l",
",",
"ncols",
")",
":",
"assert",
"isinstance",
"(",
"ncols",
",",
"int",
")",
",",
"\"ncols must be an integer\"",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"l",
")",
",",
"ncols",
")",
":",
"yield",
"l",
"[... | Yield successive n-sized chunks from list, l. | [
"Yield",
"successive",
"n",
"-",
"sized",
"chunks",
"from",
"list",
"l",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/layouts.py#L613-L617 |
30,361 | bokeh/bokeh | bokeh/document/locking.py | without_document_lock | def without_document_lock(func):
''' Wrap a callback function to execute without first obtaining the
document lock.
Args:
func (callable) : The function to wrap
Returns:
callable : a function wrapped to execute without a |Document| lock.
While inside an unlocked callback, it is completely *unsafe* to modify
``curdoc()``. The value of ``curdoc()`` inside the callback will be a
specially wrapped version of |Document| that only allows safe operations,
which are:
* :func:`~bokeh.document.Document.add_next_tick_callback`
* :func:`~bokeh.document.Document.remove_next_tick_callback`
Only these may be used safely without taking the document lock. To make
other changes to the document, you must add a next tick callback and make
your changes to ``curdoc()`` from that second callback.
Attempts to otherwise access or change the Document will result in an
exception being raised.
'''
@wraps(func)
def wrapper(*args, **kw):
return func(*args, **kw)
wrapper.nolock = True
return wrapper | python | def without_document_lock(func):
''' Wrap a callback function to execute without first obtaining the
document lock.
Args:
func (callable) : The function to wrap
Returns:
callable : a function wrapped to execute without a |Document| lock.
While inside an unlocked callback, it is completely *unsafe* to modify
``curdoc()``. The value of ``curdoc()`` inside the callback will be a
specially wrapped version of |Document| that only allows safe operations,
which are:
* :func:`~bokeh.document.Document.add_next_tick_callback`
* :func:`~bokeh.document.Document.remove_next_tick_callback`
Only these may be used safely without taking the document lock. To make
other changes to the document, you must add a next tick callback and make
your changes to ``curdoc()`` from that second callback.
Attempts to otherwise access or change the Document will result in an
exception being raised.
'''
@wraps(func)
def wrapper(*args, **kw):
return func(*args, **kw)
wrapper.nolock = True
return wrapper | [
"def",
"without_document_lock",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"wrapper",
".",
"nolock",
"=",... | Wrap a callback function to execute without first obtaining the
document lock.
Args:
func (callable) : The function to wrap
Returns:
callable : a function wrapped to execute without a |Document| lock.
While inside an unlocked callback, it is completely *unsafe* to modify
``curdoc()``. The value of ``curdoc()`` inside the callback will be a
specially wrapped version of |Document| that only allows safe operations,
which are:
* :func:`~bokeh.document.Document.add_next_tick_callback`
* :func:`~bokeh.document.Document.remove_next_tick_callback`
Only these may be used safely without taking the document lock. To make
other changes to the document, you must add a next tick callback and make
your changes to ``curdoc()`` from that second callback.
Attempts to otherwise access or change the Document will result in an
exception being raised. | [
"Wrap",
"a",
"callback",
"function",
"to",
"execute",
"without",
"first",
"obtaining",
"the",
"document",
"lock",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/locking.py#L43-L73 |
30,362 | bokeh/bokeh | bokeh/embed/server.py | server_document | def server_document(url="default", relative_urls=False, resources="default", arguments=None):
''' Return a script tag that embeds content from a Bokeh server.
Bokeh apps embedded using these methods will NOT set the browser window title.
Args:
url (str, optional) :
A URL to a Bokeh application on a Bokeh server (default: "default")
If ``"default"`` the default URL ``{DEFAULT_SERVER_HTTP_URL}`` will be used.
relative_urls (bool, optional) :
Whether to use relative URLs for resources.
If ``True`` the links generated for resources such a BokehJS
JavaScript and CSS will be relative links.
This should normally be set to ``False``, but must be set to
``True`` in situations where only relative URLs will work. E.g.
when running the Bokeh behind reverse-proxies under certain
configurations
resources (str) : A string specifying what resources need to be loaded
along with the document.
If ``default`` then the default JS/CSS bokeh files will be loaded.
If None then none of the resource files will be loaded. This is
useful if you prefer to serve those resource files via other means
(e.g. from a caching server). Be careful, however, that the resource
files you'll load separately are of the same version as that of the
server's, otherwise the rendering may not work correctly.
arguments (dict[str, str], optional) :
A dictionary of key/values to be passed as HTTP request arguments
to Bokeh application code (default: None)
Returns:
A ``<script>`` tag that will embed content from a Bokeh Server.
'''
url = _clean_url(url)
app_path = _get_app_path(url)
elementid = make_id()
src_path = _src_path(url, elementid)
src_path += _process_app_path(app_path)
src_path += _process_relative_urls(relative_urls, url)
src_path += _process_resources(resources)
src_path += _process_arguments(arguments)
tag = AUTOLOAD_TAG.render(
src_path = src_path,
app_path = app_path,
elementid = elementid,
)
return encode_utf8(tag) | python | def server_document(url="default", relative_urls=False, resources="default", arguments=None):
''' Return a script tag that embeds content from a Bokeh server.
Bokeh apps embedded using these methods will NOT set the browser window title.
Args:
url (str, optional) :
A URL to a Bokeh application on a Bokeh server (default: "default")
If ``"default"`` the default URL ``{DEFAULT_SERVER_HTTP_URL}`` will be used.
relative_urls (bool, optional) :
Whether to use relative URLs for resources.
If ``True`` the links generated for resources such a BokehJS
JavaScript and CSS will be relative links.
This should normally be set to ``False``, but must be set to
``True`` in situations where only relative URLs will work. E.g.
when running the Bokeh behind reverse-proxies under certain
configurations
resources (str) : A string specifying what resources need to be loaded
along with the document.
If ``default`` then the default JS/CSS bokeh files will be loaded.
If None then none of the resource files will be loaded. This is
useful if you prefer to serve those resource files via other means
(e.g. from a caching server). Be careful, however, that the resource
files you'll load separately are of the same version as that of the
server's, otherwise the rendering may not work correctly.
arguments (dict[str, str], optional) :
A dictionary of key/values to be passed as HTTP request arguments
to Bokeh application code (default: None)
Returns:
A ``<script>`` tag that will embed content from a Bokeh Server.
'''
url = _clean_url(url)
app_path = _get_app_path(url)
elementid = make_id()
src_path = _src_path(url, elementid)
src_path += _process_app_path(app_path)
src_path += _process_relative_urls(relative_urls, url)
src_path += _process_resources(resources)
src_path += _process_arguments(arguments)
tag = AUTOLOAD_TAG.render(
src_path = src_path,
app_path = app_path,
elementid = elementid,
)
return encode_utf8(tag) | [
"def",
"server_document",
"(",
"url",
"=",
"\"default\"",
",",
"relative_urls",
"=",
"False",
",",
"resources",
"=",
"\"default\"",
",",
"arguments",
"=",
"None",
")",
":",
"url",
"=",
"_clean_url",
"(",
"url",
")",
"app_path",
"=",
"_get_app_path",
"(",
"... | Return a script tag that embeds content from a Bokeh server.
Bokeh apps embedded using these methods will NOT set the browser window title.
Args:
url (str, optional) :
A URL to a Bokeh application on a Bokeh server (default: "default")
If ``"default"`` the default URL ``{DEFAULT_SERVER_HTTP_URL}`` will be used.
relative_urls (bool, optional) :
Whether to use relative URLs for resources.
If ``True`` the links generated for resources such a BokehJS
JavaScript and CSS will be relative links.
This should normally be set to ``False``, but must be set to
``True`` in situations where only relative URLs will work. E.g.
when running the Bokeh behind reverse-proxies under certain
configurations
resources (str) : A string specifying what resources need to be loaded
along with the document.
If ``default`` then the default JS/CSS bokeh files will be loaded.
If None then none of the resource files will be loaded. This is
useful if you prefer to serve those resource files via other means
(e.g. from a caching server). Be careful, however, that the resource
files you'll load separately are of the same version as that of the
server's, otherwise the rendering may not work correctly.
arguments (dict[str, str], optional) :
A dictionary of key/values to be passed as HTTP request arguments
to Bokeh application code (default: None)
Returns:
A ``<script>`` tag that will embed content from a Bokeh Server. | [
"Return",
"a",
"script",
"tag",
"that",
"embeds",
"content",
"from",
"a",
"Bokeh",
"server",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/server.py#L51-L110 |
30,363 | bokeh/bokeh | bokeh/embed/server.py | server_session | def server_session(model=None, session_id=None, url="default", relative_urls=False, resources="default"):
''' Return a script tag that embeds content from a specific existing session on
a Bokeh server.
This function is typically only useful for serving from a a specific session
that was previously created using the ``bokeh.client`` API.
Bokeh apps embedded using these methods will NOT set the browser window title.
.. note::
Typically you will not want to save or re-use the output of this
function for different or multiple page loads.
Args:
model (Model or None, optional) :
The object to render from the session, or None. (default: None)
If None, the entire document will be rendered.
session_id (str) :
A server session ID
url (str, optional) :
A URL to a Bokeh application on a Bokeh server (default: "default")
If ``"default"`` the default URL ``{DEFAULT_SERVER_HTTP_URL}`` will be used.
relative_urls (bool, optional) :
Whether to use relative URLs for resources.
If ``True`` the links generated for resources such a BokehJS
JavaScript and CSS will be relative links.
This should normally be set to ``False``, but must be set to
``True`` in situations where only relative URLs will work. E.g.
when running the Bokeh behind reverse-proxies under certain
configurations
resources (str) : A string specifying what resources need to be loaded
along with the document.
If ``default`` then the default JS/CSS bokeh files will be loaded.
If None then none of the resource files will be loaded. This is
useful if you prefer to serve those resource files via other means
(e.g. from a caching server). Be careful, however, that the resource
files you'll load separately are of the same version as that of the
server's, otherwise the rendering may not work correctly.
Returns:
A ``<script>`` tag that will embed content from a Bokeh Server.
.. warning::
It is typically a bad idea to re-use the same ``session_id`` for
every page load. This is likely to create scalability and security
problems, and will cause "shared Google doc" behavior, which is
probably not desired.
'''
if session_id is None:
raise ValueError("Must supply a session_id")
url = _clean_url(url)
app_path = _get_app_path(url)
elementid = make_id()
modelid = "" if model is None else model.id
src_path = _src_path(url, elementid)
src_path += _process_app_path(app_path)
src_path += _process_relative_urls(relative_urls, url)
src_path += _process_session_id(session_id)
src_path += _process_resources(resources)
tag = AUTOLOAD_TAG.render(
src_path = src_path,
app_path = app_path,
elementid = elementid,
modelid = modelid,
)
return encode_utf8(tag) | python | def server_session(model=None, session_id=None, url="default", relative_urls=False, resources="default"):
''' Return a script tag that embeds content from a specific existing session on
a Bokeh server.
This function is typically only useful for serving from a a specific session
that was previously created using the ``bokeh.client`` API.
Bokeh apps embedded using these methods will NOT set the browser window title.
.. note::
Typically you will not want to save or re-use the output of this
function for different or multiple page loads.
Args:
model (Model or None, optional) :
The object to render from the session, or None. (default: None)
If None, the entire document will be rendered.
session_id (str) :
A server session ID
url (str, optional) :
A URL to a Bokeh application on a Bokeh server (default: "default")
If ``"default"`` the default URL ``{DEFAULT_SERVER_HTTP_URL}`` will be used.
relative_urls (bool, optional) :
Whether to use relative URLs for resources.
If ``True`` the links generated for resources such a BokehJS
JavaScript and CSS will be relative links.
This should normally be set to ``False``, but must be set to
``True`` in situations where only relative URLs will work. E.g.
when running the Bokeh behind reverse-proxies under certain
configurations
resources (str) : A string specifying what resources need to be loaded
along with the document.
If ``default`` then the default JS/CSS bokeh files will be loaded.
If None then none of the resource files will be loaded. This is
useful if you prefer to serve those resource files via other means
(e.g. from a caching server). Be careful, however, that the resource
files you'll load separately are of the same version as that of the
server's, otherwise the rendering may not work correctly.
Returns:
A ``<script>`` tag that will embed content from a Bokeh Server.
.. warning::
It is typically a bad idea to re-use the same ``session_id`` for
every page load. This is likely to create scalability and security
problems, and will cause "shared Google doc" behavior, which is
probably not desired.
'''
if session_id is None:
raise ValueError("Must supply a session_id")
url = _clean_url(url)
app_path = _get_app_path(url)
elementid = make_id()
modelid = "" if model is None else model.id
src_path = _src_path(url, elementid)
src_path += _process_app_path(app_path)
src_path += _process_relative_urls(relative_urls, url)
src_path += _process_session_id(session_id)
src_path += _process_resources(resources)
tag = AUTOLOAD_TAG.render(
src_path = src_path,
app_path = app_path,
elementid = elementid,
modelid = modelid,
)
return encode_utf8(tag) | [
"def",
"server_session",
"(",
"model",
"=",
"None",
",",
"session_id",
"=",
"None",
",",
"url",
"=",
"\"default\"",
",",
"relative_urls",
"=",
"False",
",",
"resources",
"=",
"\"default\"",
")",
":",
"if",
"session_id",
"is",
"None",
":",
"raise",
"ValueEr... | Return a script tag that embeds content from a specific existing session on
a Bokeh server.
This function is typically only useful for serving from a a specific session
that was previously created using the ``bokeh.client`` API.
Bokeh apps embedded using these methods will NOT set the browser window title.
.. note::
Typically you will not want to save or re-use the output of this
function for different or multiple page loads.
Args:
model (Model or None, optional) :
The object to render from the session, or None. (default: None)
If None, the entire document will be rendered.
session_id (str) :
A server session ID
url (str, optional) :
A URL to a Bokeh application on a Bokeh server (default: "default")
If ``"default"`` the default URL ``{DEFAULT_SERVER_HTTP_URL}`` will be used.
relative_urls (bool, optional) :
Whether to use relative URLs for resources.
If ``True`` the links generated for resources such a BokehJS
JavaScript and CSS will be relative links.
This should normally be set to ``False``, but must be set to
``True`` in situations where only relative URLs will work. E.g.
when running the Bokeh behind reverse-proxies under certain
configurations
resources (str) : A string specifying what resources need to be loaded
along with the document.
If ``default`` then the default JS/CSS bokeh files will be loaded.
If None then none of the resource files will be loaded. This is
useful if you prefer to serve those resource files via other means
(e.g. from a caching server). Be careful, however, that the resource
files you'll load separately are of the same version as that of the
server's, otherwise the rendering may not work correctly.
Returns:
A ``<script>`` tag that will embed content from a Bokeh Server.
.. warning::
It is typically a bad idea to re-use the same ``session_id`` for
every page load. This is likely to create scalability and security
problems, and will cause "shared Google doc" behavior, which is
probably not desired. | [
"Return",
"a",
"script",
"tag",
"that",
"embeds",
"content",
"from",
"a",
"specific",
"existing",
"session",
"on",
"a",
"Bokeh",
"server",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/server.py#L112-L194 |
30,364 | bokeh/bokeh | bokeh/embed/server.py | _clean_url | def _clean_url(url):
''' Produce a canonical Bokeh server URL.
Args:
url (str)
A URL to clean, or "defatul". If "default" then the
``BOKEH_SERVER_HTTP_URL`` will be returned.
Returns:
str
'''
if url == 'default':
url = DEFAULT_SERVER_HTTP_URL
if url.startswith("ws"):
raise ValueError("url should be the http or https URL for the server, not the websocket URL")
return url.rstrip("/") | python | def _clean_url(url):
''' Produce a canonical Bokeh server URL.
Args:
url (str)
A URL to clean, or "defatul". If "default" then the
``BOKEH_SERVER_HTTP_URL`` will be returned.
Returns:
str
'''
if url == 'default':
url = DEFAULT_SERVER_HTTP_URL
if url.startswith("ws"):
raise ValueError("url should be the http or https URL for the server, not the websocket URL")
return url.rstrip("/") | [
"def",
"_clean_url",
"(",
"url",
")",
":",
"if",
"url",
"==",
"'default'",
":",
"url",
"=",
"DEFAULT_SERVER_HTTP_URL",
"if",
"url",
".",
"startswith",
"(",
"\"ws\"",
")",
":",
"raise",
"ValueError",
"(",
"\"url should be the http or https URL for the server, not the... | Produce a canonical Bokeh server URL.
Args:
url (str)
A URL to clean, or "defatul". If "default" then the
``BOKEH_SERVER_HTTP_URL`` will be returned.
Returns:
str | [
"Produce",
"a",
"canonical",
"Bokeh",
"server",
"URL",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/server.py#L236-L254 |
30,365 | bokeh/bokeh | bokeh/embed/server.py | _get_app_path | def _get_app_path(url):
''' Extract the app path from a Bokeh server URL
Args:
url (str) :
Returns:
str
'''
app_path = urlparse(url).path.rstrip("/")
if not app_path.startswith("/"):
app_path = "/" + app_path
return app_path | python | def _get_app_path(url):
''' Extract the app path from a Bokeh server URL
Args:
url (str) :
Returns:
str
'''
app_path = urlparse(url).path.rstrip("/")
if not app_path.startswith("/"):
app_path = "/" + app_path
return app_path | [
"def",
"_get_app_path",
"(",
"url",
")",
":",
"app_path",
"=",
"urlparse",
"(",
"url",
")",
".",
"path",
".",
"rstrip",
"(",
"\"/\"",
")",
"if",
"not",
"app_path",
".",
"startswith",
"(",
"\"/\"",
")",
":",
"app_path",
"=",
"\"/\"",
"+",
"app_path",
... | Extract the app path from a Bokeh server URL
Args:
url (str) :
Returns:
str | [
"Extract",
"the",
"app",
"path",
"from",
"a",
"Bokeh",
"server",
"URL"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/server.py#L256-L269 |
30,366 | bokeh/bokeh | bokeh/embed/server.py | _process_arguments | def _process_arguments(arguments):
''' Return user-supplied HTML arguments to add to a Bokeh server URL.
Args:
arguments (dict[str, object]) :
Key/value pairs to add to the URL
Returns:
str
'''
if arguments is None: return ""
result = ""
for key, value in arguments.items():
if not key.startswith("bokeh-"):
result += "&{}={}".format(quote_plus(str(key)), quote_plus(str(value)))
return result | python | def _process_arguments(arguments):
''' Return user-supplied HTML arguments to add to a Bokeh server URL.
Args:
arguments (dict[str, object]) :
Key/value pairs to add to the URL
Returns:
str
'''
if arguments is None: return ""
result = ""
for key, value in arguments.items():
if not key.startswith("bokeh-"):
result += "&{}={}".format(quote_plus(str(key)), quote_plus(str(value)))
return result | [
"def",
"_process_arguments",
"(",
"arguments",
")",
":",
"if",
"arguments",
"is",
"None",
":",
"return",
"\"\"",
"result",
"=",
"\"\"",
"for",
"key",
",",
"value",
"in",
"arguments",
".",
"items",
"(",
")",
":",
"if",
"not",
"key",
".",
"startswith",
"... | Return user-supplied HTML arguments to add to a Bokeh server URL.
Args:
arguments (dict[str, object]) :
Key/value pairs to add to the URL
Returns:
str | [
"Return",
"user",
"-",
"supplied",
"HTML",
"arguments",
"to",
"add",
"to",
"a",
"Bokeh",
"server",
"URL",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/server.py#L271-L287 |
30,367 | bokeh/bokeh | bokeh/server/views/ws.py | WSHandler.check_origin | def check_origin(self, origin):
''' Implement a check_origin policy for Tornado to call.
The supplied origin will be compared to the Bokeh server whitelist. If the
origin is not allow, an error will be logged and ``False`` will be returned.
Args:
origin (str) :
The URL of the connection origin
Returns:
bool, True if the connection is allowed, False otherwise
'''
from ..util import check_whitelist
parsed_origin = urlparse(origin)
origin_host = parsed_origin.netloc.lower()
allowed_hosts = self.application.websocket_origins
if settings.allowed_ws_origin():
allowed_hosts = set(settings.allowed_ws_origin())
allowed = check_whitelist(origin_host, allowed_hosts)
if allowed:
return True
else:
log.error("Refusing websocket connection from Origin '%s'; \
use --allow-websocket-origin=%s or set BOKEH_ALLOW_WS_ORIGIN=%s to permit this; currently we allow origins %r",
origin, origin_host, origin_host, allowed_hosts)
return False | python | def check_origin(self, origin):
''' Implement a check_origin policy for Tornado to call.
The supplied origin will be compared to the Bokeh server whitelist. If the
origin is not allow, an error will be logged and ``False`` will be returned.
Args:
origin (str) :
The URL of the connection origin
Returns:
bool, True if the connection is allowed, False otherwise
'''
from ..util import check_whitelist
parsed_origin = urlparse(origin)
origin_host = parsed_origin.netloc.lower()
allowed_hosts = self.application.websocket_origins
if settings.allowed_ws_origin():
allowed_hosts = set(settings.allowed_ws_origin())
allowed = check_whitelist(origin_host, allowed_hosts)
if allowed:
return True
else:
log.error("Refusing websocket connection from Origin '%s'; \
use --allow-websocket-origin=%s or set BOKEH_ALLOW_WS_ORIGIN=%s to permit this; currently we allow origins %r",
origin, origin_host, origin_host, allowed_hosts)
return False | [
"def",
"check_origin",
"(",
"self",
",",
"origin",
")",
":",
"from",
".",
".",
"util",
"import",
"check_whitelist",
"parsed_origin",
"=",
"urlparse",
"(",
"origin",
")",
"origin_host",
"=",
"parsed_origin",
".",
"netloc",
".",
"lower",
"(",
")",
"allowed_hos... | Implement a check_origin policy for Tornado to call.
The supplied origin will be compared to the Bokeh server whitelist. If the
origin is not allow, an error will be logged and ``False`` will be returned.
Args:
origin (str) :
The URL of the connection origin
Returns:
bool, True if the connection is allowed, False otherwise | [
"Implement",
"a",
"check_origin",
"policy",
"for",
"Tornado",
"to",
"call",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/views/ws.py#L79-L108 |
30,368 | bokeh/bokeh | bokeh/server/views/ws.py | WSHandler.open | def open(self):
''' Initialize a connection to a client.
Returns:
None
'''
log.info('WebSocket connection opened')
proto_version = self.get_argument("bokeh-protocol-version", default=None)
if proto_version is None:
self.close()
raise ProtocolError("No bokeh-protocol-version specified")
session_id = self.get_argument("bokeh-session-id", default=None)
if session_id is None:
self.close()
raise ProtocolError("No bokeh-session-id specified")
if not check_session_id_signature(session_id,
signed=self.application.sign_sessions,
secret_key=self.application.secret_key):
log.error("Session id had invalid signature: %r", session_id)
raise ProtocolError("Invalid session ID")
def on_fully_opened(future):
e = future.exception()
if e is not None:
# this isn't really an error (unless we have a
# bug), it just means a client disconnected
# immediately, most likely.
log.debug("Failed to fully open connection %r", e)
future = self._async_open(session_id, proto_version)
self.application.io_loop.add_future(future, on_fully_opened) | python | def open(self):
''' Initialize a connection to a client.
Returns:
None
'''
log.info('WebSocket connection opened')
proto_version = self.get_argument("bokeh-protocol-version", default=None)
if proto_version is None:
self.close()
raise ProtocolError("No bokeh-protocol-version specified")
session_id = self.get_argument("bokeh-session-id", default=None)
if session_id is None:
self.close()
raise ProtocolError("No bokeh-session-id specified")
if not check_session_id_signature(session_id,
signed=self.application.sign_sessions,
secret_key=self.application.secret_key):
log.error("Session id had invalid signature: %r", session_id)
raise ProtocolError("Invalid session ID")
def on_fully_opened(future):
e = future.exception()
if e is not None:
# this isn't really an error (unless we have a
# bug), it just means a client disconnected
# immediately, most likely.
log.debug("Failed to fully open connection %r", e)
future = self._async_open(session_id, proto_version)
self.application.io_loop.add_future(future, on_fully_opened) | [
"def",
"open",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"'WebSocket connection opened'",
")",
"proto_version",
"=",
"self",
".",
"get_argument",
"(",
"\"bokeh-protocol-version\"",
",",
"default",
"=",
"None",
")",
"if",
"proto_version",
"is",
"None",
":... | Initialize a connection to a client.
Returns:
None | [
"Initialize",
"a",
"connection",
"to",
"a",
"client",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/views/ws.py#L110-L144 |
30,369 | bokeh/bokeh | bokeh/server/views/ws.py | WSHandler._async_open | def _async_open(self, session_id, proto_version):
''' Perform the specific steps needed to open a connection to a Bokeh session
Specifically, this method coordinates:
* Getting a session for a session ID (creating a new one if needed)
* Creating a protocol receiver and hander
* Opening a new ServerConnection and sending it an ACK
Args:
session_id (str) :
A session ID to for a session to connect to
If no session exists with the given ID, a new session is made
proto_version (str):
The protocol version requested by the connecting client.
Returns:
None
'''
try:
yield self.application_context.create_session_if_needed(session_id, self.request)
session = self.application_context.get_session(session_id)
protocol = Protocol(proto_version)
self.receiver = Receiver(protocol)
log.debug("Receiver created for %r", protocol)
self.handler = ProtocolHandler()
log.debug("ProtocolHandler created for %r", protocol)
self.connection = self.application.new_connection(protocol, self, self.application_context, session)
log.info("ServerConnection created")
except ProtocolError as e:
log.error("Could not create new server session, reason: %s", e)
self.close()
raise e
msg = self.connection.protocol.create('ACK')
yield self.send_message(msg)
raise gen.Return(None) | python | def _async_open(self, session_id, proto_version):
''' Perform the specific steps needed to open a connection to a Bokeh session
Specifically, this method coordinates:
* Getting a session for a session ID (creating a new one if needed)
* Creating a protocol receiver and hander
* Opening a new ServerConnection and sending it an ACK
Args:
session_id (str) :
A session ID to for a session to connect to
If no session exists with the given ID, a new session is made
proto_version (str):
The protocol version requested by the connecting client.
Returns:
None
'''
try:
yield self.application_context.create_session_if_needed(session_id, self.request)
session = self.application_context.get_session(session_id)
protocol = Protocol(proto_version)
self.receiver = Receiver(protocol)
log.debug("Receiver created for %r", protocol)
self.handler = ProtocolHandler()
log.debug("ProtocolHandler created for %r", protocol)
self.connection = self.application.new_connection(protocol, self, self.application_context, session)
log.info("ServerConnection created")
except ProtocolError as e:
log.error("Could not create new server session, reason: %s", e)
self.close()
raise e
msg = self.connection.protocol.create('ACK')
yield self.send_message(msg)
raise gen.Return(None) | [
"def",
"_async_open",
"(",
"self",
",",
"session_id",
",",
"proto_version",
")",
":",
"try",
":",
"yield",
"self",
".",
"application_context",
".",
"create_session_if_needed",
"(",
"session_id",
",",
"self",
".",
"request",
")",
"session",
"=",
"self",
".",
... | Perform the specific steps needed to open a connection to a Bokeh session
Specifically, this method coordinates:
* Getting a session for a session ID (creating a new one if needed)
* Creating a protocol receiver and hander
* Opening a new ServerConnection and sending it an ACK
Args:
session_id (str) :
A session ID to for a session to connect to
If no session exists with the given ID, a new session is made
proto_version (str):
The protocol version requested by the connecting client.
Returns:
None | [
"Perform",
"the",
"specific",
"steps",
"needed",
"to",
"open",
"a",
"connection",
"to",
"a",
"Bokeh",
"session"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/views/ws.py#L147-L191 |
30,370 | bokeh/bokeh | bokeh/server/views/ws.py | WSHandler.on_message | def on_message(self, fragment):
''' Process an individual wire protocol fragment.
The websocket RFC specifies opcodes for distinguishing text frames
from binary frames. Tornado passes us either a text or binary string
depending on that opcode, we have to look at the type of the fragment
to see what we got.
Args:
fragment (unicode or bytes) : wire fragment to process
'''
# We shouldn't throw exceptions from on_message because the caller is
# just Tornado and it doesn't know what to do with them other than
# report them as an unhandled Future
try:
message = yield self._receive(fragment)
except Exception as e:
# If you go look at self._receive, it's catching the
# expected error types... here we have something weird.
log.error("Unhandled exception receiving a message: %r: %r", e, fragment, exc_info=True)
self._internal_error("server failed to parse a message")
try:
if message:
if _message_test_port is not None:
_message_test_port.received.append(message)
work = yield self._handle(message)
if work:
yield self._schedule(work)
except Exception as e:
log.error("Handler or its work threw an exception: %r: %r", e, message, exc_info=True)
self._internal_error("server failed to handle a message")
raise gen.Return(None) | python | def on_message(self, fragment):
''' Process an individual wire protocol fragment.
The websocket RFC specifies opcodes for distinguishing text frames
from binary frames. Tornado passes us either a text or binary string
depending on that opcode, we have to look at the type of the fragment
to see what we got.
Args:
fragment (unicode or bytes) : wire fragment to process
'''
# We shouldn't throw exceptions from on_message because the caller is
# just Tornado and it doesn't know what to do with them other than
# report them as an unhandled Future
try:
message = yield self._receive(fragment)
except Exception as e:
# If you go look at self._receive, it's catching the
# expected error types... here we have something weird.
log.error("Unhandled exception receiving a message: %r: %r", e, fragment, exc_info=True)
self._internal_error("server failed to parse a message")
try:
if message:
if _message_test_port is not None:
_message_test_port.received.append(message)
work = yield self._handle(message)
if work:
yield self._schedule(work)
except Exception as e:
log.error("Handler or its work threw an exception: %r: %r", e, message, exc_info=True)
self._internal_error("server failed to handle a message")
raise gen.Return(None) | [
"def",
"on_message",
"(",
"self",
",",
"fragment",
")",
":",
"# We shouldn't throw exceptions from on_message because the caller is",
"# just Tornado and it doesn't know what to do with them other than",
"# report them as an unhandled Future",
"try",
":",
"message",
"=",
"yield",
"se... | Process an individual wire protocol fragment.
The websocket RFC specifies opcodes for distinguishing text frames
from binary frames. Tornado passes us either a text or binary string
depending on that opcode, we have to look at the type of the fragment
to see what we got.
Args:
fragment (unicode or bytes) : wire fragment to process | [
"Process",
"an",
"individual",
"wire",
"protocol",
"fragment",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/views/ws.py#L194-L230 |
30,371 | bokeh/bokeh | bokeh/server/views/ws.py | WSHandler.send_message | def send_message(self, message):
''' Send a Bokeh Server protocol message to the connected client.
Args:
message (Message) : a message to send
'''
try:
if _message_test_port is not None:
_message_test_port.sent.append(message)
yield message.send(self)
except (WebSocketClosedError, StreamClosedError): # Tornado 4.x may raise StreamClosedError
# on_close() is / will be called anyway
log.warning("Failed sending message as connection was closed")
raise gen.Return(None) | python | def send_message(self, message):
''' Send a Bokeh Server protocol message to the connected client.
Args:
message (Message) : a message to send
'''
try:
if _message_test_port is not None:
_message_test_port.sent.append(message)
yield message.send(self)
except (WebSocketClosedError, StreamClosedError): # Tornado 4.x may raise StreamClosedError
# on_close() is / will be called anyway
log.warning("Failed sending message as connection was closed")
raise gen.Return(None) | [
"def",
"send_message",
"(",
"self",
",",
"message",
")",
":",
"try",
":",
"if",
"_message_test_port",
"is",
"not",
"None",
":",
"_message_test_port",
".",
"sent",
".",
"append",
"(",
"message",
")",
"yield",
"message",
".",
"send",
"(",
"self",
")",
"exc... | Send a Bokeh Server protocol message to the connected client.
Args:
message (Message) : a message to send | [
"Send",
"a",
"Bokeh",
"Server",
"protocol",
"message",
"to",
"the",
"connected",
"client",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/views/ws.py#L243-L257 |
30,372 | bokeh/bokeh | bokeh/server/views/ws.py | WSHandler.write_message | def write_message(self, message, binary=False, locked=True):
''' Override parent write_message with a version that acquires a
write lock before writing.
'''
if locked:
with (yield self.write_lock.acquire()):
yield super(WSHandler, self).write_message(message, binary)
else:
yield super(WSHandler, self).write_message(message, binary) | python | def write_message(self, message, binary=False, locked=True):
''' Override parent write_message with a version that acquires a
write lock before writing.
'''
if locked:
with (yield self.write_lock.acquire()):
yield super(WSHandler, self).write_message(message, binary)
else:
yield super(WSHandler, self).write_message(message, binary) | [
"def",
"write_message",
"(",
"self",
",",
"message",
",",
"binary",
"=",
"False",
",",
"locked",
"=",
"True",
")",
":",
"if",
"locked",
":",
"with",
"(",
"yield",
"self",
".",
"write_lock",
".",
"acquire",
"(",
")",
")",
":",
"yield",
"super",
"(",
... | Override parent write_message with a version that acquires a
write lock before writing. | [
"Override",
"parent",
"write_message",
"with",
"a",
"version",
"that",
"acquires",
"a",
"write",
"lock",
"before",
"writing",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/views/ws.py#L260-L269 |
30,373 | bokeh/bokeh | bokeh/server/views/ws.py | WSHandler.on_close | def on_close(self):
''' Clean up when the connection is closed.
'''
log.info('WebSocket connection closed: code=%s, reason=%r', self.close_code, self.close_reason)
if self.connection is not None:
self.application.client_lost(self.connection) | python | def on_close(self):
''' Clean up when the connection is closed.
'''
log.info('WebSocket connection closed: code=%s, reason=%r', self.close_code, self.close_reason)
if self.connection is not None:
self.application.client_lost(self.connection) | [
"def",
"on_close",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"'WebSocket connection closed: code=%s, reason=%r'",
",",
"self",
".",
"close_code",
",",
"self",
".",
"close_reason",
")",
"if",
"self",
".",
"connection",
"is",
"not",
"None",
":",
"self",
... | Clean up when the connection is closed. | [
"Clean",
"up",
"when",
"the",
"connection",
"is",
"closed",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/views/ws.py#L271-L277 |
30,374 | bokeh/bokeh | bokeh/embed/bundle.py | bundle_for_objs_and_resources | def bundle_for_objs_and_resources(objs, resources):
''' Generate rendered CSS and JS resources suitable for the given
collection of Bokeh objects
Args:
objs (seq[Model or Document]) :
resources (BaseResources or tuple[BaseResources])
Returns:
tuple
'''
if isinstance(resources, BaseResources):
js_resources = css_resources = resources
elif isinstance(resources, tuple) and len(resources) == 2 and all(r is None or isinstance(r, BaseResources) for r in resources):
js_resources, css_resources = resources
if js_resources and not css_resources:
warn('No Bokeh CSS Resources provided to template. If required you will need to provide them manually.')
if css_resources and not js_resources:
warn('No Bokeh JS Resources provided to template. If required you will need to provide them manually.')
else:
raise ValueError("expected Resources or a pair of optional Resources, got %r" % resources)
from copy import deepcopy
# XXX: force all components on server and in notebook, because we don't know in advance what will be used
use_widgets = _use_widgets(objs) if objs else True
use_tables = _use_tables(objs) if objs else True
use_gl = _use_gl(objs) if objs else True
if js_resources:
js_resources = deepcopy(js_resources)
if not use_widgets and "bokeh-widgets" in js_resources.js_components:
js_resources.js_components.remove("bokeh-widgets")
if not use_tables and "bokeh-tables" in js_resources.js_components:
js_resources.js_components.remove("bokeh-tables")
if not use_gl and "bokeh-gl" in js_resources.js_components:
js_resources.js_components.remove("bokeh-gl")
bokeh_js = js_resources.render_js()
else:
bokeh_js = None
models = [ obj.__class__ for obj in _all_objs(objs) ] if objs else None
custom_bundle = bundle_models(models)
if custom_bundle is not None:
custom_bundle = wrap_in_script_tag(custom_bundle)
if bokeh_js is not None:
bokeh_js += "\n" + custom_bundle
else:
bokeh_js = custom_bundle
if css_resources:
css_resources = deepcopy(css_resources)
if not use_widgets and "bokeh-widgets" in css_resources.css_components:
css_resources.css_components.remove("bokeh-widgets")
if not use_tables and "bokeh-tables" in css_resources.css_components:
css_resources.css_components.remove("bokeh-tables")
bokeh_css = css_resources.render_css()
else:
bokeh_css = None
return bokeh_js, bokeh_css | python | def bundle_for_objs_and_resources(objs, resources):
''' Generate rendered CSS and JS resources suitable for the given
collection of Bokeh objects
Args:
objs (seq[Model or Document]) :
resources (BaseResources or tuple[BaseResources])
Returns:
tuple
'''
if isinstance(resources, BaseResources):
js_resources = css_resources = resources
elif isinstance(resources, tuple) and len(resources) == 2 and all(r is None or isinstance(r, BaseResources) for r in resources):
js_resources, css_resources = resources
if js_resources and not css_resources:
warn('No Bokeh CSS Resources provided to template. If required you will need to provide them manually.')
if css_resources and not js_resources:
warn('No Bokeh JS Resources provided to template. If required you will need to provide them manually.')
else:
raise ValueError("expected Resources or a pair of optional Resources, got %r" % resources)
from copy import deepcopy
# XXX: force all components on server and in notebook, because we don't know in advance what will be used
use_widgets = _use_widgets(objs) if objs else True
use_tables = _use_tables(objs) if objs else True
use_gl = _use_gl(objs) if objs else True
if js_resources:
js_resources = deepcopy(js_resources)
if not use_widgets and "bokeh-widgets" in js_resources.js_components:
js_resources.js_components.remove("bokeh-widgets")
if not use_tables and "bokeh-tables" in js_resources.js_components:
js_resources.js_components.remove("bokeh-tables")
if not use_gl and "bokeh-gl" in js_resources.js_components:
js_resources.js_components.remove("bokeh-gl")
bokeh_js = js_resources.render_js()
else:
bokeh_js = None
models = [ obj.__class__ for obj in _all_objs(objs) ] if objs else None
custom_bundle = bundle_models(models)
if custom_bundle is not None:
custom_bundle = wrap_in_script_tag(custom_bundle)
if bokeh_js is not None:
bokeh_js += "\n" + custom_bundle
else:
bokeh_js = custom_bundle
if css_resources:
css_resources = deepcopy(css_resources)
if not use_widgets and "bokeh-widgets" in css_resources.css_components:
css_resources.css_components.remove("bokeh-widgets")
if not use_tables and "bokeh-tables" in css_resources.css_components:
css_resources.css_components.remove("bokeh-tables")
bokeh_css = css_resources.render_css()
else:
bokeh_css = None
return bokeh_js, bokeh_css | [
"def",
"bundle_for_objs_and_resources",
"(",
"objs",
",",
"resources",
")",
":",
"if",
"isinstance",
"(",
"resources",
",",
"BaseResources",
")",
":",
"js_resources",
"=",
"css_resources",
"=",
"resources",
"elif",
"isinstance",
"(",
"resources",
",",
"tuple",
"... | Generate rendered CSS and JS resources suitable for the given
collection of Bokeh objects
Args:
objs (seq[Model or Document]) :
resources (BaseResources or tuple[BaseResources])
Returns:
tuple | [
"Generate",
"rendered",
"CSS",
"and",
"JS",
"resources",
"suitable",
"for",
"the",
"given",
"collection",
"of",
"Bokeh",
"objects"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/bundle.py#L50-L116 |
30,375 | bokeh/bokeh | bokeh/embed/bundle.py | _any | def _any(objs, query):
''' Whether any of a collection of objects satisfies a given query predicate
Args:
objs (seq[Model or Document]) :
query (callable)
Returns:
True, if ``query(obj)`` is True for some object in ``objs``, else False
'''
for obj in objs:
if isinstance(obj, Document):
if _any(obj.roots, query):
return True
else:
if any(query(ref) for ref in obj.references()):
return True
else:
return False | python | def _any(objs, query):
''' Whether any of a collection of objects satisfies a given query predicate
Args:
objs (seq[Model or Document]) :
query (callable)
Returns:
True, if ``query(obj)`` is True for some object in ``objs``, else False
'''
for obj in objs:
if isinstance(obj, Document):
if _any(obj.roots, query):
return True
else:
if any(query(ref) for ref in obj.references()):
return True
else:
return False | [
"def",
"_any",
"(",
"objs",
",",
"query",
")",
":",
"for",
"obj",
"in",
"objs",
":",
"if",
"isinstance",
"(",
"obj",
",",
"Document",
")",
":",
"if",
"_any",
"(",
"obj",
".",
"roots",
",",
"query",
")",
":",
"return",
"True",
"else",
":",
"if",
... | Whether any of a collection of objects satisfies a given query predicate
Args:
objs (seq[Model or Document]) :
query (callable)
Returns:
True, if ``query(obj)`` is True for some object in ``objs``, else False | [
"Whether",
"any",
"of",
"a",
"collection",
"of",
"objects",
"satisfies",
"a",
"given",
"query",
"predicate"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/bundle.py#L134-L154 |
30,376 | bokeh/bokeh | bokeh/embed/bundle.py | _use_gl | def _use_gl(objs):
''' Whether a collection of Bokeh objects contains a plot requesting WebGL
Args:
objs (seq[Model or Document]) :
Returns:
bool
'''
from ..models.plots import Plot
return _any(objs, lambda obj: isinstance(obj, Plot) and obj.output_backend == "webgl") | python | def _use_gl(objs):
''' Whether a collection of Bokeh objects contains a plot requesting WebGL
Args:
objs (seq[Model or Document]) :
Returns:
bool
'''
from ..models.plots import Plot
return _any(objs, lambda obj: isinstance(obj, Plot) and obj.output_backend == "webgl") | [
"def",
"_use_gl",
"(",
"objs",
")",
":",
"from",
".",
".",
"models",
".",
"plots",
"import",
"Plot",
"return",
"_any",
"(",
"objs",
",",
"lambda",
"obj",
":",
"isinstance",
"(",
"obj",
",",
"Plot",
")",
"and",
"obj",
".",
"output_backend",
"==",
"\"w... | Whether a collection of Bokeh objects contains a plot requesting WebGL
Args:
objs (seq[Model or Document]) :
Returns:
bool | [
"Whether",
"a",
"collection",
"of",
"Bokeh",
"objects",
"contains",
"a",
"plot",
"requesting",
"WebGL"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/bundle.py#L156-L167 |
30,377 | bokeh/bokeh | bokeh/embed/bundle.py | _use_tables | def _use_tables(objs):
''' Whether a collection of Bokeh objects contains a TableWidget
Args:
objs (seq[Model or Document]) :
Returns:
bool
'''
from ..models.widgets import TableWidget
return _any(objs, lambda obj: isinstance(obj, TableWidget)) | python | def _use_tables(objs):
''' Whether a collection of Bokeh objects contains a TableWidget
Args:
objs (seq[Model or Document]) :
Returns:
bool
'''
from ..models.widgets import TableWidget
return _any(objs, lambda obj: isinstance(obj, TableWidget)) | [
"def",
"_use_tables",
"(",
"objs",
")",
":",
"from",
".",
".",
"models",
".",
"widgets",
"import",
"TableWidget",
"return",
"_any",
"(",
"objs",
",",
"lambda",
"obj",
":",
"isinstance",
"(",
"obj",
",",
"TableWidget",
")",
")"
] | Whether a collection of Bokeh objects contains a TableWidget
Args:
objs (seq[Model or Document]) :
Returns:
bool | [
"Whether",
"a",
"collection",
"of",
"Bokeh",
"objects",
"contains",
"a",
"TableWidget"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/bundle.py#L169-L180 |
30,378 | bokeh/bokeh | bokeh/embed/bundle.py | _use_widgets | def _use_widgets(objs):
''' Whether a collection of Bokeh objects contains a any Widget
Args:
objs (seq[Model or Document]) :
Returns:
bool
'''
from ..models.widgets import Widget
return _any(objs, lambda obj: isinstance(obj, Widget)) | python | def _use_widgets(objs):
''' Whether a collection of Bokeh objects contains a any Widget
Args:
objs (seq[Model or Document]) :
Returns:
bool
'''
from ..models.widgets import Widget
return _any(objs, lambda obj: isinstance(obj, Widget)) | [
"def",
"_use_widgets",
"(",
"objs",
")",
":",
"from",
".",
".",
"models",
".",
"widgets",
"import",
"Widget",
"return",
"_any",
"(",
"objs",
",",
"lambda",
"obj",
":",
"isinstance",
"(",
"obj",
",",
"Widget",
")",
")"
] | Whether a collection of Bokeh objects contains a any Widget
Args:
objs (seq[Model or Document]) :
Returns:
bool | [
"Whether",
"a",
"collection",
"of",
"Bokeh",
"objects",
"contains",
"a",
"any",
"Widget"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/bundle.py#L182-L193 |
30,379 | bokeh/bokeh | bokeh/core/property/descriptors.py | PropertyDescriptor.add_prop_descriptor_to_class | def add_prop_descriptor_to_class(self, class_name, new_class_attrs, names_with_refs, container_names, dataspecs):
''' ``MetaHasProps`` calls this during class creation as it iterates
over properties to add, to update its registry of new properties.
The parameters passed in are mutable and this function is expected to
update them accordingly.
Args:
class_name (str) :
name of the class this descriptor is added to
new_class_attrs(dict[str, PropertyDescriptor]) :
mapping of attribute names to PropertyDescriptor that this
function will update
names_with_refs (set[str]) :
set of all property names for properties that also have
references, that this function will update
container_names (set[str]) :
set of all property names for properties that are
container props, that this function will update
dataspecs(dict[str, PropertyDescriptor]) :
mapping of attribute names to PropertyDescriptor for DataSpec
properties that this function will update
Return:
None
'''
from .bases import ContainerProperty
from .dataspec import DataSpec
name = self.name
if name in new_class_attrs:
raise RuntimeError("Two property generators both created %s.%s" % (class_name, name))
new_class_attrs[name] = self
if self.has_ref:
names_with_refs.add(name)
if isinstance(self, BasicPropertyDescriptor):
if isinstance(self.property, ContainerProperty):
container_names.add(name)
if isinstance(self.property, DataSpec):
dataspecs[name] = self | python | def add_prop_descriptor_to_class(self, class_name, new_class_attrs, names_with_refs, container_names, dataspecs):
''' ``MetaHasProps`` calls this during class creation as it iterates
over properties to add, to update its registry of new properties.
The parameters passed in are mutable and this function is expected to
update them accordingly.
Args:
class_name (str) :
name of the class this descriptor is added to
new_class_attrs(dict[str, PropertyDescriptor]) :
mapping of attribute names to PropertyDescriptor that this
function will update
names_with_refs (set[str]) :
set of all property names for properties that also have
references, that this function will update
container_names (set[str]) :
set of all property names for properties that are
container props, that this function will update
dataspecs(dict[str, PropertyDescriptor]) :
mapping of attribute names to PropertyDescriptor for DataSpec
properties that this function will update
Return:
None
'''
from .bases import ContainerProperty
from .dataspec import DataSpec
name = self.name
if name in new_class_attrs:
raise RuntimeError("Two property generators both created %s.%s" % (class_name, name))
new_class_attrs[name] = self
if self.has_ref:
names_with_refs.add(name)
if isinstance(self, BasicPropertyDescriptor):
if isinstance(self.property, ContainerProperty):
container_names.add(name)
if isinstance(self.property, DataSpec):
dataspecs[name] = self | [
"def",
"add_prop_descriptor_to_class",
"(",
"self",
",",
"class_name",
",",
"new_class_attrs",
",",
"names_with_refs",
",",
"container_names",
",",
"dataspecs",
")",
":",
"from",
".",
"bases",
"import",
"ContainerProperty",
"from",
".",
"dataspec",
"import",
"DataSp... | ``MetaHasProps`` calls this during class creation as it iterates
over properties to add, to update its registry of new properties.
The parameters passed in are mutable and this function is expected to
update them accordingly.
Args:
class_name (str) :
name of the class this descriptor is added to
new_class_attrs(dict[str, PropertyDescriptor]) :
mapping of attribute names to PropertyDescriptor that this
function will update
names_with_refs (set[str]) :
set of all property names for properties that also have
references, that this function will update
container_names (set[str]) :
set of all property names for properties that are
container props, that this function will update
dataspecs(dict[str, PropertyDescriptor]) :
mapping of attribute names to PropertyDescriptor for DataSpec
properties that this function will update
Return:
None | [
"MetaHasProps",
"calls",
"this",
"during",
"class",
"creation",
"as",
"it",
"iterates",
"over",
"properties",
"to",
"add",
"to",
"update",
"its",
"registry",
"of",
"new",
"properties",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L221-L267 |
30,380 | bokeh/bokeh | bokeh/core/property/descriptors.py | PropertyDescriptor.serializable_value | def serializable_value(self, obj):
''' Produce the value as it should be serialized.
Sometimes it is desirable for the serialized value to differ from
the ``__get__`` in order for the ``__get__`` value to appear simpler
for user or developer convenience.
Args:
obj (HasProps) : the object to get the serialized attribute for
Returns:
JSON-like
'''
value = self.__get__(obj, obj.__class__)
return self.property.serialize_value(value) | python | def serializable_value(self, obj):
''' Produce the value as it should be serialized.
Sometimes it is desirable for the serialized value to differ from
the ``__get__`` in order for the ``__get__`` value to appear simpler
for user or developer convenience.
Args:
obj (HasProps) : the object to get the serialized attribute for
Returns:
JSON-like
'''
value = self.__get__(obj, obj.__class__)
return self.property.serialize_value(value) | [
"def",
"serializable_value",
"(",
"self",
",",
"obj",
")",
":",
"value",
"=",
"self",
".",
"__get__",
"(",
"obj",
",",
"obj",
".",
"__class__",
")",
"return",
"self",
".",
"property",
".",
"serialize_value",
"(",
"value",
")"
] | Produce the value as it should be serialized.
Sometimes it is desirable for the serialized value to differ from
the ``__get__`` in order for the ``__get__`` value to appear simpler
for user or developer convenience.
Args:
obj (HasProps) : the object to get the serialized attribute for
Returns:
JSON-like | [
"Produce",
"the",
"value",
"as",
"it",
"should",
"be",
"serialized",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L281-L296 |
30,381 | bokeh/bokeh | bokeh/core/property/descriptors.py | BasicPropertyDescriptor.instance_default | def instance_default(self, obj):
''' Get the default value that will be used for a specific instance.
Args:
obj (HasProps) : The instance to get the default value for.
Returns:
object
'''
return self.property.themed_default(obj.__class__, self.name, obj.themed_values()) | python | def instance_default(self, obj):
''' Get the default value that will be used for a specific instance.
Args:
obj (HasProps) : The instance to get the default value for.
Returns:
object
'''
return self.property.themed_default(obj.__class__, self.name, obj.themed_values()) | [
"def",
"instance_default",
"(",
"self",
",",
"obj",
")",
":",
"return",
"self",
".",
"property",
".",
"themed_default",
"(",
"obj",
".",
"__class__",
",",
"self",
".",
"name",
",",
"obj",
".",
"themed_values",
"(",
")",
")"
] | Get the default value that will be used for a specific instance.
Args:
obj (HasProps) : The instance to get the default value for.
Returns:
object | [
"Get",
"the",
"default",
"value",
"that",
"will",
"be",
"used",
"for",
"a",
"specific",
"instance",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L577-L587 |
30,382 | bokeh/bokeh | bokeh/core/property/descriptors.py | BasicPropertyDescriptor.trigger_if_changed | def trigger_if_changed(self, obj, old):
''' Send a change event notification if the property is set to a
value is not equal to ``old``.
Args:
obj (HasProps)
The object the property is being set on.
old (obj) :
The previous value of the property to compare
Returns:
None
'''
new_value = self.__get__(obj, obj.__class__)
if not self.property.matches(old, new_value):
self._trigger(obj, old, new_value) | python | def trigger_if_changed(self, obj, old):
''' Send a change event notification if the property is set to a
value is not equal to ``old``.
Args:
obj (HasProps)
The object the property is being set on.
old (obj) :
The previous value of the property to compare
Returns:
None
'''
new_value = self.__get__(obj, obj.__class__)
if not self.property.matches(old, new_value):
self._trigger(obj, old, new_value) | [
"def",
"trigger_if_changed",
"(",
"self",
",",
"obj",
",",
"old",
")",
":",
"new_value",
"=",
"self",
".",
"__get__",
"(",
"obj",
",",
"obj",
".",
"__class__",
")",
"if",
"not",
"self",
".",
"property",
".",
"matches",
"(",
"old",
",",
"new_value",
"... | Send a change event notification if the property is set to a
value is not equal to ``old``.
Args:
obj (HasProps)
The object the property is being set on.
old (obj) :
The previous value of the property to compare
Returns:
None | [
"Send",
"a",
"change",
"event",
"notification",
"if",
"the",
"property",
"is",
"set",
"to",
"a",
"value",
"is",
"not",
"equal",
"to",
"old",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L620-L637 |
30,383 | bokeh/bokeh | bokeh/core/property/descriptors.py | BasicPropertyDescriptor._get | def _get(self, obj):
''' Internal implementation of instance attribute access for the
``BasicPropertyDescriptor`` getter.
If the value has not been explicitly set by a user, return that
value. Otherwise, return the default.
Args:
obj (HasProps) : the instance to get a value of this property for
Returns:
object
Raises:
RuntimeError
If the |HasProps| instance has not yet been initialized, or if
this descriptor is on a class that is not a |HasProps|.
'''
if not hasattr(obj, '_property_values'):
raise RuntimeError("Cannot get a property value '%s' from a %s instance before HasProps.__init__" %
(self.name, obj.__class__.__name__))
if self.name not in obj._property_values:
return self._get_default(obj)
else:
return obj._property_values[self.name] | python | def _get(self, obj):
''' Internal implementation of instance attribute access for the
``BasicPropertyDescriptor`` getter.
If the value has not been explicitly set by a user, return that
value. Otherwise, return the default.
Args:
obj (HasProps) : the instance to get a value of this property for
Returns:
object
Raises:
RuntimeError
If the |HasProps| instance has not yet been initialized, or if
this descriptor is on a class that is not a |HasProps|.
'''
if not hasattr(obj, '_property_values'):
raise RuntimeError("Cannot get a property value '%s' from a %s instance before HasProps.__init__" %
(self.name, obj.__class__.__name__))
if self.name not in obj._property_values:
return self._get_default(obj)
else:
return obj._property_values[self.name] | [
"def",
"_get",
"(",
"self",
",",
"obj",
")",
":",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"'_property_values'",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot get a property value '%s' from a %s instance before HasProps.__init__\"",
"%",
"(",
"self",
".",
"name"... | Internal implementation of instance attribute access for the
``BasicPropertyDescriptor`` getter.
If the value has not been explicitly set by a user, return that
value. Otherwise, return the default.
Args:
obj (HasProps) : the instance to get a value of this property for
Returns:
object
Raises:
RuntimeError
If the |HasProps| instance has not yet been initialized, or if
this descriptor is on a class that is not a |HasProps|. | [
"Internal",
"implementation",
"of",
"instance",
"attribute",
"access",
"for",
"the",
"BasicPropertyDescriptor",
"getter",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L671-L697 |
30,384 | bokeh/bokeh | bokeh/core/property/descriptors.py | BasicPropertyDescriptor._get_default | def _get_default(self, obj):
''' Internal implementation of instance attribute access for default
values.
Handles bookeeping around |PropertyContainer| value, etc.
'''
if self.name in obj._property_values:
# this shouldn't happen because we should have checked before _get_default()
raise RuntimeError("Bokeh internal error, does not handle the case of self.name already in _property_values")
is_themed = obj.themed_values() is not None and self.name in obj.themed_values()
default = self.instance_default(obj)
if is_themed:
unstable_dict = obj._unstable_themed_values
else:
unstable_dict = obj._unstable_default_values
if self.name in unstable_dict:
return unstable_dict[self.name]
if self.property._may_have_unstable_default():
if isinstance(default, PropertyValueContainer):
default._register_owner(obj, self)
unstable_dict[self.name] = default
return default | python | def _get_default(self, obj):
''' Internal implementation of instance attribute access for default
values.
Handles bookeeping around |PropertyContainer| value, etc.
'''
if self.name in obj._property_values:
# this shouldn't happen because we should have checked before _get_default()
raise RuntimeError("Bokeh internal error, does not handle the case of self.name already in _property_values")
is_themed = obj.themed_values() is not None and self.name in obj.themed_values()
default = self.instance_default(obj)
if is_themed:
unstable_dict = obj._unstable_themed_values
else:
unstable_dict = obj._unstable_default_values
if self.name in unstable_dict:
return unstable_dict[self.name]
if self.property._may_have_unstable_default():
if isinstance(default, PropertyValueContainer):
default._register_owner(obj, self)
unstable_dict[self.name] = default
return default | [
"def",
"_get_default",
"(",
"self",
",",
"obj",
")",
":",
"if",
"self",
".",
"name",
"in",
"obj",
".",
"_property_values",
":",
"# this shouldn't happen because we should have checked before _get_default()",
"raise",
"RuntimeError",
"(",
"\"Bokeh internal error, does not ha... | Internal implementation of instance attribute access for default
values.
Handles bookeeping around |PropertyContainer| value, etc. | [
"Internal",
"implementation",
"of",
"instance",
"attribute",
"access",
"for",
"default",
"values",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L699-L727 |
30,385 | bokeh/bokeh | bokeh/core/property/descriptors.py | BasicPropertyDescriptor._real_set | def _real_set(self, obj, old, value, hint=None, setter=None):
''' Internal implementation helper to set property values.
This function handles bookkeeping around noting whether values have
been explicitly set, etc.
Args:
obj (HasProps)
The object the property is being set on.
old (obj) :
The previous value of the property to compare
hint (event hint or None, optional)
An optional update event hint, e.g. ``ColumnStreamedEvent``
(default: None)
Update event hints are usually used at times when better
update performance can be obtained by special-casing in
some way (e.g. streaming or patching column data sources)
setter (ClientSession or ServerSession or None, optional) :
This is used to prevent "boomerang" updates to Bokeh apps.
(default: None)
In the context of a Bokeh server application, incoming updates
to properties will be annotated with the session that is
doing the updating. This value is propagated through any
subsequent change notifications that the update triggers.
The session can compare the event setter to itself, and
suppress any updates that originate from itself.
Returns:
None
'''
# Normally we want a "no-op" if the new value and old value are identical
# but some hinted events are in-place. This check will allow those cases
# to continue on to the notification machinery
if self.property.matches(value, old) and (hint is None):
return
was_set = self.name in obj._property_values
# "old" is the logical old value, but it may not be the actual current
# attribute value if our value was mutated behind our back and we got
# _notify_mutated.
if was_set:
old_attr_value = obj._property_values[self.name]
else:
old_attr_value = old
if old_attr_value is not value:
if isinstance(old_attr_value, PropertyValueContainer):
old_attr_value._unregister_owner(obj, self)
if isinstance(value, PropertyValueContainer):
value._register_owner(obj, self)
if self.name in obj._unstable_themed_values:
del obj._unstable_themed_values[self.name]
if self.name in obj._unstable_default_values:
del obj._unstable_default_values[self.name]
obj._property_values[self.name] = value
# for notification purposes, "old" should be the logical old
self._trigger(obj, old, value, hint=hint, setter=setter) | python | def _real_set(self, obj, old, value, hint=None, setter=None):
''' Internal implementation helper to set property values.
This function handles bookkeeping around noting whether values have
been explicitly set, etc.
Args:
obj (HasProps)
The object the property is being set on.
old (obj) :
The previous value of the property to compare
hint (event hint or None, optional)
An optional update event hint, e.g. ``ColumnStreamedEvent``
(default: None)
Update event hints are usually used at times when better
update performance can be obtained by special-casing in
some way (e.g. streaming or patching column data sources)
setter (ClientSession or ServerSession or None, optional) :
This is used to prevent "boomerang" updates to Bokeh apps.
(default: None)
In the context of a Bokeh server application, incoming updates
to properties will be annotated with the session that is
doing the updating. This value is propagated through any
subsequent change notifications that the update triggers.
The session can compare the event setter to itself, and
suppress any updates that originate from itself.
Returns:
None
'''
# Normally we want a "no-op" if the new value and old value are identical
# but some hinted events are in-place. This check will allow those cases
# to continue on to the notification machinery
if self.property.matches(value, old) and (hint is None):
return
was_set = self.name in obj._property_values
# "old" is the logical old value, but it may not be the actual current
# attribute value if our value was mutated behind our back and we got
# _notify_mutated.
if was_set:
old_attr_value = obj._property_values[self.name]
else:
old_attr_value = old
if old_attr_value is not value:
if isinstance(old_attr_value, PropertyValueContainer):
old_attr_value._unregister_owner(obj, self)
if isinstance(value, PropertyValueContainer):
value._register_owner(obj, self)
if self.name in obj._unstable_themed_values:
del obj._unstable_themed_values[self.name]
if self.name in obj._unstable_default_values:
del obj._unstable_default_values[self.name]
obj._property_values[self.name] = value
# for notification purposes, "old" should be the logical old
self._trigger(obj, old, value, hint=hint, setter=setter) | [
"def",
"_real_set",
"(",
"self",
",",
"obj",
",",
"old",
",",
"value",
",",
"hint",
"=",
"None",
",",
"setter",
"=",
"None",
")",
":",
"# Normally we want a \"no-op\" if the new value and old value are identical",
"# but some hinted events are in-place. This check will allo... | Internal implementation helper to set property values.
This function handles bookkeeping around noting whether values have
been explicitly set, etc.
Args:
obj (HasProps)
The object the property is being set on.
old (obj) :
The previous value of the property to compare
hint (event hint or None, optional)
An optional update event hint, e.g. ``ColumnStreamedEvent``
(default: None)
Update event hints are usually used at times when better
update performance can be obtained by special-casing in
some way (e.g. streaming or patching column data sources)
setter (ClientSession or ServerSession or None, optional) :
This is used to prevent "boomerang" updates to Bokeh apps.
(default: None)
In the context of a Bokeh server application, incoming updates
to properties will be annotated with the session that is
doing the updating. This value is propagated through any
subsequent change notifications that the update triggers.
The session can compare the event setter to itself, and
suppress any updates that originate from itself.
Returns:
None | [
"Internal",
"implementation",
"helper",
"to",
"set",
"property",
"values",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L771-L838 |
30,386 | bokeh/bokeh | bokeh/core/property/descriptors.py | BasicPropertyDescriptor._notify_mutated | def _notify_mutated(self, obj, old, hint=None):
''' A method to call when a container is mutated "behind our back"
and we detect it with our |PropertyContainer| wrappers.
Args:
obj (HasProps) :
The object who's container value was mutated
old (object) :
The "old" value of the container
In this case, somewhat weirdly, ``old`` is a copy and the
new value should already be set unless we change it due to
validation.
hint (event hint or None, optional)
An optional update event hint, e.g. ``ColumnStreamedEvent``
(default: None)
Update event hints are usually used at times when better
update performance can be obtained by special-casing in
some way (e.g. streaming or patching column data sources)
Returns:
None
'''
value = self.__get__(obj, obj.__class__)
# re-validate because the contents of 'old' have changed,
# in some cases this could give us a new object for the value
value = self.property.prepare_value(obj, self.name, value)
self._real_set(obj, old, value, hint=hint) | python | def _notify_mutated(self, obj, old, hint=None):
''' A method to call when a container is mutated "behind our back"
and we detect it with our |PropertyContainer| wrappers.
Args:
obj (HasProps) :
The object who's container value was mutated
old (object) :
The "old" value of the container
In this case, somewhat weirdly, ``old`` is a copy and the
new value should already be set unless we change it due to
validation.
hint (event hint or None, optional)
An optional update event hint, e.g. ``ColumnStreamedEvent``
(default: None)
Update event hints are usually used at times when better
update performance can be obtained by special-casing in
some way (e.g. streaming or patching column data sources)
Returns:
None
'''
value = self.__get__(obj, obj.__class__)
# re-validate because the contents of 'old' have changed,
# in some cases this could give us a new object for the value
value = self.property.prepare_value(obj, self.name, value)
self._real_set(obj, old, value, hint=hint) | [
"def",
"_notify_mutated",
"(",
"self",
",",
"obj",
",",
"old",
",",
"hint",
"=",
"None",
")",
":",
"value",
"=",
"self",
".",
"__get__",
"(",
"obj",
",",
"obj",
".",
"__class__",
")",
"# re-validate because the contents of 'old' have changed,",
"# in some cases ... | A method to call when a container is mutated "behind our back"
and we detect it with our |PropertyContainer| wrappers.
Args:
obj (HasProps) :
The object who's container value was mutated
old (object) :
The "old" value of the container
In this case, somewhat weirdly, ``old`` is a copy and the
new value should already be set unless we change it due to
validation.
hint (event hint or None, optional)
An optional update event hint, e.g. ``ColumnStreamedEvent``
(default: None)
Update event hints are usually used at times when better
update performance can be obtained by special-casing in
some way (e.g. streaming or patching column data sources)
Returns:
None | [
"A",
"method",
"to",
"call",
"when",
"a",
"container",
"is",
"mutated",
"behind",
"our",
"back",
"and",
"we",
"detect",
"it",
"with",
"our",
"|PropertyContainer|",
"wrappers",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L842-L875 |
30,387 | bokeh/bokeh | bokeh/core/property/descriptors.py | BasicPropertyDescriptor._trigger | def _trigger(self, obj, old, value, hint=None, setter=None):
''' Unconditionally send a change event notification for the property.
Args:
obj (HasProps)
The object the property is being set on.
old (obj) :
The previous value of the property
new (obj) :
The new value of the property
hint (event hint or None, optional)
An optional update event hint, e.g. ``ColumnStreamedEvent``
(default: None)
Update event hints are usually used at times when better
update performance can be obtained by special-casing in
some way (e.g. streaming or patching column data sources)
setter (ClientSession or ServerSession or None, optional) :
This is used to prevent "boomerang" updates to Bokeh apps.
(default: None)
In the context of a Bokeh server application, incoming updates
to properties will be annotated with the session that is
doing the updating. This value is propagated through any
subsequent change notifications that the update triggers.
The session can compare the event setter to itself, and
suppress any updates that originate from itself.
Returns:
None
'''
if hasattr(obj, 'trigger'):
obj.trigger(self.name, old, value, hint, setter) | python | def _trigger(self, obj, old, value, hint=None, setter=None):
''' Unconditionally send a change event notification for the property.
Args:
obj (HasProps)
The object the property is being set on.
old (obj) :
The previous value of the property
new (obj) :
The new value of the property
hint (event hint or None, optional)
An optional update event hint, e.g. ``ColumnStreamedEvent``
(default: None)
Update event hints are usually used at times when better
update performance can be obtained by special-casing in
some way (e.g. streaming or patching column data sources)
setter (ClientSession or ServerSession or None, optional) :
This is used to prevent "boomerang" updates to Bokeh apps.
(default: None)
In the context of a Bokeh server application, incoming updates
to properties will be annotated with the session that is
doing the updating. This value is propagated through any
subsequent change notifications that the update triggers.
The session can compare the event setter to itself, and
suppress any updates that originate from itself.
Returns:
None
'''
if hasattr(obj, 'trigger'):
obj.trigger(self.name, old, value, hint, setter) | [
"def",
"_trigger",
"(",
"self",
",",
"obj",
",",
"old",
",",
"value",
",",
"hint",
"=",
"None",
",",
"setter",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'trigger'",
")",
":",
"obj",
".",
"trigger",
"(",
"self",
".",
"name",
",",
... | Unconditionally send a change event notification for the property.
Args:
obj (HasProps)
The object the property is being set on.
old (obj) :
The previous value of the property
new (obj) :
The new value of the property
hint (event hint or None, optional)
An optional update event hint, e.g. ``ColumnStreamedEvent``
(default: None)
Update event hints are usually used at times when better
update performance can be obtained by special-casing in
some way (e.g. streaming or patching column data sources)
setter (ClientSession or ServerSession or None, optional) :
This is used to prevent "boomerang" updates to Bokeh apps.
(default: None)
In the context of a Bokeh server application, incoming updates
to properties will be annotated with the session that is
doing the updating. This value is propagated through any
subsequent change notifications that the update triggers.
The session can compare the event setter to itself, and
suppress any updates that originate from itself.
Returns:
None | [
"Unconditionally",
"send",
"a",
"change",
"event",
"notification",
"for",
"the",
"property",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L877-L915 |
30,388 | bokeh/bokeh | bokeh/core/property/descriptors.py | UnitsSpecPropertyDescriptor._extract_units | def _extract_units(self, obj, value):
''' Internal helper for dealing with units associated units properties
when setting values on |UnitsSpec| properties.
When ``value`` is a dict, this function may mutate the value of the
associated units property.
Args:
obj (HasProps) : instance to update units spec property value for
value (obj) : new value to set for the property
Returns:
copy of ``value``, with 'units' key and value removed when
applicable
'''
if isinstance(value, dict):
if 'units' in value:
value = copy(value) # so we can modify it
units = value.pop("units", None)
if units:
self.units_prop.__set__(obj, units)
return value | python | def _extract_units(self, obj, value):
''' Internal helper for dealing with units associated units properties
when setting values on |UnitsSpec| properties.
When ``value`` is a dict, this function may mutate the value of the
associated units property.
Args:
obj (HasProps) : instance to update units spec property value for
value (obj) : new value to set for the property
Returns:
copy of ``value``, with 'units' key and value removed when
applicable
'''
if isinstance(value, dict):
if 'units' in value:
value = copy(value) # so we can modify it
units = value.pop("units", None)
if units:
self.units_prop.__set__(obj, units)
return value | [
"def",
"_extract_units",
"(",
"self",
",",
"obj",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"if",
"'units'",
"in",
"value",
":",
"value",
"=",
"copy",
"(",
"value",
")",
"# so we can modify it",
"units",
"=",
"val... | Internal helper for dealing with units associated units properties
when setting values on |UnitsSpec| properties.
When ``value`` is a dict, this function may mutate the value of the
associated units property.
Args:
obj (HasProps) : instance to update units spec property value for
value (obj) : new value to set for the property
Returns:
copy of ``value``, with 'units' key and value removed when
applicable | [
"Internal",
"helper",
"for",
"dealing",
"with",
"units",
"associated",
"units",
"properties",
"when",
"setting",
"values",
"on",
"|UnitsSpec|",
"properties",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L1128-L1150 |
30,389 | bokeh/bokeh | bokeh/io/notebook.py | install_notebook_hook | def install_notebook_hook(notebook_type, load, show_doc, show_app, overwrite=False):
''' Install a new notebook display hook.
Bokeh comes with support for Jupyter notebooks built-in. However, there are
other kinds of notebooks in use by different communities. This function
provides a mechanism for other projects to instruct Bokeh how to display
content in other notebooks.
This function is primarily of use to developers wishing to integrate Bokeh
with new notebook types.
Args:
notebook_type (str) :
A name for the notebook type, e.e. ``'Jupyter'`` or ``'Zeppelin'``
If the name has previously been installed, a ``RuntimeError`` will
be raised, unless ``overwrite=True``
load (callable) :
A function for loading BokehJS in a notebook type. The function
will be called with the following arguments:
.. code-block:: python
load(
resources, # A Resources object for how to load BokehJS
verbose, # Whether to display verbose loading banner
hide_banner, # Whether to hide the output banner entirely
load_timeout # Time after which to report a load fail error
)
show_doc (callable) :
A function for displaying Bokeh standalone documents in the
notebook type. This function will be called with the following
arguments:
.. code-block:: python
show_doc(
obj, # the Bokeh object to display
state, # current bokeh.io "state"
notebook_handle # whether a notebook handle was requested
)
If the notebook platform is capable of supporting in-place updates
to plots then this function may return an opaque notebook handle
that can be used for that purpose. The handle will be returned by
``show()``, and can be used by as appropriate to update plots, etc.
by additional functions in the library that installed the hooks.
show_app (callable) :
A function for displaying Bokeh applications in the notebook
type. This function will be called with the following arguments:
.. code-block:: python
show_app(
app, # the Bokeh Application to display
state, # current bokeh.io "state"
notebook_url, # URL to the current active notebook page
**kw # any backend-specific keywords passed as-is
)
overwrite (bool, optional) :
Whether to allow an existing hook to be overwritten by a new
definition (default: False)
Returns:
None
Raises:
RuntimeError
If ``notebook_type`` is already installed and ``overwrite=False``
'''
if notebook_type in _HOOKS and not overwrite:
raise RuntimeError("hook for notebook type %r already exists" % notebook_type)
_HOOKS[notebook_type] = dict(load=load, doc=show_doc, app=show_app) | python | def install_notebook_hook(notebook_type, load, show_doc, show_app, overwrite=False):
''' Install a new notebook display hook.
Bokeh comes with support for Jupyter notebooks built-in. However, there are
other kinds of notebooks in use by different communities. This function
provides a mechanism for other projects to instruct Bokeh how to display
content in other notebooks.
This function is primarily of use to developers wishing to integrate Bokeh
with new notebook types.
Args:
notebook_type (str) :
A name for the notebook type, e.e. ``'Jupyter'`` or ``'Zeppelin'``
If the name has previously been installed, a ``RuntimeError`` will
be raised, unless ``overwrite=True``
load (callable) :
A function for loading BokehJS in a notebook type. The function
will be called with the following arguments:
.. code-block:: python
load(
resources, # A Resources object for how to load BokehJS
verbose, # Whether to display verbose loading banner
hide_banner, # Whether to hide the output banner entirely
load_timeout # Time after which to report a load fail error
)
show_doc (callable) :
A function for displaying Bokeh standalone documents in the
notebook type. This function will be called with the following
arguments:
.. code-block:: python
show_doc(
obj, # the Bokeh object to display
state, # current bokeh.io "state"
notebook_handle # whether a notebook handle was requested
)
If the notebook platform is capable of supporting in-place updates
to plots then this function may return an opaque notebook handle
that can be used for that purpose. The handle will be returned by
``show()``, and can be used by as appropriate to update plots, etc.
by additional functions in the library that installed the hooks.
show_app (callable) :
A function for displaying Bokeh applications in the notebook
type. This function will be called with the following arguments:
.. code-block:: python
show_app(
app, # the Bokeh Application to display
state, # current bokeh.io "state"
notebook_url, # URL to the current active notebook page
**kw # any backend-specific keywords passed as-is
)
overwrite (bool, optional) :
Whether to allow an existing hook to be overwritten by a new
definition (default: False)
Returns:
None
Raises:
RuntimeError
If ``notebook_type`` is already installed and ``overwrite=False``
'''
if notebook_type in _HOOKS and not overwrite:
raise RuntimeError("hook for notebook type %r already exists" % notebook_type)
_HOOKS[notebook_type] = dict(load=load, doc=show_doc, app=show_app) | [
"def",
"install_notebook_hook",
"(",
"notebook_type",
",",
"load",
",",
"show_doc",
",",
"show_app",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"notebook_type",
"in",
"_HOOKS",
"and",
"not",
"overwrite",
":",
"raise",
"RuntimeError",
"(",
"\"hook for notebo... | Install a new notebook display hook.
Bokeh comes with support for Jupyter notebooks built-in. However, there are
other kinds of notebooks in use by different communities. This function
provides a mechanism for other projects to instruct Bokeh how to display
content in other notebooks.
This function is primarily of use to developers wishing to integrate Bokeh
with new notebook types.
Args:
notebook_type (str) :
A name for the notebook type, e.e. ``'Jupyter'`` or ``'Zeppelin'``
If the name has previously been installed, a ``RuntimeError`` will
be raised, unless ``overwrite=True``
load (callable) :
A function for loading BokehJS in a notebook type. The function
will be called with the following arguments:
.. code-block:: python
load(
resources, # A Resources object for how to load BokehJS
verbose, # Whether to display verbose loading banner
hide_banner, # Whether to hide the output banner entirely
load_timeout # Time after which to report a load fail error
)
show_doc (callable) :
A function for displaying Bokeh standalone documents in the
notebook type. This function will be called with the following
arguments:
.. code-block:: python
show_doc(
obj, # the Bokeh object to display
state, # current bokeh.io "state"
notebook_handle # whether a notebook handle was requested
)
If the notebook platform is capable of supporting in-place updates
to plots then this function may return an opaque notebook handle
that can be used for that purpose. The handle will be returned by
``show()``, and can be used by as appropriate to update plots, etc.
by additional functions in the library that installed the hooks.
show_app (callable) :
A function for displaying Bokeh applications in the notebook
type. This function will be called with the following arguments:
.. code-block:: python
show_app(
app, # the Bokeh Application to display
state, # current bokeh.io "state"
notebook_url, # URL to the current active notebook page
**kw # any backend-specific keywords passed as-is
)
overwrite (bool, optional) :
Whether to allow an existing hook to be overwritten by a new
definition (default: False)
Returns:
None
Raises:
RuntimeError
If ``notebook_type`` is already installed and ``overwrite=False`` | [
"Install",
"a",
"new",
"notebook",
"display",
"hook",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/notebook.py#L112-L189 |
30,390 | bokeh/bokeh | bokeh/io/notebook.py | push_notebook | def push_notebook(document=None, state=None, handle=None):
''' Update Bokeh plots in a Jupyter notebook output cells with new data
or property values.
When working the the notebook, the ``show`` function can be passed the
argument ``notebook_handle=True``, which will cause it to return a
handle object that can be used to update the Bokeh output later. When
``push_notebook`` is called, any property updates (e.g. plot titles or
data source values, etc.) since the last call to ``push_notebook`` or
the original ``show`` call are applied to the Bokeh output in the
previously rendered Jupyter output cell.
Several example notebooks can be found in the GitHub repository in
the :bokeh-tree:`examples/howto/notebook_comms` directory.
Args:
document (Document, optional) :
A :class:`~bokeh.document.Document` to push from. If None,
uses ``curdoc()``. (default: None)
state (State, optional) :
A :class:`State` object. If None, then the current default
state (set by ``output_file``, etc.) is used. (default: None)
Returns:
None
Examples:
Typical usage is typically similar to this:
.. code-block:: python
from bokeh.plotting import figure
from bokeh.io import output_notebook, push_notebook, show
output_notebook()
plot = figure()
plot.circle([1,2,3], [4,6,5])
handle = show(plot, notebook_handle=True)
# Update the plot title in the earlier cell
plot.title.text = "New Title"
push_notebook(handle=handle)
'''
from ..protocol import Protocol
if state is None:
state = curstate()
if not document:
document = state.document
if not document:
warn("No document to push")
return
if handle is None:
handle = state.last_comms_handle
if not handle:
warn("Cannot find a last shown plot to update. Call output_notebook() and show(..., notebook_handle=True) before push_notebook()")
return
events = list(handle.doc._held_events)
# This is to avoid having an exception raised for attempting to create a
# PATCH-DOC with no events. In the notebook, we just want to silently
# ignore calls to push_notebook when there are no new events
if len(events) == 0:
return
handle.doc._held_events = []
msg = Protocol("1.0").create("PATCH-DOC", events)
handle.comms.send(msg.header_json)
handle.comms.send(msg.metadata_json)
handle.comms.send(msg.content_json)
for header, payload in msg.buffers:
handle.comms.send(json.dumps(header))
handle.comms.send(buffers=[payload]) | python | def push_notebook(document=None, state=None, handle=None):
''' Update Bokeh plots in a Jupyter notebook output cells with new data
or property values.
When working the the notebook, the ``show`` function can be passed the
argument ``notebook_handle=True``, which will cause it to return a
handle object that can be used to update the Bokeh output later. When
``push_notebook`` is called, any property updates (e.g. plot titles or
data source values, etc.) since the last call to ``push_notebook`` or
the original ``show`` call are applied to the Bokeh output in the
previously rendered Jupyter output cell.
Several example notebooks can be found in the GitHub repository in
the :bokeh-tree:`examples/howto/notebook_comms` directory.
Args:
document (Document, optional) :
A :class:`~bokeh.document.Document` to push from. If None,
uses ``curdoc()``. (default: None)
state (State, optional) :
A :class:`State` object. If None, then the current default
state (set by ``output_file``, etc.) is used. (default: None)
Returns:
None
Examples:
Typical usage is typically similar to this:
.. code-block:: python
from bokeh.plotting import figure
from bokeh.io import output_notebook, push_notebook, show
output_notebook()
plot = figure()
plot.circle([1,2,3], [4,6,5])
handle = show(plot, notebook_handle=True)
# Update the plot title in the earlier cell
plot.title.text = "New Title"
push_notebook(handle=handle)
'''
from ..protocol import Protocol
if state is None:
state = curstate()
if not document:
document = state.document
if not document:
warn("No document to push")
return
if handle is None:
handle = state.last_comms_handle
if not handle:
warn("Cannot find a last shown plot to update. Call output_notebook() and show(..., notebook_handle=True) before push_notebook()")
return
events = list(handle.doc._held_events)
# This is to avoid having an exception raised for attempting to create a
# PATCH-DOC with no events. In the notebook, we just want to silently
# ignore calls to push_notebook when there are no new events
if len(events) == 0:
return
handle.doc._held_events = []
msg = Protocol("1.0").create("PATCH-DOC", events)
handle.comms.send(msg.header_json)
handle.comms.send(msg.metadata_json)
handle.comms.send(msg.content_json)
for header, payload in msg.buffers:
handle.comms.send(json.dumps(header))
handle.comms.send(buffers=[payload]) | [
"def",
"push_notebook",
"(",
"document",
"=",
"None",
",",
"state",
"=",
"None",
",",
"handle",
"=",
"None",
")",
":",
"from",
".",
".",
"protocol",
"import",
"Protocol",
"if",
"state",
"is",
"None",
":",
"state",
"=",
"curstate",
"(",
")",
"if",
"no... | Update Bokeh plots in a Jupyter notebook output cells with new data
or property values.
When working the the notebook, the ``show`` function can be passed the
argument ``notebook_handle=True``, which will cause it to return a
handle object that can be used to update the Bokeh output later. When
``push_notebook`` is called, any property updates (e.g. plot titles or
data source values, etc.) since the last call to ``push_notebook`` or
the original ``show`` call are applied to the Bokeh output in the
previously rendered Jupyter output cell.
Several example notebooks can be found in the GitHub repository in
the :bokeh-tree:`examples/howto/notebook_comms` directory.
Args:
document (Document, optional) :
A :class:`~bokeh.document.Document` to push from. If None,
uses ``curdoc()``. (default: None)
state (State, optional) :
A :class:`State` object. If None, then the current default
state (set by ``output_file``, etc.) is used. (default: None)
Returns:
None
Examples:
Typical usage is typically similar to this:
.. code-block:: python
from bokeh.plotting import figure
from bokeh.io import output_notebook, push_notebook, show
output_notebook()
plot = figure()
plot.circle([1,2,3], [4,6,5])
handle = show(plot, notebook_handle=True)
# Update the plot title in the earlier cell
plot.title.text = "New Title"
push_notebook(handle=handle) | [
"Update",
"Bokeh",
"plots",
"in",
"a",
"Jupyter",
"notebook",
"output",
"cells",
"with",
"new",
"data",
"or",
"property",
"values",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/notebook.py#L191-L275 |
30,391 | bokeh/bokeh | bokeh/io/notebook.py | run_notebook_hook | def run_notebook_hook(notebook_type, action, *args, **kw):
''' Run an installed notebook hook with supplied arguments.
Args:
noteboook_type (str) :
Name of an existing installed notebook hook
actions (str) :
Name of the hook action to execute, ``'doc'`` or ``'app'``
All other arguments and keyword arguments are passed to the hook action
exactly as supplied.
Returns:
Result of the hook action, as-is
Raises:
RuntimeError
If the hook or specific action is not installed
'''
if notebook_type not in _HOOKS:
raise RuntimeError("no display hook installed for notebook type %r" % notebook_type)
if _HOOKS[notebook_type][action] is None:
raise RuntimeError("notebook hook for %r did not install %r action" % notebook_type, action)
return _HOOKS[notebook_type][action](*args, **kw) | python | def run_notebook_hook(notebook_type, action, *args, **kw):
''' Run an installed notebook hook with supplied arguments.
Args:
noteboook_type (str) :
Name of an existing installed notebook hook
actions (str) :
Name of the hook action to execute, ``'doc'`` or ``'app'``
All other arguments and keyword arguments are passed to the hook action
exactly as supplied.
Returns:
Result of the hook action, as-is
Raises:
RuntimeError
If the hook or specific action is not installed
'''
if notebook_type not in _HOOKS:
raise RuntimeError("no display hook installed for notebook type %r" % notebook_type)
if _HOOKS[notebook_type][action] is None:
raise RuntimeError("notebook hook for %r did not install %r action" % notebook_type, action)
return _HOOKS[notebook_type][action](*args, **kw) | [
"def",
"run_notebook_hook",
"(",
"notebook_type",
",",
"action",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"if",
"notebook_type",
"not",
"in",
"_HOOKS",
":",
"raise",
"RuntimeError",
"(",
"\"no display hook installed for notebook type %r\"",
"%",
"notebook_... | Run an installed notebook hook with supplied arguments.
Args:
noteboook_type (str) :
Name of an existing installed notebook hook
actions (str) :
Name of the hook action to execute, ``'doc'`` or ``'app'``
All other arguments and keyword arguments are passed to the hook action
exactly as supplied.
Returns:
Result of the hook action, as-is
Raises:
RuntimeError
If the hook or specific action is not installed | [
"Run",
"an",
"installed",
"notebook",
"hook",
"with",
"supplied",
"arguments",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/notebook.py#L277-L302 |
30,392 | bokeh/bokeh | bokeh/io/notebook.py | destroy_server | def destroy_server(server_id):
''' Given a UUID id of a div removed or replaced in the Jupyter
notebook, destroy the corresponding server sessions and stop it.
'''
server = curstate().uuid_to_server.get(server_id, None)
if server is None:
log.debug("No server instance found for uuid: %r" % server_id)
return
try:
for session in server.get_sessions():
session.destroy()
server.stop()
del curstate().uuid_to_server[server_id]
except Exception as e:
log.debug("Could not destroy server for id %r: %s" % (server_id, e)) | python | def destroy_server(server_id):
''' Given a UUID id of a div removed or replaced in the Jupyter
notebook, destroy the corresponding server sessions and stop it.
'''
server = curstate().uuid_to_server.get(server_id, None)
if server is None:
log.debug("No server instance found for uuid: %r" % server_id)
return
try:
for session in server.get_sessions():
session.destroy()
server.stop()
del curstate().uuid_to_server[server_id]
except Exception as e:
log.debug("Could not destroy server for id %r: %s" % (server_id, e)) | [
"def",
"destroy_server",
"(",
"server_id",
")",
":",
"server",
"=",
"curstate",
"(",
")",
".",
"uuid_to_server",
".",
"get",
"(",
"server_id",
",",
"None",
")",
"if",
"server",
"is",
"None",
":",
"log",
".",
"debug",
"(",
"\"No server instance found for uuid... | Given a UUID id of a div removed or replaced in the Jupyter
notebook, destroy the corresponding server sessions and stop it. | [
"Given",
"a",
"UUID",
"id",
"of",
"a",
"div",
"removed",
"or",
"replaced",
"in",
"the",
"Jupyter",
"notebook",
"destroy",
"the",
"corresponding",
"server",
"sessions",
"and",
"stop",
"it",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/notebook.py#L308-L325 |
30,393 | bokeh/bokeh | bokeh/io/notebook.py | load_notebook | def load_notebook(resources=None, verbose=False, hide_banner=False, load_timeout=5000):
''' Prepare the IPython notebook for displaying Bokeh plots.
Args:
resources (Resource, optional) :
how and where to load BokehJS from (default: CDN)
verbose (bool, optional) :
whether to report detailed settings (default: False)
hide_banner (bool, optional):
whether to hide the Bokeh banner (default: False)
load_timeout (int, optional) :
Timeout in milliseconds when plots assume load timed out (default: 5000)
.. warning::
Clearing the output cell containing the published BokehJS
resources HTML code may cause Bokeh CSS styling to be removed.
Returns:
None
'''
global _NOTEBOOK_LOADED
from .. import __version__
from ..core.templates import NOTEBOOK_LOAD
from ..util.serialization import make_id
from ..resources import CDN
from ..util.compiler import bundle_all_models
if resources is None:
resources = CDN
if not hide_banner:
if resources.mode == 'inline':
js_info = 'inline'
css_info = 'inline'
else:
js_info = resources.js_files[0] if len(resources.js_files) == 1 else resources.js_files
css_info = resources.css_files[0] if len(resources.css_files) == 1 else resources.css_files
warnings = ["Warning: " + msg['text'] for msg in resources.messages if msg['type'] == 'warn']
if _NOTEBOOK_LOADED and verbose:
warnings.append('Warning: BokehJS previously loaded')
element_id = make_id()
html = NOTEBOOK_LOAD.render(
element_id = element_id,
verbose = verbose,
js_info = js_info,
css_info = css_info,
bokeh_version = __version__,
warnings = warnings,
)
else:
element_id = None
_NOTEBOOK_LOADED = resources
custom_models_js = bundle_all_models() or ""
nb_js = _loading_js(resources, element_id, custom_models_js, load_timeout, register_mime=True)
jl_js = _loading_js(resources, element_id, custom_models_js, load_timeout, register_mime=False)
if not hide_banner:
publish_display_data({'text/html': html})
publish_display_data({
JS_MIME_TYPE : nb_js,
LOAD_MIME_TYPE : jl_js
}) | python | def load_notebook(resources=None, verbose=False, hide_banner=False, load_timeout=5000):
''' Prepare the IPython notebook for displaying Bokeh plots.
Args:
resources (Resource, optional) :
how and where to load BokehJS from (default: CDN)
verbose (bool, optional) :
whether to report detailed settings (default: False)
hide_banner (bool, optional):
whether to hide the Bokeh banner (default: False)
load_timeout (int, optional) :
Timeout in milliseconds when plots assume load timed out (default: 5000)
.. warning::
Clearing the output cell containing the published BokehJS
resources HTML code may cause Bokeh CSS styling to be removed.
Returns:
None
'''
global _NOTEBOOK_LOADED
from .. import __version__
from ..core.templates import NOTEBOOK_LOAD
from ..util.serialization import make_id
from ..resources import CDN
from ..util.compiler import bundle_all_models
if resources is None:
resources = CDN
if not hide_banner:
if resources.mode == 'inline':
js_info = 'inline'
css_info = 'inline'
else:
js_info = resources.js_files[0] if len(resources.js_files) == 1 else resources.js_files
css_info = resources.css_files[0] if len(resources.css_files) == 1 else resources.css_files
warnings = ["Warning: " + msg['text'] for msg in resources.messages if msg['type'] == 'warn']
if _NOTEBOOK_LOADED and verbose:
warnings.append('Warning: BokehJS previously loaded')
element_id = make_id()
html = NOTEBOOK_LOAD.render(
element_id = element_id,
verbose = verbose,
js_info = js_info,
css_info = css_info,
bokeh_version = __version__,
warnings = warnings,
)
else:
element_id = None
_NOTEBOOK_LOADED = resources
custom_models_js = bundle_all_models() or ""
nb_js = _loading_js(resources, element_id, custom_models_js, load_timeout, register_mime=True)
jl_js = _loading_js(resources, element_id, custom_models_js, load_timeout, register_mime=False)
if not hide_banner:
publish_display_data({'text/html': html})
publish_display_data({
JS_MIME_TYPE : nb_js,
LOAD_MIME_TYPE : jl_js
}) | [
"def",
"load_notebook",
"(",
"resources",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
"hide_banner",
"=",
"False",
",",
"load_timeout",
"=",
"5000",
")",
":",
"global",
"_NOTEBOOK_LOADED",
"from",
".",
".",
"import",
"__version__",
"from",
".",
".",
"c... | Prepare the IPython notebook for displaying Bokeh plots.
Args:
resources (Resource, optional) :
how and where to load BokehJS from (default: CDN)
verbose (bool, optional) :
whether to report detailed settings (default: False)
hide_banner (bool, optional):
whether to hide the Bokeh banner (default: False)
load_timeout (int, optional) :
Timeout in milliseconds when plots assume load timed out (default: 5000)
.. warning::
Clearing the output cell containing the published BokehJS
resources HTML code may cause Bokeh CSS styling to be removed.
Returns:
None | [
"Prepare",
"the",
"IPython",
"notebook",
"for",
"displaying",
"Bokeh",
"plots",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/notebook.py#L348-L423 |
30,394 | bokeh/bokeh | bokeh/io/notebook.py | show_app | def show_app(app, state, notebook_url, port=0, **kw):
''' Embed a Bokeh server application in a Jupyter Notebook output cell.
Args:
app (Application or callable) :
A Bokeh Application to embed inline in a Jupyter notebook.
state (State) :
** Unused **
notebook_url (str or callable) :
The URL of the notebook server that is running the embedded app.
If ``notebook_url`` is a string, the value string is parsed to
construct the origin and full server URLs.
If notebook_url is a callable, it must accept one parameter,
which will be the server port, or None. If passed a port,
the callable must generate the server URL, otherwise if passed
None, it must generate the origin URL for the server.
port (int) :
A port for the embedded server will listen on.
By default the port is 0, which results in the server listening
on a random dynamic port.
Any additional keyword arguments are passed to :class:`~bokeh.server.Server` (added in version 1.1)
Returns:
None
'''
logging.basicConfig()
from tornado.ioloop import IOLoop
from ..server.server import Server
loop = IOLoop.current()
if callable(notebook_url):
origin = notebook_url(None)
else:
origin = _origin_url(notebook_url)
server = Server({"/": app}, io_loop=loop, port=port, allow_websocket_origin=[origin], **kw)
server_id = uuid4().hex
curstate().uuid_to_server[server_id] = server
server.start()
if callable(notebook_url):
url = notebook_url(server.port)
else:
url = _server_url(notebook_url, server.port)
logging.debug("Server URL is %s" % url)
logging.debug("Origin URL is %s" % origin)
from ..embed import server_document
script = server_document(url, resources=None)
publish_display_data({
HTML_MIME_TYPE: script,
EXEC_MIME_TYPE: ""
}, metadata={
EXEC_MIME_TYPE: {"server_id": server_id}
}) | python | def show_app(app, state, notebook_url, port=0, **kw):
''' Embed a Bokeh server application in a Jupyter Notebook output cell.
Args:
app (Application or callable) :
A Bokeh Application to embed inline in a Jupyter notebook.
state (State) :
** Unused **
notebook_url (str or callable) :
The URL of the notebook server that is running the embedded app.
If ``notebook_url`` is a string, the value string is parsed to
construct the origin and full server URLs.
If notebook_url is a callable, it must accept one parameter,
which will be the server port, or None. If passed a port,
the callable must generate the server URL, otherwise if passed
None, it must generate the origin URL for the server.
port (int) :
A port for the embedded server will listen on.
By default the port is 0, which results in the server listening
on a random dynamic port.
Any additional keyword arguments are passed to :class:`~bokeh.server.Server` (added in version 1.1)
Returns:
None
'''
logging.basicConfig()
from tornado.ioloop import IOLoop
from ..server.server import Server
loop = IOLoop.current()
if callable(notebook_url):
origin = notebook_url(None)
else:
origin = _origin_url(notebook_url)
server = Server({"/": app}, io_loop=loop, port=port, allow_websocket_origin=[origin], **kw)
server_id = uuid4().hex
curstate().uuid_to_server[server_id] = server
server.start()
if callable(notebook_url):
url = notebook_url(server.port)
else:
url = _server_url(notebook_url, server.port)
logging.debug("Server URL is %s" % url)
logging.debug("Origin URL is %s" % origin)
from ..embed import server_document
script = server_document(url, resources=None)
publish_display_data({
HTML_MIME_TYPE: script,
EXEC_MIME_TYPE: ""
}, metadata={
EXEC_MIME_TYPE: {"server_id": server_id}
}) | [
"def",
"show_app",
"(",
"app",
",",
"state",
",",
"notebook_url",
",",
"port",
"=",
"0",
",",
"*",
"*",
"kw",
")",
":",
"logging",
".",
"basicConfig",
"(",
")",
"from",
"tornado",
".",
"ioloop",
"import",
"IOLoop",
"from",
".",
".",
"server",
".",
... | Embed a Bokeh server application in a Jupyter Notebook output cell.
Args:
app (Application or callable) :
A Bokeh Application to embed inline in a Jupyter notebook.
state (State) :
** Unused **
notebook_url (str or callable) :
The URL of the notebook server that is running the embedded app.
If ``notebook_url`` is a string, the value string is parsed to
construct the origin and full server URLs.
If notebook_url is a callable, it must accept one parameter,
which will be the server port, or None. If passed a port,
the callable must generate the server URL, otherwise if passed
None, it must generate the origin URL for the server.
port (int) :
A port for the embedded server will listen on.
By default the port is 0, which results in the server listening
on a random dynamic port.
Any additional keyword arguments are passed to :class:`~bokeh.server.Server` (added in version 1.1)
Returns:
None | [
"Embed",
"a",
"Bokeh",
"server",
"application",
"in",
"a",
"Jupyter",
"Notebook",
"output",
"cell",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/notebook.py#L433-L501 |
30,395 | bokeh/bokeh | bokeh/colors/color.py | Color.clamp | def clamp(value, maximum=None):
''' Clamp numeric values to be non-negative, an optionally, less than a
given maximum.
Args:
value (float) :
A number to clamp.
maximum (float, optional) :
A max bound to to clamp to. If None, there is no upper bound,
and values are only clamped to be non-negative. (default: None)
Returns:
float
'''
value = max(value, 0)
if maximum is not None:
return min(value, maximum)
else:
return value | python | def clamp(value, maximum=None):
''' Clamp numeric values to be non-negative, an optionally, less than a
given maximum.
Args:
value (float) :
A number to clamp.
maximum (float, optional) :
A max bound to to clamp to. If None, there is no upper bound,
and values are only clamped to be non-negative. (default: None)
Returns:
float
'''
value = max(value, 0)
if maximum is not None:
return min(value, maximum)
else:
return value | [
"def",
"clamp",
"(",
"value",
",",
"maximum",
"=",
"None",
")",
":",
"value",
"=",
"max",
"(",
"value",
",",
"0",
")",
"if",
"maximum",
"is",
"not",
"None",
":",
"return",
"min",
"(",
"value",
",",
"maximum",
")",
"else",
":",
"return",
"value"
] | Clamp numeric values to be non-negative, an optionally, less than a
given maximum.
Args:
value (float) :
A number to clamp.
maximum (float, optional) :
A max bound to to clamp to. If None, there is no upper bound,
and values are only clamped to be non-negative. (default: None)
Returns:
float | [
"Clamp",
"numeric",
"values",
"to",
"be",
"non",
"-",
"negative",
"an",
"optionally",
"less",
"than",
"a",
"given",
"maximum",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/colors/color.py#L50-L71 |
30,396 | bokeh/bokeh | bokeh/models/widgets/buttons.py | Dropdown.on_click | def on_click(self, handler):
''' Set up a handler for button or menu item clicks.
Args:
handler (func) : handler function to call when button is activated.
Returns:
None
'''
self.on_event(ButtonClick, handler)
self.on_event(MenuItemClick, handler) | python | def on_click(self, handler):
''' Set up a handler for button or menu item clicks.
Args:
handler (func) : handler function to call when button is activated.
Returns:
None
'''
self.on_event(ButtonClick, handler)
self.on_event(MenuItemClick, handler) | [
"def",
"on_click",
"(",
"self",
",",
"handler",
")",
":",
"self",
".",
"on_event",
"(",
"ButtonClick",
",",
"handler",
")",
"self",
".",
"on_event",
"(",
"MenuItemClick",
",",
"handler",
")"
] | Set up a handler for button or menu item clicks.
Args:
handler (func) : handler function to call when button is activated.
Returns:
None | [
"Set",
"up",
"a",
"handler",
"for",
"button",
"or",
"menu",
"item",
"clicks",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/widgets/buttons.py#L160-L171 |
30,397 | bokeh/bokeh | bokeh/models/widgets/buttons.py | Dropdown.js_on_click | def js_on_click(self, handler):
''' Set up a JavaScript handler for button or menu item clicks. '''
self.js_on_event(ButtonClick, handler)
self.js_on_event(MenuItemClick, handler) | python | def js_on_click(self, handler):
''' Set up a JavaScript handler for button or menu item clicks. '''
self.js_on_event(ButtonClick, handler)
self.js_on_event(MenuItemClick, handler) | [
"def",
"js_on_click",
"(",
"self",
",",
"handler",
")",
":",
"self",
".",
"js_on_event",
"(",
"ButtonClick",
",",
"handler",
")",
"self",
".",
"js_on_event",
"(",
"MenuItemClick",
",",
"handler",
")"
] | Set up a JavaScript handler for button or menu item clicks. | [
"Set",
"up",
"a",
"JavaScript",
"handler",
"for",
"button",
"or",
"menu",
"item",
"clicks",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/widgets/buttons.py#L173-L176 |
30,398 | bokeh/bokeh | bokeh/util/dependencies.py | import_optional | def import_optional(mod_name):
''' Attempt to import an optional dependency.
Silently returns None if the requested module is not available.
Args:
mod_name (str) : name of the optional module to try to import
Returns:
imported module or None, if import fails
'''
try:
return import_module(mod_name)
except ImportError:
pass
except Exception:
msg = "Failed to import optional module `{}`".format(mod_name)
log.exception(msg) | python | def import_optional(mod_name):
''' Attempt to import an optional dependency.
Silently returns None if the requested module is not available.
Args:
mod_name (str) : name of the optional module to try to import
Returns:
imported module or None, if import fails
'''
try:
return import_module(mod_name)
except ImportError:
pass
except Exception:
msg = "Failed to import optional module `{}`".format(mod_name)
log.exception(msg) | [
"def",
"import_optional",
"(",
"mod_name",
")",
":",
"try",
":",
"return",
"import_module",
"(",
"mod_name",
")",
"except",
"ImportError",
":",
"pass",
"except",
"Exception",
":",
"msg",
"=",
"\"Failed to import optional module `{}`\"",
".",
"format",
"(",
"mod_na... | Attempt to import an optional dependency.
Silently returns None if the requested module is not available.
Args:
mod_name (str) : name of the optional module to try to import
Returns:
imported module or None, if import fails | [
"Attempt",
"to",
"import",
"an",
"optional",
"dependency",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/dependencies.py#L50-L68 |
30,399 | bokeh/bokeh | bokeh/util/dependencies.py | detect_phantomjs | def detect_phantomjs(version='2.1'):
''' Detect if PhantomJS is avaiable in PATH, at a minimum version.
Args:
version (str, optional) :
Required minimum version for PhantomJS (mostly for testing)
Returns:
str, path to PhantomJS
'''
if settings.phantomjs_path() is not None:
phantomjs_path = settings.phantomjs_path()
else:
if hasattr(shutil, "which"):
phantomjs_path = shutil.which("phantomjs") or "phantomjs"
else:
# Python 2 relies on Environment variable in PATH - attempt to use as follows
phantomjs_path = "phantomjs"
try:
proc = Popen([phantomjs_path, "--version"], stdout=PIPE, stderr=PIPE)
proc.wait()
out = proc.communicate()
if len(out[1]) > 0:
raise RuntimeError('Error encountered in PhantomJS detection: %r' % out[1].decode('utf8'))
required = V(version)
installed = V(out[0].decode('utf8'))
if installed < required:
raise RuntimeError('PhantomJS version to old. Version>=%s required, installed: %s' % (required, installed))
except OSError:
raise RuntimeError('PhantomJS is not present in PATH or BOKEH_PHANTOMJS_PATH. Try "conda install phantomjs" or \
"npm install -g phantomjs-prebuilt"')
return phantomjs_path | python | def detect_phantomjs(version='2.1'):
''' Detect if PhantomJS is avaiable in PATH, at a minimum version.
Args:
version (str, optional) :
Required minimum version for PhantomJS (mostly for testing)
Returns:
str, path to PhantomJS
'''
if settings.phantomjs_path() is not None:
phantomjs_path = settings.phantomjs_path()
else:
if hasattr(shutil, "which"):
phantomjs_path = shutil.which("phantomjs") or "phantomjs"
else:
# Python 2 relies on Environment variable in PATH - attempt to use as follows
phantomjs_path = "phantomjs"
try:
proc = Popen([phantomjs_path, "--version"], stdout=PIPE, stderr=PIPE)
proc.wait()
out = proc.communicate()
if len(out[1]) > 0:
raise RuntimeError('Error encountered in PhantomJS detection: %r' % out[1].decode('utf8'))
required = V(version)
installed = V(out[0].decode('utf8'))
if installed < required:
raise RuntimeError('PhantomJS version to old. Version>=%s required, installed: %s' % (required, installed))
except OSError:
raise RuntimeError('PhantomJS is not present in PATH or BOKEH_PHANTOMJS_PATH. Try "conda install phantomjs" or \
"npm install -g phantomjs-prebuilt"')
return phantomjs_path | [
"def",
"detect_phantomjs",
"(",
"version",
"=",
"'2.1'",
")",
":",
"if",
"settings",
".",
"phantomjs_path",
"(",
")",
"is",
"not",
"None",
":",
"phantomjs_path",
"=",
"settings",
".",
"phantomjs_path",
"(",
")",
"else",
":",
"if",
"hasattr",
"(",
"shutil",... | Detect if PhantomJS is avaiable in PATH, at a minimum version.
Args:
version (str, optional) :
Required minimum version for PhantomJS (mostly for testing)
Returns:
str, path to PhantomJS | [
"Detect",
"if",
"PhantomJS",
"is",
"avaiable",
"in",
"PATH",
"at",
"a",
"minimum",
"version",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/dependencies.py#L91-L128 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.