repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
bokeh/bokeh | bokeh/driving.py | sine | def sine(w, A=1, phi=0, offset=0):
''' Return a driver function that can advance a sequence of sine values.
.. code-block:: none
value = A * sin(w*i + phi) + offset
Args:
w (float) : a frequency for the sine driver
A (float) : an amplitude for the sine driver
phi (float) : a phase offset to start the sine driver with
offset (float) : a global offset to add to the driver values
'''
from math import sin
def f(i):
return A * sin(w*i + phi) + offset
return partial(force, sequence=_advance(f)) | python | def sine(w, A=1, phi=0, offset=0):
''' Return a driver function that can advance a sequence of sine values.
.. code-block:: none
value = A * sin(w*i + phi) + offset
Args:
w (float) : a frequency for the sine driver
A (float) : an amplitude for the sine driver
phi (float) : a phase offset to start the sine driver with
offset (float) : a global offset to add to the driver values
'''
from math import sin
def f(i):
return A * sin(w*i + phi) + offset
return partial(force, sequence=_advance(f)) | [
"def",
"sine",
"(",
"w",
",",
"A",
"=",
"1",
",",
"phi",
"=",
"0",
",",
"offset",
"=",
"0",
")",
":",
"from",
"math",
"import",
"sin",
"def",
"f",
"(",
"i",
")",
":",
"return",
"A",
"*",
"sin",
"(",
"w",
"*",
"i",
"+",
"phi",
")",
"+",
"offset",
"return",
"partial",
"(",
"force",
",",
"sequence",
"=",
"_advance",
"(",
"f",
")",
")"
] | Return a driver function that can advance a sequence of sine values.
.. code-block:: none
value = A * sin(w*i + phi) + offset
Args:
w (float) : a frequency for the sine driver
A (float) : an amplitude for the sine driver
phi (float) : a phase offset to start the sine driver with
offset (float) : a global offset to add to the driver values | [
"Return",
"a",
"driver",
"function",
"that",
"can",
"advance",
"a",
"sequence",
"of",
"sine",
"values",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/driving.py#L171-L188 | train |
bokeh/bokeh | bokeh/sphinxext/collapsible_code_block.py | setup | def setup(app):
''' Required Sphinx extension setup function. '''
app.add_node(
collapsible_code_block,
html=(
html_visit_collapsible_code_block,
html_depart_collapsible_code_block
)
)
app.add_directive('collapsible-code-block', CollapsibleCodeBlock) | python | def setup(app):
''' Required Sphinx extension setup function. '''
app.add_node(
collapsible_code_block,
html=(
html_visit_collapsible_code_block,
html_depart_collapsible_code_block
)
)
app.add_directive('collapsible-code-block', CollapsibleCodeBlock) | [
"def",
"setup",
"(",
"app",
")",
":",
"app",
".",
"add_node",
"(",
"collapsible_code_block",
",",
"html",
"=",
"(",
"html_visit_collapsible_code_block",
",",
"html_depart_collapsible_code_block",
")",
")",
"app",
".",
"add_directive",
"(",
"'collapsible-code-block'",
",",
"CollapsibleCodeBlock",
")"
] | Required Sphinx extension setup function. | [
"Required",
"Sphinx",
"extension",
"setup",
"function",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/sphinxext/collapsible_code_block.py#L125-L134 | train |
bokeh/bokeh | bokeh/model.py | collect_filtered_models | def collect_filtered_models(discard, *input_values):
''' Collect a duplicate-free list of all other Bokeh models referred to by
this model, or by any of its references, etc, unless filtered-out by the
provided callable.
Iterate over ``input_values`` and descend through their structure
collecting all nested ``Models`` on the go.
Args:
*discard (Callable[[Model], bool])
a callable which accepts a *Model* instance as its single argument
and returns a boolean stating whether to discard the instance. The
latter means that the instance will not be added to collected
models nor will its references be explored.
*input_values (Model)
Bokeh models to collect other models from
Returns:
None
'''
ids = set([])
collected = []
queued = []
def queue_one(obj):
if obj.id not in ids and not (callable(discard) and discard(obj)):
queued.append(obj)
for value in input_values:
_visit_value_and_its_immediate_references(value, queue_one)
while queued:
obj = queued.pop(0)
if obj.id not in ids:
ids.add(obj.id)
collected.append(obj)
_visit_immediate_value_references(obj, queue_one)
return collected | python | def collect_filtered_models(discard, *input_values):
''' Collect a duplicate-free list of all other Bokeh models referred to by
this model, or by any of its references, etc, unless filtered-out by the
provided callable.
Iterate over ``input_values`` and descend through their structure
collecting all nested ``Models`` on the go.
Args:
*discard (Callable[[Model], bool])
a callable which accepts a *Model* instance as its single argument
and returns a boolean stating whether to discard the instance. The
latter means that the instance will not be added to collected
models nor will its references be explored.
*input_values (Model)
Bokeh models to collect other models from
Returns:
None
'''
ids = set([])
collected = []
queued = []
def queue_one(obj):
if obj.id not in ids and not (callable(discard) and discard(obj)):
queued.append(obj)
for value in input_values:
_visit_value_and_its_immediate_references(value, queue_one)
while queued:
obj = queued.pop(0)
if obj.id not in ids:
ids.add(obj.id)
collected.append(obj)
_visit_immediate_value_references(obj, queue_one)
return collected | [
"def",
"collect_filtered_models",
"(",
"discard",
",",
"*",
"input_values",
")",
":",
"ids",
"=",
"set",
"(",
"[",
"]",
")",
"collected",
"=",
"[",
"]",
"queued",
"=",
"[",
"]",
"def",
"queue_one",
"(",
"obj",
")",
":",
"if",
"obj",
".",
"id",
"not",
"in",
"ids",
"and",
"not",
"(",
"callable",
"(",
"discard",
")",
"and",
"discard",
"(",
"obj",
")",
")",
":",
"queued",
".",
"append",
"(",
"obj",
")",
"for",
"value",
"in",
"input_values",
":",
"_visit_value_and_its_immediate_references",
"(",
"value",
",",
"queue_one",
")",
"while",
"queued",
":",
"obj",
"=",
"queued",
".",
"pop",
"(",
"0",
")",
"if",
"obj",
".",
"id",
"not",
"in",
"ids",
":",
"ids",
".",
"add",
"(",
"obj",
".",
"id",
")",
"collected",
".",
"append",
"(",
"obj",
")",
"_visit_immediate_value_references",
"(",
"obj",
",",
"queue_one",
")",
"return",
"collected"
] | Collect a duplicate-free list of all other Bokeh models referred to by
this model, or by any of its references, etc, unless filtered-out by the
provided callable.
Iterate over ``input_values`` and descend through their structure
collecting all nested ``Models`` on the go.
Args:
*discard (Callable[[Model], bool])
a callable which accepts a *Model* instance as its single argument
and returns a boolean stating whether to discard the instance. The
latter means that the instance will not be added to collected
models nor will its references be explored.
*input_values (Model)
Bokeh models to collect other models from
Returns:
None | [
"Collect",
"a",
"duplicate",
"-",
"free",
"list",
"of",
"all",
"other",
"Bokeh",
"models",
"referred",
"to",
"by",
"this",
"model",
"or",
"by",
"any",
"of",
"its",
"references",
"etc",
"unless",
"filtered",
"-",
"out",
"by",
"the",
"provided",
"callable",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/model.py#L62-L103 | train |
bokeh/bokeh | bokeh/model.py | get_class | def get_class(view_model_name):
''' Look up a Bokeh model class, given its view model name.
Args:
view_model_name (str) :
A view model name for a Bokeh model to look up
Returns:
Model: the model class corresponding to ``view_model_name``
Raises:
KeyError, if the model cannot be found
Example:
.. code-block:: python
>>> from bokeh.model import get_class
>>> get_class("Range1d")
<class 'bokeh.models.ranges.Range1d'>
'''
# in order to look up from the model catalog that MetaModel maintains, it
# has to be creates first. These imports ensure that all built-in Bokeh
# models are represented in the catalog.
from . import models; models
from .plotting import Figure; Figure
d = MetaModel.model_class_reverse_map
if view_model_name in d:
return d[view_model_name]
else:
raise KeyError("View model name '%s' not found" % view_model_name) | python | def get_class(view_model_name):
''' Look up a Bokeh model class, given its view model name.
Args:
view_model_name (str) :
A view model name for a Bokeh model to look up
Returns:
Model: the model class corresponding to ``view_model_name``
Raises:
KeyError, if the model cannot be found
Example:
.. code-block:: python
>>> from bokeh.model import get_class
>>> get_class("Range1d")
<class 'bokeh.models.ranges.Range1d'>
'''
# in order to look up from the model catalog that MetaModel maintains, it
# has to be creates first. These imports ensure that all built-in Bokeh
# models are represented in the catalog.
from . import models; models
from .plotting import Figure; Figure
d = MetaModel.model_class_reverse_map
if view_model_name in d:
return d[view_model_name]
else:
raise KeyError("View model name '%s' not found" % view_model_name) | [
"def",
"get_class",
"(",
"view_model_name",
")",
":",
"# in order to look up from the model catalog that MetaModel maintains, it",
"# has to be creates first. These imports ensure that all built-in Bokeh",
"# models are represented in the catalog.",
"from",
".",
"import",
"models",
"models",
"from",
".",
"plotting",
"import",
"Figure",
"Figure",
"d",
"=",
"MetaModel",
".",
"model_class_reverse_map",
"if",
"view_model_name",
"in",
"d",
":",
"return",
"d",
"[",
"view_model_name",
"]",
"else",
":",
"raise",
"KeyError",
"(",
"\"View model name '%s' not found\"",
"%",
"view_model_name",
")"
] | Look up a Bokeh model class, given its view model name.
Args:
view_model_name (str) :
A view model name for a Bokeh model to look up
Returns:
Model: the model class corresponding to ``view_model_name``
Raises:
KeyError, if the model cannot be found
Example:
.. code-block:: python
>>> from bokeh.model import get_class
>>> get_class("Range1d")
<class 'bokeh.models.ranges.Range1d'> | [
"Look",
"up",
"a",
"Bokeh",
"model",
"class",
"given",
"its",
"view",
"model",
"name",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/model.py#L123-L156 | train |
bokeh/bokeh | bokeh/model.py | _visit_immediate_value_references | def _visit_immediate_value_references(value, visitor):
''' Visit all references to another Model without recursing into any
of the child Model; may visit the same Model more than once if
it's referenced more than once. Does not visit the passed-in value.
'''
if isinstance(value, HasProps):
for attr in value.properties_with_refs():
child = getattr(value, attr)
_visit_value_and_its_immediate_references(child, visitor)
else:
_visit_value_and_its_immediate_references(value, visitor) | python | def _visit_immediate_value_references(value, visitor):
''' Visit all references to another Model without recursing into any
of the child Model; may visit the same Model more than once if
it's referenced more than once. Does not visit the passed-in value.
'''
if isinstance(value, HasProps):
for attr in value.properties_with_refs():
child = getattr(value, attr)
_visit_value_and_its_immediate_references(child, visitor)
else:
_visit_value_and_its_immediate_references(value, visitor) | [
"def",
"_visit_immediate_value_references",
"(",
"value",
",",
"visitor",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"HasProps",
")",
":",
"for",
"attr",
"in",
"value",
".",
"properties_with_refs",
"(",
")",
":",
"child",
"=",
"getattr",
"(",
"value",
",",
"attr",
")",
"_visit_value_and_its_immediate_references",
"(",
"child",
",",
"visitor",
")",
"else",
":",
"_visit_value_and_its_immediate_references",
"(",
"value",
",",
"visitor",
")"
] | Visit all references to another Model without recursing into any
of the child Model; may visit the same Model more than once if
it's referenced more than once. Does not visit the passed-in value. | [
"Visit",
"all",
"references",
"to",
"another",
"Model",
"without",
"recursing",
"into",
"any",
"of",
"the",
"child",
"Model",
";",
"may",
"visit",
"the",
"same",
"Model",
"more",
"than",
"once",
"if",
"it",
"s",
"referenced",
"more",
"than",
"once",
".",
"Does",
"not",
"visit",
"the",
"passed",
"-",
"in",
"value",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/model.py#L822-L833 | train |
bokeh/bokeh | bokeh/model.py | _visit_value_and_its_immediate_references | def _visit_value_and_its_immediate_references(obj, visitor):
''' Recurse down Models, HasProps, and Python containers
The ordering in this function is to optimize performance. We check the
most comomn types (int, float, str) first so that we can quickly return in
the common case. We avoid isinstance and issubclass checks in a couple
places with `type` checks because isinstance checks can be slow.
'''
typ = type(obj)
if typ in _common_types: # short circuit on common base types
return
if typ is list or issubclass(typ, (list, tuple)): # check common containers
for item in obj:
_visit_value_and_its_immediate_references(item, visitor)
elif issubclass(typ, dict):
for key, value in iteritems(obj):
_visit_value_and_its_immediate_references(key, visitor)
_visit_value_and_its_immediate_references(value, visitor)
elif issubclass(typ, HasProps):
if issubclass(typ, Model):
visitor(obj)
else:
# this isn't a Model, so recurse into it
_visit_immediate_value_references(obj, visitor) | python | def _visit_value_and_its_immediate_references(obj, visitor):
''' Recurse down Models, HasProps, and Python containers
The ordering in this function is to optimize performance. We check the
most comomn types (int, float, str) first so that we can quickly return in
the common case. We avoid isinstance and issubclass checks in a couple
places with `type` checks because isinstance checks can be slow.
'''
typ = type(obj)
if typ in _common_types: # short circuit on common base types
return
if typ is list or issubclass(typ, (list, tuple)): # check common containers
for item in obj:
_visit_value_and_its_immediate_references(item, visitor)
elif issubclass(typ, dict):
for key, value in iteritems(obj):
_visit_value_and_its_immediate_references(key, visitor)
_visit_value_and_its_immediate_references(value, visitor)
elif issubclass(typ, HasProps):
if issubclass(typ, Model):
visitor(obj)
else:
# this isn't a Model, so recurse into it
_visit_immediate_value_references(obj, visitor) | [
"def",
"_visit_value_and_its_immediate_references",
"(",
"obj",
",",
"visitor",
")",
":",
"typ",
"=",
"type",
"(",
"obj",
")",
"if",
"typ",
"in",
"_common_types",
":",
"# short circuit on common base types",
"return",
"if",
"typ",
"is",
"list",
"or",
"issubclass",
"(",
"typ",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"# check common containers",
"for",
"item",
"in",
"obj",
":",
"_visit_value_and_its_immediate_references",
"(",
"item",
",",
"visitor",
")",
"elif",
"issubclass",
"(",
"typ",
",",
"dict",
")",
":",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"obj",
")",
":",
"_visit_value_and_its_immediate_references",
"(",
"key",
",",
"visitor",
")",
"_visit_value_and_its_immediate_references",
"(",
"value",
",",
"visitor",
")",
"elif",
"issubclass",
"(",
"typ",
",",
"HasProps",
")",
":",
"if",
"issubclass",
"(",
"typ",
",",
"Model",
")",
":",
"visitor",
"(",
"obj",
")",
"else",
":",
"# this isn't a Model, so recurse into it",
"_visit_immediate_value_references",
"(",
"obj",
",",
"visitor",
")"
] | Recurse down Models, HasProps, and Python containers
The ordering in this function is to optimize performance. We check the
most comomn types (int, float, str) first so that we can quickly return in
the common case. We avoid isinstance and issubclass checks in a couple
places with `type` checks because isinstance checks can be slow. | [
"Recurse",
"down",
"Models",
"HasProps",
"and",
"Python",
"containers"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/model.py#L838-L861 | train |
bokeh/bokeh | bokeh/model.py | Model.ref | def ref(self):
''' A Bokeh protocol "reference" to this model, i.e. a dict of the
form:
.. code-block:: python
{
'type' : << view model name >>
'id' : << unique model id >>
}
Additionally there may be a `subtype` field if this model is a subtype.
'''
if "__subtype__" in self.__class__.__dict__:
return {
'type' : self.__view_model__,
'subtype' : self.__subtype__,
'id' : self.id,
}
else:
return {
'type' : self.__view_model__,
'id' : self.id,
} | python | def ref(self):
''' A Bokeh protocol "reference" to this model, i.e. a dict of the
form:
.. code-block:: python
{
'type' : << view model name >>
'id' : << unique model id >>
}
Additionally there may be a `subtype` field if this model is a subtype.
'''
if "__subtype__" in self.__class__.__dict__:
return {
'type' : self.__view_model__,
'subtype' : self.__subtype__,
'id' : self.id,
}
else:
return {
'type' : self.__view_model__,
'id' : self.id,
} | [
"def",
"ref",
"(",
"self",
")",
":",
"if",
"\"__subtype__\"",
"in",
"self",
".",
"__class__",
".",
"__dict__",
":",
"return",
"{",
"'type'",
":",
"self",
".",
"__view_model__",
",",
"'subtype'",
":",
"self",
".",
"__subtype__",
",",
"'id'",
":",
"self",
".",
"id",
",",
"}",
"else",
":",
"return",
"{",
"'type'",
":",
"self",
".",
"__view_model__",
",",
"'id'",
":",
"self",
".",
"id",
",",
"}"
] | A Bokeh protocol "reference" to this model, i.e. a dict of the
form:
.. code-block:: python
{
'type' : << view model name >>
'id' : << unique model id >>
}
Additionally there may be a `subtype` field if this model is a subtype. | [
"A",
"Bokeh",
"protocol",
"reference",
"to",
"this",
"model",
"i",
".",
"e",
".",
"a",
"dict",
"of",
"the",
"form",
":"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/model.py#L407-L431 | train |
bokeh/bokeh | bokeh/model.py | Model.js_link | def js_link(self, attr, other, other_attr):
''' Link two Bokeh model properties using JavaScript.
This is a convenience method that simplifies adding a CustomJS callback
to update one Bokeh model property whenever another changes value.
Args:
attr (str) :
The name of a Bokeh property on this model
other (Model):
A Bokeh model to link to self.attr
other_attr (str) :
The property on ``other`` to link together
Added in version 1.1
Raises:
ValueError
Examples:
This code with ``js_link``:
.. code :: python
select.js_link('value', plot, 'sizing_mode')
is equivalent to the following:
.. code:: python
from bokeh.models import CustomJS
select.js_on_change('value',
CustomJS(args=dict(other=plot),
code="other.sizing_mode = this.value"
)
)
'''
if attr not in self.properties():
raise ValueError("%r is not a property of self (%r)" % (attr, self))
if not isinstance(other, Model):
raise ValueError("'other' is not a Bokeh model: %r" % other)
if other_attr not in other.properties():
raise ValueError("%r is not a property of other (%r)" % (other_attr, other))
from bokeh.models.callbacks import CustomJS
cb = CustomJS(args=dict(other=other), code="other.%s = this.%s" % (other_attr, attr))
self.js_on_change(attr, cb) | python | def js_link(self, attr, other, other_attr):
''' Link two Bokeh model properties using JavaScript.
This is a convenience method that simplifies adding a CustomJS callback
to update one Bokeh model property whenever another changes value.
Args:
attr (str) :
The name of a Bokeh property on this model
other (Model):
A Bokeh model to link to self.attr
other_attr (str) :
The property on ``other`` to link together
Added in version 1.1
Raises:
ValueError
Examples:
This code with ``js_link``:
.. code :: python
select.js_link('value', plot, 'sizing_mode')
is equivalent to the following:
.. code:: python
from bokeh.models import CustomJS
select.js_on_change('value',
CustomJS(args=dict(other=plot),
code="other.sizing_mode = this.value"
)
)
'''
if attr not in self.properties():
raise ValueError("%r is not a property of self (%r)" % (attr, self))
if not isinstance(other, Model):
raise ValueError("'other' is not a Bokeh model: %r" % other)
if other_attr not in other.properties():
raise ValueError("%r is not a property of other (%r)" % (other_attr, other))
from bokeh.models.callbacks import CustomJS
cb = CustomJS(args=dict(other=other), code="other.%s = this.%s" % (other_attr, attr))
self.js_on_change(attr, cb) | [
"def",
"js_link",
"(",
"self",
",",
"attr",
",",
"other",
",",
"other_attr",
")",
":",
"if",
"attr",
"not",
"in",
"self",
".",
"properties",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"%r is not a property of self (%r)\"",
"%",
"(",
"attr",
",",
"self",
")",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"Model",
")",
":",
"raise",
"ValueError",
"(",
"\"'other' is not a Bokeh model: %r\"",
"%",
"other",
")",
"if",
"other_attr",
"not",
"in",
"other",
".",
"properties",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"%r is not a property of other (%r)\"",
"%",
"(",
"other_attr",
",",
"other",
")",
")",
"from",
"bokeh",
".",
"models",
".",
"callbacks",
"import",
"CustomJS",
"cb",
"=",
"CustomJS",
"(",
"args",
"=",
"dict",
"(",
"other",
"=",
"other",
")",
",",
"code",
"=",
"\"other.%s = this.%s\"",
"%",
"(",
"other_attr",
",",
"attr",
")",
")",
"self",
".",
"js_on_change",
"(",
"attr",
",",
"cb",
")"
] | Link two Bokeh model properties using JavaScript.
This is a convenience method that simplifies adding a CustomJS callback
to update one Bokeh model property whenever another changes value.
Args:
attr (str) :
The name of a Bokeh property on this model
other (Model):
A Bokeh model to link to self.attr
other_attr (str) :
The property on ``other`` to link together
Added in version 1.1
Raises:
ValueError
Examples:
This code with ``js_link``:
.. code :: python
select.js_link('value', plot, 'sizing_mode')
is equivalent to the following:
.. code:: python
from bokeh.models import CustomJS
select.js_on_change('value',
CustomJS(args=dict(other=plot),
code="other.sizing_mode = this.value"
)
) | [
"Link",
"two",
"Bokeh",
"model",
"properties",
"using",
"JavaScript",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/model.py#L449-L504 | train |
bokeh/bokeh | bokeh/model.py | Model.js_on_change | def js_on_change(self, event, *callbacks):
''' Attach a ``CustomJS`` callback to an arbitrary BokehJS model event.
On the BokehJS side, change events for model properties have the
form ``"change:property_name"``. As a convenience, if the event name
passed to this method is also the name of a property on the model,
then it will be prefixed with ``"change:"`` automatically:
.. code:: python
# these two are equivalent
source.js_on_change('data', callback)
source.js_on_change('change:data', callback)
However, there are other kinds of events that can be useful to respond
to, in addition to property change events. For example to run a
callback whenever data is streamed to a ``ColumnDataSource``, use the
``"stream"`` event on the source:
.. code:: python
source.js_on_change('streaming', callback)
'''
if len(callbacks) == 0:
raise ValueError("js_on_change takes an event name and one or more callbacks, got only one parameter")
# handle any CustomJS callbacks here
from bokeh.models.callbacks import CustomJS
if not all(isinstance(x, CustomJS) for x in callbacks):
raise ValueError("not all callback values are CustomJS instances")
if event in self.properties():
event = "change:%s" % event
if event not in self.js_property_callbacks:
self.js_property_callbacks[event] = []
for callback in callbacks:
if callback in self.js_property_callbacks[event]:
continue
self.js_property_callbacks[event].append(callback) | python | def js_on_change(self, event, *callbacks):
''' Attach a ``CustomJS`` callback to an arbitrary BokehJS model event.
On the BokehJS side, change events for model properties have the
form ``"change:property_name"``. As a convenience, if the event name
passed to this method is also the name of a property on the model,
then it will be prefixed with ``"change:"`` automatically:
.. code:: python
# these two are equivalent
source.js_on_change('data', callback)
source.js_on_change('change:data', callback)
However, there are other kinds of events that can be useful to respond
to, in addition to property change events. For example to run a
callback whenever data is streamed to a ``ColumnDataSource``, use the
``"stream"`` event on the source:
.. code:: python
source.js_on_change('streaming', callback)
'''
if len(callbacks) == 0:
raise ValueError("js_on_change takes an event name and one or more callbacks, got only one parameter")
# handle any CustomJS callbacks here
from bokeh.models.callbacks import CustomJS
if not all(isinstance(x, CustomJS) for x in callbacks):
raise ValueError("not all callback values are CustomJS instances")
if event in self.properties():
event = "change:%s" % event
if event not in self.js_property_callbacks:
self.js_property_callbacks[event] = []
for callback in callbacks:
if callback in self.js_property_callbacks[event]:
continue
self.js_property_callbacks[event].append(callback) | [
"def",
"js_on_change",
"(",
"self",
",",
"event",
",",
"*",
"callbacks",
")",
":",
"if",
"len",
"(",
"callbacks",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"js_on_change takes an event name and one or more callbacks, got only one parameter\"",
")",
"# handle any CustomJS callbacks here",
"from",
"bokeh",
".",
"models",
".",
"callbacks",
"import",
"CustomJS",
"if",
"not",
"all",
"(",
"isinstance",
"(",
"x",
",",
"CustomJS",
")",
"for",
"x",
"in",
"callbacks",
")",
":",
"raise",
"ValueError",
"(",
"\"not all callback values are CustomJS instances\"",
")",
"if",
"event",
"in",
"self",
".",
"properties",
"(",
")",
":",
"event",
"=",
"\"change:%s\"",
"%",
"event",
"if",
"event",
"not",
"in",
"self",
".",
"js_property_callbacks",
":",
"self",
".",
"js_property_callbacks",
"[",
"event",
"]",
"=",
"[",
"]",
"for",
"callback",
"in",
"callbacks",
":",
"if",
"callback",
"in",
"self",
".",
"js_property_callbacks",
"[",
"event",
"]",
":",
"continue",
"self",
".",
"js_property_callbacks",
"[",
"event",
"]",
".",
"append",
"(",
"callback",
")"
] | Attach a ``CustomJS`` callback to an arbitrary BokehJS model event.
On the BokehJS side, change events for model properties have the
form ``"change:property_name"``. As a convenience, if the event name
passed to this method is also the name of a property on the model,
then it will be prefixed with ``"change:"`` automatically:
.. code:: python
# these two are equivalent
source.js_on_change('data', callback)
source.js_on_change('change:data', callback)
However, there are other kinds of events that can be useful to respond
to, in addition to property change events. For example to run a
callback whenever data is streamed to a ``ColumnDataSource``, use the
``"stream"`` event on the source:
.. code:: python
source.js_on_change('streaming', callback) | [
"Attach",
"a",
"CustomJS",
"callback",
"to",
"an",
"arbitrary",
"BokehJS",
"model",
"event",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/model.py#L506-L546 | train |
bokeh/bokeh | bokeh/model.py | Model.on_change | def on_change(self, attr, *callbacks):
''' Add a callback on this object to trigger when ``attr`` changes.
Args:
attr (str) : an attribute name on this object
*callbacks (callable) : callback functions to register
Returns:
None
Example:
.. code-block:: python
widget.on_change('value', callback1, callback2, ..., callback_n)
'''
if attr not in self.properties():
raise ValueError("attempted to add a callback on nonexistent %s.%s property" % (self.__class__.__name__, attr))
super(Model, self).on_change(attr, *callbacks) | python | def on_change(self, attr, *callbacks):
''' Add a callback on this object to trigger when ``attr`` changes.
Args:
attr (str) : an attribute name on this object
*callbacks (callable) : callback functions to register
Returns:
None
Example:
.. code-block:: python
widget.on_change('value', callback1, callback2, ..., callback_n)
'''
if attr not in self.properties():
raise ValueError("attempted to add a callback on nonexistent %s.%s property" % (self.__class__.__name__, attr))
super(Model, self).on_change(attr, *callbacks) | [
"def",
"on_change",
"(",
"self",
",",
"attr",
",",
"*",
"callbacks",
")",
":",
"if",
"attr",
"not",
"in",
"self",
".",
"properties",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"attempted to add a callback on nonexistent %s.%s property\"",
"%",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"attr",
")",
")",
"super",
"(",
"Model",
",",
"self",
")",
".",
"on_change",
"(",
"attr",
",",
"*",
"callbacks",
")"
] | Add a callback on this object to trigger when ``attr`` changes.
Args:
attr (str) : an attribute name on this object
*callbacks (callable) : callback functions to register
Returns:
None
Example:
.. code-block:: python
widget.on_change('value', callback1, callback2, ..., callback_n) | [
"Add",
"a",
"callback",
"on",
"this",
"object",
"to",
"trigger",
"when",
"attr",
"changes",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/model.py#L557-L576 | train |
bokeh/bokeh | bokeh/model.py | Model.set_select | def set_select(self, selector, updates):
''' Update objects that match a given selector with the specified
attribute/value updates.
Args:
selector (JSON-like) :
updates (dict) :
Returns:
None
'''
for obj in self.select(selector):
for key, val in updates.items():
setattr(obj, key, val) | python | def set_select(self, selector, updates):
''' Update objects that match a given selector with the specified
attribute/value updates.
Args:
selector (JSON-like) :
updates (dict) :
Returns:
None
'''
for obj in self.select(selector):
for key, val in updates.items():
setattr(obj, key, val) | [
"def",
"set_select",
"(",
"self",
",",
"selector",
",",
"updates",
")",
":",
"for",
"obj",
"in",
"self",
".",
"select",
"(",
"selector",
")",
":",
"for",
"key",
",",
"val",
"in",
"updates",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"obj",
",",
"key",
",",
"val",
")"
] | Update objects that match a given selector with the specified
attribute/value updates.
Args:
selector (JSON-like) :
updates (dict) :
Returns:
None | [
"Update",
"objects",
"that",
"match",
"a",
"given",
"selector",
"with",
"the",
"specified",
"attribute",
"/",
"value",
"updates",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/model.py#L614-L628 | train |
bokeh/bokeh | bokeh/model.py | Model.to_json_string | def to_json_string(self, include_defaults):
''' Returns a JSON string encoding the attributes of this object.
References to other objects are serialized as references
(just the object ID and type info), so the deserializer
will need to separately have the full attributes of those
other objects.
There's no corresponding ``from_json_string()`` because to
deserialize an object is normally done in the context of a
Document (since the Document can resolve references).
For most purposes it's best to serialize and deserialize
entire documents.
Args:
include_defaults (bool) : whether to include attributes
that haven't been changed from the default
'''
json_like = self._to_json_like(include_defaults=include_defaults)
json_like['id'] = self.id
# serialize_json "fixes" the JSON from _to_json_like by converting
# all types into plain JSON types # (it converts Model into refs,
# for example).
return serialize_json(json_like) | python | def to_json_string(self, include_defaults):
''' Returns a JSON string encoding the attributes of this object.
References to other objects are serialized as references
(just the object ID and type info), so the deserializer
will need to separately have the full attributes of those
other objects.
There's no corresponding ``from_json_string()`` because to
deserialize an object is normally done in the context of a
Document (since the Document can resolve references).
For most purposes it's best to serialize and deserialize
entire documents.
Args:
include_defaults (bool) : whether to include attributes
that haven't been changed from the default
'''
json_like = self._to_json_like(include_defaults=include_defaults)
json_like['id'] = self.id
# serialize_json "fixes" the JSON from _to_json_like by converting
# all types into plain JSON types # (it converts Model into refs,
# for example).
return serialize_json(json_like) | [
"def",
"to_json_string",
"(",
"self",
",",
"include_defaults",
")",
":",
"json_like",
"=",
"self",
".",
"_to_json_like",
"(",
"include_defaults",
"=",
"include_defaults",
")",
"json_like",
"[",
"'id'",
"]",
"=",
"self",
".",
"id",
"# serialize_json \"fixes\" the JSON from _to_json_like by converting",
"# all types into plain JSON types # (it converts Model into refs,",
"# for example).",
"return",
"serialize_json",
"(",
"json_like",
")"
] | Returns a JSON string encoding the attributes of this object.
References to other objects are serialized as references
(just the object ID and type info), so the deserializer
will need to separately have the full attributes of those
other objects.
There's no corresponding ``from_json_string()`` because to
deserialize an object is normally done in the context of a
Document (since the Document can resolve references).
For most purposes it's best to serialize and deserialize
entire documents.
Args:
include_defaults (bool) : whether to include attributes
that haven't been changed from the default | [
"Returns",
"a",
"JSON",
"string",
"encoding",
"the",
"attributes",
"of",
"this",
"object",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/model.py#L654-L679 | train |
bokeh/bokeh | bokeh/model.py | Model._attach_document | def _attach_document(self, doc):
''' Attach a model to a Bokeh |Document|.
This private interface should only ever called by the Document
implementation to set the private ._document field properly
'''
if self._document is not None and self._document is not doc:
raise RuntimeError("Models must be owned by only a single document, %r is already in a doc" % (self))
doc.theme.apply_to_model(self)
self._document = doc
self._update_event_callbacks() | python | def _attach_document(self, doc):
''' Attach a model to a Bokeh |Document|.
This private interface should only ever called by the Document
implementation to set the private ._document field properly
'''
if self._document is not None and self._document is not doc:
raise RuntimeError("Models must be owned by only a single document, %r is already in a doc" % (self))
doc.theme.apply_to_model(self)
self._document = doc
self._update_event_callbacks() | [
"def",
"_attach_document",
"(",
"self",
",",
"doc",
")",
":",
"if",
"self",
".",
"_document",
"is",
"not",
"None",
"and",
"self",
".",
"_document",
"is",
"not",
"doc",
":",
"raise",
"RuntimeError",
"(",
"\"Models must be owned by only a single document, %r is already in a doc\"",
"%",
"(",
"self",
")",
")",
"doc",
".",
"theme",
".",
"apply_to_model",
"(",
"self",
")",
"self",
".",
"_document",
"=",
"doc",
"self",
".",
"_update_event_callbacks",
"(",
")"
] | Attach a model to a Bokeh |Document|.
This private interface should only ever called by the Document
implementation to set the private ._document field properly | [
"Attach",
"a",
"model",
"to",
"a",
"Bokeh",
"|Document|",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/model.py#L704-L715 | train |
bokeh/bokeh | bokeh/model.py | Model._to_json_like | def _to_json_like(self, include_defaults):
''' Returns a dictionary of the attributes of this object, in
a layout corresponding to what BokehJS expects at unmarshalling time.
This method does not convert "Bokeh types" into "plain JSON types,"
for example each child Model will still be a Model, rather
than turning into a reference, numpy isn't handled, etc.
That's what "json like" means.
This method should be considered "private" or "protected",
for use internal to Bokeh; use ``to_json()`` instead because
it gives you only plain JSON-compatible types.
Args:
include_defaults (bool) : whether to include attributes
that haven't been changed from the default.
'''
all_attrs = self.properties_with_values(include_defaults=include_defaults)
# If __subtype__ is defined, then this model may introduce properties
# that don't exist on __view_model__ in bokehjs. Don't serialize such
# properties.
subtype = getattr(self.__class__, "__subtype__", None)
if subtype is not None and subtype != self.__class__.__view_model__:
attrs = {}
for attr, value in all_attrs.items():
if attr in self.__class__.__dict__:
continue
else:
attrs[attr] = value
else:
attrs = all_attrs
for (k, v) in attrs.items():
# we can't serialize Infinity, we send it as None and
# the other side has to fix it up. This transformation
# can't be in our json_encoder because the json
# module checks for inf before it calls the custom
# encoder.
if isinstance(v, float) and v == float('inf'):
attrs[k] = None
return attrs | python | def _to_json_like(self, include_defaults):
''' Returns a dictionary of the attributes of this object, in
a layout corresponding to what BokehJS expects at unmarshalling time.
This method does not convert "Bokeh types" into "plain JSON types,"
for example each child Model will still be a Model, rather
than turning into a reference, numpy isn't handled, etc.
That's what "json like" means.
This method should be considered "private" or "protected",
for use internal to Bokeh; use ``to_json()`` instead because
it gives you only plain JSON-compatible types.
Args:
include_defaults (bool) : whether to include attributes
that haven't been changed from the default.
'''
all_attrs = self.properties_with_values(include_defaults=include_defaults)
# If __subtype__ is defined, then this model may introduce properties
# that don't exist on __view_model__ in bokehjs. Don't serialize such
# properties.
subtype = getattr(self.__class__, "__subtype__", None)
if subtype is not None and subtype != self.__class__.__view_model__:
attrs = {}
for attr, value in all_attrs.items():
if attr in self.__class__.__dict__:
continue
else:
attrs[attr] = value
else:
attrs = all_attrs
for (k, v) in attrs.items():
# we can't serialize Infinity, we send it as None and
# the other side has to fix it up. This transformation
# can't be in our json_encoder because the json
# module checks for inf before it calls the custom
# encoder.
if isinstance(v, float) and v == float('inf'):
attrs[k] = None
return attrs | [
"def",
"_to_json_like",
"(",
"self",
",",
"include_defaults",
")",
":",
"all_attrs",
"=",
"self",
".",
"properties_with_values",
"(",
"include_defaults",
"=",
"include_defaults",
")",
"# If __subtype__ is defined, then this model may introduce properties",
"# that don't exist on __view_model__ in bokehjs. Don't serialize such",
"# properties.",
"subtype",
"=",
"getattr",
"(",
"self",
".",
"__class__",
",",
"\"__subtype__\"",
",",
"None",
")",
"if",
"subtype",
"is",
"not",
"None",
"and",
"subtype",
"!=",
"self",
".",
"__class__",
".",
"__view_model__",
":",
"attrs",
"=",
"{",
"}",
"for",
"attr",
",",
"value",
"in",
"all_attrs",
".",
"items",
"(",
")",
":",
"if",
"attr",
"in",
"self",
".",
"__class__",
".",
"__dict__",
":",
"continue",
"else",
":",
"attrs",
"[",
"attr",
"]",
"=",
"value",
"else",
":",
"attrs",
"=",
"all_attrs",
"for",
"(",
"k",
",",
"v",
")",
"in",
"attrs",
".",
"items",
"(",
")",
":",
"# we can't serialize Infinity, we send it as None and",
"# the other side has to fix it up. This transformation",
"# can't be in our json_encoder because the json",
"# module checks for inf before it calls the custom",
"# encoder.",
"if",
"isinstance",
"(",
"v",
",",
"float",
")",
"and",
"v",
"==",
"float",
"(",
"'inf'",
")",
":",
"attrs",
"[",
"k",
"]",
"=",
"None",
"return",
"attrs"
] | Returns a dictionary of the attributes of this object, in
a layout corresponding to what BokehJS expects at unmarshalling time.
This method does not convert "Bokeh types" into "plain JSON types,"
for example each child Model will still be a Model, rather
than turning into a reference, numpy isn't handled, etc.
That's what "json like" means.
This method should be considered "private" or "protected",
for use internal to Bokeh; use ``to_json()`` instead because
it gives you only plain JSON-compatible types.
Args:
include_defaults (bool) : whether to include attributes
that haven't been changed from the default. | [
"Returns",
"a",
"dictionary",
"of",
"the",
"attributes",
"of",
"this",
"object",
"in",
"a",
"layout",
"corresponding",
"to",
"what",
"BokehJS",
"expects",
"at",
"unmarshalling",
"time",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/model.py#L734-L777 | train |
bokeh/bokeh | bokeh/plotting/gmap.py | gmap | def gmap(google_api_key, map_options, **kwargs):
''' Create a new :class:`~bokeh.plotting.gmap.GMap` for plotting.
Args:
google_api_key (str):
Google requires an API key be supplied for maps to function. See:
https://developers.google.com/maps/documentation/javascript/get-api-key
map_options: (GMapOptions)
Configuration specific to a Google Map
In addition to the standard :class:`~bokeh.plotting.gmap.GMap` keyword
arguments (e.g. ``plot_width`` or ``sizing_mode``), the following
additional options can be passed as well:
.. bokeh-options:: GMapFigureOptions
:module: bokeh.plotting.gmap
Returns:
GMap
'''
return GMap(api_key=google_api_key, map_options=map_options, **kwargs) | python | def gmap(google_api_key, map_options, **kwargs):
''' Create a new :class:`~bokeh.plotting.gmap.GMap` for plotting.
Args:
google_api_key (str):
Google requires an API key be supplied for maps to function. See:
https://developers.google.com/maps/documentation/javascript/get-api-key
map_options: (GMapOptions)
Configuration specific to a Google Map
In addition to the standard :class:`~bokeh.plotting.gmap.GMap` keyword
arguments (e.g. ``plot_width`` or ``sizing_mode``), the following
additional options can be passed as well:
.. bokeh-options:: GMapFigureOptions
:module: bokeh.plotting.gmap
Returns:
GMap
'''
return GMap(api_key=google_api_key, map_options=map_options, **kwargs) | [
"def",
"gmap",
"(",
"google_api_key",
",",
"map_options",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"GMap",
"(",
"api_key",
"=",
"google_api_key",
",",
"map_options",
"=",
"map_options",
",",
"*",
"*",
"kwargs",
")"
] | Create a new :class:`~bokeh.plotting.gmap.GMap` for plotting.
Args:
google_api_key (str):
Google requires an API key be supplied for maps to function. See:
https://developers.google.com/maps/documentation/javascript/get-api-key
map_options: (GMapOptions)
Configuration specific to a Google Map
In addition to the standard :class:`~bokeh.plotting.gmap.GMap` keyword
arguments (e.g. ``plot_width`` or ``sizing_mode``), the following
additional options can be passed as well:
.. bokeh-options:: GMapFigureOptions
:module: bokeh.plotting.gmap
Returns:
GMap | [
"Create",
"a",
"new",
":",
"class",
":",
"~bokeh",
".",
"plotting",
".",
"gmap",
".",
"GMap",
"for",
"plotting",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/plotting/gmap.py#L180-L204 | train |
bokeh/bokeh | bokeh/colors/hsl.py | HSL.copy | def copy(self):
''' Return a copy of this color value.
Returns:
HSL
'''
return HSL(self.h, self.s, self.l, self.a) | python | def copy(self):
''' Return a copy of this color value.
Returns:
HSL
'''
return HSL(self.h, self.s, self.l, self.a) | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"HSL",
"(",
"self",
".",
"h",
",",
"self",
".",
"s",
",",
"self",
".",
"l",
",",
"self",
".",
"a",
")"
] | Return a copy of this color value.
Returns:
HSL | [
"Return",
"a",
"copy",
"of",
"this",
"color",
"value",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/colors/hsl.py#L73-L80 | train |
bokeh/bokeh | bokeh/colors/hsl.py | HSL.to_css | def to_css(self):
''' Generate the CSS representation of this HSL color.
Returns:
str, ``"hsl(...)"`` or ``"hsla(...)"``
'''
if self.a == 1.0:
return "hsl(%d, %s%%, %s%%)" % (self.h, self.s*100, self.l*100)
else:
return "hsla(%d, %s%%, %s%%, %s)" % (self.h, self.s*100, self.l*100, self.a) | python | def to_css(self):
''' Generate the CSS representation of this HSL color.
Returns:
str, ``"hsl(...)"`` or ``"hsla(...)"``
'''
if self.a == 1.0:
return "hsl(%d, %s%%, %s%%)" % (self.h, self.s*100, self.l*100)
else:
return "hsla(%d, %s%%, %s%%, %s)" % (self.h, self.s*100, self.l*100, self.a) | [
"def",
"to_css",
"(",
"self",
")",
":",
"if",
"self",
".",
"a",
"==",
"1.0",
":",
"return",
"\"hsl(%d, %s%%, %s%%)\"",
"%",
"(",
"self",
".",
"h",
",",
"self",
".",
"s",
"*",
"100",
",",
"self",
".",
"l",
"*",
"100",
")",
"else",
":",
"return",
"\"hsla(%d, %s%%, %s%%, %s)\"",
"%",
"(",
"self",
".",
"h",
",",
"self",
".",
"s",
"*",
"100",
",",
"self",
".",
"l",
"*",
"100",
",",
"self",
".",
"a",
")"
] | Generate the CSS representation of this HSL color.
Returns:
str, ``"hsl(...)"`` or ``"hsla(...)"`` | [
"Generate",
"the",
"CSS",
"representation",
"of",
"this",
"HSL",
"color",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/colors/hsl.py#L110-L120 | train |
bokeh/bokeh | bokeh/colors/hsl.py | HSL.to_rgb | def to_rgb(self):
''' Return a corresponding :class:`~bokeh.colors.rgb.RGB` color for
this HSL color.
Returns:
HSL
'''
from .rgb import RGB # prevent circular import
r, g, b = colorsys.hls_to_rgb(float(self.h)/360, self.l, self.s)
return RGB(round(r*255), round(g*255), round(b*255), self.a) | python | def to_rgb(self):
''' Return a corresponding :class:`~bokeh.colors.rgb.RGB` color for
this HSL color.
Returns:
HSL
'''
from .rgb import RGB # prevent circular import
r, g, b = colorsys.hls_to_rgb(float(self.h)/360, self.l, self.s)
return RGB(round(r*255), round(g*255), round(b*255), self.a) | [
"def",
"to_rgb",
"(",
"self",
")",
":",
"from",
".",
"rgb",
"import",
"RGB",
"# prevent circular import",
"r",
",",
"g",
",",
"b",
"=",
"colorsys",
".",
"hls_to_rgb",
"(",
"float",
"(",
"self",
".",
"h",
")",
"/",
"360",
",",
"self",
".",
"l",
",",
"self",
".",
"s",
")",
"return",
"RGB",
"(",
"round",
"(",
"r",
"*",
"255",
")",
",",
"round",
"(",
"g",
"*",
"255",
")",
",",
"round",
"(",
"b",
"*",
"255",
")",
",",
"self",
".",
"a",
")"
] | Return a corresponding :class:`~bokeh.colors.rgb.RGB` color for
this HSL color.
Returns:
HSL | [
"Return",
"a",
"corresponding",
":",
"class",
":",
"~bokeh",
".",
"colors",
".",
"rgb",
".",
"RGB",
"color",
"for",
"this",
"HSL",
"color",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/colors/hsl.py#L131-L141 | train |
bokeh/bokeh | bokeh/util/paths.py | serverdir | def serverdir():
""" Get the location of the server subpackage
"""
path = join(ROOT_DIR, 'server')
path = normpath(path)
if sys.platform == 'cygwin': path = realpath(path)
return path | python | def serverdir():
""" Get the location of the server subpackage
"""
path = join(ROOT_DIR, 'server')
path = normpath(path)
if sys.platform == 'cygwin': path = realpath(path)
return path | [
"def",
"serverdir",
"(",
")",
":",
"path",
"=",
"join",
"(",
"ROOT_DIR",
",",
"'server'",
")",
"path",
"=",
"normpath",
"(",
"path",
")",
"if",
"sys",
".",
"platform",
"==",
"'cygwin'",
":",
"path",
"=",
"realpath",
"(",
"path",
")",
"return",
"path"
] | Get the location of the server subpackage | [
"Get",
"the",
"location",
"of",
"the",
"server",
"subpackage"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/paths.py#L44-L50 | train |
bokeh/bokeh | bokeh/util/paths.py | bokehjsdir | def bokehjsdir(dev=False):
""" Get the location of the bokehjs source files. If dev is True,
the files in bokehjs/build are preferred. Otherwise uses the files
in bokeh/server/static.
"""
dir1 = join(ROOT_DIR, '..', 'bokehjs', 'build')
dir2 = join(serverdir(), 'static')
if dev and isdir(dir1):
return dir1
else:
return dir2 | python | def bokehjsdir(dev=False):
""" Get the location of the bokehjs source files. If dev is True,
the files in bokehjs/build are preferred. Otherwise uses the files
in bokeh/server/static.
"""
dir1 = join(ROOT_DIR, '..', 'bokehjs', 'build')
dir2 = join(serverdir(), 'static')
if dev and isdir(dir1):
return dir1
else:
return dir2 | [
"def",
"bokehjsdir",
"(",
"dev",
"=",
"False",
")",
":",
"dir1",
"=",
"join",
"(",
"ROOT_DIR",
",",
"'..'",
",",
"'bokehjs'",
",",
"'build'",
")",
"dir2",
"=",
"join",
"(",
"serverdir",
"(",
")",
",",
"'static'",
")",
"if",
"dev",
"and",
"isdir",
"(",
"dir1",
")",
":",
"return",
"dir1",
"else",
":",
"return",
"dir2"
] | Get the location of the bokehjs source files. If dev is True,
the files in bokehjs/build are preferred. Otherwise uses the files
in bokeh/server/static. | [
"Get",
"the",
"location",
"of",
"the",
"bokehjs",
"source",
"files",
".",
"If",
"dev",
"is",
"True",
"the",
"files",
"in",
"bokehjs",
"/",
"build",
"are",
"preferred",
".",
"Otherwise",
"uses",
"the",
"files",
"in",
"bokeh",
"/",
"server",
"/",
"static",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/paths.py#L53-L63 | train |
bokeh/bokeh | bokeh/server/server.py | BaseServer.start | def start(self):
''' Install the Bokeh Server and its background tasks on a Tornado
``IOLoop``.
This method does *not* block and does *not* affect the state of the
Tornado ``IOLoop`` You must start and stop the loop yourself, i.e.
this method is typically useful when you are already explicitly
managing an ``IOLoop`` yourself.
To start a Bokeh server and immediately "run forever" in a blocking
manner, see :func:`~bokeh.server.server.BaseServer.run_until_shutdown`.
'''
assert not self._started, "Already started"
self._started = True
self._tornado.start() | python | def start(self):
''' Install the Bokeh Server and its background tasks on a Tornado
``IOLoop``.
This method does *not* block and does *not* affect the state of the
Tornado ``IOLoop`` You must start and stop the loop yourself, i.e.
this method is typically useful when you are already explicitly
managing an ``IOLoop`` yourself.
To start a Bokeh server and immediately "run forever" in a blocking
manner, see :func:`~bokeh.server.server.BaseServer.run_until_shutdown`.
'''
assert not self._started, "Already started"
self._started = True
self._tornado.start() | [
"def",
"start",
"(",
"self",
")",
":",
"assert",
"not",
"self",
".",
"_started",
",",
"\"Already started\"",
"self",
".",
"_started",
"=",
"True",
"self",
".",
"_tornado",
".",
"start",
"(",
")"
] | Install the Bokeh Server and its background tasks on a Tornado
``IOLoop``.
This method does *not* block and does *not* affect the state of the
Tornado ``IOLoop`` You must start and stop the loop yourself, i.e.
this method is typically useful when you are already explicitly
managing an ``IOLoop`` yourself.
To start a Bokeh server and immediately "run forever" in a blocking
manner, see :func:`~bokeh.server.server.BaseServer.run_until_shutdown`. | [
"Install",
"the",
"Bokeh",
"Server",
"and",
"its",
"background",
"tasks",
"on",
"a",
"Tornado",
"IOLoop",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/server.py#L120-L135 | train |
bokeh/bokeh | bokeh/server/server.py | BaseServer.stop | def stop(self, wait=True):
''' Stop the Bokeh Server.
This stops and removes all Bokeh Server ``IOLoop`` callbacks, as well
as stops the ``HTTPServer`` that this instance was configured with.
Args:
fast (bool):
Whether to wait for orderly cleanup (default: True)
Returns:
None
'''
assert not self._stopped, "Already stopped"
self._stopped = True
self._tornado.stop(wait)
self._http.stop() | python | def stop(self, wait=True):
''' Stop the Bokeh Server.
This stops and removes all Bokeh Server ``IOLoop`` callbacks, as well
as stops the ``HTTPServer`` that this instance was configured with.
Args:
fast (bool):
Whether to wait for orderly cleanup (default: True)
Returns:
None
'''
assert not self._stopped, "Already stopped"
self._stopped = True
self._tornado.stop(wait)
self._http.stop() | [
"def",
"stop",
"(",
"self",
",",
"wait",
"=",
"True",
")",
":",
"assert",
"not",
"self",
".",
"_stopped",
",",
"\"Already stopped\"",
"self",
".",
"_stopped",
"=",
"True",
"self",
".",
"_tornado",
".",
"stop",
"(",
"wait",
")",
"self",
".",
"_http",
".",
"stop",
"(",
")"
] | Stop the Bokeh Server.
This stops and removes all Bokeh Server ``IOLoop`` callbacks, as well
as stops the ``HTTPServer`` that this instance was configured with.
Args:
fast (bool):
Whether to wait for orderly cleanup (default: True)
Returns:
None | [
"Stop",
"the",
"Bokeh",
"Server",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/server.py#L137-L154 | train |
bokeh/bokeh | bokeh/server/server.py | BaseServer.run_until_shutdown | def run_until_shutdown(self):
''' Run the Bokeh Server until shutdown is requested by the user,
either via a Keyboard interrupt (Ctrl-C) or SIGTERM.
Calling this method will start the Tornado ``IOLoop`` and block
all execution in the calling process.
Returns:
None
'''
if not self._started:
self.start()
# Install shutdown hooks
atexit.register(self._atexit)
signal.signal(signal.SIGTERM, self._sigterm)
try:
self._loop.start()
except KeyboardInterrupt:
print("\nInterrupted, shutting down")
self.stop() | python | def run_until_shutdown(self):
''' Run the Bokeh Server until shutdown is requested by the user,
either via a Keyboard interrupt (Ctrl-C) or SIGTERM.
Calling this method will start the Tornado ``IOLoop`` and block
all execution in the calling process.
Returns:
None
'''
if not self._started:
self.start()
# Install shutdown hooks
atexit.register(self._atexit)
signal.signal(signal.SIGTERM, self._sigterm)
try:
self._loop.start()
except KeyboardInterrupt:
print("\nInterrupted, shutting down")
self.stop() | [
"def",
"run_until_shutdown",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_started",
":",
"self",
".",
"start",
"(",
")",
"# Install shutdown hooks",
"atexit",
".",
"register",
"(",
"self",
".",
"_atexit",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGTERM",
",",
"self",
".",
"_sigterm",
")",
"try",
":",
"self",
".",
"_loop",
".",
"start",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"print",
"(",
"\"\\nInterrupted, shutting down\"",
")",
"self",
".",
"stop",
"(",
")"
] | Run the Bokeh Server until shutdown is requested by the user,
either via a Keyboard interrupt (Ctrl-C) or SIGTERM.
Calling this method will start the Tornado ``IOLoop`` and block
all execution in the calling process.
Returns:
None | [
"Run",
"the",
"Bokeh",
"Server",
"until",
"shutdown",
"is",
"requested",
"by",
"the",
"user",
"either",
"via",
"a",
"Keyboard",
"interrupt",
"(",
"Ctrl",
"-",
"C",
")",
"or",
"SIGTERM",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/server.py#L167-L187 | train |
bokeh/bokeh | bokeh/server/server.py | BaseServer.get_sessions | def get_sessions(self, app_path=None):
''' Gets all currently active sessions for applications.
Args:
app_path (str, optional) :
The configured application path for the application to return
sessions for. If None, return active sessions for all
applications. (default: None)
Returns:
list[ServerSession]
'''
if app_path is not None:
return self._tornado.get_sessions(app_path)
all_sessions = []
for path in self._tornado.app_paths:
all_sessions += self._tornado.get_sessions(path)
return all_sessions | python | def get_sessions(self, app_path=None):
''' Gets all currently active sessions for applications.
Args:
app_path (str, optional) :
The configured application path for the application to return
sessions for. If None, return active sessions for all
applications. (default: None)
Returns:
list[ServerSession]
'''
if app_path is not None:
return self._tornado.get_sessions(app_path)
all_sessions = []
for path in self._tornado.app_paths:
all_sessions += self._tornado.get_sessions(path)
return all_sessions | [
"def",
"get_sessions",
"(",
"self",
",",
"app_path",
"=",
"None",
")",
":",
"if",
"app_path",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_tornado",
".",
"get_sessions",
"(",
"app_path",
")",
"all_sessions",
"=",
"[",
"]",
"for",
"path",
"in",
"self",
".",
"_tornado",
".",
"app_paths",
":",
"all_sessions",
"+=",
"self",
".",
"_tornado",
".",
"get_sessions",
"(",
"path",
")",
"return",
"all_sessions"
] | Gets all currently active sessions for applications.
Args:
app_path (str, optional) :
The configured application path for the application to return
sessions for. If None, return active sessions for all
applications. (default: None)
Returns:
list[ServerSession] | [
"Gets",
"all",
"currently",
"active",
"sessions",
"for",
"applications",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/server.py#L206-L224 | train |
bokeh/bokeh | bokeh/server/server.py | BaseServer.show | def show(self, app_path, browser=None, new='tab'):
''' Opens an app in a browser window or tab.
This method is useful for testing or running Bokeh server applications
on a local machine but should not call when running Bokeh server for
an actual deployment.
Args:
app_path (str) : the app path to open
The part of the URL after the hostname:port, with leading slash.
browser (str, optional) : browser to show with (default: None)
For systems that support it, the **browser** argument allows
specifying which browser to display in, e.g. "safari", "firefox",
"opera", "windows-default" (see the ``webbrowser`` module
documentation in the standard lib for more details).
new (str, optional) : window or tab (default: "tab")
If ``new`` is 'tab', then opens a new tab.
If ``new`` is 'window', then opens a new window.
Returns:
None
'''
if not app_path.startswith("/"):
raise ValueError("app_path must start with a /")
address_string = 'localhost'
if self.address is not None and self.address != '':
address_string = self.address
url = "http://%s:%d%s%s" % (address_string, self.port, self.prefix, app_path)
from bokeh.util.browser import view
view(url, browser=browser, new=new) | python | def show(self, app_path, browser=None, new='tab'):
''' Opens an app in a browser window or tab.
This method is useful for testing or running Bokeh server applications
on a local machine but should not call when running Bokeh server for
an actual deployment.
Args:
app_path (str) : the app path to open
The part of the URL after the hostname:port, with leading slash.
browser (str, optional) : browser to show with (default: None)
For systems that support it, the **browser** argument allows
specifying which browser to display in, e.g. "safari", "firefox",
"opera", "windows-default" (see the ``webbrowser`` module
documentation in the standard lib for more details).
new (str, optional) : window or tab (default: "tab")
If ``new`` is 'tab', then opens a new tab.
If ``new`` is 'window', then opens a new window.
Returns:
None
'''
if not app_path.startswith("/"):
raise ValueError("app_path must start with a /")
address_string = 'localhost'
if self.address is not None and self.address != '':
address_string = self.address
url = "http://%s:%d%s%s" % (address_string, self.port, self.prefix, app_path)
from bokeh.util.browser import view
view(url, browser=browser, new=new) | [
"def",
"show",
"(",
"self",
",",
"app_path",
",",
"browser",
"=",
"None",
",",
"new",
"=",
"'tab'",
")",
":",
"if",
"not",
"app_path",
".",
"startswith",
"(",
"\"/\"",
")",
":",
"raise",
"ValueError",
"(",
"\"app_path must start with a /\"",
")",
"address_string",
"=",
"'localhost'",
"if",
"self",
".",
"address",
"is",
"not",
"None",
"and",
"self",
".",
"address",
"!=",
"''",
":",
"address_string",
"=",
"self",
".",
"address",
"url",
"=",
"\"http://%s:%d%s%s\"",
"%",
"(",
"address_string",
",",
"self",
".",
"port",
",",
"self",
".",
"prefix",
",",
"app_path",
")",
"from",
"bokeh",
".",
"util",
".",
"browser",
"import",
"view",
"view",
"(",
"url",
",",
"browser",
"=",
"browser",
",",
"new",
"=",
"new",
")"
] | Opens an app in a browser window or tab.
This method is useful for testing or running Bokeh server applications
on a local machine but should not call when running Bokeh server for
an actual deployment.
Args:
app_path (str) : the app path to open
The part of the URL after the hostname:port, with leading slash.
browser (str, optional) : browser to show with (default: None)
For systems that support it, the **browser** argument allows
specifying which browser to display in, e.g. "safari", "firefox",
"opera", "windows-default" (see the ``webbrowser`` module
documentation in the standard lib for more details).
new (str, optional) : window or tab (default: "tab")
If ``new`` is 'tab', then opens a new tab.
If ``new`` is 'window', then opens a new window.
Returns:
None | [
"Opens",
"an",
"app",
"in",
"a",
"browser",
"window",
"or",
"tab",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/server.py#L226-L261 | train |
bokeh/bokeh | bokeh/application/handlers/code_runner.py | CodeRunner.new_module | def new_module(self):
''' Make a fresh module to run in.
Returns:
Module
'''
self.reset_run_errors()
if self._code is None:
return None
module_name = 'bk_script_' + make_id().replace('-', '')
module = ModuleType(str(module_name)) # str needed for py2.7
module.__dict__['__file__'] = os.path.abspath(self._path)
return module | python | def new_module(self):
''' Make a fresh module to run in.
Returns:
Module
'''
self.reset_run_errors()
if self._code is None:
return None
module_name = 'bk_script_' + make_id().replace('-', '')
module = ModuleType(str(module_name)) # str needed for py2.7
module.__dict__['__file__'] = os.path.abspath(self._path)
return module | [
"def",
"new_module",
"(",
"self",
")",
":",
"self",
".",
"reset_run_errors",
"(",
")",
"if",
"self",
".",
"_code",
"is",
"None",
":",
"return",
"None",
"module_name",
"=",
"'bk_script_'",
"+",
"make_id",
"(",
")",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
"module",
"=",
"ModuleType",
"(",
"str",
"(",
"module_name",
")",
")",
"# str needed for py2.7",
"module",
".",
"__dict__",
"[",
"'__file__'",
"]",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"self",
".",
"_path",
")",
"return",
"module"
] | Make a fresh module to run in.
Returns:
Module | [
"Make",
"a",
"fresh",
"module",
"to",
"run",
"in",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/application/handlers/code_runner.py#L129-L145 | train |
bokeh/bokeh | bokeh/application/handlers/code_runner.py | CodeRunner.run | def run(self, module, post_check):
''' Execute the configured source code in a module and run any post
checks.
Args:
module (Module) : a module to execute the configured code in.
post_check(callable) : a function that can raise an exception
if expected post-conditions are not met after code execution.
'''
try:
# Simulate the sys.path behaviour decribed here:
#
# https://docs.python.org/2/library/sys.html#sys.path
_cwd = os.getcwd()
_sys_path = list(sys.path)
_sys_argv = list(sys.argv)
sys.path.insert(0, os.path.dirname(self._path))
sys.argv = [os.path.basename(self._path)] + self._argv
exec(self._code, module.__dict__)
post_check()
except Exception as e:
self._failed = True
self._error_detail = traceback.format_exc()
_exc_type, _exc_value, exc_traceback = sys.exc_info()
filename, line_number, func, txt = traceback.extract_tb(exc_traceback)[-1]
self._error = "%s\nFile \"%s\", line %d, in %s:\n%s" % (str(e), os.path.basename(filename), line_number, func, txt)
finally:
# undo sys.path, CWD fixups
os.chdir(_cwd)
sys.path = _sys_path
sys.argv = _sys_argv
self.ran = True | python | def run(self, module, post_check):
''' Execute the configured source code in a module and run any post
checks.
Args:
module (Module) : a module to execute the configured code in.
post_check(callable) : a function that can raise an exception
if expected post-conditions are not met after code execution.
'''
try:
# Simulate the sys.path behaviour decribed here:
#
# https://docs.python.org/2/library/sys.html#sys.path
_cwd = os.getcwd()
_sys_path = list(sys.path)
_sys_argv = list(sys.argv)
sys.path.insert(0, os.path.dirname(self._path))
sys.argv = [os.path.basename(self._path)] + self._argv
exec(self._code, module.__dict__)
post_check()
except Exception as e:
self._failed = True
self._error_detail = traceback.format_exc()
_exc_type, _exc_value, exc_traceback = sys.exc_info()
filename, line_number, func, txt = traceback.extract_tb(exc_traceback)[-1]
self._error = "%s\nFile \"%s\", line %d, in %s:\n%s" % (str(e), os.path.basename(filename), line_number, func, txt)
finally:
# undo sys.path, CWD fixups
os.chdir(_cwd)
sys.path = _sys_path
sys.argv = _sys_argv
self.ran = True | [
"def",
"run",
"(",
"self",
",",
"module",
",",
"post_check",
")",
":",
"try",
":",
"# Simulate the sys.path behaviour decribed here:",
"#",
"# https://docs.python.org/2/library/sys.html#sys.path",
"_cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"_sys_path",
"=",
"list",
"(",
"sys",
".",
"path",
")",
"_sys_argv",
"=",
"list",
"(",
"sys",
".",
"argv",
")",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"_path",
")",
")",
"sys",
".",
"argv",
"=",
"[",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"_path",
")",
"]",
"+",
"self",
".",
"_argv",
"exec",
"(",
"self",
".",
"_code",
",",
"module",
".",
"__dict__",
")",
"post_check",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"_failed",
"=",
"True",
"self",
".",
"_error_detail",
"=",
"traceback",
".",
"format_exc",
"(",
")",
"_exc_type",
",",
"_exc_value",
",",
"exc_traceback",
"=",
"sys",
".",
"exc_info",
"(",
")",
"filename",
",",
"line_number",
",",
"func",
",",
"txt",
"=",
"traceback",
".",
"extract_tb",
"(",
"exc_traceback",
")",
"[",
"-",
"1",
"]",
"self",
".",
"_error",
"=",
"\"%s\\nFile \\\"%s\\\", line %d, in %s:\\n%s\"",
"%",
"(",
"str",
"(",
"e",
")",
",",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
",",
"line_number",
",",
"func",
",",
"txt",
")",
"finally",
":",
"# undo sys.path, CWD fixups",
"os",
".",
"chdir",
"(",
"_cwd",
")",
"sys",
".",
"path",
"=",
"_sys_path",
"sys",
".",
"argv",
"=",
"_sys_argv",
"self",
".",
"ran",
"=",
"True"
] | Execute the configured source code in a module and run any post
checks.
Args:
module (Module) : a module to execute the configured code in.
post_check(callable) : a function that can raise an exception
if expected post-conditions are not met after code execution. | [
"Execute",
"the",
"configured",
"source",
"code",
"in",
"a",
"module",
"and",
"run",
"any",
"post",
"checks",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/application/handlers/code_runner.py#L158-L196 | train |
bokeh/bokeh | bokeh/client/connection.py | ClientConnection.loop_until_closed | def loop_until_closed(self):
''' Execute a blocking loop that runs and executes event callbacks
until the connection is closed (e.g. by hitting Ctrl-C).
While this method can be used to run Bokeh application code "outside"
the Bokeh server, this practice is HIGHLY DISCOURAGED for any real
use case.
'''
if isinstance(self._state, NOT_YET_CONNECTED):
# we don't use self._transition_to_disconnected here
# because _transition is a coroutine
self._tell_session_about_disconnect()
self._state = DISCONNECTED()
else:
def closed():
return isinstance(self._state, DISCONNECTED)
self._loop_until(closed) | python | def loop_until_closed(self):
''' Execute a blocking loop that runs and executes event callbacks
until the connection is closed (e.g. by hitting Ctrl-C).
While this method can be used to run Bokeh application code "outside"
the Bokeh server, this practice is HIGHLY DISCOURAGED for any real
use case.
'''
if isinstance(self._state, NOT_YET_CONNECTED):
# we don't use self._transition_to_disconnected here
# because _transition is a coroutine
self._tell_session_about_disconnect()
self._state = DISCONNECTED()
else:
def closed():
return isinstance(self._state, DISCONNECTED)
self._loop_until(closed) | [
"def",
"loop_until_closed",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"_state",
",",
"NOT_YET_CONNECTED",
")",
":",
"# we don't use self._transition_to_disconnected here",
"# because _transition is a coroutine",
"self",
".",
"_tell_session_about_disconnect",
"(",
")",
"self",
".",
"_state",
"=",
"DISCONNECTED",
"(",
")",
"else",
":",
"def",
"closed",
"(",
")",
":",
"return",
"isinstance",
"(",
"self",
".",
"_state",
",",
"DISCONNECTED",
")",
"self",
".",
"_loop_until",
"(",
"closed",
")"
] | Execute a blocking loop that runs and executes event callbacks
until the connection is closed (e.g. by hitting Ctrl-C).
While this method can be used to run Bokeh application code "outside"
the Bokeh server, this practice is HIGHLY DISCOURAGED for any real
use case. | [
"Execute",
"a",
"blocking",
"loop",
"that",
"runs",
"and",
"executes",
"event",
"callbacks",
"until",
"the",
"connection",
"is",
"closed",
"(",
"e",
".",
"g",
".",
"by",
"hitting",
"Ctrl",
"-",
"C",
")",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/client/connection.py#L134-L151 | train |
bokeh/bokeh | bokeh/client/connection.py | ClientConnection.pull_doc | def pull_doc(self, document):
''' Pull a document from the server, overwriting the passed-in document
Args:
document : (Document)
The document to overwrite with server content.
Returns:
None
'''
msg = self._protocol.create('PULL-DOC-REQ')
reply = self._send_message_wait_for_reply(msg)
if reply is None:
raise RuntimeError("Connection to server was lost")
elif reply.header['msgtype'] == 'ERROR':
raise RuntimeError("Failed to pull document: " + reply.content['text'])
else:
reply.push_to_document(document) | python | def pull_doc(self, document):
''' Pull a document from the server, overwriting the passed-in document
Args:
document : (Document)
The document to overwrite with server content.
Returns:
None
'''
msg = self._protocol.create('PULL-DOC-REQ')
reply = self._send_message_wait_for_reply(msg)
if reply is None:
raise RuntimeError("Connection to server was lost")
elif reply.header['msgtype'] == 'ERROR':
raise RuntimeError("Failed to pull document: " + reply.content['text'])
else:
reply.push_to_document(document) | [
"def",
"pull_doc",
"(",
"self",
",",
"document",
")",
":",
"msg",
"=",
"self",
".",
"_protocol",
".",
"create",
"(",
"'PULL-DOC-REQ'",
")",
"reply",
"=",
"self",
".",
"_send_message_wait_for_reply",
"(",
"msg",
")",
"if",
"reply",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"Connection to server was lost\"",
")",
"elif",
"reply",
".",
"header",
"[",
"'msgtype'",
"]",
"==",
"'ERROR'",
":",
"raise",
"RuntimeError",
"(",
"\"Failed to pull document: \"",
"+",
"reply",
".",
"content",
"[",
"'text'",
"]",
")",
"else",
":",
"reply",
".",
"push_to_document",
"(",
"document",
")"
] | Pull a document from the server, overwriting the passed-in document
Args:
document : (Document)
The document to overwrite with server content.
Returns:
None | [
"Pull",
"a",
"document",
"from",
"the",
"server",
"overwriting",
"the",
"passed",
"-",
"in",
"document"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/client/connection.py#L153-L171 | train |
bokeh/bokeh | bokeh/client/connection.py | ClientConnection.push_doc | def push_doc(self, document):
''' Push a document to the server, overwriting any existing server-side doc.
Args:
document : (Document)
A Document to push to the server
Returns:
The server reply
'''
msg = self._protocol.create('PUSH-DOC', document)
reply = self._send_message_wait_for_reply(msg)
if reply is None:
raise RuntimeError("Connection to server was lost")
elif reply.header['msgtype'] == 'ERROR':
raise RuntimeError("Failed to push document: " + reply.content['text'])
else:
return reply | python | def push_doc(self, document):
''' Push a document to the server, overwriting any existing server-side doc.
Args:
document : (Document)
A Document to push to the server
Returns:
The server reply
'''
msg = self._protocol.create('PUSH-DOC', document)
reply = self._send_message_wait_for_reply(msg)
if reply is None:
raise RuntimeError("Connection to server was lost")
elif reply.header['msgtype'] == 'ERROR':
raise RuntimeError("Failed to push document: " + reply.content['text'])
else:
return reply | [
"def",
"push_doc",
"(",
"self",
",",
"document",
")",
":",
"msg",
"=",
"self",
".",
"_protocol",
".",
"create",
"(",
"'PUSH-DOC'",
",",
"document",
")",
"reply",
"=",
"self",
".",
"_send_message_wait_for_reply",
"(",
"msg",
")",
"if",
"reply",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"Connection to server was lost\"",
")",
"elif",
"reply",
".",
"header",
"[",
"'msgtype'",
"]",
"==",
"'ERROR'",
":",
"raise",
"RuntimeError",
"(",
"\"Failed to push document: \"",
"+",
"reply",
".",
"content",
"[",
"'text'",
"]",
")",
"else",
":",
"return",
"reply"
] | Push a document to the server, overwriting any existing server-side doc.
Args:
document : (Document)
A Document to push to the server
Returns:
The server reply | [
"Push",
"a",
"document",
"to",
"the",
"server",
"overwriting",
"any",
"existing",
"server",
"-",
"side",
"doc",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/client/connection.py#L173-L191 | train |
bokeh/bokeh | bokeh/client/connection.py | ClientConnection.request_server_info | def request_server_info(self):
''' Ask for information about the server.
Returns:
A dictionary of server attributes.
'''
if self._server_info is None:
self._server_info = self._send_request_server_info()
return self._server_info | python | def request_server_info(self):
''' Ask for information about the server.
Returns:
A dictionary of server attributes.
'''
if self._server_info is None:
self._server_info = self._send_request_server_info()
return self._server_info | [
"def",
"request_server_info",
"(",
"self",
")",
":",
"if",
"self",
".",
"_server_info",
"is",
"None",
":",
"self",
".",
"_server_info",
"=",
"self",
".",
"_send_request_server_info",
"(",
")",
"return",
"self",
".",
"_server_info"
] | Ask for information about the server.
Returns:
A dictionary of server attributes. | [
"Ask",
"for",
"information",
"about",
"the",
"server",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/client/connection.py#L193-L202 | train |
bokeh/bokeh | bokeh/io/export.py | export_png | def export_png(obj, filename=None, height=None, width=None, webdriver=None, timeout=5):
''' Export the ``LayoutDOM`` object or document as a PNG.
If the filename is not given, it is derived from the script name (e.g.
``/foo/myplot.py`` will create ``/foo/myplot.png``)
Args:
obj (LayoutDOM or Document) : a Layout (Row/Column), Plot or Widget
object or Document to export.
filename (str, optional) : filename to save document under (default: None)
If None, infer from the filename.
height (int) : the desired height of the exported layout obj only if
it's a Plot instance. Otherwise the height kwarg is ignored.
width (int) : the desired width of the exported layout obj only if
it's a Plot instance. Otherwise the width kwarg is ignored.
webdriver (selenium.webdriver) : a selenium webdriver instance to use
to export the image.
timeout (int) : the maximum amount of time (in seconds) to wait for
Bokeh to initialize (default: 5) (Added in 1.1.1).
Returns:
filename (str) : the filename where the static file is saved.
If you would like to access an Image object directly, rather than save a
file to disk, use the lower-level :func:`~bokeh.io.export.get_screenshot_as_png`
function.
.. warning::
Responsive sizing_modes may generate layouts with unexpected size and
aspect ratios. It is recommended to use the default ``fixed`` sizing mode.
'''
image = get_screenshot_as_png(obj, height=height, width=width, driver=webdriver, timeout=timeout)
if filename is None:
filename = default_filename("png")
if image.width == 0 or image.height == 0:
raise ValueError("unable to save an empty image")
image.save(filename)
return abspath(filename) | python | def export_png(obj, filename=None, height=None, width=None, webdriver=None, timeout=5):
''' Export the ``LayoutDOM`` object or document as a PNG.
If the filename is not given, it is derived from the script name (e.g.
``/foo/myplot.py`` will create ``/foo/myplot.png``)
Args:
obj (LayoutDOM or Document) : a Layout (Row/Column), Plot or Widget
object or Document to export.
filename (str, optional) : filename to save document under (default: None)
If None, infer from the filename.
height (int) : the desired height of the exported layout obj only if
it's a Plot instance. Otherwise the height kwarg is ignored.
width (int) : the desired width of the exported layout obj only if
it's a Plot instance. Otherwise the width kwarg is ignored.
webdriver (selenium.webdriver) : a selenium webdriver instance to use
to export the image.
timeout (int) : the maximum amount of time (in seconds) to wait for
Bokeh to initialize (default: 5) (Added in 1.1.1).
Returns:
filename (str) : the filename where the static file is saved.
If you would like to access an Image object directly, rather than save a
file to disk, use the lower-level :func:`~bokeh.io.export.get_screenshot_as_png`
function.
.. warning::
Responsive sizing_modes may generate layouts with unexpected size and
aspect ratios. It is recommended to use the default ``fixed`` sizing mode.
'''
image = get_screenshot_as_png(obj, height=height, width=width, driver=webdriver, timeout=timeout)
if filename is None:
filename = default_filename("png")
if image.width == 0 or image.height == 0:
raise ValueError("unable to save an empty image")
image.save(filename)
return abspath(filename) | [
"def",
"export_png",
"(",
"obj",
",",
"filename",
"=",
"None",
",",
"height",
"=",
"None",
",",
"width",
"=",
"None",
",",
"webdriver",
"=",
"None",
",",
"timeout",
"=",
"5",
")",
":",
"image",
"=",
"get_screenshot_as_png",
"(",
"obj",
",",
"height",
"=",
"height",
",",
"width",
"=",
"width",
",",
"driver",
"=",
"webdriver",
",",
"timeout",
"=",
"timeout",
")",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"default_filename",
"(",
"\"png\"",
")",
"if",
"image",
".",
"width",
"==",
"0",
"or",
"image",
".",
"height",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"unable to save an empty image\"",
")",
"image",
".",
"save",
"(",
"filename",
")",
"return",
"abspath",
"(",
"filename",
")"
] | Export the ``LayoutDOM`` object or document as a PNG.
If the filename is not given, it is derived from the script name (e.g.
``/foo/myplot.py`` will create ``/foo/myplot.png``)
Args:
obj (LayoutDOM or Document) : a Layout (Row/Column), Plot or Widget
object or Document to export.
filename (str, optional) : filename to save document under (default: None)
If None, infer from the filename.
height (int) : the desired height of the exported layout obj only if
it's a Plot instance. Otherwise the height kwarg is ignored.
width (int) : the desired width of the exported layout obj only if
it's a Plot instance. Otherwise the width kwarg is ignored.
webdriver (selenium.webdriver) : a selenium webdriver instance to use
to export the image.
timeout (int) : the maximum amount of time (in seconds) to wait for
Bokeh to initialize (default: 5) (Added in 1.1.1).
Returns:
filename (str) : the filename where the static file is saved.
If you would like to access an Image object directly, rather than save a
file to disk, use the lower-level :func:`~bokeh.io.export.get_screenshot_as_png`
function.
.. warning::
Responsive sizing_modes may generate layouts with unexpected size and
aspect ratios. It is recommended to use the default ``fixed`` sizing mode. | [
"Export",
"the",
"LayoutDOM",
"object",
"or",
"document",
"as",
"a",
"PNG",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/export.py#L59-L107 | train |
bokeh/bokeh | bokeh/io/export.py | export_svgs | def export_svgs(obj, filename=None, height=None, width=None, webdriver=None, timeout=5):
''' Export the SVG-enabled plots within a layout. Each plot will result
in a distinct SVG file.
If the filename is not given, it is derived from the script name
(e.g. ``/foo/myplot.py`` will create ``/foo/myplot.svg``)
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, infer from the filename.
height (int) : the desired height of the exported layout obj only if
it's a Plot instance. Otherwise the height kwarg is ignored.
width (int) : the desired width of the exported layout obj only if
it's a Plot instance. Otherwise the width kwarg is ignored.
webdriver (selenium.webdriver) : a selenium webdriver instance to use
to export the image.
timeout (int) : the maximum amount of time (in seconds) to wait for
Bokeh to initialize (default: 5) (Added in 1.1.1).
Returns:
filenames (list(str)) : the list of filenames where the SVGs files are
saved.
.. warning::
Responsive sizing_modes may generate layouts with unexpected size and
aspect ratios. It is recommended to use the default ``fixed`` sizing mode.
'''
svgs = get_svgs(obj, height=height, width=width, driver=webdriver, timeout=timeout)
if len(svgs) == 0:
log.warning("No SVG Plots were found.")
return
if filename is None:
filename = default_filename("svg")
filenames = []
for i, svg in enumerate(svgs):
if i == 0:
filename = filename
else:
idx = filename.find(".svg")
filename = filename[:idx] + "_{}".format(i) + filename[idx:]
with io.open(filename, mode="w", encoding="utf-8") as f:
f.write(svg)
filenames.append(filename)
return filenames | python | def export_svgs(obj, filename=None, height=None, width=None, webdriver=None, timeout=5):
''' Export the SVG-enabled plots within a layout. Each plot will result
in a distinct SVG file.
If the filename is not given, it is derived from the script name
(e.g. ``/foo/myplot.py`` will create ``/foo/myplot.svg``)
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, infer from the filename.
height (int) : the desired height of the exported layout obj only if
it's a Plot instance. Otherwise the height kwarg is ignored.
width (int) : the desired width of the exported layout obj only if
it's a Plot instance. Otherwise the width kwarg is ignored.
webdriver (selenium.webdriver) : a selenium webdriver instance to use
to export the image.
timeout (int) : the maximum amount of time (in seconds) to wait for
Bokeh to initialize (default: 5) (Added in 1.1.1).
Returns:
filenames (list(str)) : the list of filenames where the SVGs files are
saved.
.. warning::
Responsive sizing_modes may generate layouts with unexpected size and
aspect ratios. It is recommended to use the default ``fixed`` sizing mode.
'''
svgs = get_svgs(obj, height=height, width=width, driver=webdriver, timeout=timeout)
if len(svgs) == 0:
log.warning("No SVG Plots were found.")
return
if filename is None:
filename = default_filename("svg")
filenames = []
for i, svg in enumerate(svgs):
if i == 0:
filename = filename
else:
idx = filename.find(".svg")
filename = filename[:idx] + "_{}".format(i) + filename[idx:]
with io.open(filename, mode="w", encoding="utf-8") as f:
f.write(svg)
filenames.append(filename)
return filenames | [
"def",
"export_svgs",
"(",
"obj",
",",
"filename",
"=",
"None",
",",
"height",
"=",
"None",
",",
"width",
"=",
"None",
",",
"webdriver",
"=",
"None",
",",
"timeout",
"=",
"5",
")",
":",
"svgs",
"=",
"get_svgs",
"(",
"obj",
",",
"height",
"=",
"height",
",",
"width",
"=",
"width",
",",
"driver",
"=",
"webdriver",
",",
"timeout",
"=",
"timeout",
")",
"if",
"len",
"(",
"svgs",
")",
"==",
"0",
":",
"log",
".",
"warning",
"(",
"\"No SVG Plots were found.\"",
")",
"return",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"default_filename",
"(",
"\"svg\"",
")",
"filenames",
"=",
"[",
"]",
"for",
"i",
",",
"svg",
"in",
"enumerate",
"(",
"svgs",
")",
":",
"if",
"i",
"==",
"0",
":",
"filename",
"=",
"filename",
"else",
":",
"idx",
"=",
"filename",
".",
"find",
"(",
"\".svg\"",
")",
"filename",
"=",
"filename",
"[",
":",
"idx",
"]",
"+",
"\"_{}\"",
".",
"format",
"(",
"i",
")",
"+",
"filename",
"[",
"idx",
":",
"]",
"with",
"io",
".",
"open",
"(",
"filename",
",",
"mode",
"=",
"\"w\"",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"svg",
")",
"filenames",
".",
"append",
"(",
"filename",
")",
"return",
"filenames"
] | Export the SVG-enabled plots within a layout. Each plot will result
in a distinct SVG file.
If the filename is not given, it is derived from the script name
(e.g. ``/foo/myplot.py`` will create ``/foo/myplot.svg``)
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, infer from the filename.
height (int) : the desired height of the exported layout obj only if
it's a Plot instance. Otherwise the height kwarg is ignored.
width (int) : the desired width of the exported layout obj only if
it's a Plot instance. Otherwise the width kwarg is ignored.
webdriver (selenium.webdriver) : a selenium webdriver instance to use
to export the image.
timeout (int) : the maximum amount of time (in seconds) to wait for
Bokeh to initialize (default: 5) (Added in 1.1.1).
Returns:
filenames (list(str)) : the list of filenames where the SVGs files are
saved.
.. warning::
Responsive sizing_modes may generate layouts with unexpected size and
aspect ratios. It is recommended to use the default ``fixed`` sizing mode. | [
"Export",
"the",
"SVG",
"-",
"enabled",
"plots",
"within",
"a",
"layout",
".",
"Each",
"plot",
"will",
"result",
"in",
"a",
"distinct",
"SVG",
"file",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/export.py#L109-L166 | train |
bokeh/bokeh | bokeh/io/export.py | get_screenshot_as_png | def get_screenshot_as_png(obj, driver=None, timeout=5, **kwargs):
''' Get a screenshot of a ``LayoutDOM`` object.
Args:
obj (LayoutDOM or Document) : a Layout (Row/Column), Plot or Widget
object or Document to export.
driver (selenium.webdriver) : a selenium webdriver instance to use
to export the image.
timeout (int) : the maximum amount of time to wait for initialization.
It will be used as a timeout for loading Bokeh, then when waiting for
the layout to be rendered.
Returns:
cropped_image (PIL.Image.Image) : a pillow image loaded from PNG.
.. warning::
Responsive sizing_modes may generate layouts with unexpected size and
aspect ratios. It is recommended to use the default ``fixed`` sizing mode.
'''
Image = import_required('PIL.Image',
'To use bokeh.io.export_png you need pillow ' +
'("conda install pillow" or "pip install pillow")')
with _tmp_html() as tmp:
html = get_layout_html(obj, **kwargs)
with io.open(tmp.path, mode="w", encoding="utf-8") as file:
file.write(decode_utf8(html))
web_driver = driver if driver is not None else webdriver_control.get()
web_driver.get("file:///" + tmp.path)
web_driver.maximize_window()
## resize for PhantomJS compat
web_driver.execute_script("document.body.style.width = '100%';")
wait_until_render_complete(web_driver, timeout)
png = web_driver.get_screenshot_as_png()
b_rect = web_driver.execute_script(_BOUNDING_RECT_SCRIPT)
image = Image.open(io.BytesIO(png))
cropped_image = _crop_image(image, **b_rect)
return cropped_image | python | def get_screenshot_as_png(obj, driver=None, timeout=5, **kwargs):
''' Get a screenshot of a ``LayoutDOM`` object.
Args:
obj (LayoutDOM or Document) : a Layout (Row/Column), Plot or Widget
object or Document to export.
driver (selenium.webdriver) : a selenium webdriver instance to use
to export the image.
timeout (int) : the maximum amount of time to wait for initialization.
It will be used as a timeout for loading Bokeh, then when waiting for
the layout to be rendered.
Returns:
cropped_image (PIL.Image.Image) : a pillow image loaded from PNG.
.. warning::
Responsive sizing_modes may generate layouts with unexpected size and
aspect ratios. It is recommended to use the default ``fixed`` sizing mode.
'''
Image = import_required('PIL.Image',
'To use bokeh.io.export_png you need pillow ' +
'("conda install pillow" or "pip install pillow")')
with _tmp_html() as tmp:
html = get_layout_html(obj, **kwargs)
with io.open(tmp.path, mode="w", encoding="utf-8") as file:
file.write(decode_utf8(html))
web_driver = driver if driver is not None else webdriver_control.get()
web_driver.get("file:///" + tmp.path)
web_driver.maximize_window()
## resize for PhantomJS compat
web_driver.execute_script("document.body.style.width = '100%';")
wait_until_render_complete(web_driver, timeout)
png = web_driver.get_screenshot_as_png()
b_rect = web_driver.execute_script(_BOUNDING_RECT_SCRIPT)
image = Image.open(io.BytesIO(png))
cropped_image = _crop_image(image, **b_rect)
return cropped_image | [
"def",
"get_screenshot_as_png",
"(",
"obj",
",",
"driver",
"=",
"None",
",",
"timeout",
"=",
"5",
",",
"*",
"*",
"kwargs",
")",
":",
"Image",
"=",
"import_required",
"(",
"'PIL.Image'",
",",
"'To use bokeh.io.export_png you need pillow '",
"+",
"'(\"conda install pillow\" or \"pip install pillow\")'",
")",
"with",
"_tmp_html",
"(",
")",
"as",
"tmp",
":",
"html",
"=",
"get_layout_html",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
"with",
"io",
".",
"open",
"(",
"tmp",
".",
"path",
",",
"mode",
"=",
"\"w\"",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"file",
":",
"file",
".",
"write",
"(",
"decode_utf8",
"(",
"html",
")",
")",
"web_driver",
"=",
"driver",
"if",
"driver",
"is",
"not",
"None",
"else",
"webdriver_control",
".",
"get",
"(",
")",
"web_driver",
".",
"get",
"(",
"\"file:///\"",
"+",
"tmp",
".",
"path",
")",
"web_driver",
".",
"maximize_window",
"(",
")",
"## resize for PhantomJS compat",
"web_driver",
".",
"execute_script",
"(",
"\"document.body.style.width = '100%';\"",
")",
"wait_until_render_complete",
"(",
"web_driver",
",",
"timeout",
")",
"png",
"=",
"web_driver",
".",
"get_screenshot_as_png",
"(",
")",
"b_rect",
"=",
"web_driver",
".",
"execute_script",
"(",
"_BOUNDING_RECT_SCRIPT",
")",
"image",
"=",
"Image",
".",
"open",
"(",
"io",
".",
"BytesIO",
"(",
"png",
")",
")",
"cropped_image",
"=",
"_crop_image",
"(",
"image",
",",
"*",
"*",
"b_rect",
")",
"return",
"cropped_image"
] | Get a screenshot of a ``LayoutDOM`` object.
Args:
obj (LayoutDOM or Document) : a Layout (Row/Column), Plot or Widget
object or Document to export.
driver (selenium.webdriver) : a selenium webdriver instance to use
to export the image.
timeout (int) : the maximum amount of time to wait for initialization.
It will be used as a timeout for loading Bokeh, then when waiting for
the layout to be rendered.
Returns:
cropped_image (PIL.Image.Image) : a pillow image loaded from PNG.
.. warning::
Responsive sizing_modes may generate layouts with unexpected size and
aspect ratios. It is recommended to use the default ``fixed`` sizing mode. | [
"Get",
"a",
"screenshot",
"of",
"a",
"LayoutDOM",
"object",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/export.py#L186-L234 | train |
bokeh/bokeh | bokeh/io/export.py | _crop_image | def _crop_image(image, left=0, top=0, right=0, bottom=0, **kwargs):
''' Crop the border from the layout
'''
return image.crop((left, top, right, bottom)) | python | def _crop_image(image, left=0, top=0, right=0, bottom=0, **kwargs):
''' Crop the border from the layout
'''
return image.crop((left, top, right, bottom)) | [
"def",
"_crop_image",
"(",
"image",
",",
"left",
"=",
"0",
",",
"top",
"=",
"0",
",",
"right",
"=",
"0",
",",
"bottom",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"image",
".",
"crop",
"(",
"(",
"left",
",",
"top",
",",
"right",
",",
"bottom",
")",
")"
] | Crop the border from the layout | [
"Crop",
"the",
"border",
"from",
"the",
"layout"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/export.py#L354-L358 | train |
bokeh/bokeh | bokeh/models/sources.py | ColumnDataSource._data_from_df | def _data_from_df(df):
''' Create a ``dict`` of columns from a Pandas ``DataFrame``,
suitable for creating a ColumnDataSource.
Args:
df (DataFrame) : data to convert
Returns:
dict[str, np.array]
'''
_df = df.copy()
# Flatten columns
if isinstance(df.columns, pd.MultiIndex):
try:
_df.columns = ['_'.join(col) for col in _df.columns.values]
except TypeError:
raise TypeError('Could not flatten MultiIndex columns. '
'use string column names or flatten manually')
# Transform columns CategoricalIndex in list
if isinstance(df.columns, pd.CategoricalIndex):
_df.columns = df.columns.tolist()
# Flatten index
index_name = ColumnDataSource._df_index_name(df)
if index_name == 'index':
_df.index = pd.Index(_df.index.values)
else:
_df.index = pd.Index(_df.index.values, name=index_name)
_df.reset_index(inplace=True)
tmp_data = {c: v.values for c, v in _df.iteritems()}
new_data = {}
for k, v in tmp_data.items():
new_data[k] = v
return new_data | python | def _data_from_df(df):
''' Create a ``dict`` of columns from a Pandas ``DataFrame``,
suitable for creating a ColumnDataSource.
Args:
df (DataFrame) : data to convert
Returns:
dict[str, np.array]
'''
_df = df.copy()
# Flatten columns
if isinstance(df.columns, pd.MultiIndex):
try:
_df.columns = ['_'.join(col) for col in _df.columns.values]
except TypeError:
raise TypeError('Could not flatten MultiIndex columns. '
'use string column names or flatten manually')
# Transform columns CategoricalIndex in list
if isinstance(df.columns, pd.CategoricalIndex):
_df.columns = df.columns.tolist()
# Flatten index
index_name = ColumnDataSource._df_index_name(df)
if index_name == 'index':
_df.index = pd.Index(_df.index.values)
else:
_df.index = pd.Index(_df.index.values, name=index_name)
_df.reset_index(inplace=True)
tmp_data = {c: v.values for c, v in _df.iteritems()}
new_data = {}
for k, v in tmp_data.items():
new_data[k] = v
return new_data | [
"def",
"_data_from_df",
"(",
"df",
")",
":",
"_df",
"=",
"df",
".",
"copy",
"(",
")",
"# Flatten columns",
"if",
"isinstance",
"(",
"df",
".",
"columns",
",",
"pd",
".",
"MultiIndex",
")",
":",
"try",
":",
"_df",
".",
"columns",
"=",
"[",
"'_'",
".",
"join",
"(",
"col",
")",
"for",
"col",
"in",
"_df",
".",
"columns",
".",
"values",
"]",
"except",
"TypeError",
":",
"raise",
"TypeError",
"(",
"'Could not flatten MultiIndex columns. '",
"'use string column names or flatten manually'",
")",
"# Transform columns CategoricalIndex in list",
"if",
"isinstance",
"(",
"df",
".",
"columns",
",",
"pd",
".",
"CategoricalIndex",
")",
":",
"_df",
".",
"columns",
"=",
"df",
".",
"columns",
".",
"tolist",
"(",
")",
"# Flatten index",
"index_name",
"=",
"ColumnDataSource",
".",
"_df_index_name",
"(",
"df",
")",
"if",
"index_name",
"==",
"'index'",
":",
"_df",
".",
"index",
"=",
"pd",
".",
"Index",
"(",
"_df",
".",
"index",
".",
"values",
")",
"else",
":",
"_df",
".",
"index",
"=",
"pd",
".",
"Index",
"(",
"_df",
".",
"index",
".",
"values",
",",
"name",
"=",
"index_name",
")",
"_df",
".",
"reset_index",
"(",
"inplace",
"=",
"True",
")",
"tmp_data",
"=",
"{",
"c",
":",
"v",
".",
"values",
"for",
"c",
",",
"v",
"in",
"_df",
".",
"iteritems",
"(",
")",
"}",
"new_data",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"tmp_data",
".",
"items",
"(",
")",
":",
"new_data",
"[",
"k",
"]",
"=",
"v",
"return",
"new_data"
] | Create a ``dict`` of columns from a Pandas ``DataFrame``,
suitable for creating a ColumnDataSource.
Args:
df (DataFrame) : data to convert
Returns:
dict[str, np.array] | [
"Create",
"a",
"dict",
"of",
"columns",
"from",
"a",
"Pandas",
"DataFrame",
"suitable",
"for",
"creating",
"a",
"ColumnDataSource",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/sources.py#L195-L232 | train |
bokeh/bokeh | bokeh/models/sources.py | ColumnDataSource._df_index_name | def _df_index_name(df):
''' Return the Bokeh-appropriate column name for a ``DataFrame`` index
If there is no named index, then `"index" is returned.
If there is a single named index, then ``df.index.name`` is returned.
If there is a multi-index, and the index names are all strings, then
the names are joined with '_' and the result is returned, e.g. for a
multi-index ``['ind1', 'ind2']`` the result will be "ind1_ind2".
Otherwise if any index name is not a string, the fallback name "index"
is returned.
Args:
df (DataFrame) : the ``DataFrame`` to find an index name for
Returns:
str
'''
if df.index.name:
return df.index.name
elif df.index.names:
try:
return "_".join(df.index.names)
except TypeError:
return "index"
else:
return "index" | python | def _df_index_name(df):
''' Return the Bokeh-appropriate column name for a ``DataFrame`` index
If there is no named index, then `"index" is returned.
If there is a single named index, then ``df.index.name`` is returned.
If there is a multi-index, and the index names are all strings, then
the names are joined with '_' and the result is returned, e.g. for a
multi-index ``['ind1', 'ind2']`` the result will be "ind1_ind2".
Otherwise if any index name is not a string, the fallback name "index"
is returned.
Args:
df (DataFrame) : the ``DataFrame`` to find an index name for
Returns:
str
'''
if df.index.name:
return df.index.name
elif df.index.names:
try:
return "_".join(df.index.names)
except TypeError:
return "index"
else:
return "index" | [
"def",
"_df_index_name",
"(",
"df",
")",
":",
"if",
"df",
".",
"index",
".",
"name",
":",
"return",
"df",
".",
"index",
".",
"name",
"elif",
"df",
".",
"index",
".",
"names",
":",
"try",
":",
"return",
"\"_\"",
".",
"join",
"(",
"df",
".",
"index",
".",
"names",
")",
"except",
"TypeError",
":",
"return",
"\"index\"",
"else",
":",
"return",
"\"index\""
] | Return the Bokeh-appropriate column name for a ``DataFrame`` index
If there is no named index, then `"index" is returned.
If there is a single named index, then ``df.index.name`` is returned.
If there is a multi-index, and the index names are all strings, then
the names are joined with '_' and the result is returned, e.g. for a
multi-index ``['ind1', 'ind2']`` the result will be "ind1_ind2".
Otherwise if any index name is not a string, the fallback name "index"
is returned.
Args:
df (DataFrame) : the ``DataFrame`` to find an index name for
Returns:
str | [
"Return",
"the",
"Bokeh",
"-",
"appropriate",
"column",
"name",
"for",
"a",
"DataFrame",
"index"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/sources.py#L252-L280 | train |
bokeh/bokeh | bokeh/models/sources.py | ColumnDataSource.add | def add(self, data, name=None):
''' Appends a new column of data to the data source.
Args:
data (seq) : new data to add
name (str, optional) : column name to use.
If not supplied, generate a name of the form "Series ####"
Returns:
str: the column name used
'''
if name is None:
n = len(self.data)
while "Series %d"%n in self.data:
n += 1
name = "Series %d"%n
self.data[name] = data
return name | python | def add(self, data, name=None):
''' Appends a new column of data to the data source.
Args:
data (seq) : new data to add
name (str, optional) : column name to use.
If not supplied, generate a name of the form "Series ####"
Returns:
str: the column name used
'''
if name is None:
n = len(self.data)
while "Series %d"%n in self.data:
n += 1
name = "Series %d"%n
self.data[name] = data
return name | [
"def",
"add",
"(",
"self",
",",
"data",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"n",
"=",
"len",
"(",
"self",
".",
"data",
")",
"while",
"\"Series %d\"",
"%",
"n",
"in",
"self",
".",
"data",
":",
"n",
"+=",
"1",
"name",
"=",
"\"Series %d\"",
"%",
"n",
"self",
".",
"data",
"[",
"name",
"]",
"=",
"data",
"return",
"name"
] | Appends a new column of data to the data source.
Args:
data (seq) : new data to add
name (str, optional) : column name to use.
If not supplied, generate a name of the form "Series ####"
Returns:
str: the column name used | [
"Appends",
"a",
"new",
"column",
"of",
"data",
"to",
"the",
"data",
"source",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/sources.py#L325-L343 | train |
bokeh/bokeh | bokeh/models/sources.py | ColumnDataSource.remove | def remove(self, name):
''' Remove a column of data.
Args:
name (str) : name of the column to remove
Returns:
None
.. note::
If the column name does not exist, a warning is issued.
'''
try:
del self.data[name]
except (ValueError, KeyError):
import warnings
warnings.warn("Unable to find column '%s' in data source" % name) | python | def remove(self, name):
''' Remove a column of data.
Args:
name (str) : name of the column to remove
Returns:
None
.. note::
If the column name does not exist, a warning is issued.
'''
try:
del self.data[name]
except (ValueError, KeyError):
import warnings
warnings.warn("Unable to find column '%s' in data source" % name) | [
"def",
"remove",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"del",
"self",
".",
"data",
"[",
"name",
"]",
"except",
"(",
"ValueError",
",",
"KeyError",
")",
":",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"\"Unable to find column '%s' in data source\"",
"%",
"name",
")"
] | Remove a column of data.
Args:
name (str) : name of the column to remove
Returns:
None
.. note::
If the column name does not exist, a warning is issued. | [
"Remove",
"a",
"column",
"of",
"data",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/sources.py#L346-L363 | train |
bokeh/bokeh | bokeh/models/sources.py | ColumnDataSource._stream | def _stream(self, new_data, rollover=None, setter=None):
''' Internal implementation to efficiently update data source columns
with new append-only data. The internal implementation adds the setter
attribute. [https://github.com/bokeh/bokeh/issues/6577]
In cases where it is necessary to update data columns in, this method
can efficiently send only the new data, instead of requiring the
entire data set to be re-sent.
Args:
new_data (dict[str, seq] or DataFrame or Series) : a mapping of
column names to sequences of new data to append to each column,
a pandas DataFrame, or a pandas Series in case of a single row -
in this case the Series index is used as column names
All columns of the data source must be present in ``new_data``,
with identical-length append data.
rollover (int, optional) : A maximum column size, above which data
from the start of the column begins to be discarded. If None,
then columns will continue to grow unbounded (default: None)
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
Raises:
ValueError
Example:
.. code-block:: python
source = ColumnDataSource(data=dict(foo=[], bar=[]))
# has new, identical-length updates for all columns in source
new_data = {
'foo' : [10, 20],
'bar' : [100, 200],
}
source.stream(new_data)
'''
needs_length_check = True
if pd and isinstance(new_data, pd.Series):
new_data = new_data.to_frame().T
if pd and isinstance(new_data, pd.DataFrame):
needs_length_check = False # DataFrame lengths equal by definition
_df = new_data
newkeys = set(_df.columns)
index_name = ColumnDataSource._df_index_name(_df)
newkeys.add(index_name)
new_data = dict(_df.iteritems())
new_data[index_name] = _df.index.values
else:
newkeys = set(new_data.keys())
oldkeys = set(self.data.keys())
if newkeys != oldkeys:
missing = oldkeys - newkeys
extra = newkeys - oldkeys
if missing and extra:
raise ValueError(
"Must stream updates to all existing columns (missing: %s, extra: %s)" % (", ".join(sorted(missing)), ", ".join(sorted(extra)))
)
elif missing:
raise ValueError("Must stream updates to all existing columns (missing: %s)" % ", ".join(sorted(missing)))
else:
raise ValueError("Must stream updates to all existing columns (extra: %s)" % ", ".join(sorted(extra)))
import numpy as np
if needs_length_check:
lengths = set()
arr_types = (np.ndarray, pd.Series) if pd else np.ndarray
for k, x in new_data.items():
if isinstance(x, arr_types):
if len(x.shape) != 1:
raise ValueError("stream(...) only supports 1d sequences, got ndarray with size %r" % (x.shape,))
lengths.add(x.shape[0])
else:
lengths.add(len(x))
if len(lengths) > 1:
raise ValueError("All streaming column updates must be the same length")
# slightly awkward that we have to call convert_datetime_array here ourselves
# but the downstream code expects things to already be ms-since-epoch
for key, values in new_data.items():
if pd and isinstance(values, (pd.Series, pd.Index)):
values = values.values
old_values = self.data[key]
# Apply the transformation if the new data contains datetimes
# but the current data has already been transformed
if (isinstance(values, np.ndarray) and values.dtype.kind.lower() == 'm' and
isinstance(old_values, np.ndarray) and old_values.dtype.kind.lower() != 'm'):
new_data[key] = convert_datetime_array(values)
else:
new_data[key] = values
self.data._stream(self.document, self, new_data, rollover, setter) | python | def _stream(self, new_data, rollover=None, setter=None):
''' Internal implementation to efficiently update data source columns
with new append-only data. The internal implementation adds the setter
attribute. [https://github.com/bokeh/bokeh/issues/6577]
In cases where it is necessary to update data columns in, this method
can efficiently send only the new data, instead of requiring the
entire data set to be re-sent.
Args:
new_data (dict[str, seq] or DataFrame or Series) : a mapping of
column names to sequences of new data to append to each column,
a pandas DataFrame, or a pandas Series in case of a single row -
in this case the Series index is used as column names
All columns of the data source must be present in ``new_data``,
with identical-length append data.
rollover (int, optional) : A maximum column size, above which data
from the start of the column begins to be discarded. If None,
then columns will continue to grow unbounded (default: None)
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
Raises:
ValueError
Example:
.. code-block:: python
source = ColumnDataSource(data=dict(foo=[], bar=[]))
# has new, identical-length updates for all columns in source
new_data = {
'foo' : [10, 20],
'bar' : [100, 200],
}
source.stream(new_data)
'''
needs_length_check = True
if pd and isinstance(new_data, pd.Series):
new_data = new_data.to_frame().T
if pd and isinstance(new_data, pd.DataFrame):
needs_length_check = False # DataFrame lengths equal by definition
_df = new_data
newkeys = set(_df.columns)
index_name = ColumnDataSource._df_index_name(_df)
newkeys.add(index_name)
new_data = dict(_df.iteritems())
new_data[index_name] = _df.index.values
else:
newkeys = set(new_data.keys())
oldkeys = set(self.data.keys())
if newkeys != oldkeys:
missing = oldkeys - newkeys
extra = newkeys - oldkeys
if missing and extra:
raise ValueError(
"Must stream updates to all existing columns (missing: %s, extra: %s)" % (", ".join(sorted(missing)), ", ".join(sorted(extra)))
)
elif missing:
raise ValueError("Must stream updates to all existing columns (missing: %s)" % ", ".join(sorted(missing)))
else:
raise ValueError("Must stream updates to all existing columns (extra: %s)" % ", ".join(sorted(extra)))
import numpy as np
if needs_length_check:
lengths = set()
arr_types = (np.ndarray, pd.Series) if pd else np.ndarray
for k, x in new_data.items():
if isinstance(x, arr_types):
if len(x.shape) != 1:
raise ValueError("stream(...) only supports 1d sequences, got ndarray with size %r" % (x.shape,))
lengths.add(x.shape[0])
else:
lengths.add(len(x))
if len(lengths) > 1:
raise ValueError("All streaming column updates must be the same length")
# slightly awkward that we have to call convert_datetime_array here ourselves
# but the downstream code expects things to already be ms-since-epoch
for key, values in new_data.items():
if pd and isinstance(values, (pd.Series, pd.Index)):
values = values.values
old_values = self.data[key]
# Apply the transformation if the new data contains datetimes
# but the current data has already been transformed
if (isinstance(values, np.ndarray) and values.dtype.kind.lower() == 'm' and
isinstance(old_values, np.ndarray) and old_values.dtype.kind.lower() != 'm'):
new_data[key] = convert_datetime_array(values)
else:
new_data[key] = values
self.data._stream(self.document, self, new_data, rollover, setter) | [
"def",
"_stream",
"(",
"self",
",",
"new_data",
",",
"rollover",
"=",
"None",
",",
"setter",
"=",
"None",
")",
":",
"needs_length_check",
"=",
"True",
"if",
"pd",
"and",
"isinstance",
"(",
"new_data",
",",
"pd",
".",
"Series",
")",
":",
"new_data",
"=",
"new_data",
".",
"to_frame",
"(",
")",
".",
"T",
"if",
"pd",
"and",
"isinstance",
"(",
"new_data",
",",
"pd",
".",
"DataFrame",
")",
":",
"needs_length_check",
"=",
"False",
"# DataFrame lengths equal by definition",
"_df",
"=",
"new_data",
"newkeys",
"=",
"set",
"(",
"_df",
".",
"columns",
")",
"index_name",
"=",
"ColumnDataSource",
".",
"_df_index_name",
"(",
"_df",
")",
"newkeys",
".",
"add",
"(",
"index_name",
")",
"new_data",
"=",
"dict",
"(",
"_df",
".",
"iteritems",
"(",
")",
")",
"new_data",
"[",
"index_name",
"]",
"=",
"_df",
".",
"index",
".",
"values",
"else",
":",
"newkeys",
"=",
"set",
"(",
"new_data",
".",
"keys",
"(",
")",
")",
"oldkeys",
"=",
"set",
"(",
"self",
".",
"data",
".",
"keys",
"(",
")",
")",
"if",
"newkeys",
"!=",
"oldkeys",
":",
"missing",
"=",
"oldkeys",
"-",
"newkeys",
"extra",
"=",
"newkeys",
"-",
"oldkeys",
"if",
"missing",
"and",
"extra",
":",
"raise",
"ValueError",
"(",
"\"Must stream updates to all existing columns (missing: %s, extra: %s)\"",
"%",
"(",
"\", \"",
".",
"join",
"(",
"sorted",
"(",
"missing",
")",
")",
",",
"\", \"",
".",
"join",
"(",
"sorted",
"(",
"extra",
")",
")",
")",
")",
"elif",
"missing",
":",
"raise",
"ValueError",
"(",
"\"Must stream updates to all existing columns (missing: %s)\"",
"%",
"\", \"",
".",
"join",
"(",
"sorted",
"(",
"missing",
")",
")",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Must stream updates to all existing columns (extra: %s)\"",
"%",
"\", \"",
".",
"join",
"(",
"sorted",
"(",
"extra",
")",
")",
")",
"import",
"numpy",
"as",
"np",
"if",
"needs_length_check",
":",
"lengths",
"=",
"set",
"(",
")",
"arr_types",
"=",
"(",
"np",
".",
"ndarray",
",",
"pd",
".",
"Series",
")",
"if",
"pd",
"else",
"np",
".",
"ndarray",
"for",
"k",
",",
"x",
"in",
"new_data",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"arr_types",
")",
":",
"if",
"len",
"(",
"x",
".",
"shape",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"stream(...) only supports 1d sequences, got ndarray with size %r\"",
"%",
"(",
"x",
".",
"shape",
",",
")",
")",
"lengths",
".",
"add",
"(",
"x",
".",
"shape",
"[",
"0",
"]",
")",
"else",
":",
"lengths",
".",
"add",
"(",
"len",
"(",
"x",
")",
")",
"if",
"len",
"(",
"lengths",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"All streaming column updates must be the same length\"",
")",
"# slightly awkward that we have to call convert_datetime_array here ourselves",
"# but the downstream code expects things to already be ms-since-epoch",
"for",
"key",
",",
"values",
"in",
"new_data",
".",
"items",
"(",
")",
":",
"if",
"pd",
"and",
"isinstance",
"(",
"values",
",",
"(",
"pd",
".",
"Series",
",",
"pd",
".",
"Index",
")",
")",
":",
"values",
"=",
"values",
".",
"values",
"old_values",
"=",
"self",
".",
"data",
"[",
"key",
"]",
"# Apply the transformation if the new data contains datetimes",
"# but the current data has already been transformed",
"if",
"(",
"isinstance",
"(",
"values",
",",
"np",
".",
"ndarray",
")",
"and",
"values",
".",
"dtype",
".",
"kind",
".",
"lower",
"(",
")",
"==",
"'m'",
"and",
"isinstance",
"(",
"old_values",
",",
"np",
".",
"ndarray",
")",
"and",
"old_values",
".",
"dtype",
".",
"kind",
".",
"lower",
"(",
")",
"!=",
"'m'",
")",
":",
"new_data",
"[",
"key",
"]",
"=",
"convert_datetime_array",
"(",
"values",
")",
"else",
":",
"new_data",
"[",
"key",
"]",
"=",
"values",
"self",
".",
"data",
".",
"_stream",
"(",
"self",
".",
"document",
",",
"self",
",",
"new_data",
",",
"rollover",
",",
"setter",
")"
] | Internal implementation to efficiently update data source columns
with new append-only data. The internal implementation adds the setter
attribute. [https://github.com/bokeh/bokeh/issues/6577]
In cases where it is necessary to update data columns in, this method
can efficiently send only the new data, instead of requiring the
entire data set to be re-sent.
Args:
new_data (dict[str, seq] or DataFrame or Series) : a mapping of
column names to sequences of new data to append to each column,
a pandas DataFrame, or a pandas Series in case of a single row -
in this case the Series index is used as column names
All columns of the data source must be present in ``new_data``,
with identical-length append data.
rollover (int, optional) : A maximum column size, above which data
from the start of the column begins to be discarded. If None,
then columns will continue to grow unbounded (default: None)
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
Raises:
ValueError
Example:
.. code-block:: python
source = ColumnDataSource(data=dict(foo=[], bar=[]))
# has new, identical-length updates for all columns in source
new_data = {
'foo' : [10, 20],
'bar' : [100, 200],
}
source.stream(new_data) | [
"Internal",
"implementation",
"to",
"efficiently",
"update",
"data",
"source",
"columns",
"with",
"new",
"append",
"-",
"only",
"data",
".",
"The",
"internal",
"implementation",
"adds",
"the",
"setter",
"attribute",
".",
"[",
"https",
":",
"//",
"github",
".",
"com",
"/",
"bokeh",
"/",
"bokeh",
"/",
"issues",
"/",
"6577",
"]"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/sources.py#L407-L517 | train |
bokeh/bokeh | bokeh/models/sources.py | ColumnDataSource.patch | def patch(self, patches, setter=None):
''' Efficiently update data source columns at specific locations
If it is only necessary to update a small subset of data in a
``ColumnDataSource``, this method can be used to efficiently update only
the subset, instead of requiring the entire data set to be sent.
This method should be passed a dictionary that maps column names to
lists of tuples that describe a patch change to apply. To replace
individual items in columns entirely, the tuples should be of the
form:
.. code-block:: python
(index, new_value) # replace a single column value
# or
(slice, new_values) # replace several column values
Values at an index or slice will be replaced with the corresponding
new values.
In the case of columns whose values are other arrays or lists, (e.g.
image or patches glyphs), it is also possible to patch "subregions".
In this case the first item of the tuple should be a whose first
element is the index of the array item in the CDS patch, and whose
subsequent elements are integer indices or slices into the array item:
.. code-block:: python
# replace the entire 10th column of the 2nd array:
+----------------- index of item in column data source
|
| +--------- row subindex into array item
| |
| | +- column subindex into array item
V V V
([2, slice(None), 10], new_values)
Imagining a list of 2d NumPy arrays, the patch above is roughly
equivalent to:
.. code-block:: python
data = [arr1, arr2, ...] # list of 2d arrays
data[2][:, 10] = new_data
There are some limitations to the kinds of slices and data that can
be accepted.
* Negative ``start``, ``stop``, or ``step`` values for slices will
result in a ``ValueError``.
* In a slice, ``start > stop`` will result in a ``ValueError``
* When patching 1d or 2d subitems, the subitems must be NumPy arrays.
* New values must be supplied as a **flattened one-dimensional array**
of the appropriate size.
Args:
patches (dict[str, list[tuple]]) : lists of patches for each column
Returns:
None
Raises:
ValueError
Example:
The following example shows how to patch entire column elements. In this case,
.. code-block:: python
source = ColumnDataSource(data=dict(foo=[10, 20, 30], bar=[100, 200, 300]))
patches = {
'foo' : [ (slice(2), [11, 12]) ],
'bar' : [ (0, 101), (2, 301) ],
}
source.patch(patches)
After this operation, the value of the ``source.data`` will be:
.. code-block:: python
dict(foo=[11, 12, 30], bar=[101, 200, 301])
For a more comprehensive complete example, see :bokeh-tree:`examples/howto/patch_app.py`.
'''
import numpy as np
extra = set(patches.keys()) - set(self.data.keys())
if extra:
raise ValueError("Can only patch existing columns (extra: %s)" % ", ".join(sorted(extra)))
for name, patch in patches.items():
col_len = len(self.data[name])
for ind, value in patch:
# integer index, patch single value of 1d column
if isinstance(ind, int):
if ind > col_len or ind < 0:
raise ValueError("Out-of bounds index (%d) in patch for column: %s" % (ind, name))
# slice index, patch multiple values of 1d column
elif isinstance(ind, slice):
_check_slice(ind)
if ind.stop is not None and ind.stop > col_len:
raise ValueError("Out-of bounds slice index stop (%d) in patch for column: %s" % (ind.stop, name))
# multi-index, patch sub-regions of "n-d" column
elif isinstance(ind, (list, tuple)):
if len(ind) == 0:
raise ValueError("Empty (length zero) patch multi-index")
if len(ind) == 1:
raise ValueError("Patch multi-index must contain more than one subindex")
if not isinstance(ind[0], int):
raise ValueError("Initial patch sub-index may only be integer, got: %s" % ind[0])
if ind[0] > col_len or ind[0] < 0:
raise ValueError("Out-of bounds initial sub-index (%d) in patch for column: %s" % (ind, name))
if not isinstance(self.data[name][ind[0]], np.ndarray):
raise ValueError("Can only sub-patch into columns with NumPy array items")
if len(self.data[name][ind[0]].shape) != (len(ind)-1):
raise ValueError("Shape mismatch between patch slice and sliced data")
elif isinstance(ind[0], slice):
_check_slice(ind[0])
if ind[0].stop is not None and ind[0].stop > col_len:
raise ValueError("Out-of bounds initial slice sub-index stop (%d) in patch for column: %s" % (ind.stop, name))
# Note: bounds of sub-indices after the first are not checked!
for subind in ind[1:]:
if not isinstance(subind, (int, slice)):
raise ValueError("Invalid patch sub-index: %s" % subind)
if isinstance(subind, slice):
_check_slice(subind)
else:
raise ValueError("Invalid patch index: %s" % ind)
self.data._patch(self.document, self, patches, setter) | python | def patch(self, patches, setter=None):
''' Efficiently update data source columns at specific locations
If it is only necessary to update a small subset of data in a
``ColumnDataSource``, this method can be used to efficiently update only
the subset, instead of requiring the entire data set to be sent.
This method should be passed a dictionary that maps column names to
lists of tuples that describe a patch change to apply. To replace
individual items in columns entirely, the tuples should be of the
form:
.. code-block:: python
(index, new_value) # replace a single column value
# or
(slice, new_values) # replace several column values
Values at an index or slice will be replaced with the corresponding
new values.
In the case of columns whose values are other arrays or lists, (e.g.
image or patches glyphs), it is also possible to patch "subregions".
In this case the first item of the tuple should be a whose first
element is the index of the array item in the CDS patch, and whose
subsequent elements are integer indices or slices into the array item:
.. code-block:: python
# replace the entire 10th column of the 2nd array:
+----------------- index of item in column data source
|
| +--------- row subindex into array item
| |
| | +- column subindex into array item
V V V
([2, slice(None), 10], new_values)
Imagining a list of 2d NumPy arrays, the patch above is roughly
equivalent to:
.. code-block:: python
data = [arr1, arr2, ...] # list of 2d arrays
data[2][:, 10] = new_data
There are some limitations to the kinds of slices and data that can
be accepted.
* Negative ``start``, ``stop``, or ``step`` values for slices will
result in a ``ValueError``.
* In a slice, ``start > stop`` will result in a ``ValueError``
* When patching 1d or 2d subitems, the subitems must be NumPy arrays.
* New values must be supplied as a **flattened one-dimensional array**
of the appropriate size.
Args:
patches (dict[str, list[tuple]]) : lists of patches for each column
Returns:
None
Raises:
ValueError
Example:
The following example shows how to patch entire column elements. In this case,
.. code-block:: python
source = ColumnDataSource(data=dict(foo=[10, 20, 30], bar=[100, 200, 300]))
patches = {
'foo' : [ (slice(2), [11, 12]) ],
'bar' : [ (0, 101), (2, 301) ],
}
source.patch(patches)
After this operation, the value of the ``source.data`` will be:
.. code-block:: python
dict(foo=[11, 12, 30], bar=[101, 200, 301])
For a more comprehensive complete example, see :bokeh-tree:`examples/howto/patch_app.py`.
'''
import numpy as np
extra = set(patches.keys()) - set(self.data.keys())
if extra:
raise ValueError("Can only patch existing columns (extra: %s)" % ", ".join(sorted(extra)))
for name, patch in patches.items():
col_len = len(self.data[name])
for ind, value in patch:
# integer index, patch single value of 1d column
if isinstance(ind, int):
if ind > col_len or ind < 0:
raise ValueError("Out-of bounds index (%d) in patch for column: %s" % (ind, name))
# slice index, patch multiple values of 1d column
elif isinstance(ind, slice):
_check_slice(ind)
if ind.stop is not None and ind.stop > col_len:
raise ValueError("Out-of bounds slice index stop (%d) in patch for column: %s" % (ind.stop, name))
# multi-index, patch sub-regions of "n-d" column
elif isinstance(ind, (list, tuple)):
if len(ind) == 0:
raise ValueError("Empty (length zero) patch multi-index")
if len(ind) == 1:
raise ValueError("Patch multi-index must contain more than one subindex")
if not isinstance(ind[0], int):
raise ValueError("Initial patch sub-index may only be integer, got: %s" % ind[0])
if ind[0] > col_len or ind[0] < 0:
raise ValueError("Out-of bounds initial sub-index (%d) in patch for column: %s" % (ind, name))
if not isinstance(self.data[name][ind[0]], np.ndarray):
raise ValueError("Can only sub-patch into columns with NumPy array items")
if len(self.data[name][ind[0]].shape) != (len(ind)-1):
raise ValueError("Shape mismatch between patch slice and sliced data")
elif isinstance(ind[0], slice):
_check_slice(ind[0])
if ind[0].stop is not None and ind[0].stop > col_len:
raise ValueError("Out-of bounds initial slice sub-index stop (%d) in patch for column: %s" % (ind.stop, name))
# Note: bounds of sub-indices after the first are not checked!
for subind in ind[1:]:
if not isinstance(subind, (int, slice)):
raise ValueError("Invalid patch sub-index: %s" % subind)
if isinstance(subind, slice):
_check_slice(subind)
else:
raise ValueError("Invalid patch index: %s" % ind)
self.data._patch(self.document, self, patches, setter) | [
"def",
"patch",
"(",
"self",
",",
"patches",
",",
"setter",
"=",
"None",
")",
":",
"import",
"numpy",
"as",
"np",
"extra",
"=",
"set",
"(",
"patches",
".",
"keys",
"(",
")",
")",
"-",
"set",
"(",
"self",
".",
"data",
".",
"keys",
"(",
")",
")",
"if",
"extra",
":",
"raise",
"ValueError",
"(",
"\"Can only patch existing columns (extra: %s)\"",
"%",
"\", \"",
".",
"join",
"(",
"sorted",
"(",
"extra",
")",
")",
")",
"for",
"name",
",",
"patch",
"in",
"patches",
".",
"items",
"(",
")",
":",
"col_len",
"=",
"len",
"(",
"self",
".",
"data",
"[",
"name",
"]",
")",
"for",
"ind",
",",
"value",
"in",
"patch",
":",
"# integer index, patch single value of 1d column",
"if",
"isinstance",
"(",
"ind",
",",
"int",
")",
":",
"if",
"ind",
">",
"col_len",
"or",
"ind",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Out-of bounds index (%d) in patch for column: %s\"",
"%",
"(",
"ind",
",",
"name",
")",
")",
"# slice index, patch multiple values of 1d column",
"elif",
"isinstance",
"(",
"ind",
",",
"slice",
")",
":",
"_check_slice",
"(",
"ind",
")",
"if",
"ind",
".",
"stop",
"is",
"not",
"None",
"and",
"ind",
".",
"stop",
">",
"col_len",
":",
"raise",
"ValueError",
"(",
"\"Out-of bounds slice index stop (%d) in patch for column: %s\"",
"%",
"(",
"ind",
".",
"stop",
",",
"name",
")",
")",
"# multi-index, patch sub-regions of \"n-d\" column",
"elif",
"isinstance",
"(",
"ind",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"if",
"len",
"(",
"ind",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"Empty (length zero) patch multi-index\"",
")",
"if",
"len",
"(",
"ind",
")",
"==",
"1",
":",
"raise",
"ValueError",
"(",
"\"Patch multi-index must contain more than one subindex\"",
")",
"if",
"not",
"isinstance",
"(",
"ind",
"[",
"0",
"]",
",",
"int",
")",
":",
"raise",
"ValueError",
"(",
"\"Initial patch sub-index may only be integer, got: %s\"",
"%",
"ind",
"[",
"0",
"]",
")",
"if",
"ind",
"[",
"0",
"]",
">",
"col_len",
"or",
"ind",
"[",
"0",
"]",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Out-of bounds initial sub-index (%d) in patch for column: %s\"",
"%",
"(",
"ind",
",",
"name",
")",
")",
"if",
"not",
"isinstance",
"(",
"self",
".",
"data",
"[",
"name",
"]",
"[",
"ind",
"[",
"0",
"]",
"]",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"ValueError",
"(",
"\"Can only sub-patch into columns with NumPy array items\"",
")",
"if",
"len",
"(",
"self",
".",
"data",
"[",
"name",
"]",
"[",
"ind",
"[",
"0",
"]",
"]",
".",
"shape",
")",
"!=",
"(",
"len",
"(",
"ind",
")",
"-",
"1",
")",
":",
"raise",
"ValueError",
"(",
"\"Shape mismatch between patch slice and sliced data\"",
")",
"elif",
"isinstance",
"(",
"ind",
"[",
"0",
"]",
",",
"slice",
")",
":",
"_check_slice",
"(",
"ind",
"[",
"0",
"]",
")",
"if",
"ind",
"[",
"0",
"]",
".",
"stop",
"is",
"not",
"None",
"and",
"ind",
"[",
"0",
"]",
".",
"stop",
">",
"col_len",
":",
"raise",
"ValueError",
"(",
"\"Out-of bounds initial slice sub-index stop (%d) in patch for column: %s\"",
"%",
"(",
"ind",
".",
"stop",
",",
"name",
")",
")",
"# Note: bounds of sub-indices after the first are not checked!",
"for",
"subind",
"in",
"ind",
"[",
"1",
":",
"]",
":",
"if",
"not",
"isinstance",
"(",
"subind",
",",
"(",
"int",
",",
"slice",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid patch sub-index: %s\"",
"%",
"subind",
")",
"if",
"isinstance",
"(",
"subind",
",",
"slice",
")",
":",
"_check_slice",
"(",
"subind",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Invalid patch index: %s\"",
"%",
"ind",
")",
"self",
".",
"data",
".",
"_patch",
"(",
"self",
".",
"document",
",",
"self",
",",
"patches",
",",
"setter",
")"
] | Efficiently update data source columns at specific locations
If it is only necessary to update a small subset of data in a
``ColumnDataSource``, this method can be used to efficiently update only
the subset, instead of requiring the entire data set to be sent.
This method should be passed a dictionary that maps column names to
lists of tuples that describe a patch change to apply. To replace
individual items in columns entirely, the tuples should be of the
form:
.. code-block:: python
(index, new_value) # replace a single column value
# or
(slice, new_values) # replace several column values
Values at an index or slice will be replaced with the corresponding
new values.
In the case of columns whose values are other arrays or lists, (e.g.
image or patches glyphs), it is also possible to patch "subregions".
In this case the first item of the tuple should be a whose first
element is the index of the array item in the CDS patch, and whose
subsequent elements are integer indices or slices into the array item:
.. code-block:: python
# replace the entire 10th column of the 2nd array:
+----------------- index of item in column data source
|
| +--------- row subindex into array item
| |
| | +- column subindex into array item
V V V
([2, slice(None), 10], new_values)
Imagining a list of 2d NumPy arrays, the patch above is roughly
equivalent to:
.. code-block:: python
data = [arr1, arr2, ...] # list of 2d arrays
data[2][:, 10] = new_data
There are some limitations to the kinds of slices and data that can
be accepted.
* Negative ``start``, ``stop``, or ``step`` values for slices will
result in a ``ValueError``.
* In a slice, ``start > stop`` will result in a ``ValueError``
* When patching 1d or 2d subitems, the subitems must be NumPy arrays.
* New values must be supplied as a **flattened one-dimensional array**
of the appropriate size.
Args:
patches (dict[str, list[tuple]]) : lists of patches for each column
Returns:
None
Raises:
ValueError
Example:
The following example shows how to patch entire column elements. In this case,
.. code-block:: python
source = ColumnDataSource(data=dict(foo=[10, 20, 30], bar=[100, 200, 300]))
patches = {
'foo' : [ (slice(2), [11, 12]) ],
'bar' : [ (0, 101), (2, 301) ],
}
source.patch(patches)
After this operation, the value of the ``source.data`` will be:
.. code-block:: python
dict(foo=[11, 12, 30], bar=[101, 200, 301])
For a more comprehensive complete example, see :bokeh-tree:`examples/howto/patch_app.py`. | [
"Efficiently",
"update",
"data",
"source",
"columns",
"at",
"specific",
"locations"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/sources.py#L519-L674 | train |
bokeh/bokeh | bokeh/core/validation/check.py | silence | def silence(warning, silence=True):
''' Silence a particular warning on all Bokeh models.
Args:
warning (Warning) : Bokeh warning to silence
silence (bool) : Whether or not to silence the warning
Returns:
A set containing the all silenced warnings
This function adds or removes warnings from a set of silencers which
is referred to when running ``check_integrity``. If a warning
is added to the silencers - then it will never be raised.
.. code-block:: python
>>> from bokeh.core.validation.warnings import EMPTY_LAYOUT
>>> bokeh.core.validation.silence(EMPTY_LAYOUT, True)
{1002}
To turn a warning back on use the same method but with the silence
argument set to false
.. code-block:: python
>>> bokeh.core.validation.silence(EMPTY_LAYOUT, False)
set()
'''
if not isinstance(warning, int):
raise ValueError('Input to silence should be a warning object '
'- not of type {}'.format(type(warning)))
if silence:
__silencers__.add(warning)
elif warning in __silencers__:
__silencers__.remove(warning)
return __silencers__ | python | def silence(warning, silence=True):
''' Silence a particular warning on all Bokeh models.
Args:
warning (Warning) : Bokeh warning to silence
silence (bool) : Whether or not to silence the warning
Returns:
A set containing the all silenced warnings
This function adds or removes warnings from a set of silencers which
is referred to when running ``check_integrity``. If a warning
is added to the silencers - then it will never be raised.
.. code-block:: python
>>> from bokeh.core.validation.warnings import EMPTY_LAYOUT
>>> bokeh.core.validation.silence(EMPTY_LAYOUT, True)
{1002}
To turn a warning back on use the same method but with the silence
argument set to false
.. code-block:: python
>>> bokeh.core.validation.silence(EMPTY_LAYOUT, False)
set()
'''
if not isinstance(warning, int):
raise ValueError('Input to silence should be a warning object '
'- not of type {}'.format(type(warning)))
if silence:
__silencers__.add(warning)
elif warning in __silencers__:
__silencers__.remove(warning)
return __silencers__ | [
"def",
"silence",
"(",
"warning",
",",
"silence",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"warning",
",",
"int",
")",
":",
"raise",
"ValueError",
"(",
"'Input to silence should be a warning object '",
"'- not of type {}'",
".",
"format",
"(",
"type",
"(",
"warning",
")",
")",
")",
"if",
"silence",
":",
"__silencers__",
".",
"add",
"(",
"warning",
")",
"elif",
"warning",
"in",
"__silencers__",
":",
"__silencers__",
".",
"remove",
"(",
"warning",
")",
"return",
"__silencers__"
] | Silence a particular warning on all Bokeh models.
Args:
warning (Warning) : Bokeh warning to silence
silence (bool) : Whether or not to silence the warning
Returns:
A set containing the all silenced warnings
This function adds or removes warnings from a set of silencers which
is referred to when running ``check_integrity``. If a warning
is added to the silencers - then it will never be raised.
.. code-block:: python
>>> from bokeh.core.validation.warnings import EMPTY_LAYOUT
>>> bokeh.core.validation.silence(EMPTY_LAYOUT, True)
{1002}
To turn a warning back on use the same method but with the silence
argument set to false
.. code-block:: python
>>> bokeh.core.validation.silence(EMPTY_LAYOUT, False)
set() | [
"Silence",
"a",
"particular",
"warning",
"on",
"all",
"Bokeh",
"models",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/validation/check.py#L43-L79 | train |
bokeh/bokeh | bokeh/core/validation/check.py | check_integrity | def check_integrity(models):
''' Apply validation and integrity checks to a collection of Bokeh models.
Args:
models (seq[Model]) : a collection of Models to test
Returns:
None
This function will emit log warning and error messages for all error or
warning conditions that are detected. For example, layouts without any
children will trigger a warning:
.. code-block:: python
>>> empty_row = Row
>>> check_integrity([empty_row])
W-1002 (EMPTY_LAYOUT): Layout has no children: Row(id='2404a029-c69b-4e30-9b7d-4b7b6cdaad5b', ...)
'''
messages = dict(error=[], warning=[])
for model in models:
validators = []
for name in dir(model):
if not name.startswith("_check"): continue
obj = getattr(model, name)
if getattr(obj, "validator_type", None):
validators.append(obj)
for func in validators:
messages[func.validator_type].extend(func())
for msg in sorted(messages['error']):
log.error("E-%d (%s): %s: %s" % msg)
for msg in sorted(messages['warning']):
code, name, desc, obj = msg
if code not in __silencers__:
log.warning("W-%d (%s): %s: %s" % msg) | python | def check_integrity(models):
''' Apply validation and integrity checks to a collection of Bokeh models.
Args:
models (seq[Model]) : a collection of Models to test
Returns:
None
This function will emit log warning and error messages for all error or
warning conditions that are detected. For example, layouts without any
children will trigger a warning:
.. code-block:: python
>>> empty_row = Row
>>> check_integrity([empty_row])
W-1002 (EMPTY_LAYOUT): Layout has no children: Row(id='2404a029-c69b-4e30-9b7d-4b7b6cdaad5b', ...)
'''
messages = dict(error=[], warning=[])
for model in models:
validators = []
for name in dir(model):
if not name.startswith("_check"): continue
obj = getattr(model, name)
if getattr(obj, "validator_type", None):
validators.append(obj)
for func in validators:
messages[func.validator_type].extend(func())
for msg in sorted(messages['error']):
log.error("E-%d (%s): %s: %s" % msg)
for msg in sorted(messages['warning']):
code, name, desc, obj = msg
if code not in __silencers__:
log.warning("W-%d (%s): %s: %s" % msg) | [
"def",
"check_integrity",
"(",
"models",
")",
":",
"messages",
"=",
"dict",
"(",
"error",
"=",
"[",
"]",
",",
"warning",
"=",
"[",
"]",
")",
"for",
"model",
"in",
"models",
":",
"validators",
"=",
"[",
"]",
"for",
"name",
"in",
"dir",
"(",
"model",
")",
":",
"if",
"not",
"name",
".",
"startswith",
"(",
"\"_check\"",
")",
":",
"continue",
"obj",
"=",
"getattr",
"(",
"model",
",",
"name",
")",
"if",
"getattr",
"(",
"obj",
",",
"\"validator_type\"",
",",
"None",
")",
":",
"validators",
".",
"append",
"(",
"obj",
")",
"for",
"func",
"in",
"validators",
":",
"messages",
"[",
"func",
".",
"validator_type",
"]",
".",
"extend",
"(",
"func",
"(",
")",
")",
"for",
"msg",
"in",
"sorted",
"(",
"messages",
"[",
"'error'",
"]",
")",
":",
"log",
".",
"error",
"(",
"\"E-%d (%s): %s: %s\"",
"%",
"msg",
")",
"for",
"msg",
"in",
"sorted",
"(",
"messages",
"[",
"'warning'",
"]",
")",
":",
"code",
",",
"name",
",",
"desc",
",",
"obj",
"=",
"msg",
"if",
"code",
"not",
"in",
"__silencers__",
":",
"log",
".",
"warning",
"(",
"\"W-%d (%s): %s: %s\"",
"%",
"msg",
")"
] | Apply validation and integrity checks to a collection of Bokeh models.
Args:
models (seq[Model]) : a collection of Models to test
Returns:
None
This function will emit log warning and error messages for all error or
warning conditions that are detected. For example, layouts without any
children will trigger a warning:
.. code-block:: python
>>> empty_row = Row
>>> check_integrity([empty_row])
W-1002 (EMPTY_LAYOUT): Layout has no children: Row(id='2404a029-c69b-4e30-9b7d-4b7b6cdaad5b', ...) | [
"Apply",
"validation",
"and",
"integrity",
"checks",
"to",
"a",
"collection",
"of",
"Bokeh",
"models",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/validation/check.py#L82-L121 | train |
bokeh/bokeh | bokeh/themes/theme.py | Theme.apply_to_model | def apply_to_model(self, model):
''' Apply this theme to a model.
.. warning::
Typically, don't call this method directly. Instead, set the theme
on the :class:`~bokeh.document.Document` the model is a part of.
'''
model.apply_theme(self._for_class(model.__class__))
# a little paranoia because it would be Bad(tm) to mess
# this up... would be nicer if python had a way to freeze
# the dict.
if len(_empty_dict) > 0:
raise RuntimeError("Somebody put stuff in _empty_dict") | python | def apply_to_model(self, model):
''' Apply this theme to a model.
.. warning::
Typically, don't call this method directly. Instead, set the theme
on the :class:`~bokeh.document.Document` the model is a part of.
'''
model.apply_theme(self._for_class(model.__class__))
# a little paranoia because it would be Bad(tm) to mess
# this up... would be nicer if python had a way to freeze
# the dict.
if len(_empty_dict) > 0:
raise RuntimeError("Somebody put stuff in _empty_dict") | [
"def",
"apply_to_model",
"(",
"self",
",",
"model",
")",
":",
"model",
".",
"apply_theme",
"(",
"self",
".",
"_for_class",
"(",
"model",
".",
"__class__",
")",
")",
"# a little paranoia because it would be Bad(tm) to mess",
"# this up... would be nicer if python had a way to freeze",
"# the dict.",
"if",
"len",
"(",
"_empty_dict",
")",
">",
"0",
":",
"raise",
"RuntimeError",
"(",
"\"Somebody put stuff in _empty_dict\"",
")"
] | Apply this theme to a model.
.. warning::
Typically, don't call this method directly. Instead, set the theme
on the :class:`~bokeh.document.Document` the model is a part of. | [
"Apply",
"this",
"theme",
"to",
"a",
"model",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/themes/theme.py#L186-L200 | train |
bokeh/bokeh | bokeh/embed/util.py | OutputDocumentFor | def OutputDocumentFor(objs, apply_theme=None, always_new=False):
''' Find or create a (possibly temporary) Document to use for serializing
Bokeh content.
Typical usage is similar to:
.. code-block:: python
with OutputDocumentFor(models):
(docs_json, [render_item]) = standalone_docs_json_and_render_items(models)
Inside the context manager, the models will be considered to be part of a single
Document, with any theme specified, which can thus be serialized as a unit. Where
possible, OutputDocumentFor attempts to use an existing Document. However, this is
not possible in three cases:
* If passed a series of models that have no Document at all, a new Document will
be created, and all the models will be added as roots. After the context manager
exits, the new Document will continue to be the models' document.
* If passed a subset of Document.roots, then OutputDocumentFor temporarily "re-homes"
the models in a new bare Document that is only available inside the context manager.
* If passed a list of models that have differnet documents, then OutputDocumentFor
temporarily "re-homes" the models in a new bare Document that is only available
inside the context manager.
OutputDocumentFor will also perfom document validation before yielding, if
``settings.perform_document_validation()`` is True.
objs (seq[Model]) :
a sequence of Models that will be serialized, and need a common document
apply_theme (Theme or FromCurdoc or None, optional):
Sets the theme for the doc while inside this context manager. (default: None)
If None, use whatever theme is on the document that is found or created
If FromCurdoc, use curdoc().theme, restoring any previous theme afterwards
If a Theme instance, use that theme, restoring any previous theme afterwards
always_new (bool, optional) :
Always return a new document, even in cases where it is otherwise possible
to use an existing document on models.
Yields:
Document
'''
# Note: Comms handling relies on the fact that the new_doc returned
# has models with the same IDs as they were started with
if not isinstance(objs, collections_abc.Sequence) or len(objs) == 0 or not all(isinstance(x, Model) for x in objs):
raise ValueError("OutputDocumentFor expects a sequence of Models")
def finish(): pass
docs = set(x.document for x in objs)
if None in docs: docs.remove(None)
if always_new:
def finish(): # NOQA
_dispose_temp_doc(objs)
doc = _create_temp_doc(objs)
else:
if len(docs) == 0:
doc = Document()
for model in objs:
doc.add_root(model)
# handle a single shared document
elif len(docs) == 1:
doc = docs.pop()
# we are not using all the roots, make a quick clone for outputting purposes
if set(objs) != set(doc.roots):
def finish(): # NOQA
_dispose_temp_doc(objs)
doc = _create_temp_doc(objs)
# we are using all the roots of a single doc, just use doc as-is
pass
# models have mixed docs, just make a quick clone
else:
def finish(): # NOQA
_dispose_temp_doc(objs)
doc = _create_temp_doc(objs)
if settings.perform_document_validation():
doc.validate()
_set_temp_theme(doc, apply_theme)
yield doc
_unset_temp_theme(doc)
finish() | python | def OutputDocumentFor(objs, apply_theme=None, always_new=False):
''' Find or create a (possibly temporary) Document to use for serializing
Bokeh content.
Typical usage is similar to:
.. code-block:: python
with OutputDocumentFor(models):
(docs_json, [render_item]) = standalone_docs_json_and_render_items(models)
Inside the context manager, the models will be considered to be part of a single
Document, with any theme specified, which can thus be serialized as a unit. Where
possible, OutputDocumentFor attempts to use an existing Document. However, this is
not possible in three cases:
* If passed a series of models that have no Document at all, a new Document will
be created, and all the models will be added as roots. After the context manager
exits, the new Document will continue to be the models' document.
* If passed a subset of Document.roots, then OutputDocumentFor temporarily "re-homes"
the models in a new bare Document that is only available inside the context manager.
* If passed a list of models that have differnet documents, then OutputDocumentFor
temporarily "re-homes" the models in a new bare Document that is only available
inside the context manager.
OutputDocumentFor will also perfom document validation before yielding, if
``settings.perform_document_validation()`` is True.
objs (seq[Model]) :
a sequence of Models that will be serialized, and need a common document
apply_theme (Theme or FromCurdoc or None, optional):
Sets the theme for the doc while inside this context manager. (default: None)
If None, use whatever theme is on the document that is found or created
If FromCurdoc, use curdoc().theme, restoring any previous theme afterwards
If a Theme instance, use that theme, restoring any previous theme afterwards
always_new (bool, optional) :
Always return a new document, even in cases where it is otherwise possible
to use an existing document on models.
Yields:
Document
'''
# Note: Comms handling relies on the fact that the new_doc returned
# has models with the same IDs as they were started with
if not isinstance(objs, collections_abc.Sequence) or len(objs) == 0 or not all(isinstance(x, Model) for x in objs):
raise ValueError("OutputDocumentFor expects a sequence of Models")
def finish(): pass
docs = set(x.document for x in objs)
if None in docs: docs.remove(None)
if always_new:
def finish(): # NOQA
_dispose_temp_doc(objs)
doc = _create_temp_doc(objs)
else:
if len(docs) == 0:
doc = Document()
for model in objs:
doc.add_root(model)
# handle a single shared document
elif len(docs) == 1:
doc = docs.pop()
# we are not using all the roots, make a quick clone for outputting purposes
if set(objs) != set(doc.roots):
def finish(): # NOQA
_dispose_temp_doc(objs)
doc = _create_temp_doc(objs)
# we are using all the roots of a single doc, just use doc as-is
pass
# models have mixed docs, just make a quick clone
else:
def finish(): # NOQA
_dispose_temp_doc(objs)
doc = _create_temp_doc(objs)
if settings.perform_document_validation():
doc.validate()
_set_temp_theme(doc, apply_theme)
yield doc
_unset_temp_theme(doc)
finish() | [
"def",
"OutputDocumentFor",
"(",
"objs",
",",
"apply_theme",
"=",
"None",
",",
"always_new",
"=",
"False",
")",
":",
"# Note: Comms handling relies on the fact that the new_doc returned",
"# has models with the same IDs as they were started with",
"if",
"not",
"isinstance",
"(",
"objs",
",",
"collections_abc",
".",
"Sequence",
")",
"or",
"len",
"(",
"objs",
")",
"==",
"0",
"or",
"not",
"all",
"(",
"isinstance",
"(",
"x",
",",
"Model",
")",
"for",
"x",
"in",
"objs",
")",
":",
"raise",
"ValueError",
"(",
"\"OutputDocumentFor expects a sequence of Models\"",
")",
"def",
"finish",
"(",
")",
":",
"pass",
"docs",
"=",
"set",
"(",
"x",
".",
"document",
"for",
"x",
"in",
"objs",
")",
"if",
"None",
"in",
"docs",
":",
"docs",
".",
"remove",
"(",
"None",
")",
"if",
"always_new",
":",
"def",
"finish",
"(",
")",
":",
"# NOQA",
"_dispose_temp_doc",
"(",
"objs",
")",
"doc",
"=",
"_create_temp_doc",
"(",
"objs",
")",
"else",
":",
"if",
"len",
"(",
"docs",
")",
"==",
"0",
":",
"doc",
"=",
"Document",
"(",
")",
"for",
"model",
"in",
"objs",
":",
"doc",
".",
"add_root",
"(",
"model",
")",
"# handle a single shared document",
"elif",
"len",
"(",
"docs",
")",
"==",
"1",
":",
"doc",
"=",
"docs",
".",
"pop",
"(",
")",
"# we are not using all the roots, make a quick clone for outputting purposes",
"if",
"set",
"(",
"objs",
")",
"!=",
"set",
"(",
"doc",
".",
"roots",
")",
":",
"def",
"finish",
"(",
")",
":",
"# NOQA",
"_dispose_temp_doc",
"(",
"objs",
")",
"doc",
"=",
"_create_temp_doc",
"(",
"objs",
")",
"# we are using all the roots of a single doc, just use doc as-is",
"pass",
"# models have mixed docs, just make a quick clone",
"else",
":",
"def",
"finish",
"(",
")",
":",
"# NOQA",
"_dispose_temp_doc",
"(",
"objs",
")",
"doc",
"=",
"_create_temp_doc",
"(",
"objs",
")",
"if",
"settings",
".",
"perform_document_validation",
"(",
")",
":",
"doc",
".",
"validate",
"(",
")",
"_set_temp_theme",
"(",
"doc",
",",
"apply_theme",
")",
"yield",
"doc",
"_unset_temp_theme",
"(",
"doc",
")",
"finish",
"(",
")"
] | Find or create a (possibly temporary) Document to use for serializing
Bokeh content.
Typical usage is similar to:
.. code-block:: python
with OutputDocumentFor(models):
(docs_json, [render_item]) = standalone_docs_json_and_render_items(models)
Inside the context manager, the models will be considered to be part of a single
Document, with any theme specified, which can thus be serialized as a unit. Where
possible, OutputDocumentFor attempts to use an existing Document. However, this is
not possible in three cases:
* If passed a series of models that have no Document at all, a new Document will
be created, and all the models will be added as roots. After the context manager
exits, the new Document will continue to be the models' document.
* If passed a subset of Document.roots, then OutputDocumentFor temporarily "re-homes"
the models in a new bare Document that is only available inside the context manager.
* If passed a list of models that have differnet documents, then OutputDocumentFor
temporarily "re-homes" the models in a new bare Document that is only available
inside the context manager.
OutputDocumentFor will also perfom document validation before yielding, if
``settings.perform_document_validation()`` is True.
objs (seq[Model]) :
a sequence of Models that will be serialized, and need a common document
apply_theme (Theme or FromCurdoc or None, optional):
Sets the theme for the doc while inside this context manager. (default: None)
If None, use whatever theme is on the document that is found or created
If FromCurdoc, use curdoc().theme, restoring any previous theme afterwards
If a Theme instance, use that theme, restoring any previous theme afterwards
always_new (bool, optional) :
Always return a new document, even in cases where it is otherwise possible
to use an existing document on models.
Yields:
Document | [
"Find",
"or",
"create",
"a",
"(",
"possibly",
"temporary",
")",
"Document",
"to",
"use",
"for",
"serializing",
"Bokeh",
"content",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/util.py#L67-L168 | train |
bokeh/bokeh | bokeh/embed/util.py | submodel_has_python_callbacks | def submodel_has_python_callbacks(models):
''' Traverses submodels to check for Python (event) callbacks
'''
has_python_callback = False
for model in collect_models(models):
if len(model._callbacks) > 0 or len(model._event_callbacks) > 0:
has_python_callback = True
break
return has_python_callback | python | def submodel_has_python_callbacks(models):
''' Traverses submodels to check for Python (event) callbacks
'''
has_python_callback = False
for model in collect_models(models):
if len(model._callbacks) > 0 or len(model._event_callbacks) > 0:
has_python_callback = True
break
return has_python_callback | [
"def",
"submodel_has_python_callbacks",
"(",
"models",
")",
":",
"has_python_callback",
"=",
"False",
"for",
"model",
"in",
"collect_models",
"(",
"models",
")",
":",
"if",
"len",
"(",
"model",
".",
"_callbacks",
")",
">",
"0",
"or",
"len",
"(",
"model",
".",
"_event_callbacks",
")",
">",
"0",
":",
"has_python_callback",
"=",
"True",
"break",
"return",
"has_python_callback"
] | Traverses submodels to check for Python (event) callbacks | [
"Traverses",
"submodels",
"to",
"check",
"for",
"Python",
"(",
"event",
")",
"callbacks"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/util.py#L305-L315 | train |
bokeh/bokeh | bokeh/models/graphs.py | from_networkx | def from_networkx(graph, layout_function, **kwargs):
'''
Generate a ``GraphRenderer`` from a ``networkx.Graph`` object and networkx
layout function. Any keyword arguments will be passed to the
layout function.
Only two dimensional layouts are supported.
Args:
graph (networkx.Graph) : a networkx graph to render
layout_function (function or dict) : a networkx layout function or mapping of node keys to positions.
The position is a two element sequence containing the x and y coordinate.
Returns:
instance (GraphRenderer)
.. note::
Node and edge attributes may be lists or tuples. However, a given
attribute must either have *all* lists or tuple values, or *all*
scalar values, for nodes or edges it is defined on.
.. warning::
Node attributes labeled 'index' and edge attributes labeled 'start' or 'end' are ignored.
If you want to convert these attributes, please re-label them to other names.
Raises:
ValueError
'''
# inline import to prevent circular imports
from ..models.renderers import GraphRenderer
from ..models.graphs import StaticLayoutProvider
# Handles nx 1.x vs 2.x data structure change
# Convert node attributes
node_dict = dict()
node_attr_keys = [attr_key for node in list(graph.nodes(data=True))
for attr_key in node[1].keys()]
node_attr_keys = list(set(node_attr_keys))
for attr_key in node_attr_keys:
values = [node_attr[attr_key] if attr_key in node_attr.keys() else None
for _, node_attr in graph.nodes(data=True)]
values = _handle_sublists(values)
node_dict[attr_key] = values
if 'index' in node_attr_keys:
from warnings import warn
warn("Converting node attributes labeled 'index' are skipped. "
"If you want to convert these attributes, please re-label with other names.")
node_dict['index'] = list(graph.nodes())
# Convert edge attributes
edge_dict = dict()
edge_attr_keys = [attr_key for edge in graph.edges(data=True)
for attr_key in edge[2].keys()]
edge_attr_keys = list(set(edge_attr_keys))
for attr_key in edge_attr_keys:
values = [edge_attr[attr_key] if attr_key in edge_attr.keys() else None
for _, _, edge_attr in graph.edges(data=True)]
values = _handle_sublists(values)
edge_dict[attr_key] = values
if 'start' in edge_attr_keys or 'end' in edge_attr_keys:
from warnings import warn
warn("Converting edge attributes labeled 'start' or 'end' are skipped. "
"If you want to convert these attributes, please re-label them with other names.")
edge_dict['start'] = [x[0] for x in graph.edges()]
edge_dict['end'] = [x[1] for x in graph.edges()]
node_source = ColumnDataSource(data=node_dict)
edge_source = ColumnDataSource(data=edge_dict)
graph_renderer = GraphRenderer()
graph_renderer.node_renderer.data_source.data = node_source.data
graph_renderer.edge_renderer.data_source.data = edge_source.data
if callable(layout_function):
graph_layout = layout_function(graph, **kwargs)
else:
graph_layout = layout_function
node_keys = graph_renderer.node_renderer.data_source.data['index']
if set(node_keys) != set(layout_function.keys()):
from warnings import warn
warn("Node keys in 'layout_function' don't match node keys in the graph. "
"These nodes may not be displayed correctly.")
graph_renderer.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)
return graph_renderer | python | def from_networkx(graph, layout_function, **kwargs):
'''
Generate a ``GraphRenderer`` from a ``networkx.Graph`` object and networkx
layout function. Any keyword arguments will be passed to the
layout function.
Only two dimensional layouts are supported.
Args:
graph (networkx.Graph) : a networkx graph to render
layout_function (function or dict) : a networkx layout function or mapping of node keys to positions.
The position is a two element sequence containing the x and y coordinate.
Returns:
instance (GraphRenderer)
.. note::
Node and edge attributes may be lists or tuples. However, a given
attribute must either have *all* lists or tuple values, or *all*
scalar values, for nodes or edges it is defined on.
.. warning::
Node attributes labeled 'index' and edge attributes labeled 'start' or 'end' are ignored.
If you want to convert these attributes, please re-label them to other names.
Raises:
ValueError
'''
# inline import to prevent circular imports
from ..models.renderers import GraphRenderer
from ..models.graphs import StaticLayoutProvider
# Handles nx 1.x vs 2.x data structure change
# Convert node attributes
node_dict = dict()
node_attr_keys = [attr_key for node in list(graph.nodes(data=True))
for attr_key in node[1].keys()]
node_attr_keys = list(set(node_attr_keys))
for attr_key in node_attr_keys:
values = [node_attr[attr_key] if attr_key in node_attr.keys() else None
for _, node_attr in graph.nodes(data=True)]
values = _handle_sublists(values)
node_dict[attr_key] = values
if 'index' in node_attr_keys:
from warnings import warn
warn("Converting node attributes labeled 'index' are skipped. "
"If you want to convert these attributes, please re-label with other names.")
node_dict['index'] = list(graph.nodes())
# Convert edge attributes
edge_dict = dict()
edge_attr_keys = [attr_key for edge in graph.edges(data=True)
for attr_key in edge[2].keys()]
edge_attr_keys = list(set(edge_attr_keys))
for attr_key in edge_attr_keys:
values = [edge_attr[attr_key] if attr_key in edge_attr.keys() else None
for _, _, edge_attr in graph.edges(data=True)]
values = _handle_sublists(values)
edge_dict[attr_key] = values
if 'start' in edge_attr_keys or 'end' in edge_attr_keys:
from warnings import warn
warn("Converting edge attributes labeled 'start' or 'end' are skipped. "
"If you want to convert these attributes, please re-label them with other names.")
edge_dict['start'] = [x[0] for x in graph.edges()]
edge_dict['end'] = [x[1] for x in graph.edges()]
node_source = ColumnDataSource(data=node_dict)
edge_source = ColumnDataSource(data=edge_dict)
graph_renderer = GraphRenderer()
graph_renderer.node_renderer.data_source.data = node_source.data
graph_renderer.edge_renderer.data_source.data = edge_source.data
if callable(layout_function):
graph_layout = layout_function(graph, **kwargs)
else:
graph_layout = layout_function
node_keys = graph_renderer.node_renderer.data_source.data['index']
if set(node_keys) != set(layout_function.keys()):
from warnings import warn
warn("Node keys in 'layout_function' don't match node keys in the graph. "
"These nodes may not be displayed correctly.")
graph_renderer.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)
return graph_renderer | [
"def",
"from_networkx",
"(",
"graph",
",",
"layout_function",
",",
"*",
"*",
"kwargs",
")",
":",
"# inline import to prevent circular imports",
"from",
".",
".",
"models",
".",
"renderers",
"import",
"GraphRenderer",
"from",
".",
".",
"models",
".",
"graphs",
"import",
"StaticLayoutProvider",
"# Handles nx 1.x vs 2.x data structure change",
"# Convert node attributes",
"node_dict",
"=",
"dict",
"(",
")",
"node_attr_keys",
"=",
"[",
"attr_key",
"for",
"node",
"in",
"list",
"(",
"graph",
".",
"nodes",
"(",
"data",
"=",
"True",
")",
")",
"for",
"attr_key",
"in",
"node",
"[",
"1",
"]",
".",
"keys",
"(",
")",
"]",
"node_attr_keys",
"=",
"list",
"(",
"set",
"(",
"node_attr_keys",
")",
")",
"for",
"attr_key",
"in",
"node_attr_keys",
":",
"values",
"=",
"[",
"node_attr",
"[",
"attr_key",
"]",
"if",
"attr_key",
"in",
"node_attr",
".",
"keys",
"(",
")",
"else",
"None",
"for",
"_",
",",
"node_attr",
"in",
"graph",
".",
"nodes",
"(",
"data",
"=",
"True",
")",
"]",
"values",
"=",
"_handle_sublists",
"(",
"values",
")",
"node_dict",
"[",
"attr_key",
"]",
"=",
"values",
"if",
"'index'",
"in",
"node_attr_keys",
":",
"from",
"warnings",
"import",
"warn",
"warn",
"(",
"\"Converting node attributes labeled 'index' are skipped. \"",
"\"If you want to convert these attributes, please re-label with other names.\"",
")",
"node_dict",
"[",
"'index'",
"]",
"=",
"list",
"(",
"graph",
".",
"nodes",
"(",
")",
")",
"# Convert edge attributes",
"edge_dict",
"=",
"dict",
"(",
")",
"edge_attr_keys",
"=",
"[",
"attr_key",
"for",
"edge",
"in",
"graph",
".",
"edges",
"(",
"data",
"=",
"True",
")",
"for",
"attr_key",
"in",
"edge",
"[",
"2",
"]",
".",
"keys",
"(",
")",
"]",
"edge_attr_keys",
"=",
"list",
"(",
"set",
"(",
"edge_attr_keys",
")",
")",
"for",
"attr_key",
"in",
"edge_attr_keys",
":",
"values",
"=",
"[",
"edge_attr",
"[",
"attr_key",
"]",
"if",
"attr_key",
"in",
"edge_attr",
".",
"keys",
"(",
")",
"else",
"None",
"for",
"_",
",",
"_",
",",
"edge_attr",
"in",
"graph",
".",
"edges",
"(",
"data",
"=",
"True",
")",
"]",
"values",
"=",
"_handle_sublists",
"(",
"values",
")",
"edge_dict",
"[",
"attr_key",
"]",
"=",
"values",
"if",
"'start'",
"in",
"edge_attr_keys",
"or",
"'end'",
"in",
"edge_attr_keys",
":",
"from",
"warnings",
"import",
"warn",
"warn",
"(",
"\"Converting edge attributes labeled 'start' or 'end' are skipped. \"",
"\"If you want to convert these attributes, please re-label them with other names.\"",
")",
"edge_dict",
"[",
"'start'",
"]",
"=",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"graph",
".",
"edges",
"(",
")",
"]",
"edge_dict",
"[",
"'end'",
"]",
"=",
"[",
"x",
"[",
"1",
"]",
"for",
"x",
"in",
"graph",
".",
"edges",
"(",
")",
"]",
"node_source",
"=",
"ColumnDataSource",
"(",
"data",
"=",
"node_dict",
")",
"edge_source",
"=",
"ColumnDataSource",
"(",
"data",
"=",
"edge_dict",
")",
"graph_renderer",
"=",
"GraphRenderer",
"(",
")",
"graph_renderer",
".",
"node_renderer",
".",
"data_source",
".",
"data",
"=",
"node_source",
".",
"data",
"graph_renderer",
".",
"edge_renderer",
".",
"data_source",
".",
"data",
"=",
"edge_source",
".",
"data",
"if",
"callable",
"(",
"layout_function",
")",
":",
"graph_layout",
"=",
"layout_function",
"(",
"graph",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"graph_layout",
"=",
"layout_function",
"node_keys",
"=",
"graph_renderer",
".",
"node_renderer",
".",
"data_source",
".",
"data",
"[",
"'index'",
"]",
"if",
"set",
"(",
"node_keys",
")",
"!=",
"set",
"(",
"layout_function",
".",
"keys",
"(",
")",
")",
":",
"from",
"warnings",
"import",
"warn",
"warn",
"(",
"\"Node keys in 'layout_function' don't match node keys in the graph. \"",
"\"These nodes may not be displayed correctly.\"",
")",
"graph_renderer",
".",
"layout_provider",
"=",
"StaticLayoutProvider",
"(",
"graph_layout",
"=",
"graph_layout",
")",
"return",
"graph_renderer"
] | Generate a ``GraphRenderer`` from a ``networkx.Graph`` object and networkx
layout function. Any keyword arguments will be passed to the
layout function.
Only two dimensional layouts are supported.
Args:
graph (networkx.Graph) : a networkx graph to render
layout_function (function or dict) : a networkx layout function or mapping of node keys to positions.
The position is a two element sequence containing the x and y coordinate.
Returns:
instance (GraphRenderer)
.. note::
Node and edge attributes may be lists or tuples. However, a given
attribute must either have *all* lists or tuple values, or *all*
scalar values, for nodes or edges it is defined on.
.. warning::
Node attributes labeled 'index' and edge attributes labeled 'start' or 'end' are ignored.
If you want to convert these attributes, please re-label them to other names.
Raises:
ValueError | [
"Generate",
"a",
"GraphRenderer",
"from",
"a",
"networkx",
".",
"Graph",
"object",
"and",
"networkx",
"layout",
"function",
".",
"Any",
"keyword",
"arguments",
"will",
"be",
"passed",
"to",
"the",
"layout",
"function",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/graphs.py#L71-L169 | train |
bokeh/bokeh | bokeh/core/enums.py | enumeration | def enumeration(*values, **kwargs):
''' Create an |Enumeration| object from a sequence of values.
Call ``enumeration`` with a sequence of (unique) strings to create an
Enumeration object:
.. code-block:: python
#: Specify the horizontal alignment for rendering text
TextAlign = enumeration("left", "right", "center")
Args:
values (str) : string enumeration values, passed as positional arguments
The order of arguments is the order of the enumeration, and the
first element will be considered the default value when used
to create |Enum| properties.
Keyword Args:
case_sensitive (bool, optional) :
Whether validation should consider case or not (default: True)
quote (bool, optional):
Whther values should be quoted in the string representations
(default: False)
Raises:
ValueError if values empty, if any value is not a string or not unique
Returns:
Enumeration
'''
if not (values and all(isinstance(value, string_types) and value for value in values)):
raise ValueError("expected a non-empty sequence of strings, got %s" % values)
if len(values) != len(set(values)):
raise ValueError("enumeration items must be unique, got %s" % values)
attrs = {value: value for value in values}
attrs.update({
"_values": list(values),
"_default": values[0],
"_case_sensitive": kwargs.get("case_sensitive", True),
"_quote": kwargs.get("quote", False),
})
return type(str("Enumeration"), (Enumeration,), attrs)() | python | def enumeration(*values, **kwargs):
''' Create an |Enumeration| object from a sequence of values.
Call ``enumeration`` with a sequence of (unique) strings to create an
Enumeration object:
.. code-block:: python
#: Specify the horizontal alignment for rendering text
TextAlign = enumeration("left", "right", "center")
Args:
values (str) : string enumeration values, passed as positional arguments
The order of arguments is the order of the enumeration, and the
first element will be considered the default value when used
to create |Enum| properties.
Keyword Args:
case_sensitive (bool, optional) :
Whether validation should consider case or not (default: True)
quote (bool, optional):
Whther values should be quoted in the string representations
(default: False)
Raises:
ValueError if values empty, if any value is not a string or not unique
Returns:
Enumeration
'''
if not (values and all(isinstance(value, string_types) and value for value in values)):
raise ValueError("expected a non-empty sequence of strings, got %s" % values)
if len(values) != len(set(values)):
raise ValueError("enumeration items must be unique, got %s" % values)
attrs = {value: value for value in values}
attrs.update({
"_values": list(values),
"_default": values[0],
"_case_sensitive": kwargs.get("case_sensitive", True),
"_quote": kwargs.get("quote", False),
})
return type(str("Enumeration"), (Enumeration,), attrs)() | [
"def",
"enumeration",
"(",
"*",
"values",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"(",
"values",
"and",
"all",
"(",
"isinstance",
"(",
"value",
",",
"string_types",
")",
"and",
"value",
"for",
"value",
"in",
"values",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"expected a non-empty sequence of strings, got %s\"",
"%",
"values",
")",
"if",
"len",
"(",
"values",
")",
"!=",
"len",
"(",
"set",
"(",
"values",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"enumeration items must be unique, got %s\"",
"%",
"values",
")",
"attrs",
"=",
"{",
"value",
":",
"value",
"for",
"value",
"in",
"values",
"}",
"attrs",
".",
"update",
"(",
"{",
"\"_values\"",
":",
"list",
"(",
"values",
")",
",",
"\"_default\"",
":",
"values",
"[",
"0",
"]",
",",
"\"_case_sensitive\"",
":",
"kwargs",
".",
"get",
"(",
"\"case_sensitive\"",
",",
"True",
")",
",",
"\"_quote\"",
":",
"kwargs",
".",
"get",
"(",
"\"quote\"",
",",
"False",
")",
",",
"}",
")",
"return",
"type",
"(",
"str",
"(",
"\"Enumeration\"",
")",
",",
"(",
"Enumeration",
",",
")",
",",
"attrs",
")",
"(",
")"
] | Create an |Enumeration| object from a sequence of values.
Call ``enumeration`` with a sequence of (unique) strings to create an
Enumeration object:
.. code-block:: python
#: Specify the horizontal alignment for rendering text
TextAlign = enumeration("left", "right", "center")
Args:
values (str) : string enumeration values, passed as positional arguments
The order of arguments is the order of the enumeration, and the
first element will be considered the default value when used
to create |Enum| properties.
Keyword Args:
case_sensitive (bool, optional) :
Whether validation should consider case or not (default: True)
quote (bool, optional):
Whther values should be quoted in the string representations
(default: False)
Raises:
ValueError if values empty, if any value is not a string or not unique
Returns:
Enumeration | [
"Create",
"an",
"|Enumeration|",
"object",
"from",
"a",
"sequence",
"of",
"values",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/enums.py#L176-L223 | train |
bokeh/bokeh | bokeh/util/session_id.py | generate_session_id | def generate_session_id(secret_key=settings.secret_key_bytes(), signed=settings.sign_sessions()):
"""Generate a random session ID.
Typically, each browser tab connected to a Bokeh application
has its own session ID. In production deployments of a Bokeh
app, session IDs should be random and unguessable - otherwise
users of the app could interfere with one another.
If session IDs are signed with a secret key, the server can
verify that the generator of the session ID was "authorized"
(the generator had to know the secret key). This can be used
to have a separate process, such as another web application,
which generates new sessions on a Bokeh server. This other
process may require users to log in before redirecting them to
the Bokeh server with a valid session ID, for example.
Args:
secret_key (str, optional) : Secret key (default: value of 'BOKEH_SECRET_KEY' env var)
signed (bool, optional) : Whether to sign the session ID (default: value of
'BOKEH_SIGN_SESSIONS' env var)
"""
secret_key = _ensure_bytes(secret_key)
if signed:
# note: '-' can also be in the base64 encoded signature
base_id = _get_random_string(secret_key=secret_key)
return base_id + '-' + _signature(base_id, secret_key)
else:
return _get_random_string(secret_key=secret_key) | python | def generate_session_id(secret_key=settings.secret_key_bytes(), signed=settings.sign_sessions()):
"""Generate a random session ID.
Typically, each browser tab connected to a Bokeh application
has its own session ID. In production deployments of a Bokeh
app, session IDs should be random and unguessable - otherwise
users of the app could interfere with one another.
If session IDs are signed with a secret key, the server can
verify that the generator of the session ID was "authorized"
(the generator had to know the secret key). This can be used
to have a separate process, such as another web application,
which generates new sessions on a Bokeh server. This other
process may require users to log in before redirecting them to
the Bokeh server with a valid session ID, for example.
Args:
secret_key (str, optional) : Secret key (default: value of 'BOKEH_SECRET_KEY' env var)
signed (bool, optional) : Whether to sign the session ID (default: value of
'BOKEH_SIGN_SESSIONS' env var)
"""
secret_key = _ensure_bytes(secret_key)
if signed:
# note: '-' can also be in the base64 encoded signature
base_id = _get_random_string(secret_key=secret_key)
return base_id + '-' + _signature(base_id, secret_key)
else:
return _get_random_string(secret_key=secret_key) | [
"def",
"generate_session_id",
"(",
"secret_key",
"=",
"settings",
".",
"secret_key_bytes",
"(",
")",
",",
"signed",
"=",
"settings",
".",
"sign_sessions",
"(",
")",
")",
":",
"secret_key",
"=",
"_ensure_bytes",
"(",
"secret_key",
")",
"if",
"signed",
":",
"# note: '-' can also be in the base64 encoded signature",
"base_id",
"=",
"_get_random_string",
"(",
"secret_key",
"=",
"secret_key",
")",
"return",
"base_id",
"+",
"'-'",
"+",
"_signature",
"(",
"base_id",
",",
"secret_key",
")",
"else",
":",
"return",
"_get_random_string",
"(",
"secret_key",
"=",
"secret_key",
")"
] | Generate a random session ID.
Typically, each browser tab connected to a Bokeh application
has its own session ID. In production deployments of a Bokeh
app, session IDs should be random and unguessable - otherwise
users of the app could interfere with one another.
If session IDs are signed with a secret key, the server can
verify that the generator of the session ID was "authorized"
(the generator had to know the secret key). This can be used
to have a separate process, such as another web application,
which generates new sessions on a Bokeh server. This other
process may require users to log in before redirecting them to
the Bokeh server with a valid session ID, for example.
Args:
secret_key (str, optional) : Secret key (default: value of 'BOKEH_SECRET_KEY' env var)
signed (bool, optional) : Whether to sign the session ID (default: value of
'BOKEH_SIGN_SESSIONS' env var) | [
"Generate",
"a",
"random",
"session",
"ID",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/session_id.py#L63-L91 | train |
bokeh/bokeh | bokeh/util/session_id.py | check_session_id_signature | def check_session_id_signature(session_id, secret_key=settings.secret_key_bytes(),
signed=settings.sign_sessions()):
"""Check the signature of a session ID, returning True if it's valid.
The server uses this function to check whether a session ID
was generated with the correct secret key. If signed sessions are disabled,
this function always returns True.
Args:
session_id (str) : The session ID to check
secret_key (str, optional) : Secret key (default: value of 'BOKEH_SECRET_KEY' env var)
signed (bool, optional) : Whether to check anything (default: value of
'BOKEH_SIGN_SESSIONS' env var)
"""
secret_key = _ensure_bytes(secret_key)
if signed:
pieces = session_id.split('-', 1)
if len(pieces) != 2:
return False
base_id = pieces[0]
provided_signature = pieces[1]
expected_signature = _signature(base_id, secret_key)
# hmac.compare_digest() uses a string compare algorithm that doesn't
# short-circuit so we don't allow timing analysis
# encode_utf8 is used to ensure that strings have same encoding
return hmac.compare_digest(encode_utf8(expected_signature), encode_utf8(provided_signature))
else:
return True | python | def check_session_id_signature(session_id, secret_key=settings.secret_key_bytes(),
signed=settings.sign_sessions()):
"""Check the signature of a session ID, returning True if it's valid.
The server uses this function to check whether a session ID
was generated with the correct secret key. If signed sessions are disabled,
this function always returns True.
Args:
session_id (str) : The session ID to check
secret_key (str, optional) : Secret key (default: value of 'BOKEH_SECRET_KEY' env var)
signed (bool, optional) : Whether to check anything (default: value of
'BOKEH_SIGN_SESSIONS' env var)
"""
secret_key = _ensure_bytes(secret_key)
if signed:
pieces = session_id.split('-', 1)
if len(pieces) != 2:
return False
base_id = pieces[0]
provided_signature = pieces[1]
expected_signature = _signature(base_id, secret_key)
# hmac.compare_digest() uses a string compare algorithm that doesn't
# short-circuit so we don't allow timing analysis
# encode_utf8 is used to ensure that strings have same encoding
return hmac.compare_digest(encode_utf8(expected_signature), encode_utf8(provided_signature))
else:
return True | [
"def",
"check_session_id_signature",
"(",
"session_id",
",",
"secret_key",
"=",
"settings",
".",
"secret_key_bytes",
"(",
")",
",",
"signed",
"=",
"settings",
".",
"sign_sessions",
"(",
")",
")",
":",
"secret_key",
"=",
"_ensure_bytes",
"(",
"secret_key",
")",
"if",
"signed",
":",
"pieces",
"=",
"session_id",
".",
"split",
"(",
"'-'",
",",
"1",
")",
"if",
"len",
"(",
"pieces",
")",
"!=",
"2",
":",
"return",
"False",
"base_id",
"=",
"pieces",
"[",
"0",
"]",
"provided_signature",
"=",
"pieces",
"[",
"1",
"]",
"expected_signature",
"=",
"_signature",
"(",
"base_id",
",",
"secret_key",
")",
"# hmac.compare_digest() uses a string compare algorithm that doesn't",
"# short-circuit so we don't allow timing analysis",
"# encode_utf8 is used to ensure that strings have same encoding",
"return",
"hmac",
".",
"compare_digest",
"(",
"encode_utf8",
"(",
"expected_signature",
")",
",",
"encode_utf8",
"(",
"provided_signature",
")",
")",
"else",
":",
"return",
"True"
] | Check the signature of a session ID, returning True if it's valid.
The server uses this function to check whether a session ID
was generated with the correct secret key. If signed sessions are disabled,
this function always returns True.
Args:
session_id (str) : The session ID to check
secret_key (str, optional) : Secret key (default: value of 'BOKEH_SECRET_KEY' env var)
signed (bool, optional) : Whether to check anything (default: value of
'BOKEH_SIGN_SESSIONS' env var) | [
"Check",
"the",
"signature",
"of",
"a",
"session",
"ID",
"returning",
"True",
"if",
"it",
"s",
"valid",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/session_id.py#L93-L121 | train |
bokeh/bokeh | bokeh/util/session_id.py | _get_random_string | def _get_random_string(length=44,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
secret_key=settings.secret_key_bytes()):
"""
Return a securely generated random string.
With the a-z, A-Z, 0-9 character set:
Length 12 is a 71-bit value. log_2((26+26+10)^12) =~ 71
Length 44 is a 261-bit value. log_2((26+26+10)^44) = 261
"""
secret_key = _ensure_bytes(secret_key)
_reseed_if_needed(using_sysrandom, secret_key)
return ''.join(random.choice(allowed_chars) for i in range(length)) | python | def _get_random_string(length=44,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
secret_key=settings.secret_key_bytes()):
"""
Return a securely generated random string.
With the a-z, A-Z, 0-9 character set:
Length 12 is a 71-bit value. log_2((26+26+10)^12) =~ 71
Length 44 is a 261-bit value. log_2((26+26+10)^44) = 261
"""
secret_key = _ensure_bytes(secret_key)
_reseed_if_needed(using_sysrandom, secret_key)
return ''.join(random.choice(allowed_chars) for i in range(length)) | [
"def",
"_get_random_string",
"(",
"length",
"=",
"44",
",",
"allowed_chars",
"=",
"'abcdefghijklmnopqrstuvwxyz'",
"'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'",
",",
"secret_key",
"=",
"settings",
".",
"secret_key_bytes",
"(",
")",
")",
":",
"secret_key",
"=",
"_ensure_bytes",
"(",
"secret_key",
")",
"_reseed_if_needed",
"(",
"using_sysrandom",
",",
"secret_key",
")",
"return",
"''",
".",
"join",
"(",
"random",
".",
"choice",
"(",
"allowed_chars",
")",
"for",
"i",
"in",
"range",
"(",
"length",
")",
")"
] | Return a securely generated random string.
With the a-z, A-Z, 0-9 character set:
Length 12 is a 71-bit value. log_2((26+26+10)^12) =~ 71
Length 44 is a 261-bit value. log_2((26+26+10)^44) = 261 | [
"Return",
"a",
"securely",
"generated",
"random",
"string",
".",
"With",
"the",
"a",
"-",
"z",
"A",
"-",
"Z",
"0",
"-",
"9",
"character",
"set",
":",
"Length",
"12",
"is",
"a",
"71",
"-",
"bit",
"value",
".",
"log_2",
"((",
"26",
"+",
"26",
"+",
"10",
")",
"^12",
")",
"=",
"~",
"71",
"Length",
"44",
"is",
"a",
"261",
"-",
"bit",
"value",
".",
"log_2",
"((",
"26",
"+",
"26",
"+",
"10",
")",
"^44",
")",
"=",
"261"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/session_id.py#L192-L204 | train |
bokeh/bokeh | bokeh/embed/notebook.py | notebook_content | def notebook_content(model, notebook_comms_target=None, theme=FromCurdoc):
''' Return script and div that will display a Bokeh plot in a Jupyter
Notebook.
The data for the plot is stored directly in the returned HTML.
Args:
model (Model) : Bokeh object to render
notebook_comms_target (str, optional) :
A target name for a Jupyter Comms object that can update
the document that is rendered to this notebook 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.
Returns:
script, div, Document
.. note::
Assumes :func:`~bokeh.io.notebook.load_notebook` or the equivalent
has already been executed.
'''
if not isinstance(model, Model):
raise ValueError("notebook_content expects a single Model instance")
# Comms handling relies on the fact that the new_doc returned here
# has models with the same IDs as they were started with
with OutputDocumentFor([model], apply_theme=theme, always_new=True) as new_doc:
(docs_json, [render_item]) = standalone_docs_json_and_render_items([model])
div = div_for_render_item(render_item)
render_item = render_item.to_json()
if notebook_comms_target:
render_item["notebook_comms_target"] = notebook_comms_target
script = DOC_NB_JS.render(
docs_json=serialize_json(docs_json),
render_items=serialize_json([render_item]),
)
return encode_utf8(script), encode_utf8(div), new_doc | python | def notebook_content(model, notebook_comms_target=None, theme=FromCurdoc):
''' Return script and div that will display a Bokeh plot in a Jupyter
Notebook.
The data for the plot is stored directly in the returned HTML.
Args:
model (Model) : Bokeh object to render
notebook_comms_target (str, optional) :
A target name for a Jupyter Comms object that can update
the document that is rendered to this notebook 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.
Returns:
script, div, Document
.. note::
Assumes :func:`~bokeh.io.notebook.load_notebook` or the equivalent
has already been executed.
'''
if not isinstance(model, Model):
raise ValueError("notebook_content expects a single Model instance")
# Comms handling relies on the fact that the new_doc returned here
# has models with the same IDs as they were started with
with OutputDocumentFor([model], apply_theme=theme, always_new=True) as new_doc:
(docs_json, [render_item]) = standalone_docs_json_and_render_items([model])
div = div_for_render_item(render_item)
render_item = render_item.to_json()
if notebook_comms_target:
render_item["notebook_comms_target"] = notebook_comms_target
script = DOC_NB_JS.render(
docs_json=serialize_json(docs_json),
render_items=serialize_json([render_item]),
)
return encode_utf8(script), encode_utf8(div), new_doc | [
"def",
"notebook_content",
"(",
"model",
",",
"notebook_comms_target",
"=",
"None",
",",
"theme",
"=",
"FromCurdoc",
")",
":",
"if",
"not",
"isinstance",
"(",
"model",
",",
"Model",
")",
":",
"raise",
"ValueError",
"(",
"\"notebook_content expects a single Model instance\"",
")",
"# Comms handling relies on the fact that the new_doc returned here",
"# has models with the same IDs as they were started with",
"with",
"OutputDocumentFor",
"(",
"[",
"model",
"]",
",",
"apply_theme",
"=",
"theme",
",",
"always_new",
"=",
"True",
")",
"as",
"new_doc",
":",
"(",
"docs_json",
",",
"[",
"render_item",
"]",
")",
"=",
"standalone_docs_json_and_render_items",
"(",
"[",
"model",
"]",
")",
"div",
"=",
"div_for_render_item",
"(",
"render_item",
")",
"render_item",
"=",
"render_item",
".",
"to_json",
"(",
")",
"if",
"notebook_comms_target",
":",
"render_item",
"[",
"\"notebook_comms_target\"",
"]",
"=",
"notebook_comms_target",
"script",
"=",
"DOC_NB_JS",
".",
"render",
"(",
"docs_json",
"=",
"serialize_json",
"(",
"docs_json",
")",
",",
"render_items",
"=",
"serialize_json",
"(",
"[",
"render_item",
"]",
")",
",",
")",
"return",
"encode_utf8",
"(",
"script",
")",
",",
"encode_utf8",
"(",
"div",
")",
",",
"new_doc"
] | Return script and div that will display a Bokeh plot in a Jupyter
Notebook.
The data for the plot is stored directly in the returned HTML.
Args:
model (Model) : Bokeh object to render
notebook_comms_target (str, optional) :
A target name for a Jupyter Comms object that can update
the document that is rendered to this notebook 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.
Returns:
script, div, Document
.. note::
Assumes :func:`~bokeh.io.notebook.load_notebook` or the equivalent
has already been executed. | [
"Return",
"script",
"and",
"div",
"that",
"will",
"display",
"a",
"Bokeh",
"plot",
"in",
"a",
"Jupyter",
"Notebook",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/notebook.py#L51-L98 | train |
bokeh/bokeh | bokeh/models/transforms.py | CustomJSTransform.from_py_func | def from_py_func(cls, func, v_func):
''' Create a ``CustomJSTransform`` instance from a pair of Python
functions. The function is translated to JavaScript using PScript.
The python functions must have no positional arguments. It's
possible to pass Bokeh models (e.g. a ``ColumnDataSource``) as keyword
arguments to the functions.
The ``func`` function namespace will contain the variable ``x`` (the
untransformed value) at render time. The ``v_func`` function namespace
will contain the variable ``xs`` (the untransformed vector) at render
time.
.. warning::
The vectorized function, ``v_func``, must return an array of the
same length as the input ``xs`` array.
Example:
.. code-block:: python
def transform():
from pscript.stubs import Math
return Math.cos(x)
def v_transform():
from pscript.stubs import Math
return [Math.cos(x) for x in xs]
customjs_transform = CustomJSTransform.from_py_func(transform, v_transform)
Args:
func (function) : a scalar function to transform a single ``x`` value
v_func (function) : a vectorized function to transform a vector ``xs``
Returns:
CustomJSTransform
'''
from bokeh.util.deprecation import deprecated
deprecated("'from_py_func' is deprecated and will be removed in an eventual 2.0 release. "
"Use CustomJSTransform directly instead.")
if not isinstance(func, FunctionType) or not isinstance(v_func, FunctionType):
raise ValueError('CustomJSTransform.from_py_func only accepts function objects.')
pscript = import_required(
'pscript',
dedent("""\
To use Python functions for CustomJSTransform, you need PScript
'("conda install -c conda-forge pscript" or "pip install pscript")""")
)
def pscript_compile(func):
sig = signature(func)
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 `formatter` and call it
# with arguments that match the `args` attr
code = pscript.py2js(func, 'transformer') + 'return transformer(%s);\n' % ', '.join(all_names)
return code, func_kwargs
jsfunc, func_kwargs = pscript_compile(func)
v_jsfunc, v_func_kwargs = pscript_compile(v_func)
# Have to merge the function arguments
func_kwargs.update(v_func_kwargs)
return cls(func=jsfunc, v_func=v_jsfunc, args=func_kwargs) | python | def from_py_func(cls, func, v_func):
''' Create a ``CustomJSTransform`` instance from a pair of Python
functions. The function is translated to JavaScript using PScript.
The python functions must have no positional arguments. It's
possible to pass Bokeh models (e.g. a ``ColumnDataSource``) as keyword
arguments to the functions.
The ``func`` function namespace will contain the variable ``x`` (the
untransformed value) at render time. The ``v_func`` function namespace
will contain the variable ``xs`` (the untransformed vector) at render
time.
.. warning::
The vectorized function, ``v_func``, must return an array of the
same length as the input ``xs`` array.
Example:
.. code-block:: python
def transform():
from pscript.stubs import Math
return Math.cos(x)
def v_transform():
from pscript.stubs import Math
return [Math.cos(x) for x in xs]
customjs_transform = CustomJSTransform.from_py_func(transform, v_transform)
Args:
func (function) : a scalar function to transform a single ``x`` value
v_func (function) : a vectorized function to transform a vector ``xs``
Returns:
CustomJSTransform
'''
from bokeh.util.deprecation import deprecated
deprecated("'from_py_func' is deprecated and will be removed in an eventual 2.0 release. "
"Use CustomJSTransform directly instead.")
if not isinstance(func, FunctionType) or not isinstance(v_func, FunctionType):
raise ValueError('CustomJSTransform.from_py_func only accepts function objects.')
pscript = import_required(
'pscript',
dedent("""\
To use Python functions for CustomJSTransform, you need PScript
'("conda install -c conda-forge pscript" or "pip install pscript")""")
)
def pscript_compile(func):
sig = signature(func)
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 `formatter` and call it
# with arguments that match the `args` attr
code = pscript.py2js(func, 'transformer') + 'return transformer(%s);\n' % ', '.join(all_names)
return code, func_kwargs
jsfunc, func_kwargs = pscript_compile(func)
v_jsfunc, v_func_kwargs = pscript_compile(v_func)
# Have to merge the function arguments
func_kwargs.update(v_func_kwargs)
return cls(func=jsfunc, v_func=v_jsfunc, args=func_kwargs) | [
"def",
"from_py_func",
"(",
"cls",
",",
"func",
",",
"v_func",
")",
":",
"from",
"bokeh",
".",
"util",
".",
"deprecation",
"import",
"deprecated",
"deprecated",
"(",
"\"'from_py_func' is deprecated and will be removed in an eventual 2.0 release. \"",
"\"Use CustomJSTransform directly instead.\"",
")",
"if",
"not",
"isinstance",
"(",
"func",
",",
"FunctionType",
")",
"or",
"not",
"isinstance",
"(",
"v_func",
",",
"FunctionType",
")",
":",
"raise",
"ValueError",
"(",
"'CustomJSTransform.from_py_func only accepts function objects.'",
")",
"pscript",
"=",
"import_required",
"(",
"'pscript'",
",",
"dedent",
"(",
"\"\"\"\\\n To use Python functions for CustomJSTransform, you need PScript\n '(\"conda install -c conda-forge pscript\" or \"pip install pscript\")\"\"\"",
")",
")",
"def",
"pscript_compile",
"(",
"func",
")",
":",
"sig",
"=",
"signature",
"(",
"func",
")",
"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 `formatter` and call it",
"# with arguments that match the `args` attr",
"code",
"=",
"pscript",
".",
"py2js",
"(",
"func",
",",
"'transformer'",
")",
"+",
"'return transformer(%s);\\n'",
"%",
"', '",
".",
"join",
"(",
"all_names",
")",
"return",
"code",
",",
"func_kwargs",
"jsfunc",
",",
"func_kwargs",
"=",
"pscript_compile",
"(",
"func",
")",
"v_jsfunc",
",",
"v_func_kwargs",
"=",
"pscript_compile",
"(",
"v_func",
")",
"# Have to merge the function arguments",
"func_kwargs",
".",
"update",
"(",
"v_func_kwargs",
")",
"return",
"cls",
"(",
"func",
"=",
"jsfunc",
",",
"v_func",
"=",
"v_jsfunc",
",",
"args",
"=",
"func_kwargs",
")"
] | Create a ``CustomJSTransform`` instance from a pair of Python
functions. The function is translated to JavaScript using PScript.
The python functions must have no positional arguments. It's
possible to pass Bokeh models (e.g. a ``ColumnDataSource``) as keyword
arguments to the functions.
The ``func`` function namespace will contain the variable ``x`` (the
untransformed value) at render time. The ``v_func`` function namespace
will contain the variable ``xs`` (the untransformed vector) at render
time.
.. warning::
The vectorized function, ``v_func``, must return an array of the
same length as the input ``xs`` array.
Example:
.. code-block:: python
def transform():
from pscript.stubs import Math
return Math.cos(x)
def v_transform():
from pscript.stubs import Math
return [Math.cos(x) for x in xs]
customjs_transform = CustomJSTransform.from_py_func(transform, v_transform)
Args:
func (function) : a scalar function to transform a single ``x`` value
v_func (function) : a vectorized function to transform a vector ``xs``
Returns:
CustomJSTransform | [
"Create",
"a",
"CustomJSTransform",
"instance",
"from",
"a",
"pair",
"of",
"Python",
"functions",
".",
"The",
"function",
"is",
"translated",
"to",
"JavaScript",
"using",
"PScript",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/transforms.py#L89-L167 | train |
bokeh/bokeh | bokeh/models/transforms.py | CustomJSTransform.from_coffeescript | def from_coffeescript(cls, func, v_func, args={}):
''' Create a ``CustomJSTransform`` instance from a pair of CoffeeScript
snippets. The function bodies are translated to JavaScript functions
using node and therefore require return statements.
The ``func`` snippet namespace will contain the variable ``x`` (the
untransformed value) at render time. The ``v_func`` snippet namespace
will contain the variable ``xs`` (the untransformed vector) at render
time.
Example:
.. code-block:: coffeescript
func = "return Math.cos(x)"
v_func = "return [Math.cos(x) for x in xs]"
transform = CustomJSTransform.from_coffeescript(func, v_func)
Args:
func (str) : a coffeescript snippet to transform a single ``x`` value
v_func (str) : a coffeescript snippet function to transform a vector ``xs``
Returns:
CustomJSTransform
'''
compiled = nodejs_compile(func, lang="coffeescript", file="???")
if "error" in compiled:
raise CompilationError(compiled.error)
v_compiled = nodejs_compile(v_func, lang="coffeescript", file="???")
if "error" in v_compiled:
raise CompilationError(v_compiled.error)
return cls(func=compiled.code, v_func=v_compiled.code, args=args) | python | def from_coffeescript(cls, func, v_func, args={}):
''' Create a ``CustomJSTransform`` instance from a pair of CoffeeScript
snippets. The function bodies are translated to JavaScript functions
using node and therefore require return statements.
The ``func`` snippet namespace will contain the variable ``x`` (the
untransformed value) at render time. The ``v_func`` snippet namespace
will contain the variable ``xs`` (the untransformed vector) at render
time.
Example:
.. code-block:: coffeescript
func = "return Math.cos(x)"
v_func = "return [Math.cos(x) for x in xs]"
transform = CustomJSTransform.from_coffeescript(func, v_func)
Args:
func (str) : a coffeescript snippet to transform a single ``x`` value
v_func (str) : a coffeescript snippet function to transform a vector ``xs``
Returns:
CustomJSTransform
'''
compiled = nodejs_compile(func, lang="coffeescript", file="???")
if "error" in compiled:
raise CompilationError(compiled.error)
v_compiled = nodejs_compile(v_func, lang="coffeescript", file="???")
if "error" in v_compiled:
raise CompilationError(v_compiled.error)
return cls(func=compiled.code, v_func=v_compiled.code, args=args) | [
"def",
"from_coffeescript",
"(",
"cls",
",",
"func",
",",
"v_func",
",",
"args",
"=",
"{",
"}",
")",
":",
"compiled",
"=",
"nodejs_compile",
"(",
"func",
",",
"lang",
"=",
"\"coffeescript\"",
",",
"file",
"=",
"\"???\"",
")",
"if",
"\"error\"",
"in",
"compiled",
":",
"raise",
"CompilationError",
"(",
"compiled",
".",
"error",
")",
"v_compiled",
"=",
"nodejs_compile",
"(",
"v_func",
",",
"lang",
"=",
"\"coffeescript\"",
",",
"file",
"=",
"\"???\"",
")",
"if",
"\"error\"",
"in",
"v_compiled",
":",
"raise",
"CompilationError",
"(",
"v_compiled",
".",
"error",
")",
"return",
"cls",
"(",
"func",
"=",
"compiled",
".",
"code",
",",
"v_func",
"=",
"v_compiled",
".",
"code",
",",
"args",
"=",
"args",
")"
] | Create a ``CustomJSTransform`` instance from a pair of CoffeeScript
snippets. The function bodies are translated to JavaScript functions
using node and therefore require return statements.
The ``func`` snippet namespace will contain the variable ``x`` (the
untransformed value) at render time. The ``v_func`` snippet namespace
will contain the variable ``xs`` (the untransformed vector) at render
time.
Example:
.. code-block:: coffeescript
func = "return Math.cos(x)"
v_func = "return [Math.cos(x) for x in xs]"
transform = CustomJSTransform.from_coffeescript(func, v_func)
Args:
func (str) : a coffeescript snippet to transform a single ``x`` value
v_func (str) : a coffeescript snippet function to transform a vector ``xs``
Returns:
CustomJSTransform | [
"Create",
"a",
"CustomJSTransform",
"instance",
"from",
"a",
"pair",
"of",
"CoffeeScript",
"snippets",
".",
"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/transforms.py#L170-L206 | train |
bokeh/bokeh | bokeh/core/has_props.py | abstract | def abstract(cls):
''' A decorator to mark abstract base classes derived from |HasProps|.
'''
if not issubclass(cls, HasProps):
raise TypeError("%s is not a subclass of HasProps" % cls.__name__)
# running python with -OO will discard docstrings -> __doc__ is None
if cls.__doc__ is not None:
cls.__doc__ += _ABSTRACT_ADMONITION
return cls | python | def abstract(cls):
''' A decorator to mark abstract base classes derived from |HasProps|.
'''
if not issubclass(cls, HasProps):
raise TypeError("%s is not a subclass of HasProps" % cls.__name__)
# running python with -OO will discard docstrings -> __doc__ is None
if cls.__doc__ is not None:
cls.__doc__ += _ABSTRACT_ADMONITION
return cls | [
"def",
"abstract",
"(",
"cls",
")",
":",
"if",
"not",
"issubclass",
"(",
"cls",
",",
"HasProps",
")",
":",
"raise",
"TypeError",
"(",
"\"%s is not a subclass of HasProps\"",
"%",
"cls",
".",
"__name__",
")",
"# running python with -OO will discard docstrings -> __doc__ is None",
"if",
"cls",
".",
"__doc__",
"is",
"not",
"None",
":",
"cls",
".",
"__doc__",
"+=",
"_ABSTRACT_ADMONITION",
"return",
"cls"
] | A decorator to mark abstract base classes derived from |HasProps|. | [
"A",
"decorator",
"to",
"mark",
"abstract",
"base",
"classes",
"derived",
"from",
"|HasProps|",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/has_props.py#L65-L76 | train |
bokeh/bokeh | bokeh/core/has_props.py | accumulate_from_superclasses | def accumulate_from_superclasses(cls, propname):
''' Traverse the class hierarchy and accumulate the special sets of names
``MetaHasProps`` stores on classes:
Args:
name (str) : name of the special attribute to collect.
Typically meaningful values are: ``__container_props__``,
``__properties__``, ``__properties_with_refs__``
'''
cachename = "__cached_all" + propname
# we MUST use cls.__dict__ NOT hasattr(). hasattr() would also look at base
# classes, and the cache must be separate for each class
if cachename not in cls.__dict__:
s = set()
for c in inspect.getmro(cls):
if issubclass(c, HasProps) and hasattr(c, propname):
base = getattr(c, propname)
s.update(base)
setattr(cls, cachename, s)
return cls.__dict__[cachename] | python | def accumulate_from_superclasses(cls, propname):
''' Traverse the class hierarchy and accumulate the special sets of names
``MetaHasProps`` stores on classes:
Args:
name (str) : name of the special attribute to collect.
Typically meaningful values are: ``__container_props__``,
``__properties__``, ``__properties_with_refs__``
'''
cachename = "__cached_all" + propname
# we MUST use cls.__dict__ NOT hasattr(). hasattr() would also look at base
# classes, and the cache must be separate for each class
if cachename not in cls.__dict__:
s = set()
for c in inspect.getmro(cls):
if issubclass(c, HasProps) and hasattr(c, propname):
base = getattr(c, propname)
s.update(base)
setattr(cls, cachename, s)
return cls.__dict__[cachename] | [
"def",
"accumulate_from_superclasses",
"(",
"cls",
",",
"propname",
")",
":",
"cachename",
"=",
"\"__cached_all\"",
"+",
"propname",
"# we MUST use cls.__dict__ NOT hasattr(). hasattr() would also look at base",
"# classes, and the cache must be separate for each class",
"if",
"cachename",
"not",
"in",
"cls",
".",
"__dict__",
":",
"s",
"=",
"set",
"(",
")",
"for",
"c",
"in",
"inspect",
".",
"getmro",
"(",
"cls",
")",
":",
"if",
"issubclass",
"(",
"c",
",",
"HasProps",
")",
"and",
"hasattr",
"(",
"c",
",",
"propname",
")",
":",
"base",
"=",
"getattr",
"(",
"c",
",",
"propname",
")",
"s",
".",
"update",
"(",
"base",
")",
"setattr",
"(",
"cls",
",",
"cachename",
",",
"s",
")",
"return",
"cls",
".",
"__dict__",
"[",
"cachename",
"]"
] | Traverse the class hierarchy and accumulate the special sets of names
``MetaHasProps`` stores on classes:
Args:
name (str) : name of the special attribute to collect.
Typically meaningful values are: ``__container_props__``,
``__properties__``, ``__properties_with_refs__`` | [
"Traverse",
"the",
"class",
"hierarchy",
"and",
"accumulate",
"the",
"special",
"sets",
"of",
"names",
"MetaHasProps",
"stores",
"on",
"classes",
":"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/has_props.py#L191-L212 | train |
bokeh/bokeh | bokeh/core/has_props.py | accumulate_dict_from_superclasses | def accumulate_dict_from_superclasses(cls, propname):
''' Traverse the class hierarchy and accumulate the special dicts
``MetaHasProps`` stores on classes:
Args:
name (str) : name of the special attribute to collect.
Typically meaningful values are: ``__dataspecs__``,
``__overridden_defaults__``
'''
cachename = "__cached_all" + propname
# we MUST use cls.__dict__ NOT hasattr(). hasattr() would also look at base
# classes, and the cache must be separate for each class
if cachename not in cls.__dict__:
d = dict()
for c in inspect.getmro(cls):
if issubclass(c, HasProps) and hasattr(c, propname):
base = getattr(c, propname)
for k,v in base.items():
if k not in d:
d[k] = v
setattr(cls, cachename, d)
return cls.__dict__[cachename] | python | def accumulate_dict_from_superclasses(cls, propname):
''' Traverse the class hierarchy and accumulate the special dicts
``MetaHasProps`` stores on classes:
Args:
name (str) : name of the special attribute to collect.
Typically meaningful values are: ``__dataspecs__``,
``__overridden_defaults__``
'''
cachename = "__cached_all" + propname
# we MUST use cls.__dict__ NOT hasattr(). hasattr() would also look at base
# classes, and the cache must be separate for each class
if cachename not in cls.__dict__:
d = dict()
for c in inspect.getmro(cls):
if issubclass(c, HasProps) and hasattr(c, propname):
base = getattr(c, propname)
for k,v in base.items():
if k not in d:
d[k] = v
setattr(cls, cachename, d)
return cls.__dict__[cachename] | [
"def",
"accumulate_dict_from_superclasses",
"(",
"cls",
",",
"propname",
")",
":",
"cachename",
"=",
"\"__cached_all\"",
"+",
"propname",
"# we MUST use cls.__dict__ NOT hasattr(). hasattr() would also look at base",
"# classes, and the cache must be separate for each class",
"if",
"cachename",
"not",
"in",
"cls",
".",
"__dict__",
":",
"d",
"=",
"dict",
"(",
")",
"for",
"c",
"in",
"inspect",
".",
"getmro",
"(",
"cls",
")",
":",
"if",
"issubclass",
"(",
"c",
",",
"HasProps",
")",
"and",
"hasattr",
"(",
"c",
",",
"propname",
")",
":",
"base",
"=",
"getattr",
"(",
"c",
",",
"propname",
")",
"for",
"k",
",",
"v",
"in",
"base",
".",
"items",
"(",
")",
":",
"if",
"k",
"not",
"in",
"d",
":",
"d",
"[",
"k",
"]",
"=",
"v",
"setattr",
"(",
"cls",
",",
"cachename",
",",
"d",
")",
"return",
"cls",
".",
"__dict__",
"[",
"cachename",
"]"
] | Traverse the class hierarchy and accumulate the special dicts
``MetaHasProps`` stores on classes:
Args:
name (str) : name of the special attribute to collect.
Typically meaningful values are: ``__dataspecs__``,
``__overridden_defaults__`` | [
"Traverse",
"the",
"class",
"hierarchy",
"and",
"accumulate",
"the",
"special",
"dicts",
"MetaHasProps",
"stores",
"on",
"classes",
":"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/has_props.py#L214-L237 | train |
bokeh/bokeh | bokeh/core/has_props.py | HasProps.equals | def equals(self, other):
''' Structural equality of models.
Args:
other (HasProps) : the other instance to compare to
Returns:
True, if properties are structurally equal, otherwise False
'''
# NOTE: don't try to use this to implement __eq__. Because then
# you will be tempted to implement __hash__, which would interfere
# with mutability of models. However, not implementing __hash__
# will make bokeh unusable in Python 3, where proper implementation
# of __hash__ is required when implementing __eq__.
if not isinstance(other, self.__class__):
return False
else:
return self.properties_with_values() == other.properties_with_values() | python | def equals(self, other):
''' Structural equality of models.
Args:
other (HasProps) : the other instance to compare to
Returns:
True, if properties are structurally equal, otherwise False
'''
# NOTE: don't try to use this to implement __eq__. Because then
# you will be tempted to implement __hash__, which would interfere
# with mutability of models. However, not implementing __hash__
# will make bokeh unusable in Python 3, where proper implementation
# of __hash__ is required when implementing __eq__.
if not isinstance(other, self.__class__):
return False
else:
return self.properties_with_values() == other.properties_with_values() | [
"def",
"equals",
"(",
"self",
",",
"other",
")",
":",
"# NOTE: don't try to use this to implement __eq__. Because then",
"# you will be tempted to implement __hash__, which would interfere",
"# with mutability of models. However, not implementing __hash__",
"# will make bokeh unusable in Python 3, where proper implementation",
"# of __hash__ is required when implementing __eq__.",
"if",
"not",
"isinstance",
"(",
"other",
",",
"self",
".",
"__class__",
")",
":",
"return",
"False",
"else",
":",
"return",
"self",
".",
"properties_with_values",
"(",
")",
"==",
"other",
".",
"properties_with_values",
"(",
")"
] | Structural equality of models.
Args:
other (HasProps) : the other instance to compare to
Returns:
True, if properties are structurally equal, otherwise False | [
"Structural",
"equality",
"of",
"models",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/has_props.py#L295-L314 | train |
bokeh/bokeh | bokeh/core/has_props.py | HasProps.set_from_json | def set_from_json(self, name, json, models=None, setter=None):
''' Set a property value on this object from JSON.
Args:
name: (str) : name of the attribute to set
json: (JSON-value) : value to set to the attribute to
models (dict or None, optional) :
Mapping of model ids to models (default: None)
This is needed in cases where the attributes to update also
have values that have references.
setter(ClientSession or ServerSession or None, optional) :
This is used to prevent "boomerang" updates to Bokeh apps.
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 name in self.properties():
log.trace("Patching attribute %r of %r with %r", name, self, json)
descriptor = self.lookup(name)
descriptor.set_from_json(self, json, models, setter)
else:
log.warning("JSON had attr %r on obj %r, which is a client-only or invalid attribute that shouldn't have been sent", name, self) | python | def set_from_json(self, name, json, models=None, setter=None):
''' Set a property value on this object from JSON.
Args:
name: (str) : name of the attribute to set
json: (JSON-value) : value to set to the attribute to
models (dict or None, optional) :
Mapping of model ids to models (default: None)
This is needed in cases where the attributes to update also
have values that have references.
setter(ClientSession or ServerSession or None, optional) :
This is used to prevent "boomerang" updates to Bokeh apps.
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 name in self.properties():
log.trace("Patching attribute %r of %r with %r", name, self, json)
descriptor = self.lookup(name)
descriptor.set_from_json(self, json, models, setter)
else:
log.warning("JSON had attr %r on obj %r, which is a client-only or invalid attribute that shouldn't have been sent", name, self) | [
"def",
"set_from_json",
"(",
"self",
",",
"name",
",",
"json",
",",
"models",
"=",
"None",
",",
"setter",
"=",
"None",
")",
":",
"if",
"name",
"in",
"self",
".",
"properties",
"(",
")",
":",
"log",
".",
"trace",
"(",
"\"Patching attribute %r of %r with %r\"",
",",
"name",
",",
"self",
",",
"json",
")",
"descriptor",
"=",
"self",
".",
"lookup",
"(",
"name",
")",
"descriptor",
".",
"set_from_json",
"(",
"self",
",",
"json",
",",
"models",
",",
"setter",
")",
"else",
":",
"log",
".",
"warning",
"(",
"\"JSON had attr %r on obj %r, which is a client-only or invalid attribute that shouldn't have been sent\"",
",",
"name",
",",
"self",
")"
] | Set a property value on this object from JSON.
Args:
name: (str) : name of the attribute to set
json: (JSON-value) : value to set to the attribute to
models (dict or None, optional) :
Mapping of model ids to models (default: None)
This is needed in cases where the attributes to update also
have values that have references.
setter(ClientSession or ServerSession or None, optional) :
This is used to prevent "boomerang" updates to Bokeh apps.
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 | [
"Set",
"a",
"property",
"value",
"on",
"this",
"object",
"from",
"JSON",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/has_props.py#L316-L349 | train |
bokeh/bokeh | bokeh/core/has_props.py | HasProps.update_from_json | def update_from_json(self, json_attributes, models=None, setter=None):
''' Updates the object's properties from a JSON attributes dictionary.
Args:
json_attributes: (JSON-dict) : attributes and values to update
models (dict or None, optional) :
Mapping of model ids to models (default: None)
This is needed in cases where the attributes to update also
have values that have references.
setter(ClientSession or ServerSession or None, optional) :
This is used to prevent "boomerang" updates to Bokeh apps.
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
'''
for k, v in json_attributes.items():
self.set_from_json(k, v, models, setter) | python | def update_from_json(self, json_attributes, models=None, setter=None):
''' Updates the object's properties from a JSON attributes dictionary.
Args:
json_attributes: (JSON-dict) : attributes and values to update
models (dict or None, optional) :
Mapping of model ids to models (default: None)
This is needed in cases where the attributes to update also
have values that have references.
setter(ClientSession or ServerSession or None, optional) :
This is used to prevent "boomerang" updates to Bokeh apps.
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
'''
for k, v in json_attributes.items():
self.set_from_json(k, v, models, setter) | [
"def",
"update_from_json",
"(",
"self",
",",
"json_attributes",
",",
"models",
"=",
"None",
",",
"setter",
"=",
"None",
")",
":",
"for",
"k",
",",
"v",
"in",
"json_attributes",
".",
"items",
"(",
")",
":",
"self",
".",
"set_from_json",
"(",
"k",
",",
"v",
",",
"models",
",",
"setter",
")"
] | Updates the object's properties from a JSON attributes dictionary.
Args:
json_attributes: (JSON-dict) : attributes and values to update
models (dict or None, optional) :
Mapping of model ids to models (default: None)
This is needed in cases where the attributes to update also
have values that have references.
setter(ClientSession or ServerSession or None, optional) :
This is used to prevent "boomerang" updates to Bokeh apps.
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 | [
"Updates",
"the",
"object",
"s",
"properties",
"from",
"a",
"JSON",
"attributes",
"dictionary",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/has_props.py#L378-L405 | train |
bokeh/bokeh | bokeh/core/has_props.py | HasProps.properties | def properties(cls, with_bases=True):
''' Collect the names of properties on this class.
This method *optionally* traverses the class hierarchy and includes
properties defined on any parent classes.
Args:
with_bases (bool, optional) :
Whether to include properties defined on parent classes in
the results. (default: True)
Returns:
set[str] : property names
'''
if with_bases:
return accumulate_from_superclasses(cls, "__properties__")
else:
return set(cls.__properties__) | python | def properties(cls, with_bases=True):
''' Collect the names of properties on this class.
This method *optionally* traverses the class hierarchy and includes
properties defined on any parent classes.
Args:
with_bases (bool, optional) :
Whether to include properties defined on parent classes in
the results. (default: True)
Returns:
set[str] : property names
'''
if with_bases:
return accumulate_from_superclasses(cls, "__properties__")
else:
return set(cls.__properties__) | [
"def",
"properties",
"(",
"cls",
",",
"with_bases",
"=",
"True",
")",
":",
"if",
"with_bases",
":",
"return",
"accumulate_from_superclasses",
"(",
"cls",
",",
"\"__properties__\"",
")",
"else",
":",
"return",
"set",
"(",
"cls",
".",
"__properties__",
")"
] | Collect the names of properties on this class.
This method *optionally* traverses the class hierarchy and includes
properties defined on any parent classes.
Args:
with_bases (bool, optional) :
Whether to include properties defined on parent classes in
the results. (default: True)
Returns:
set[str] : property names | [
"Collect",
"the",
"names",
"of",
"properties",
"on",
"this",
"class",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/has_props.py#L449-L467 | train |
bokeh/bokeh | bokeh/core/has_props.py | HasProps.properties_with_values | def properties_with_values(self, include_defaults=True):
''' Collect a dict mapping property names to their values.
This method *always* traverses the class hierarchy and includes
properties defined on any parent classes.
Non-serializable properties are skipped and property values are in
"serialized" format which may be slightly different from the values
you would normally read from the properties; the intent of this method
is to return the information needed to losslessly reconstitute the
object instance.
Args:
include_defaults (bool, optional) :
Whether to include properties that haven't been explicitly set
since the object was created. (default: True)
Returns:
dict : mapping from property names to their values
'''
return self.query_properties_with_values(lambda prop: prop.serialized, include_defaults) | python | def properties_with_values(self, include_defaults=True):
''' Collect a dict mapping property names to their values.
This method *always* traverses the class hierarchy and includes
properties defined on any parent classes.
Non-serializable properties are skipped and property values are in
"serialized" format which may be slightly different from the values
you would normally read from the properties; the intent of this method
is to return the information needed to losslessly reconstitute the
object instance.
Args:
include_defaults (bool, optional) :
Whether to include properties that haven't been explicitly set
since the object was created. (default: True)
Returns:
dict : mapping from property names to their values
'''
return self.query_properties_with_values(lambda prop: prop.serialized, include_defaults) | [
"def",
"properties_with_values",
"(",
"self",
",",
"include_defaults",
"=",
"True",
")",
":",
"return",
"self",
".",
"query_properties_with_values",
"(",
"lambda",
"prop",
":",
"prop",
".",
"serialized",
",",
"include_defaults",
")"
] | Collect a dict mapping property names to their values.
This method *always* traverses the class hierarchy and includes
properties defined on any parent classes.
Non-serializable properties are skipped and property values are in
"serialized" format which may be slightly different from the values
you would normally read from the properties; the intent of this method
is to return the information needed to losslessly reconstitute the
object instance.
Args:
include_defaults (bool, optional) :
Whether to include properties that haven't been explicitly set
since the object was created. (default: True)
Returns:
dict : mapping from property names to their values | [
"Collect",
"a",
"dict",
"mapping",
"property",
"names",
"to",
"their",
"values",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/has_props.py#L496-L517 | train |
bokeh/bokeh | bokeh/core/has_props.py | HasProps.query_properties_with_values | def query_properties_with_values(self, query, include_defaults=True):
''' Query the properties values of |HasProps| instances with a
predicate.
Args:
query (callable) :
A callable that accepts property descriptors and returns True
or False
include_defaults (bool, optional) :
Whether to include properties that have not been explicitly
set by a user (default: True)
Returns:
dict : mapping of property names and values for matching properties
'''
themed_keys = set()
result = dict()
if include_defaults:
keys = self.properties()
else:
# TODO (bev) For now, include unstable default values. Things rely on Instances
# always getting serialized, even defaults, and adding unstable defaults here
# accomplishes that. Unmodified defaults for property value containers will be
# weeded out below.
keys = set(self._property_values.keys()) | set(self._unstable_default_values.keys())
if self.themed_values():
themed_keys = set(self.themed_values().keys())
keys |= themed_keys
for key in keys:
descriptor = self.lookup(key)
if not query(descriptor):
continue
value = descriptor.serializable_value(self)
if not include_defaults and key not in themed_keys:
if isinstance(value, PropertyValueContainer) and key in self._unstable_default_values:
continue
result[key] = value
return result | python | def query_properties_with_values(self, query, include_defaults=True):
''' Query the properties values of |HasProps| instances with a
predicate.
Args:
query (callable) :
A callable that accepts property descriptors and returns True
or False
include_defaults (bool, optional) :
Whether to include properties that have not been explicitly
set by a user (default: True)
Returns:
dict : mapping of property names and values for matching properties
'''
themed_keys = set()
result = dict()
if include_defaults:
keys = self.properties()
else:
# TODO (bev) For now, include unstable default values. Things rely on Instances
# always getting serialized, even defaults, and adding unstable defaults here
# accomplishes that. Unmodified defaults for property value containers will be
# weeded out below.
keys = set(self._property_values.keys()) | set(self._unstable_default_values.keys())
if self.themed_values():
themed_keys = set(self.themed_values().keys())
keys |= themed_keys
for key in keys:
descriptor = self.lookup(key)
if not query(descriptor):
continue
value = descriptor.serializable_value(self)
if not include_defaults and key not in themed_keys:
if isinstance(value, PropertyValueContainer) and key in self._unstable_default_values:
continue
result[key] = value
return result | [
"def",
"query_properties_with_values",
"(",
"self",
",",
"query",
",",
"include_defaults",
"=",
"True",
")",
":",
"themed_keys",
"=",
"set",
"(",
")",
"result",
"=",
"dict",
"(",
")",
"if",
"include_defaults",
":",
"keys",
"=",
"self",
".",
"properties",
"(",
")",
"else",
":",
"# TODO (bev) For now, include unstable default values. Things rely on Instances",
"# always getting serialized, even defaults, and adding unstable defaults here",
"# accomplishes that. Unmodified defaults for property value containers will be",
"# weeded out below.",
"keys",
"=",
"set",
"(",
"self",
".",
"_property_values",
".",
"keys",
"(",
")",
")",
"|",
"set",
"(",
"self",
".",
"_unstable_default_values",
".",
"keys",
"(",
")",
")",
"if",
"self",
".",
"themed_values",
"(",
")",
":",
"themed_keys",
"=",
"set",
"(",
"self",
".",
"themed_values",
"(",
")",
".",
"keys",
"(",
")",
")",
"keys",
"|=",
"themed_keys",
"for",
"key",
"in",
"keys",
":",
"descriptor",
"=",
"self",
".",
"lookup",
"(",
"key",
")",
"if",
"not",
"query",
"(",
"descriptor",
")",
":",
"continue",
"value",
"=",
"descriptor",
".",
"serializable_value",
"(",
"self",
")",
"if",
"not",
"include_defaults",
"and",
"key",
"not",
"in",
"themed_keys",
":",
"if",
"isinstance",
"(",
"value",
",",
"PropertyValueContainer",
")",
"and",
"key",
"in",
"self",
".",
"_unstable_default_values",
":",
"continue",
"result",
"[",
"key",
"]",
"=",
"value",
"return",
"result"
] | Query the properties values of |HasProps| instances with a
predicate.
Args:
query (callable) :
A callable that accepts property descriptors and returns True
or False
include_defaults (bool, optional) :
Whether to include properties that have not been explicitly
set by a user (default: True)
Returns:
dict : mapping of property names and values for matching properties | [
"Query",
"the",
"properties",
"values",
"of",
"|HasProps|",
"instances",
"with",
"a",
"predicate",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/has_props.py#L528-L570 | train |
bokeh/bokeh | bokeh/core/has_props.py | HasProps.apply_theme | def apply_theme(self, property_values):
''' Apply a set of theme values which will be used rather than
defaults, but will not override application-set values.
The passed-in dictionary may be kept around as-is and shared with
other instances to save memory (so neither the caller nor the
|HasProps| instance should modify it).
Args:
property_values (dict) : theme values to use in place of defaults
Returns:
None
'''
old_dict = self.themed_values()
# if the same theme is set again, it should reuse the same dict
if old_dict is property_values:
return
removed = set()
# we're doing a little song-and-dance to avoid storing __themed_values__ or
# an empty dict, if there's no theme that applies to this HasProps instance.
if old_dict is not None:
removed.update(set(old_dict.keys()))
added = set(property_values.keys())
old_values = dict()
for k in added.union(removed):
old_values[k] = getattr(self, k)
if len(property_values) > 0:
setattr(self, '__themed_values__', property_values)
elif hasattr(self, '__themed_values__'):
delattr(self, '__themed_values__')
# Property container values might be cached even if unmodified. Invalidate
# any cached values that are not modified at this point.
for k, v in old_values.items():
if k in self._unstable_themed_values:
del self._unstable_themed_values[k]
# Emit any change notifications that result
for k, v in old_values.items():
descriptor = self.lookup(k)
descriptor.trigger_if_changed(self, v) | python | def apply_theme(self, property_values):
''' Apply a set of theme values which will be used rather than
defaults, but will not override application-set values.
The passed-in dictionary may be kept around as-is and shared with
other instances to save memory (so neither the caller nor the
|HasProps| instance should modify it).
Args:
property_values (dict) : theme values to use in place of defaults
Returns:
None
'''
old_dict = self.themed_values()
# if the same theme is set again, it should reuse the same dict
if old_dict is property_values:
return
removed = set()
# we're doing a little song-and-dance to avoid storing __themed_values__ or
# an empty dict, if there's no theme that applies to this HasProps instance.
if old_dict is not None:
removed.update(set(old_dict.keys()))
added = set(property_values.keys())
old_values = dict()
for k in added.union(removed):
old_values[k] = getattr(self, k)
if len(property_values) > 0:
setattr(self, '__themed_values__', property_values)
elif hasattr(self, '__themed_values__'):
delattr(self, '__themed_values__')
# Property container values might be cached even if unmodified. Invalidate
# any cached values that are not modified at this point.
for k, v in old_values.items():
if k in self._unstable_themed_values:
del self._unstable_themed_values[k]
# Emit any change notifications that result
for k, v in old_values.items():
descriptor = self.lookup(k)
descriptor.trigger_if_changed(self, v) | [
"def",
"apply_theme",
"(",
"self",
",",
"property_values",
")",
":",
"old_dict",
"=",
"self",
".",
"themed_values",
"(",
")",
"# if the same theme is set again, it should reuse the same dict",
"if",
"old_dict",
"is",
"property_values",
":",
"return",
"removed",
"=",
"set",
"(",
")",
"# we're doing a little song-and-dance to avoid storing __themed_values__ or",
"# an empty dict, if there's no theme that applies to this HasProps instance.",
"if",
"old_dict",
"is",
"not",
"None",
":",
"removed",
".",
"update",
"(",
"set",
"(",
"old_dict",
".",
"keys",
"(",
")",
")",
")",
"added",
"=",
"set",
"(",
"property_values",
".",
"keys",
"(",
")",
")",
"old_values",
"=",
"dict",
"(",
")",
"for",
"k",
"in",
"added",
".",
"union",
"(",
"removed",
")",
":",
"old_values",
"[",
"k",
"]",
"=",
"getattr",
"(",
"self",
",",
"k",
")",
"if",
"len",
"(",
"property_values",
")",
">",
"0",
":",
"setattr",
"(",
"self",
",",
"'__themed_values__'",
",",
"property_values",
")",
"elif",
"hasattr",
"(",
"self",
",",
"'__themed_values__'",
")",
":",
"delattr",
"(",
"self",
",",
"'__themed_values__'",
")",
"# Property container values might be cached even if unmodified. Invalidate",
"# any cached values that are not modified at this point.",
"for",
"k",
",",
"v",
"in",
"old_values",
".",
"items",
"(",
")",
":",
"if",
"k",
"in",
"self",
".",
"_unstable_themed_values",
":",
"del",
"self",
".",
"_unstable_themed_values",
"[",
"k",
"]",
"# Emit any change notifications that result",
"for",
"k",
",",
"v",
"in",
"old_values",
".",
"items",
"(",
")",
":",
"descriptor",
"=",
"self",
".",
"lookup",
"(",
"k",
")",
"descriptor",
".",
"trigger_if_changed",
"(",
"self",
",",
"v",
")"
] | Apply a set of theme values which will be used rather than
defaults, but will not override application-set values.
The passed-in dictionary may be kept around as-is and shared with
other instances to save memory (so neither the caller nor the
|HasProps| instance should modify it).
Args:
property_values (dict) : theme values to use in place of defaults
Returns:
None | [
"Apply",
"a",
"set",
"of",
"theme",
"values",
"which",
"will",
"be",
"used",
"rather",
"than",
"defaults",
"but",
"will",
"not",
"override",
"application",
"-",
"set",
"values",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/has_props.py#L584-L629 | train |
bokeh/bokeh | bokeh/util/string.py | indent | def indent(text, n=2, ch=" "):
''' Indent all the lines in a given block of text by a specified amount.
Args:
text (str) :
The text to indent
n (int, optional) :
The amount to indent each line by (default: 2)
ch (char, optional) :
What character to fill the indentation with (default: " ")
'''
padding = ch * n
return "\n".join(padding+line for line in text.split("\n")) | python | def indent(text, n=2, ch=" "):
''' Indent all the lines in a given block of text by a specified amount.
Args:
text (str) :
The text to indent
n (int, optional) :
The amount to indent each line by (default: 2)
ch (char, optional) :
What character to fill the indentation with (default: " ")
'''
padding = ch * n
return "\n".join(padding+line for line in text.split("\n")) | [
"def",
"indent",
"(",
"text",
",",
"n",
"=",
"2",
",",
"ch",
"=",
"\" \"",
")",
":",
"padding",
"=",
"ch",
"*",
"n",
"return",
"\"\\n\"",
".",
"join",
"(",
"padding",
"+",
"line",
"for",
"line",
"in",
"text",
".",
"split",
"(",
"\"\\n\"",
")",
")"
] | Indent all the lines in a given block of text by a specified amount.
Args:
text (str) :
The text to indent
n (int, optional) :
The amount to indent each line by (default: 2)
ch (char, optional) :
What character to fill the indentation with (default: " ") | [
"Indent",
"all",
"the",
"lines",
"in",
"a",
"given",
"block",
"of",
"text",
"by",
"a",
"specified",
"amount",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/string.py#L105-L120 | train |
bokeh/bokeh | bokeh/util/string.py | nice_join | def nice_join(seq, sep=", ", conjuction="or"):
''' Join together sequences of strings into English-friendly phrases using
the conjunction ``or`` when appropriate.
Args:
seq (seq[str]) : a sequence of strings to nicely join
sep (str, optional) : a sequence delimiter to use (default: ", ")
conjunction (str or None, optional) : a conjuction to use for the last
two items, or None to reproduce basic join behaviour (default: "or")
Returns:
a joined string
Examples:
>>> nice_join(["a", "b", "c"])
'a, b or c'
'''
seq = [str(x) for x in seq]
if len(seq) <= 1 or conjuction is None:
return sep.join(seq)
else:
return "%s %s %s" % (sep.join(seq[:-1]), conjuction, seq[-1]) | python | def nice_join(seq, sep=", ", conjuction="or"):
''' Join together sequences of strings into English-friendly phrases using
the conjunction ``or`` when appropriate.
Args:
seq (seq[str]) : a sequence of strings to nicely join
sep (str, optional) : a sequence delimiter to use (default: ", ")
conjunction (str or None, optional) : a conjuction to use for the last
two items, or None to reproduce basic join behaviour (default: "or")
Returns:
a joined string
Examples:
>>> nice_join(["a", "b", "c"])
'a, b or c'
'''
seq = [str(x) for x in seq]
if len(seq) <= 1 or conjuction is None:
return sep.join(seq)
else:
return "%s %s %s" % (sep.join(seq[:-1]), conjuction, seq[-1]) | [
"def",
"nice_join",
"(",
"seq",
",",
"sep",
"=",
"\", \"",
",",
"conjuction",
"=",
"\"or\"",
")",
":",
"seq",
"=",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"seq",
"]",
"if",
"len",
"(",
"seq",
")",
"<=",
"1",
"or",
"conjuction",
"is",
"None",
":",
"return",
"sep",
".",
"join",
"(",
"seq",
")",
"else",
":",
"return",
"\"%s %s %s\"",
"%",
"(",
"sep",
".",
"join",
"(",
"seq",
"[",
":",
"-",
"1",
"]",
")",
",",
"conjuction",
",",
"seq",
"[",
"-",
"1",
"]",
")"
] | Join together sequences of strings into English-friendly phrases using
the conjunction ``or`` when appropriate.
Args:
seq (seq[str]) : a sequence of strings to nicely join
sep (str, optional) : a sequence delimiter to use (default: ", ")
conjunction (str or None, optional) : a conjuction to use for the last
two items, or None to reproduce basic join behaviour (default: "or")
Returns:
a joined string
Examples:
>>> nice_join(["a", "b", "c"])
'a, b or c' | [
"Join",
"together",
"sequences",
"of",
"strings",
"into",
"English",
"-",
"friendly",
"phrases",
"using",
"the",
"conjunction",
"or",
"when",
"appropriate",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/string.py#L122-L145 | train |
bokeh/bokeh | bokeh/util/string.py | snakify | def snakify(name, sep='_'):
''' Convert CamelCase to snake_case. '''
name = re.sub("([A-Z]+)([A-Z][a-z])", r"\1%s\2" % sep, name)
name = re.sub("([a-z\\d])([A-Z])", r"\1%s\2" % sep, name)
return name.lower() | python | def snakify(name, sep='_'):
''' Convert CamelCase to snake_case. '''
name = re.sub("([A-Z]+)([A-Z][a-z])", r"\1%s\2" % sep, name)
name = re.sub("([a-z\\d])([A-Z])", r"\1%s\2" % sep, name)
return name.lower() | [
"def",
"snakify",
"(",
"name",
",",
"sep",
"=",
"'_'",
")",
":",
"name",
"=",
"re",
".",
"sub",
"(",
"\"([A-Z]+)([A-Z][a-z])\"",
",",
"r\"\\1%s\\2\"",
"%",
"sep",
",",
"name",
")",
"name",
"=",
"re",
".",
"sub",
"(",
"\"([a-z\\\\d])([A-Z])\"",
",",
"r\"\\1%s\\2\"",
"%",
"sep",
",",
"name",
")",
"return",
"name",
".",
"lower",
"(",
")"
] | Convert CamelCase to snake_case. | [
"Convert",
"CamelCase",
"to",
"snake_case",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/string.py#L147-L151 | train |
bokeh/bokeh | bokeh/application/handlers/document_lifecycle.py | _on_session_destroyed | def _on_session_destroyed(session_context):
'''
Calls any on_session_destroyed callbacks defined on the Document
'''
callbacks = session_context._document.session_destroyed_callbacks
session_context._document.session_destroyed_callbacks = set()
for callback in callbacks:
try:
callback(session_context)
except Exception as e:
log.warning('DocumentLifeCycleHandler on_session_destroyed '
'callback %s failed with following error: %s'
% (callback, e))
if callbacks:
# If any session callbacks were defined garbage collect after deleting all references
del callback
del callbacks
import gc
gc.collect() | python | def _on_session_destroyed(session_context):
'''
Calls any on_session_destroyed callbacks defined on the Document
'''
callbacks = session_context._document.session_destroyed_callbacks
session_context._document.session_destroyed_callbacks = set()
for callback in callbacks:
try:
callback(session_context)
except Exception as e:
log.warning('DocumentLifeCycleHandler on_session_destroyed '
'callback %s failed with following error: %s'
% (callback, e))
if callbacks:
# If any session callbacks were defined garbage collect after deleting all references
del callback
del callbacks
import gc
gc.collect() | [
"def",
"_on_session_destroyed",
"(",
"session_context",
")",
":",
"callbacks",
"=",
"session_context",
".",
"_document",
".",
"session_destroyed_callbacks",
"session_context",
".",
"_document",
".",
"session_destroyed_callbacks",
"=",
"set",
"(",
")",
"for",
"callback",
"in",
"callbacks",
":",
"try",
":",
"callback",
"(",
"session_context",
")",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"warning",
"(",
"'DocumentLifeCycleHandler on_session_destroyed '",
"'callback %s failed with following error: %s'",
"%",
"(",
"callback",
",",
"e",
")",
")",
"if",
"callbacks",
":",
"# If any session callbacks were defined garbage collect after deleting all references",
"del",
"callback",
"del",
"callbacks",
"import",
"gc",
"gc",
".",
"collect",
"(",
")"
] | Calls any on_session_destroyed callbacks defined on the Document | [
"Calls",
"any",
"on_session_destroyed",
"callbacks",
"defined",
"on",
"the",
"Document"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/application/handlers/document_lifecycle.py#L60-L79 | train |
bokeh/bokeh | bokeh/protocol/messages/__init__.py | register | def register(cls):
''' Decorator to add a Message (and its revision) to the Protocol index.
Example:
.. code-block:: python
@register
class some_msg_1(Message):
msgtype = 'SOME-MSG'
revision = 1
@classmethod
def create(cls, **metadata):
header = cls.create_header()
content = {}
return cls(header, metadata, content)
'''
key = (cls.msgtype, cls.revision)
if key in index:
raise ProtocolError("Duplicate message specification encountered: %r" % key)
index[key] = cls
return cls | python | def register(cls):
''' Decorator to add a Message (and its revision) to the Protocol index.
Example:
.. code-block:: python
@register
class some_msg_1(Message):
msgtype = 'SOME-MSG'
revision = 1
@classmethod
def create(cls, **metadata):
header = cls.create_header()
content = {}
return cls(header, metadata, content)
'''
key = (cls.msgtype, cls.revision)
if key in index:
raise ProtocolError("Duplicate message specification encountered: %r" % key)
index[key] = cls
return cls | [
"def",
"register",
"(",
"cls",
")",
":",
"key",
"=",
"(",
"cls",
".",
"msgtype",
",",
"cls",
".",
"revision",
")",
"if",
"key",
"in",
"index",
":",
"raise",
"ProtocolError",
"(",
"\"Duplicate message specification encountered: %r\"",
"%",
"key",
")",
"index",
"[",
"key",
"]",
"=",
"cls",
"return",
"cls"
] | Decorator to add a Message (and its revision) to the Protocol index.
Example:
.. code-block:: python
@register
class some_msg_1(Message):
msgtype = 'SOME-MSG'
revision = 1
@classmethod
def create(cls, **metadata):
header = cls.create_header()
content = {}
return cls(header, metadata, content) | [
"Decorator",
"to",
"add",
"a",
"Message",
"(",
"and",
"its",
"revision",
")",
"to",
"the",
"Protocol",
"index",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/protocol/messages/__init__.py#L49-L73 | train |
bokeh/bokeh | bokeh/client/session.py | pull_session | def pull_session(session_id=None, url='default', io_loop=None, arguments=None):
''' Create a session by loading the current server-side document.
``session.document`` will be a fresh document loaded from
the server. While the connection to the server is open,
changes made on the server side will be applied to this
document, and changes made on the client side will be
synced to the server.
If you don't plan to modify ``session.document`` you probably
don't need to use this function; instead you can directly
``show_session()`` or ``server_session()`` without downloading
the session's document into your process first. It's much
more efficient to avoid downloading the session if you don't need
to.
In a production scenario, the ``session_id`` should be
unique for each browser tab, which keeps users from
stomping on each other. It's neither scalable nor secure to
use predictable session IDs or to share session IDs across
users.
For a notebook running on a single machine, ``session_id``
could be something human-readable such as ``"default"`` for
convenience.
If you allow ``pull_session()`` to generate a unique
``session_id``, you can obtain the generated ID with the
``id`` property on the returned ``ClientSession``.
Args:
session_id (string, optional) :
The name of the session, None to autogenerate a random one (default: None)
url : (str, optional): The URL to a Bokeh application on a Bokeh server
can also be `"default"` which will connect to the default app URL
io_loop (``tornado.ioloop.IOLoop``, optional) :
The ``IOLoop`` to use for the websocket
arguments (dict[str, str], optional) :
A dictionary of key/values to be passed as HTTP request arguments
to Bokeh application code (default: None)
Note that should only be provided when pulling new sessions.
If ``session_id`` is not None, or a session with ``session_id``
already exists, these arguments will have no effect.
Returns:
ClientSession :
A new ``ClientSession`` connected to the server
'''
coords = _SessionCoordinates(session_id=session_id, url=url)
session = ClientSession(session_id=session_id, websocket_url=websocket_url_for_server_url(coords.url), io_loop=io_loop, arguments=arguments)
session.pull()
return session | python | def pull_session(session_id=None, url='default', io_loop=None, arguments=None):
''' Create a session by loading the current server-side document.
``session.document`` will be a fresh document loaded from
the server. While the connection to the server is open,
changes made on the server side will be applied to this
document, and changes made on the client side will be
synced to the server.
If you don't plan to modify ``session.document`` you probably
don't need to use this function; instead you can directly
``show_session()`` or ``server_session()`` without downloading
the session's document into your process first. It's much
more efficient to avoid downloading the session if you don't need
to.
In a production scenario, the ``session_id`` should be
unique for each browser tab, which keeps users from
stomping on each other. It's neither scalable nor secure to
use predictable session IDs or to share session IDs across
users.
For a notebook running on a single machine, ``session_id``
could be something human-readable such as ``"default"`` for
convenience.
If you allow ``pull_session()`` to generate a unique
``session_id``, you can obtain the generated ID with the
``id`` property on the returned ``ClientSession``.
Args:
session_id (string, optional) :
The name of the session, None to autogenerate a random one (default: None)
url : (str, optional): The URL to a Bokeh application on a Bokeh server
can also be `"default"` which will connect to the default app URL
io_loop (``tornado.ioloop.IOLoop``, optional) :
The ``IOLoop`` to use for the websocket
arguments (dict[str, str], optional) :
A dictionary of key/values to be passed as HTTP request arguments
to Bokeh application code (default: None)
Note that should only be provided when pulling new sessions.
If ``session_id`` is not None, or a session with ``session_id``
already exists, these arguments will have no effect.
Returns:
ClientSession :
A new ``ClientSession`` connected to the server
'''
coords = _SessionCoordinates(session_id=session_id, url=url)
session = ClientSession(session_id=session_id, websocket_url=websocket_url_for_server_url(coords.url), io_loop=io_loop, arguments=arguments)
session.pull()
return session | [
"def",
"pull_session",
"(",
"session_id",
"=",
"None",
",",
"url",
"=",
"'default'",
",",
"io_loop",
"=",
"None",
",",
"arguments",
"=",
"None",
")",
":",
"coords",
"=",
"_SessionCoordinates",
"(",
"session_id",
"=",
"session_id",
",",
"url",
"=",
"url",
")",
"session",
"=",
"ClientSession",
"(",
"session_id",
"=",
"session_id",
",",
"websocket_url",
"=",
"websocket_url_for_server_url",
"(",
"coords",
".",
"url",
")",
",",
"io_loop",
"=",
"io_loop",
",",
"arguments",
"=",
"arguments",
")",
"session",
".",
"pull",
"(",
")",
"return",
"session"
] | Create a session by loading the current server-side document.
``session.document`` will be a fresh document loaded from
the server. While the connection to the server is open,
changes made on the server side will be applied to this
document, and changes made on the client side will be
synced to the server.
If you don't plan to modify ``session.document`` you probably
don't need to use this function; instead you can directly
``show_session()`` or ``server_session()`` without downloading
the session's document into your process first. It's much
more efficient to avoid downloading the session if you don't need
to.
In a production scenario, the ``session_id`` should be
unique for each browser tab, which keeps users from
stomping on each other. It's neither scalable nor secure to
use predictable session IDs or to share session IDs across
users.
For a notebook running on a single machine, ``session_id``
could be something human-readable such as ``"default"`` for
convenience.
If you allow ``pull_session()`` to generate a unique
``session_id``, you can obtain the generated ID with the
``id`` property on the returned ``ClientSession``.
Args:
session_id (string, optional) :
The name of the session, None to autogenerate a random one (default: None)
url : (str, optional): The URL to a Bokeh application on a Bokeh server
can also be `"default"` which will connect to the default app URL
io_loop (``tornado.ioloop.IOLoop``, optional) :
The ``IOLoop`` to use for the websocket
arguments (dict[str, str], optional) :
A dictionary of key/values to be passed as HTTP request arguments
to Bokeh application code (default: None)
Note that should only be provided when pulling new sessions.
If ``session_id`` is not None, or a session with ``session_id``
already exists, these arguments will have no effect.
Returns:
ClientSession :
A new ``ClientSession`` connected to the server | [
"Create",
"a",
"session",
"by",
"loading",
"the",
"current",
"server",
"-",
"side",
"document",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/client/session.py#L68-L125 | train |
bokeh/bokeh | bokeh/client/session.py | push_session | def push_session(document, session_id=None, url='default', io_loop=None):
''' Create a session by pushing the given document to the server,
overwriting any existing server-side document.
``session.document`` in the returned session will be your supplied
document. While the connection to the server is open, changes made on the
server side will be applied to this document, and changes made on the
client side will be synced to the server.
In a production scenario, the ``session_id`` should be unique for each
browser tab, which keeps users from stomping on each other. It's neither
scalable nor secure to use predictable session IDs or to share session
IDs across users.
For a notebook running on a single machine, ``session_id`` could be
something human-readable such as ``"default"`` for convenience.
If you allow ``push_session()`` to generate a unique ``session_id``, you
can obtain the generated ID with the ``id`` property on the returned
``ClientSession``.
Args:
document : (bokeh.document.Document)
The document to be pushed and set as session.document
session_id : (string, optional)
The name of the session, None to autogenerate a random one (default: None)
url : (str, optional): The URL to a Bokeh application on a Bokeh server
can also be `"default"` which will connect to the default app URL
io_loop : (tornado.ioloop.IOLoop, optional)
The IOLoop to use for the websocket
Returns:
ClientSession
A new ClientSession connected to the server
'''
coords = _SessionCoordinates(session_id=session_id, url=url)
session = ClientSession(session_id=coords.session_id, websocket_url=websocket_url_for_server_url(coords.url), io_loop=io_loop)
session.push(document)
return session | python | def push_session(document, session_id=None, url='default', io_loop=None):
''' Create a session by pushing the given document to the server,
overwriting any existing server-side document.
``session.document`` in the returned session will be your supplied
document. While the connection to the server is open, changes made on the
server side will be applied to this document, and changes made on the
client side will be synced to the server.
In a production scenario, the ``session_id`` should be unique for each
browser tab, which keeps users from stomping on each other. It's neither
scalable nor secure to use predictable session IDs or to share session
IDs across users.
For a notebook running on a single machine, ``session_id`` could be
something human-readable such as ``"default"`` for convenience.
If you allow ``push_session()`` to generate a unique ``session_id``, you
can obtain the generated ID with the ``id`` property on the returned
``ClientSession``.
Args:
document : (bokeh.document.Document)
The document to be pushed and set as session.document
session_id : (string, optional)
The name of the session, None to autogenerate a random one (default: None)
url : (str, optional): The URL to a Bokeh application on a Bokeh server
can also be `"default"` which will connect to the default app URL
io_loop : (tornado.ioloop.IOLoop, optional)
The IOLoop to use for the websocket
Returns:
ClientSession
A new ClientSession connected to the server
'''
coords = _SessionCoordinates(session_id=session_id, url=url)
session = ClientSession(session_id=coords.session_id, websocket_url=websocket_url_for_server_url(coords.url), io_loop=io_loop)
session.push(document)
return session | [
"def",
"push_session",
"(",
"document",
",",
"session_id",
"=",
"None",
",",
"url",
"=",
"'default'",
",",
"io_loop",
"=",
"None",
")",
":",
"coords",
"=",
"_SessionCoordinates",
"(",
"session_id",
"=",
"session_id",
",",
"url",
"=",
"url",
")",
"session",
"=",
"ClientSession",
"(",
"session_id",
"=",
"coords",
".",
"session_id",
",",
"websocket_url",
"=",
"websocket_url_for_server_url",
"(",
"coords",
".",
"url",
")",
",",
"io_loop",
"=",
"io_loop",
")",
"session",
".",
"push",
"(",
"document",
")",
"return",
"session"
] | Create a session by pushing the given document to the server,
overwriting any existing server-side document.
``session.document`` in the returned session will be your supplied
document. While the connection to the server is open, changes made on the
server side will be applied to this document, and changes made on the
client side will be synced to the server.
In a production scenario, the ``session_id`` should be unique for each
browser tab, which keeps users from stomping on each other. It's neither
scalable nor secure to use predictable session IDs or to share session
IDs across users.
For a notebook running on a single machine, ``session_id`` could be
something human-readable such as ``"default"`` for convenience.
If you allow ``push_session()`` to generate a unique ``session_id``, you
can obtain the generated ID with the ``id`` property on the returned
``ClientSession``.
Args:
document : (bokeh.document.Document)
The document to be pushed and set as session.document
session_id : (string, optional)
The name of the session, None to autogenerate a random one (default: None)
url : (str, optional): The URL to a Bokeh application on a Bokeh server
can also be `"default"` which will connect to the default app URL
io_loop : (tornado.ioloop.IOLoop, optional)
The IOLoop to use for the websocket
Returns:
ClientSession
A new ClientSession connected to the server | [
"Create",
"a",
"session",
"by",
"pushing",
"the",
"given",
"document",
"to",
"the",
"server",
"overwriting",
"any",
"existing",
"server",
"-",
"side",
"document",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/client/session.py#L127-L169 | train |
bokeh/bokeh | bokeh/client/session.py | show_session | def show_session(session_id=None, url='default', session=None, browser=None, new="tab", controller=None):
''' Open a browser displaying a session document.
If you have a session from ``pull_session()`` or ``push_session`` you
can ``show_session(session=mysession)``. If you don't need to open a
connection to the server yourself, you can show a new session in a
browser by providing just the ``url``.
Args:
session_id (string, optional) :
The name of the session, None to autogenerate a random one (default: None)
url : (str, optional): The URL to a Bokeh application on a Bokeh server
can also be `"default"` which will connect to the default app URL
session (ClientSession, optional) : session to get session ID and server URL from
If you specify this, you don't need to specify session_id and url
browser (str, optional) : browser to show with (default: None)
For systems that support it, the **browser** argument allows
specifying which browser to display in, e.g. "safari", "firefox",
"opera", "windows-default" (see the ``webbrowser`` module
documentation in the standard lib for more details).
new (str, optional) : new file output mode (default: "tab")
For file-based output, opens or raises the browser window
showing the current output file. If **new** is 'tab', then
opens a new tab. If **new** is 'window', then opens a new window.
'''
if session is not None:
server_url = server_url_for_websocket_url(session._connection.url)
session_id = session.id
else:
coords = _SessionCoordinates(session_id=session_id, url=url)
server_url = coords.url
session_id = coords.session_id
if controller is None:
from bokeh.util.browser import get_browser_controller
controller = get_browser_controller(browser=browser)
controller.open(server_url + "?bokeh-session-id=" + quote_plus(session_id),
new=NEW_PARAM[new]) | python | def show_session(session_id=None, url='default', session=None, browser=None, new="tab", controller=None):
''' Open a browser displaying a session document.
If you have a session from ``pull_session()`` or ``push_session`` you
can ``show_session(session=mysession)``. If you don't need to open a
connection to the server yourself, you can show a new session in a
browser by providing just the ``url``.
Args:
session_id (string, optional) :
The name of the session, None to autogenerate a random one (default: None)
url : (str, optional): The URL to a Bokeh application on a Bokeh server
can also be `"default"` which will connect to the default app URL
session (ClientSession, optional) : session to get session ID and server URL from
If you specify this, you don't need to specify session_id and url
browser (str, optional) : browser to show with (default: None)
For systems that support it, the **browser** argument allows
specifying which browser to display in, e.g. "safari", "firefox",
"opera", "windows-default" (see the ``webbrowser`` module
documentation in the standard lib for more details).
new (str, optional) : new file output mode (default: "tab")
For file-based output, opens or raises the browser window
showing the current output file. If **new** is 'tab', then
opens a new tab. If **new** is 'window', then opens a new window.
'''
if session is not None:
server_url = server_url_for_websocket_url(session._connection.url)
session_id = session.id
else:
coords = _SessionCoordinates(session_id=session_id, url=url)
server_url = coords.url
session_id = coords.session_id
if controller is None:
from bokeh.util.browser import get_browser_controller
controller = get_browser_controller(browser=browser)
controller.open(server_url + "?bokeh-session-id=" + quote_plus(session_id),
new=NEW_PARAM[new]) | [
"def",
"show_session",
"(",
"session_id",
"=",
"None",
",",
"url",
"=",
"'default'",
",",
"session",
"=",
"None",
",",
"browser",
"=",
"None",
",",
"new",
"=",
"\"tab\"",
",",
"controller",
"=",
"None",
")",
":",
"if",
"session",
"is",
"not",
"None",
":",
"server_url",
"=",
"server_url_for_websocket_url",
"(",
"session",
".",
"_connection",
".",
"url",
")",
"session_id",
"=",
"session",
".",
"id",
"else",
":",
"coords",
"=",
"_SessionCoordinates",
"(",
"session_id",
"=",
"session_id",
",",
"url",
"=",
"url",
")",
"server_url",
"=",
"coords",
".",
"url",
"session_id",
"=",
"coords",
".",
"session_id",
"if",
"controller",
"is",
"None",
":",
"from",
"bokeh",
".",
"util",
".",
"browser",
"import",
"get_browser_controller",
"controller",
"=",
"get_browser_controller",
"(",
"browser",
"=",
"browser",
")",
"controller",
".",
"open",
"(",
"server_url",
"+",
"\"?bokeh-session-id=\"",
"+",
"quote_plus",
"(",
"session_id",
")",
",",
"new",
"=",
"NEW_PARAM",
"[",
"new",
"]",
")"
] | Open a browser displaying a session document.
If you have a session from ``pull_session()`` or ``push_session`` you
can ``show_session(session=mysession)``. If you don't need to open a
connection to the server yourself, you can show a new session in a
browser by providing just the ``url``.
Args:
session_id (string, optional) :
The name of the session, None to autogenerate a random one (default: None)
url : (str, optional): The URL to a Bokeh application on a Bokeh server
can also be `"default"` which will connect to the default app URL
session (ClientSession, optional) : session to get session ID and server URL from
If you specify this, you don't need to specify session_id and url
browser (str, optional) : browser to show with (default: None)
For systems that support it, the **browser** argument allows
specifying which browser to display in, e.g. "safari", "firefox",
"opera", "windows-default" (see the ``webbrowser`` module
documentation in the standard lib for more details).
new (str, optional) : new file output mode (default: "tab")
For file-based output, opens or raises the browser window
showing the current output file. If **new** is 'tab', then
opens a new tab. If **new** is 'window', then opens a new window. | [
"Open",
"a",
"browser",
"displaying",
"a",
"session",
"document",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/client/session.py#L171-L214 | train |
bokeh/bokeh | bokeh/client/session.py | ClientSession.loop_until_closed | def loop_until_closed(self, suppress_warning=False):
''' Execute a blocking loop that runs and executes event callbacks
until the connection is closed (e.g. by hitting Ctrl-C).
While this method can be used to run Bokeh application code "outside"
the Bokeh server, this practice is HIGHLY DISCOURAGED for any real
use case. This function is intented to facilitate testing ONLY.
'''
suppress_warning # shut up flake
from bokeh.util.deprecation import deprecated
deprecated("ClientSession.loop_until_closed is deprecated, and will be removed in an eventual 2.0 release. "
"Run Bokeh applications directly on a Bokeh server instead. See:\n\n"
" https//docs.bokeh.org/en/latest/docs/user_guide/server.html\n")
self._connection.loop_until_closed() | python | def loop_until_closed(self, suppress_warning=False):
''' Execute a blocking loop that runs and executes event callbacks
until the connection is closed (e.g. by hitting Ctrl-C).
While this method can be used to run Bokeh application code "outside"
the Bokeh server, this practice is HIGHLY DISCOURAGED for any real
use case. This function is intented to facilitate testing ONLY.
'''
suppress_warning # shut up flake
from bokeh.util.deprecation import deprecated
deprecated("ClientSession.loop_until_closed is deprecated, and will be removed in an eventual 2.0 release. "
"Run Bokeh applications directly on a Bokeh server instead. See:\n\n"
" https//docs.bokeh.org/en/latest/docs/user_guide/server.html\n")
self._connection.loop_until_closed() | [
"def",
"loop_until_closed",
"(",
"self",
",",
"suppress_warning",
"=",
"False",
")",
":",
"suppress_warning",
"# shut up flake",
"from",
"bokeh",
".",
"util",
".",
"deprecation",
"import",
"deprecated",
"deprecated",
"(",
"\"ClientSession.loop_until_closed is deprecated, and will be removed in an eventual 2.0 release. \"",
"\"Run Bokeh applications directly on a Bokeh server instead. See:\\n\\n\"",
"\" https//docs.bokeh.org/en/latest/docs/user_guide/server.html\\n\"",
")",
"self",
".",
"_connection",
".",
"loop_until_closed",
"(",
")"
] | Execute a blocking loop that runs and executes event callbacks
until the connection is closed (e.g. by hitting Ctrl-C).
While this method can be used to run Bokeh application code "outside"
the Bokeh server, this practice is HIGHLY DISCOURAGED for any real
use case. This function is intented to facilitate testing ONLY. | [
"Execute",
"a",
"blocking",
"loop",
"that",
"runs",
"and",
"executes",
"event",
"callbacks",
"until",
"the",
"connection",
"is",
"closed",
"(",
"e",
".",
"g",
".",
"by",
"hitting",
"Ctrl",
"-",
"C",
")",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/client/session.py#L337-L354 | train |
bokeh/bokeh | bokeh/client/session.py | ClientSession.pull | def pull(self):
''' Pull the server's state and set it as session.document.
If this is called more than once, session.document will be the same
object instance but its contents will be overwritten.
Automatically calls :func:`connect` before pulling.
'''
self.connect()
if not self.connected:
raise IOError("Cannot pull session document because we failed to connect to the server (to start the server, try the 'bokeh serve' command)")
if self.document is None:
doc = Document()
else:
doc = self.document
self._connection.pull_doc(doc)
if self.document is None:
self._attach_document(doc) | python | def pull(self):
''' Pull the server's state and set it as session.document.
If this is called more than once, session.document will be the same
object instance but its contents will be overwritten.
Automatically calls :func:`connect` before pulling.
'''
self.connect()
if not self.connected:
raise IOError("Cannot pull session document because we failed to connect to the server (to start the server, try the 'bokeh serve' command)")
if self.document is None:
doc = Document()
else:
doc = self.document
self._connection.pull_doc(doc)
if self.document is None:
self._attach_document(doc) | [
"def",
"pull",
"(",
"self",
")",
":",
"self",
".",
"connect",
"(",
")",
"if",
"not",
"self",
".",
"connected",
":",
"raise",
"IOError",
"(",
"\"Cannot pull session document because we failed to connect to the server (to start the server, try the 'bokeh serve' command)\"",
")",
"if",
"self",
".",
"document",
"is",
"None",
":",
"doc",
"=",
"Document",
"(",
")",
"else",
":",
"doc",
"=",
"self",
".",
"document",
"self",
".",
"_connection",
".",
"pull_doc",
"(",
"doc",
")",
"if",
"self",
".",
"document",
"is",
"None",
":",
"self",
".",
"_attach_document",
"(",
"doc",
")"
] | Pull the server's state and set it as session.document.
If this is called more than once, session.document will be the same
object instance but its contents will be overwritten.
Automatically calls :func:`connect` before pulling. | [
"Pull",
"the",
"server",
"s",
"state",
"and",
"set",
"it",
"as",
"session",
".",
"document",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/client/session.py#L356-L375 | train |
bokeh/bokeh | bokeh/client/session.py | ClientSession.push | def push(self, document=None):
''' Push the given document to the server and record it as session.document.
If this is called more than once, the Document has to be the same (or None
to mean "session.document").
.. note::
Automatically calls :func:`~connect` before pushing.
Args:
document (:class:`~bokeh.document.Document`, optional) :
The document which will be kept in sync with the server document.
None to use session.document or create a new document.
'''
if self.document is None:
if document is None:
doc = Document()
else:
doc = document
else:
if document is None:
doc = self.document
else:
raise ValueError("Cannot push() a different document from existing session.document")
self.connect()
if not self.connected:
raise IOError("Cannot push session document because we failed to connect to the server (to start the server, try the 'bokeh serve' command)")
self._connection.push_doc(doc)
if self._document is None:
self._attach_document(doc) | python | def push(self, document=None):
''' Push the given document to the server and record it as session.document.
If this is called more than once, the Document has to be the same (or None
to mean "session.document").
.. note::
Automatically calls :func:`~connect` before pushing.
Args:
document (:class:`~bokeh.document.Document`, optional) :
The document which will be kept in sync with the server document.
None to use session.document or create a new document.
'''
if self.document is None:
if document is None:
doc = Document()
else:
doc = document
else:
if document is None:
doc = self.document
else:
raise ValueError("Cannot push() a different document from existing session.document")
self.connect()
if not self.connected:
raise IOError("Cannot push session document because we failed to connect to the server (to start the server, try the 'bokeh serve' command)")
self._connection.push_doc(doc)
if self._document is None:
self._attach_document(doc) | [
"def",
"push",
"(",
"self",
",",
"document",
"=",
"None",
")",
":",
"if",
"self",
".",
"document",
"is",
"None",
":",
"if",
"document",
"is",
"None",
":",
"doc",
"=",
"Document",
"(",
")",
"else",
":",
"doc",
"=",
"document",
"else",
":",
"if",
"document",
"is",
"None",
":",
"doc",
"=",
"self",
".",
"document",
"else",
":",
"raise",
"ValueError",
"(",
"\"Cannot push() a different document from existing session.document\"",
")",
"self",
".",
"connect",
"(",
")",
"if",
"not",
"self",
".",
"connected",
":",
"raise",
"IOError",
"(",
"\"Cannot push session document because we failed to connect to the server (to start the server, try the 'bokeh serve' command)\"",
")",
"self",
".",
"_connection",
".",
"push_doc",
"(",
"doc",
")",
"if",
"self",
".",
"_document",
"is",
"None",
":",
"self",
".",
"_attach_document",
"(",
"doc",
")"
] | Push the given document to the server and record it as session.document.
If this is called more than once, the Document has to be the same (or None
to mean "session.document").
.. note::
Automatically calls :func:`~connect` before pushing.
Args:
document (:class:`~bokeh.document.Document`, optional) :
The document which will be kept in sync with the server document.
None to use session.document or create a new document. | [
"Push",
"the",
"given",
"document",
"to",
"the",
"server",
"and",
"record",
"it",
"as",
"session",
".",
"document",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/client/session.py#L377-L408 | train |
bokeh/bokeh | bokeh/client/session.py | ClientSession.show | def show(self, obj=None, browser=None, new="tab"):
''' Open a browser displaying this session.
Args:
obj (LayoutDOM object, optional) : a Layout (Row/Column),
Plot or Widget object to display. The object will be added
to the session's document.
browser (str, optional) : browser to show with (default: None)
For systems that support it, the **browser** argument allows
specifying which browser to display in, e.g. "safari", "firefox",
"opera", "windows-default" (see the ``webbrowser`` module
documentation in the standard lib for more details).
new (str, optional) : new file output mode (default: "tab")
For file-based output, opens or raises the browser window
showing the current output file. If **new** is 'tab', then
opens a new tab. If **new** is 'window', then opens a new window.
'''
if obj and obj not in self.document.roots:
self.document.add_root(obj)
show_session(session=self, browser=browser, new=new) | python | def show(self, obj=None, browser=None, new="tab"):
''' Open a browser displaying this session.
Args:
obj (LayoutDOM object, optional) : a Layout (Row/Column),
Plot or Widget object to display. The object will be added
to the session's document.
browser (str, optional) : browser to show with (default: None)
For systems that support it, the **browser** argument allows
specifying which browser to display in, e.g. "safari", "firefox",
"opera", "windows-default" (see the ``webbrowser`` module
documentation in the standard lib for more details).
new (str, optional) : new file output mode (default: "tab")
For file-based output, opens or raises the browser window
showing the current output file. If **new** is 'tab', then
opens a new tab. If **new** is 'window', then opens a new window.
'''
if obj and obj not in self.document.roots:
self.document.add_root(obj)
show_session(session=self, browser=browser, new=new) | [
"def",
"show",
"(",
"self",
",",
"obj",
"=",
"None",
",",
"browser",
"=",
"None",
",",
"new",
"=",
"\"tab\"",
")",
":",
"if",
"obj",
"and",
"obj",
"not",
"in",
"self",
".",
"document",
".",
"roots",
":",
"self",
".",
"document",
".",
"add_root",
"(",
"obj",
")",
"show_session",
"(",
"session",
"=",
"self",
",",
"browser",
"=",
"browser",
",",
"new",
"=",
"new",
")"
] | Open a browser displaying this session.
Args:
obj (LayoutDOM object, optional) : a Layout (Row/Column),
Plot or Widget object to display. The object will be added
to the session's document.
browser (str, optional) : browser to show with (default: None)
For systems that support it, the **browser** argument allows
specifying which browser to display in, e.g. "safari", "firefox",
"opera", "windows-default" (see the ``webbrowser`` module
documentation in the standard lib for more details).
new (str, optional) : new file output mode (default: "tab")
For file-based output, opens or raises the browser window
showing the current output file. If **new** is 'tab', then
opens a new tab. If **new** is 'window', then opens a new window. | [
"Open",
"a",
"browser",
"displaying",
"this",
"session",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/client/session.py#L419-L441 | train |
bokeh/bokeh | bokeh/client/session.py | ClientSession._notify_disconnected | def _notify_disconnected(self):
''' Called by the ClientConnection we are using to notify us of disconnect.
'''
if self.document is not None:
self.document.remove_on_change(self)
self._callbacks.remove_all_callbacks() | python | def _notify_disconnected(self):
''' Called by the ClientConnection we are using to notify us of disconnect.
'''
if self.document is not None:
self.document.remove_on_change(self)
self._callbacks.remove_all_callbacks() | [
"def",
"_notify_disconnected",
"(",
"self",
")",
":",
"if",
"self",
".",
"document",
"is",
"not",
"None",
":",
"self",
".",
"document",
".",
"remove_on_change",
"(",
"self",
")",
"self",
".",
"_callbacks",
".",
"remove_all_callbacks",
"(",
")"
] | Called by the ClientConnection we are using to notify us of disconnect. | [
"Called",
"by",
"the",
"ClientConnection",
"we",
"are",
"using",
"to",
"notify",
"us",
"of",
"disconnect",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/client/session.py#L471-L477 | train |
bokeh/bokeh | bokeh/protocol/message.py | Message.assemble | def assemble(cls, header_json, metadata_json, content_json):
''' Creates a new message, assembled from JSON fragments.
Args:
header_json (``JSON``) :
metadata_json (``JSON``) :
content_json (``JSON``) :
Returns:
Message subclass
Raises:
MessageError
'''
try:
header = json_decode(header_json)
except ValueError:
raise MessageError("header could not be decoded")
try:
metadata = json_decode(metadata_json)
except ValueError:
raise MessageError("metadata could not be decoded")
try:
content = json_decode(content_json)
except ValueError:
raise MessageError("content could not be decoded")
msg = cls(header, metadata, content)
msg._header_json = header_json
msg._metadata_json = metadata_json
msg._content_json = content_json
return msg | python | def assemble(cls, header_json, metadata_json, content_json):
''' Creates a new message, assembled from JSON fragments.
Args:
header_json (``JSON``) :
metadata_json (``JSON``) :
content_json (``JSON``) :
Returns:
Message subclass
Raises:
MessageError
'''
try:
header = json_decode(header_json)
except ValueError:
raise MessageError("header could not be decoded")
try:
metadata = json_decode(metadata_json)
except ValueError:
raise MessageError("metadata could not be decoded")
try:
content = json_decode(content_json)
except ValueError:
raise MessageError("content could not be decoded")
msg = cls(header, metadata, content)
msg._header_json = header_json
msg._metadata_json = metadata_json
msg._content_json = content_json
return msg | [
"def",
"assemble",
"(",
"cls",
",",
"header_json",
",",
"metadata_json",
",",
"content_json",
")",
":",
"try",
":",
"header",
"=",
"json_decode",
"(",
"header_json",
")",
"except",
"ValueError",
":",
"raise",
"MessageError",
"(",
"\"header could not be decoded\"",
")",
"try",
":",
"metadata",
"=",
"json_decode",
"(",
"metadata_json",
")",
"except",
"ValueError",
":",
"raise",
"MessageError",
"(",
"\"metadata could not be decoded\"",
")",
"try",
":",
"content",
"=",
"json_decode",
"(",
"content_json",
")",
"except",
"ValueError",
":",
"raise",
"MessageError",
"(",
"\"content could not be decoded\"",
")",
"msg",
"=",
"cls",
"(",
"header",
",",
"metadata",
",",
"content",
")",
"msg",
".",
"_header_json",
"=",
"header_json",
"msg",
".",
"_metadata_json",
"=",
"metadata_json",
"msg",
".",
"_content_json",
"=",
"content_json",
"return",
"msg"
] | Creates a new message, assembled from JSON fragments.
Args:
header_json (``JSON``) :
metadata_json (``JSON``) :
content_json (``JSON``) :
Returns:
Message subclass
Raises:
MessageError | [
"Creates",
"a",
"new",
"message",
"assembled",
"from",
"JSON",
"fragments",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/protocol/message.py#L119-L158 | train |
bokeh/bokeh | bokeh/protocol/message.py | Message.add_buffer | def add_buffer(self, buf_header, buf_payload):
''' Associate a buffer header and payload with this message.
Args:
buf_header (``JSON``) : a buffer header
buf_payload (``JSON`` or bytes) : a buffer payload
Returns:
None
Raises:
MessageError
'''
if 'num_buffers' in self._header:
self._header['num_buffers'] += 1
else:
self._header['num_buffers'] = 1
self._header_json = None
self._buffers.append((buf_header, buf_payload)) | python | def add_buffer(self, buf_header, buf_payload):
''' Associate a buffer header and payload with this message.
Args:
buf_header (``JSON``) : a buffer header
buf_payload (``JSON`` or bytes) : a buffer payload
Returns:
None
Raises:
MessageError
'''
if 'num_buffers' in self._header:
self._header['num_buffers'] += 1
else:
self._header['num_buffers'] = 1
self._header_json = None
self._buffers.append((buf_header, buf_payload)) | [
"def",
"add_buffer",
"(",
"self",
",",
"buf_header",
",",
"buf_payload",
")",
":",
"if",
"'num_buffers'",
"in",
"self",
".",
"_header",
":",
"self",
".",
"_header",
"[",
"'num_buffers'",
"]",
"+=",
"1",
"else",
":",
"self",
".",
"_header",
"[",
"'num_buffers'",
"]",
"=",
"1",
"self",
".",
"_header_json",
"=",
"None",
"self",
".",
"_buffers",
".",
"append",
"(",
"(",
"buf_header",
",",
"buf_payload",
")",
")"
] | Associate a buffer header and payload with this message.
Args:
buf_header (``JSON``) : a buffer header
buf_payload (``JSON`` or bytes) : a buffer payload
Returns:
None
Raises:
MessageError | [
"Associate",
"a",
"buffer",
"header",
"and",
"payload",
"with",
"this",
"message",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/protocol/message.py#L160-L181 | train |
bokeh/bokeh | bokeh/protocol/message.py | Message.assemble_buffer | def assemble_buffer(self, buf_header, buf_payload):
''' Add a buffer header and payload that we read from the socket.
This differs from add_buffer() because we're validating vs.
the header's num_buffers, instead of filling in the header.
Args:
buf_header (``JSON``) : a buffer header
buf_payload (``JSON`` or bytes) : a buffer payload
Returns:
None
Raises:
ProtocolError
'''
if self.header.get('num_buffers', 0) <= len(self._buffers):
raise ProtocolError("too many buffers received expecting " + str(self.header['num_buffers']))
self._buffers.append((buf_header, buf_payload)) | python | def assemble_buffer(self, buf_header, buf_payload):
''' Add a buffer header and payload that we read from the socket.
This differs from add_buffer() because we're validating vs.
the header's num_buffers, instead of filling in the header.
Args:
buf_header (``JSON``) : a buffer header
buf_payload (``JSON`` or bytes) : a buffer payload
Returns:
None
Raises:
ProtocolError
'''
if self.header.get('num_buffers', 0) <= len(self._buffers):
raise ProtocolError("too many buffers received expecting " + str(self.header['num_buffers']))
self._buffers.append((buf_header, buf_payload)) | [
"def",
"assemble_buffer",
"(",
"self",
",",
"buf_header",
",",
"buf_payload",
")",
":",
"if",
"self",
".",
"header",
".",
"get",
"(",
"'num_buffers'",
",",
"0",
")",
"<=",
"len",
"(",
"self",
".",
"_buffers",
")",
":",
"raise",
"ProtocolError",
"(",
"\"too many buffers received expecting \"",
"+",
"str",
"(",
"self",
".",
"header",
"[",
"'num_buffers'",
"]",
")",
")",
"self",
".",
"_buffers",
".",
"append",
"(",
"(",
"buf_header",
",",
"buf_payload",
")",
")"
] | Add a buffer header and payload that we read from the socket.
This differs from add_buffer() because we're validating vs.
the header's num_buffers, instead of filling in the header.
Args:
buf_header (``JSON``) : a buffer header
buf_payload (``JSON`` or bytes) : a buffer payload
Returns:
None
Raises:
ProtocolError | [
"Add",
"a",
"buffer",
"header",
"and",
"payload",
"that",
"we",
"read",
"from",
"the",
"socket",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/protocol/message.py#L183-L201 | train |
bokeh/bokeh | bokeh/protocol/message.py | Message.write_buffers | def write_buffers(self, conn, locked=True):
''' Write any buffer headers and payloads to the given connection.
Args:
conn (object) :
May be any object with a ``write_message`` method. Typically,
a Tornado ``WSHandler`` or ``WebSocketClientConnection``
locked (bool) :
Returns:
int : number of bytes sent
'''
if conn is None:
raise ValueError("Cannot write_buffers to connection None")
sent = 0
for header, payload in self._buffers:
yield conn.write_message(header, locked=locked)
yield conn.write_message(payload, binary=True, locked=locked)
sent += (len(header) + len(payload))
raise gen.Return(sent) | python | def write_buffers(self, conn, locked=True):
''' Write any buffer headers and payloads to the given connection.
Args:
conn (object) :
May be any object with a ``write_message`` method. Typically,
a Tornado ``WSHandler`` or ``WebSocketClientConnection``
locked (bool) :
Returns:
int : number of bytes sent
'''
if conn is None:
raise ValueError("Cannot write_buffers to connection None")
sent = 0
for header, payload in self._buffers:
yield conn.write_message(header, locked=locked)
yield conn.write_message(payload, binary=True, locked=locked)
sent += (len(header) + len(payload))
raise gen.Return(sent) | [
"def",
"write_buffers",
"(",
"self",
",",
"conn",
",",
"locked",
"=",
"True",
")",
":",
"if",
"conn",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Cannot write_buffers to connection None\"",
")",
"sent",
"=",
"0",
"for",
"header",
",",
"payload",
"in",
"self",
".",
"_buffers",
":",
"yield",
"conn",
".",
"write_message",
"(",
"header",
",",
"locked",
"=",
"locked",
")",
"yield",
"conn",
".",
"write_message",
"(",
"payload",
",",
"binary",
"=",
"True",
",",
"locked",
"=",
"locked",
")",
"sent",
"+=",
"(",
"len",
"(",
"header",
")",
"+",
"len",
"(",
"payload",
")",
")",
"raise",
"gen",
".",
"Return",
"(",
"sent",
")"
] | Write any buffer headers and payloads to the given connection.
Args:
conn (object) :
May be any object with a ``write_message`` method. Typically,
a Tornado ``WSHandler`` or ``WebSocketClientConnection``
locked (bool) :
Returns:
int : number of bytes sent | [
"Write",
"any",
"buffer",
"headers",
"and",
"payloads",
"to",
"the",
"given",
"connection",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/protocol/message.py#L204-L225 | train |
bokeh/bokeh | bokeh/protocol/message.py | Message.create_header | def create_header(cls, request_id=None):
''' Return a message header fragment dict.
Args:
request_id (str or None) :
Message ID of the message this message replies to
Returns:
dict : a message header
'''
header = {
'msgid' : bkserial.make_id(),
'msgtype' : cls.msgtype
}
if request_id is not None:
header['reqid'] = request_id
return header | python | def create_header(cls, request_id=None):
''' Return a message header fragment dict.
Args:
request_id (str or None) :
Message ID of the message this message replies to
Returns:
dict : a message header
'''
header = {
'msgid' : bkserial.make_id(),
'msgtype' : cls.msgtype
}
if request_id is not None:
header['reqid'] = request_id
return header | [
"def",
"create_header",
"(",
"cls",
",",
"request_id",
"=",
"None",
")",
":",
"header",
"=",
"{",
"'msgid'",
":",
"bkserial",
".",
"make_id",
"(",
")",
",",
"'msgtype'",
":",
"cls",
".",
"msgtype",
"}",
"if",
"request_id",
"is",
"not",
"None",
":",
"header",
"[",
"'reqid'",
"]",
"=",
"request_id",
"return",
"header"
] | Return a message header fragment dict.
Args:
request_id (str or None) :
Message ID of the message this message replies to
Returns:
dict : a message header | [
"Return",
"a",
"message",
"header",
"fragment",
"dict",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/protocol/message.py#L228-L245 | train |
bokeh/bokeh | bokeh/protocol/message.py | Message.send | def send(self, conn):
''' Send the message on the given connection.
Args:
conn (WebSocketHandler) : a WebSocketHandler to send messages
Returns:
int : number of bytes sent
'''
if conn is None:
raise ValueError("Cannot send to connection None")
with (yield conn.write_lock.acquire()):
sent = 0
yield conn.write_message(self.header_json, locked=False)
sent += len(self.header_json)
# uncomment this to make it a lot easier to reproduce lock-related bugs
#yield gen.sleep(0.1)
yield conn.write_message(self.metadata_json, locked=False)
sent += len(self.metadata_json)
# uncomment this to make it a lot easier to reproduce lock-related bugs
#yield gen.sleep(0.1)
yield conn.write_message(self.content_json, locked=False)
sent += len(self.content_json)
sent += yield self.write_buffers(conn, locked=False)
raise gen.Return(sent) | python | def send(self, conn):
''' Send the message on the given connection.
Args:
conn (WebSocketHandler) : a WebSocketHandler to send messages
Returns:
int : number of bytes sent
'''
if conn is None:
raise ValueError("Cannot send to connection None")
with (yield conn.write_lock.acquire()):
sent = 0
yield conn.write_message(self.header_json, locked=False)
sent += len(self.header_json)
# uncomment this to make it a lot easier to reproduce lock-related bugs
#yield gen.sleep(0.1)
yield conn.write_message(self.metadata_json, locked=False)
sent += len(self.metadata_json)
# uncomment this to make it a lot easier to reproduce lock-related bugs
#yield gen.sleep(0.1)
yield conn.write_message(self.content_json, locked=False)
sent += len(self.content_json)
sent += yield self.write_buffers(conn, locked=False)
raise gen.Return(sent) | [
"def",
"send",
"(",
"self",
",",
"conn",
")",
":",
"if",
"conn",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Cannot send to connection None\"",
")",
"with",
"(",
"yield",
"conn",
".",
"write_lock",
".",
"acquire",
"(",
")",
")",
":",
"sent",
"=",
"0",
"yield",
"conn",
".",
"write_message",
"(",
"self",
".",
"header_json",
",",
"locked",
"=",
"False",
")",
"sent",
"+=",
"len",
"(",
"self",
".",
"header_json",
")",
"# uncomment this to make it a lot easier to reproduce lock-related bugs",
"#yield gen.sleep(0.1)",
"yield",
"conn",
".",
"write_message",
"(",
"self",
".",
"metadata_json",
",",
"locked",
"=",
"False",
")",
"sent",
"+=",
"len",
"(",
"self",
".",
"metadata_json",
")",
"# uncomment this to make it a lot easier to reproduce lock-related bugs",
"#yield gen.sleep(0.1)",
"yield",
"conn",
".",
"write_message",
"(",
"self",
".",
"content_json",
",",
"locked",
"=",
"False",
")",
"sent",
"+=",
"len",
"(",
"self",
".",
"content_json",
")",
"sent",
"+=",
"yield",
"self",
".",
"write_buffers",
"(",
"conn",
",",
"locked",
"=",
"False",
")",
"raise",
"gen",
".",
"Return",
"(",
"sent",
")"
] | Send the message on the given connection.
Args:
conn (WebSocketHandler) : a WebSocketHandler to send messages
Returns:
int : number of bytes sent | [
"Send",
"the",
"message",
"on",
"the",
"given",
"connection",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/protocol/message.py#L248-L281 | train |
bokeh/bokeh | bokeh/protocol/message.py | Message.complete | def complete(self):
''' Returns whether all required parts of a message are present.
Returns:
bool : True if the message is complete, False otherwise
'''
return self.header is not None and \
self.metadata is not None and \
self.content is not None and \
self.header.get('num_buffers', 0) == len(self._buffers) | python | def complete(self):
''' Returns whether all required parts of a message are present.
Returns:
bool : True if the message is complete, False otherwise
'''
return self.header is not None and \
self.metadata is not None and \
self.content is not None and \
self.header.get('num_buffers', 0) == len(self._buffers) | [
"def",
"complete",
"(",
"self",
")",
":",
"return",
"self",
".",
"header",
"is",
"not",
"None",
"and",
"self",
".",
"metadata",
"is",
"not",
"None",
"and",
"self",
".",
"content",
"is",
"not",
"None",
"and",
"self",
".",
"header",
".",
"get",
"(",
"'num_buffers'",
",",
"0",
")",
"==",
"len",
"(",
"self",
".",
"_buffers",
")"
] | Returns whether all required parts of a message are present.
Returns:
bool : True if the message is complete, False otherwise | [
"Returns",
"whether",
"all",
"required",
"parts",
"of",
"a",
"message",
"are",
"present",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/protocol/message.py#L284-L294 | train |
bokeh/bokeh | bokeh/util/logconfig.py | basicConfig | def basicConfig(*args, **kwargs):
"""
A logging.basicConfig() wrapper that also undoes the default
Bokeh-specific configuration.
"""
if default_handler is not None:
bokeh_logger.removeHandler(default_handler)
bokeh_logger.propagate = True
return logging.basicConfig(*args, **kwargs) | python | def basicConfig(*args, **kwargs):
"""
A logging.basicConfig() wrapper that also undoes the default
Bokeh-specific configuration.
"""
if default_handler is not None:
bokeh_logger.removeHandler(default_handler)
bokeh_logger.propagate = True
return logging.basicConfig(*args, **kwargs) | [
"def",
"basicConfig",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"default_handler",
"is",
"not",
"None",
":",
"bokeh_logger",
".",
"removeHandler",
"(",
"default_handler",
")",
"bokeh_logger",
".",
"propagate",
"=",
"True",
"return",
"logging",
".",
"basicConfig",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | A logging.basicConfig() wrapper that also undoes the default
Bokeh-specific configuration. | [
"A",
"logging",
".",
"basicConfig",
"()",
"wrapper",
"that",
"also",
"undoes",
"the",
"default",
"Bokeh",
"-",
"specific",
"configuration",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/logconfig.py#L57-L65 | train |
bokeh/bokeh | bokeh/util/deprecation.py | deprecated | def deprecated(since_or_msg, old=None, new=None, extra=None):
""" Issue a nicely formatted deprecation warning. """
if isinstance(since_or_msg, tuple):
if old is None or new is None:
raise ValueError("deprecated entity and a replacement are required")
if len(since_or_msg) != 3 or not all(isinstance(x, int) and x >=0 for x in since_or_msg):
raise ValueError("invalid version tuple: %r" % (since_or_msg,))
since = "%d.%d.%d" % since_or_msg
message = "%(old)s was deprecated in Bokeh %(since)s and will be removed, use %(new)s instead."
message = message % dict(old=old, since=since, new=new)
if extra is not None:
message += " " + extra.strip()
elif isinstance(since_or_msg, six.string_types):
if not (old is None and new is None and extra is None):
raise ValueError("deprecated(message) signature doesn't allow extra arguments")
message = since_or_msg
else:
raise ValueError("expected a version tuple or string message")
warn(message) | python | def deprecated(since_or_msg, old=None, new=None, extra=None):
""" Issue a nicely formatted deprecation warning. """
if isinstance(since_or_msg, tuple):
if old is None or new is None:
raise ValueError("deprecated entity and a replacement are required")
if len(since_or_msg) != 3 or not all(isinstance(x, int) and x >=0 for x in since_or_msg):
raise ValueError("invalid version tuple: %r" % (since_or_msg,))
since = "%d.%d.%d" % since_or_msg
message = "%(old)s was deprecated in Bokeh %(since)s and will be removed, use %(new)s instead."
message = message % dict(old=old, since=since, new=new)
if extra is not None:
message += " " + extra.strip()
elif isinstance(since_or_msg, six.string_types):
if not (old is None and new is None and extra is None):
raise ValueError("deprecated(message) signature doesn't allow extra arguments")
message = since_or_msg
else:
raise ValueError("expected a version tuple or string message")
warn(message) | [
"def",
"deprecated",
"(",
"since_or_msg",
",",
"old",
"=",
"None",
",",
"new",
"=",
"None",
",",
"extra",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"since_or_msg",
",",
"tuple",
")",
":",
"if",
"old",
"is",
"None",
"or",
"new",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"deprecated entity and a replacement are required\"",
")",
"if",
"len",
"(",
"since_or_msg",
")",
"!=",
"3",
"or",
"not",
"all",
"(",
"isinstance",
"(",
"x",
",",
"int",
")",
"and",
"x",
">=",
"0",
"for",
"x",
"in",
"since_or_msg",
")",
":",
"raise",
"ValueError",
"(",
"\"invalid version tuple: %r\"",
"%",
"(",
"since_or_msg",
",",
")",
")",
"since",
"=",
"\"%d.%d.%d\"",
"%",
"since_or_msg",
"message",
"=",
"\"%(old)s was deprecated in Bokeh %(since)s and will be removed, use %(new)s instead.\"",
"message",
"=",
"message",
"%",
"dict",
"(",
"old",
"=",
"old",
",",
"since",
"=",
"since",
",",
"new",
"=",
"new",
")",
"if",
"extra",
"is",
"not",
"None",
":",
"message",
"+=",
"\" \"",
"+",
"extra",
".",
"strip",
"(",
")",
"elif",
"isinstance",
"(",
"since_or_msg",
",",
"six",
".",
"string_types",
")",
":",
"if",
"not",
"(",
"old",
"is",
"None",
"and",
"new",
"is",
"None",
"and",
"extra",
"is",
"None",
")",
":",
"raise",
"ValueError",
"(",
"\"deprecated(message) signature doesn't allow extra arguments\"",
")",
"message",
"=",
"since_or_msg",
"else",
":",
"raise",
"ValueError",
"(",
"\"expected a version tuple or string message\"",
")",
"warn",
"(",
"message",
")"
] | Issue a nicely formatted deprecation warning. | [
"Issue",
"a",
"nicely",
"formatted",
"deprecation",
"warning",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/deprecation.py#L45-L68 | train |
bokeh/bokeh | bokeh/__main__.py | main | def main():
''' Execute the "bokeh" command line program.
'''
import sys
from bokeh.command.bootstrap import main as _main
# Main entry point (see setup.py)
_main(sys.argv) | python | def main():
''' Execute the "bokeh" command line program.
'''
import sys
from bokeh.command.bootstrap import main as _main
# Main entry point (see setup.py)
_main(sys.argv) | [
"def",
"main",
"(",
")",
":",
"import",
"sys",
"from",
"bokeh",
".",
"command",
".",
"bootstrap",
"import",
"main",
"as",
"_main",
"# Main entry point (see setup.py)",
"_main",
"(",
"sys",
".",
"argv",
")"
] | Execute the "bokeh" command line program. | [
"Execute",
"the",
"bokeh",
"command",
"line",
"program",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/__main__.py#L56-L64 | train |
bokeh/bokeh | bokeh/server/connection.py | ServerConnection.detach_session | def detach_session(self):
"""Allow the session to be discarded and don't get change notifications from it anymore"""
if self._session is not None:
self._session.unsubscribe(self)
self._session = None | python | def detach_session(self):
"""Allow the session to be discarded and don't get change notifications from it anymore"""
if self._session is not None:
self._session.unsubscribe(self)
self._session = None | [
"def",
"detach_session",
"(",
"self",
")",
":",
"if",
"self",
".",
"_session",
"is",
"not",
"None",
":",
"self",
".",
"_session",
".",
"unsubscribe",
"(",
"self",
")",
"self",
".",
"_session",
"=",
"None"
] | Allow the session to be discarded and don't get change notifications from it anymore | [
"Allow",
"the",
"session",
"to",
"be",
"discarded",
"and",
"don",
"t",
"get",
"change",
"notifications",
"from",
"it",
"anymore"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/connection.py#L62-L66 | train |
bokeh/bokeh | bokeh/server/connection.py | ServerConnection.send_patch_document | def send_patch_document(self, event):
""" Sends a PATCH-DOC message, returning a Future that's completed when it's written out. """
msg = self.protocol.create('PATCH-DOC', [event])
return self._socket.send_message(msg) | python | def send_patch_document(self, event):
""" Sends a PATCH-DOC message, returning a Future that's completed when it's written out. """
msg = self.protocol.create('PATCH-DOC', [event])
return self._socket.send_message(msg) | [
"def",
"send_patch_document",
"(",
"self",
",",
"event",
")",
":",
"msg",
"=",
"self",
".",
"protocol",
".",
"create",
"(",
"'PATCH-DOC'",
",",
"[",
"event",
"]",
")",
"return",
"self",
".",
"_socket",
".",
"send_message",
"(",
"msg",
")"
] | Sends a PATCH-DOC message, returning a Future that's completed when it's written out. | [
"Sends",
"a",
"PATCH",
"-",
"DOC",
"message",
"returning",
"a",
"Future",
"that",
"s",
"completed",
"when",
"it",
"s",
"written",
"out",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/connection.py#L74-L77 | train |
bokeh/bokeh | bokeh/document/util.py | initialize_references_json | def initialize_references_json(references_json, references, setter=None):
''' Given a JSON representation of the models in a graph, and new model
objects, set the properties on the models from the JSON
Args:
references_json (``JSON``)
JSON specifying attributes and values to initialize new model
objects with.
references (dict[str, Model])
A dictionary mapping model IDs to newly created (but not yet
initialized) Bokeh models.
**This is an "out" parameter**. The values it contains will be
modified in-place.
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.
'''
for obj in references_json:
obj_id = obj['id']
obj_attrs = obj['attributes']
instance = references[obj_id]
# We want to avoid any Model specific initialization that happens with
# Slider(...) when reconstituting from JSON, but we do need to perform
# general HasProps machinery that sets properties, so call it explicitly
HasProps.__init__(instance)
instance.update_from_json(obj_attrs, models=references, setter=setter) | python | def initialize_references_json(references_json, references, setter=None):
''' Given a JSON representation of the models in a graph, and new model
objects, set the properties on the models from the JSON
Args:
references_json (``JSON``)
JSON specifying attributes and values to initialize new model
objects with.
references (dict[str, Model])
A dictionary mapping model IDs to newly created (but not yet
initialized) Bokeh models.
**This is an "out" parameter**. The values it contains will be
modified in-place.
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.
'''
for obj in references_json:
obj_id = obj['id']
obj_attrs = obj['attributes']
instance = references[obj_id]
# We want to avoid any Model specific initialization that happens with
# Slider(...) when reconstituting from JSON, but we do need to perform
# general HasProps machinery that sets properties, so call it explicitly
HasProps.__init__(instance)
instance.update_from_json(obj_attrs, models=references, setter=setter) | [
"def",
"initialize_references_json",
"(",
"references_json",
",",
"references",
",",
"setter",
"=",
"None",
")",
":",
"for",
"obj",
"in",
"references_json",
":",
"obj_id",
"=",
"obj",
"[",
"'id'",
"]",
"obj_attrs",
"=",
"obj",
"[",
"'attributes'",
"]",
"instance",
"=",
"references",
"[",
"obj_id",
"]",
"# We want to avoid any Model specific initialization that happens with",
"# Slider(...) when reconstituting from JSON, but we do need to perform",
"# general HasProps machinery that sets properties, so call it explicitly",
"HasProps",
".",
"__init__",
"(",
"instance",
")",
"instance",
".",
"update_from_json",
"(",
"obj_attrs",
",",
"models",
"=",
"references",
",",
"setter",
"=",
"setter",
")"
] | Given a JSON representation of the models in a graph, and new model
objects, set the properties on the models from the JSON
Args:
references_json (``JSON``)
JSON specifying attributes and values to initialize new model
objects with.
references (dict[str, Model])
A dictionary mapping model IDs to newly created (but not yet
initialized) Bokeh models.
**This is an "out" parameter**. The values it contains will be
modified in-place.
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. | [
"Given",
"a",
"JSON",
"representation",
"of",
"the",
"models",
"in",
"a",
"graph",
"and",
"new",
"model",
"objects",
"set",
"the",
"properties",
"on",
"the",
"models",
"from",
"the",
"JSON"
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/util.py#L50-L90 | train |
bokeh/bokeh | bokeh/document/util.py | instantiate_references_json | def instantiate_references_json(references_json):
''' Given a JSON representation of all the models in a graph, return a
dict of new model objects.
Args:
references_json (``JSON``)
JSON specifying new Bokeh models to create
Returns:
dict[str, Model]
'''
# Create all instances, but without setting their props
references = {}
for obj in references_json:
obj_id = obj['id']
obj_type = obj.get('subtype', obj['type'])
cls = get_class(obj_type)
instance = cls.__new__(cls, id=obj_id)
if instance is None:
raise RuntimeError('Error loading model from JSON (type: %s, id: %s)' % (obj_type, obj_id))
references[instance.id] = instance
return references | python | def instantiate_references_json(references_json):
''' Given a JSON representation of all the models in a graph, return a
dict of new model objects.
Args:
references_json (``JSON``)
JSON specifying new Bokeh models to create
Returns:
dict[str, Model]
'''
# Create all instances, but without setting their props
references = {}
for obj in references_json:
obj_id = obj['id']
obj_type = obj.get('subtype', obj['type'])
cls = get_class(obj_type)
instance = cls.__new__(cls, id=obj_id)
if instance is None:
raise RuntimeError('Error loading model from JSON (type: %s, id: %s)' % (obj_type, obj_id))
references[instance.id] = instance
return references | [
"def",
"instantiate_references_json",
"(",
"references_json",
")",
":",
"# Create all instances, but without setting their props",
"references",
"=",
"{",
"}",
"for",
"obj",
"in",
"references_json",
":",
"obj_id",
"=",
"obj",
"[",
"'id'",
"]",
"obj_type",
"=",
"obj",
".",
"get",
"(",
"'subtype'",
",",
"obj",
"[",
"'type'",
"]",
")",
"cls",
"=",
"get_class",
"(",
"obj_type",
")",
"instance",
"=",
"cls",
".",
"__new__",
"(",
"cls",
",",
"id",
"=",
"obj_id",
")",
"if",
"instance",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'Error loading model from JSON (type: %s, id: %s)'",
"%",
"(",
"obj_type",
",",
"obj_id",
")",
")",
"references",
"[",
"instance",
".",
"id",
"]",
"=",
"instance",
"return",
"references"
] | Given a JSON representation of all the models in a graph, return a
dict of new model objects.
Args:
references_json (``JSON``)
JSON specifying new Bokeh models to create
Returns:
dict[str, Model] | [
"Given",
"a",
"JSON",
"representation",
"of",
"all",
"the",
"models",
"in",
"a",
"graph",
"return",
"a",
"dict",
"of",
"new",
"model",
"objects",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/util.py#L92-L117 | train |
bokeh/bokeh | bokeh/document/util.py | references_json | def references_json(references):
''' Given a list of all models in a graph, return JSON representing
them and their properties.
Args:
references (seq[Model]) :
A list of models to convert to JSON
Returns:
list
'''
references_json = []
for r in references:
ref = r.ref
ref['attributes'] = r._to_json_like(include_defaults=False)
references_json.append(ref)
return references_json | python | def references_json(references):
''' Given a list of all models in a graph, return JSON representing
them and their properties.
Args:
references (seq[Model]) :
A list of models to convert to JSON
Returns:
list
'''
references_json = []
for r in references:
ref = r.ref
ref['attributes'] = r._to_json_like(include_defaults=False)
references_json.append(ref)
return references_json | [
"def",
"references_json",
"(",
"references",
")",
":",
"references_json",
"=",
"[",
"]",
"for",
"r",
"in",
"references",
":",
"ref",
"=",
"r",
".",
"ref",
"ref",
"[",
"'attributes'",
"]",
"=",
"r",
".",
"_to_json_like",
"(",
"include_defaults",
"=",
"False",
")",
"references_json",
".",
"append",
"(",
"ref",
")",
"return",
"references_json"
] | Given a list of all models in a graph, return JSON representing
them and their properties.
Args:
references (seq[Model]) :
A list of models to convert to JSON
Returns:
list | [
"Given",
"a",
"list",
"of",
"all",
"models",
"in",
"a",
"graph",
"return",
"JSON",
"representing",
"them",
"and",
"their",
"properties",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/util.py#L119-L138 | train |
bokeh/bokeh | bokeh/events.py | Event.decode_json | def decode_json(cls, dct):
''' Custom JSON decoder for Events.
Can be used as the ``object_hook`` argument of ``json.load`` or
``json.loads``.
Args:
dct (dict) : a JSON dictionary to decode
The dictionary should have keys ``event_name`` and ``event_values``
Raises:
ValueError, if the event_name is unknown
Examples:
.. code-block:: python
>>> import json
>>> from bokeh.events import Event
>>> data = '{"event_name": "pan", "event_values" : {"model_id": 1, "x": 10, "y": 20, "sx": 200, "sy": 37}}'
>>> json.loads(data, object_hook=Event.decode_json)
<bokeh.events.Pan object at 0x1040f84a8>
'''
if not ('event_name' in dct and 'event_values' in dct):
return dct
event_name = dct['event_name']
if event_name not in _CONCRETE_EVENT_CLASSES:
raise ValueError("Could not find appropriate Event class for event_name: %r" % event_name)
event_values = dct['event_values']
model_id = event_values.pop('model_id')
event = _CONCRETE_EVENT_CLASSES[event_name](model=None, **event_values)
event._model_id = model_id
return event | python | def decode_json(cls, dct):
''' Custom JSON decoder for Events.
Can be used as the ``object_hook`` argument of ``json.load`` or
``json.loads``.
Args:
dct (dict) : a JSON dictionary to decode
The dictionary should have keys ``event_name`` and ``event_values``
Raises:
ValueError, if the event_name is unknown
Examples:
.. code-block:: python
>>> import json
>>> from bokeh.events import Event
>>> data = '{"event_name": "pan", "event_values" : {"model_id": 1, "x": 10, "y": 20, "sx": 200, "sy": 37}}'
>>> json.loads(data, object_hook=Event.decode_json)
<bokeh.events.Pan object at 0x1040f84a8>
'''
if not ('event_name' in dct and 'event_values' in dct):
return dct
event_name = dct['event_name']
if event_name not in _CONCRETE_EVENT_CLASSES:
raise ValueError("Could not find appropriate Event class for event_name: %r" % event_name)
event_values = dct['event_values']
model_id = event_values.pop('model_id')
event = _CONCRETE_EVENT_CLASSES[event_name](model=None, **event_values)
event._model_id = model_id
return event | [
"def",
"decode_json",
"(",
"cls",
",",
"dct",
")",
":",
"if",
"not",
"(",
"'event_name'",
"in",
"dct",
"and",
"'event_values'",
"in",
"dct",
")",
":",
"return",
"dct",
"event_name",
"=",
"dct",
"[",
"'event_name'",
"]",
"if",
"event_name",
"not",
"in",
"_CONCRETE_EVENT_CLASSES",
":",
"raise",
"ValueError",
"(",
"\"Could not find appropriate Event class for event_name: %r\"",
"%",
"event_name",
")",
"event_values",
"=",
"dct",
"[",
"'event_values'",
"]",
"model_id",
"=",
"event_values",
".",
"pop",
"(",
"'model_id'",
")",
"event",
"=",
"_CONCRETE_EVENT_CLASSES",
"[",
"event_name",
"]",
"(",
"model",
"=",
"None",
",",
"*",
"*",
"event_values",
")",
"event",
".",
"_model_id",
"=",
"model_id",
"return",
"event"
] | Custom JSON decoder for Events.
Can be used as the ``object_hook`` argument of ``json.load`` or
``json.loads``.
Args:
dct (dict) : a JSON dictionary to decode
The dictionary should have keys ``event_name`` and ``event_values``
Raises:
ValueError, if the event_name is unknown
Examples:
.. code-block:: python
>>> import json
>>> from bokeh.events import Event
>>> data = '{"event_name": "pan", "event_values" : {"model_id": 1, "x": 10, "y": 20, "sx": 200, "sy": 37}}'
>>> json.loads(data, object_hook=Event.decode_json)
<bokeh.events.Pan object at 0x1040f84a8> | [
"Custom",
"JSON",
"decoder",
"for",
"Events",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/events.py#L150-L186 | train |
bokeh/bokeh | bokeh/sphinxext/bokeh_palette.py | bokeh_palette | def bokeh_palette(name, rawtext, text, lineno, inliner, options=None, content=None):
''' Generate an inline visual representations of a single color palette.
This function evaluates the expression ``"palette = %s" % text``, in the
context of a ``globals`` namespace that has previously imported all of
``bokeh.plotting``. The resulting value for ``palette`` is used to
construct a sequence of HTML ``<span>`` elements for each color.
If evaluating the palette expression fails or does not produce a list or
tuple of all strings, then a SphinxError is raised to terminate the build.
For details on the arguments to this function, consult the Docutils docs:
http://docutils.sourceforge.net/docs/howto/rst-roles.html#define-the-role-function
'''
try:
exec("palette = %s" % text, _globals)
except Exception as e:
raise SphinxError("cannot evaluate palette expression '%r', reason: %s" % (text, e))
p = _globals.get('palette', None)
if not isinstance(p, (list, tuple)) or not all(isinstance(x, str) for x in p):
raise SphinxError("palette expression '%r' generated invalid or no output: %s" % (text, p))
w = 20 if len(p) < 15 else 10 if len(p) < 32 else 5 if len(p) < 64 else 2 if len(p) < 128 else 1
html = PALETTE_DETAIL.render(palette=p, width=w)
node = nodes.raw('', html, format="html")
return [node], [] | python | def bokeh_palette(name, rawtext, text, lineno, inliner, options=None, content=None):
''' Generate an inline visual representations of a single color palette.
This function evaluates the expression ``"palette = %s" % text``, in the
context of a ``globals`` namespace that has previously imported all of
``bokeh.plotting``. The resulting value for ``palette`` is used to
construct a sequence of HTML ``<span>`` elements for each color.
If evaluating the palette expression fails or does not produce a list or
tuple of all strings, then a SphinxError is raised to terminate the build.
For details on the arguments to this function, consult the Docutils docs:
http://docutils.sourceforge.net/docs/howto/rst-roles.html#define-the-role-function
'''
try:
exec("palette = %s" % text, _globals)
except Exception as e:
raise SphinxError("cannot evaluate palette expression '%r', reason: %s" % (text, e))
p = _globals.get('palette', None)
if not isinstance(p, (list, tuple)) or not all(isinstance(x, str) for x in p):
raise SphinxError("palette expression '%r' generated invalid or no output: %s" % (text, p))
w = 20 if len(p) < 15 else 10 if len(p) < 32 else 5 if len(p) < 64 else 2 if len(p) < 128 else 1
html = PALETTE_DETAIL.render(palette=p, width=w)
node = nodes.raw('', html, format="html")
return [node], [] | [
"def",
"bokeh_palette",
"(",
"name",
",",
"rawtext",
",",
"text",
",",
"lineno",
",",
"inliner",
",",
"options",
"=",
"None",
",",
"content",
"=",
"None",
")",
":",
"try",
":",
"exec",
"(",
"\"palette = %s\"",
"%",
"text",
",",
"_globals",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"SphinxError",
"(",
"\"cannot evaluate palette expression '%r', reason: %s\"",
"%",
"(",
"text",
",",
"e",
")",
")",
"p",
"=",
"_globals",
".",
"get",
"(",
"'palette'",
",",
"None",
")",
"if",
"not",
"isinstance",
"(",
"p",
",",
"(",
"list",
",",
"tuple",
")",
")",
"or",
"not",
"all",
"(",
"isinstance",
"(",
"x",
",",
"str",
")",
"for",
"x",
"in",
"p",
")",
":",
"raise",
"SphinxError",
"(",
"\"palette expression '%r' generated invalid or no output: %s\"",
"%",
"(",
"text",
",",
"p",
")",
")",
"w",
"=",
"20",
"if",
"len",
"(",
"p",
")",
"<",
"15",
"else",
"10",
"if",
"len",
"(",
"p",
")",
"<",
"32",
"else",
"5",
"if",
"len",
"(",
"p",
")",
"<",
"64",
"else",
"2",
"if",
"len",
"(",
"p",
")",
"<",
"128",
"else",
"1",
"html",
"=",
"PALETTE_DETAIL",
".",
"render",
"(",
"palette",
"=",
"p",
",",
"width",
"=",
"w",
")",
"node",
"=",
"nodes",
".",
"raw",
"(",
"''",
",",
"html",
",",
"format",
"=",
"\"html\"",
")",
"return",
"[",
"node",
"]",
",",
"[",
"]"
] | Generate an inline visual representations of a single color palette.
This function evaluates the expression ``"palette = %s" % text``, in the
context of a ``globals`` namespace that has previously imported all of
``bokeh.plotting``. The resulting value for ``palette`` is used to
construct a sequence of HTML ``<span>`` elements for each color.
If evaluating the palette expression fails or does not produce a list or
tuple of all strings, then a SphinxError is raised to terminate the build.
For details on the arguments to this function, consult the Docutils docs:
http://docutils.sourceforge.net/docs/howto/rst-roles.html#define-the-role-function | [
"Generate",
"an",
"inline",
"visual",
"representations",
"of",
"a",
"single",
"color",
"palette",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/sphinxext/bokeh_palette.py#L89-L115 | train |
bokeh/bokeh | bokeh/transform.py | cumsum | def cumsum(field, include_zero=False):
''' Create a Create a ``DataSpec`` dict to generate a ``CumSum`` expression
for a ``ColumnDataSource``.
Examples:
.. code-block:: python
p.wedge(start_angle=cumsum('angle', include_zero=True),
end_angle=cumsum('angle'),
...)
will generate a ``CumSum`` expressions that sum the ``"angle"`` column
of a data source. For the ``start_angle`` value, the cumulative sums
will start with a zero value. For ``start_angle``, no initial zero will
be added (i.e. the sums will start with the first angle value, and
include the last).
'''
return expr(CumSum(field=field, include_zero=include_zero)) | python | def cumsum(field, include_zero=False):
''' Create a Create a ``DataSpec`` dict to generate a ``CumSum`` expression
for a ``ColumnDataSource``.
Examples:
.. code-block:: python
p.wedge(start_angle=cumsum('angle', include_zero=True),
end_angle=cumsum('angle'),
...)
will generate a ``CumSum`` expressions that sum the ``"angle"`` column
of a data source. For the ``start_angle`` value, the cumulative sums
will start with a zero value. For ``start_angle``, no initial zero will
be added (i.e. the sums will start with the first angle value, and
include the last).
'''
return expr(CumSum(field=field, include_zero=include_zero)) | [
"def",
"cumsum",
"(",
"field",
",",
"include_zero",
"=",
"False",
")",
":",
"return",
"expr",
"(",
"CumSum",
"(",
"field",
"=",
"field",
",",
"include_zero",
"=",
"include_zero",
")",
")"
] | Create a Create a ``DataSpec`` dict to generate a ``CumSum`` expression
for a ``ColumnDataSource``.
Examples:
.. code-block:: python
p.wedge(start_angle=cumsum('angle', include_zero=True),
end_angle=cumsum('angle'),
...)
will generate a ``CumSum`` expressions that sum the ``"angle"`` column
of a data source. For the ``start_angle`` value, the cumulative sums
will start with a zero value. For ``start_angle``, no initial zero will
be added (i.e. the sums will start with the first angle value, and
include the last). | [
"Create",
"a",
"Create",
"a",
"DataSpec",
"dict",
"to",
"generate",
"a",
"CumSum",
"expression",
"for",
"a",
"ColumnDataSource",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/transform.py#L55-L74 | train |
bokeh/bokeh | bokeh/transform.py | dodge | def dodge(field_name, value, range=None):
''' Create a ``DataSpec`` dict that applies a client-side ``Jitter``
transformation to a ``ColumnDataSource`` column.
Args:
field_name (str) : a field name to configure ``DataSpec`` with
value (float) : the fixed offset to add to column data
range (Range, optional) : a range to use for computing synthetic
coordinates when necessary, e.g. a ``FactorRange`` when the
column data is categorical (default: None)
Returns:
dict
'''
return field(field_name, Dodge(value=value, range=range)) | python | def dodge(field_name, value, range=None):
''' Create a ``DataSpec`` dict that applies a client-side ``Jitter``
transformation to a ``ColumnDataSource`` column.
Args:
field_name (str) : a field name to configure ``DataSpec`` with
value (float) : the fixed offset to add to column data
range (Range, optional) : a range to use for computing synthetic
coordinates when necessary, e.g. a ``FactorRange`` when the
column data is categorical (default: None)
Returns:
dict
'''
return field(field_name, Dodge(value=value, range=range)) | [
"def",
"dodge",
"(",
"field_name",
",",
"value",
",",
"range",
"=",
"None",
")",
":",
"return",
"field",
"(",
"field_name",
",",
"Dodge",
"(",
"value",
"=",
"value",
",",
"range",
"=",
"range",
")",
")"
] | Create a ``DataSpec`` dict that applies a client-side ``Jitter``
transformation to a ``ColumnDataSource`` column.
Args:
field_name (str) : a field name to configure ``DataSpec`` with
value (float) : the fixed offset to add to column data
range (Range, optional) : a range to use for computing synthetic
coordinates when necessary, e.g. a ``FactorRange`` when the
column data is categorical (default: None)
Returns:
dict | [
"Create",
"a",
"DataSpec",
"dict",
"that",
"applies",
"a",
"client",
"-",
"side",
"Jitter",
"transformation",
"to",
"a",
"ColumnDataSource",
"column",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/transform.py#L76-L93 | train |
bokeh/bokeh | bokeh/transform.py | factor_cmap | def factor_cmap(field_name, palette, factors, start=0, end=None, nan_color="gray"):
''' Create a ``DataSpec`` dict that applies a client-side
``CategoricalColorMapper`` transformation to a ``ColumnDataSource``
column.
Args:
field_name (str) : a field name to configure ``DataSpec`` with
palette (seq[color]) : a list of colors to use for colormapping
factors (seq) : a sequences of categorical factors corresponding to
the palette
start (int, optional) : a start slice index to apply when the column
data has factors with multiple levels. (default: 0)
end (int, optional) : an end slice index to apply when the column
data has factors with multiple levels. (default: None)
nan_color (color, optional) : a default color to use when mapping data
from a column does not succeed (default: "gray")
Returns:
dict
'''
return field(field_name, CategoricalColorMapper(palette=palette,
factors=factors,
start=start,
end=end,
nan_color=nan_color)) | python | def factor_cmap(field_name, palette, factors, start=0, end=None, nan_color="gray"):
''' Create a ``DataSpec`` dict that applies a client-side
``CategoricalColorMapper`` transformation to a ``ColumnDataSource``
column.
Args:
field_name (str) : a field name to configure ``DataSpec`` with
palette (seq[color]) : a list of colors to use for colormapping
factors (seq) : a sequences of categorical factors corresponding to
the palette
start (int, optional) : a start slice index to apply when the column
data has factors with multiple levels. (default: 0)
end (int, optional) : an end slice index to apply when the column
data has factors with multiple levels. (default: None)
nan_color (color, optional) : a default color to use when mapping data
from a column does not succeed (default: "gray")
Returns:
dict
'''
return field(field_name, CategoricalColorMapper(palette=palette,
factors=factors,
start=start,
end=end,
nan_color=nan_color)) | [
"def",
"factor_cmap",
"(",
"field_name",
",",
"palette",
",",
"factors",
",",
"start",
"=",
"0",
",",
"end",
"=",
"None",
",",
"nan_color",
"=",
"\"gray\"",
")",
":",
"return",
"field",
"(",
"field_name",
",",
"CategoricalColorMapper",
"(",
"palette",
"=",
"palette",
",",
"factors",
"=",
"factors",
",",
"start",
"=",
"start",
",",
"end",
"=",
"end",
",",
"nan_color",
"=",
"nan_color",
")",
")"
] | Create a ``DataSpec`` dict that applies a client-side
``CategoricalColorMapper`` transformation to a ``ColumnDataSource``
column.
Args:
field_name (str) : a field name to configure ``DataSpec`` with
palette (seq[color]) : a list of colors to use for colormapping
factors (seq) : a sequences of categorical factors corresponding to
the palette
start (int, optional) : a start slice index to apply when the column
data has factors with multiple levels. (default: 0)
end (int, optional) : an end slice index to apply when the column
data has factors with multiple levels. (default: None)
nan_color (color, optional) : a default color to use when mapping data
from a column does not succeed (default: "gray")
Returns:
dict | [
"Create",
"a",
"DataSpec",
"dict",
"that",
"applies",
"a",
"client",
"-",
"side",
"CategoricalColorMapper",
"transformation",
"to",
"a",
"ColumnDataSource",
"column",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/transform.py#L95-L125 | train |
bokeh/bokeh | bokeh/transform.py | factor_hatch | def factor_hatch(field_name, patterns, factors, start=0, end=None):
''' Create a ``DataSpec`` dict that applies a client-side
``CategoricalPatternMapper`` transformation to a ``ColumnDataSource``
column.
Args:
field_name (str) : a field name to configure ``DataSpec`` with
patterns (seq[string]) : a list of hatch patterns to use to map to
factors (seq) : a sequences of categorical factors corresponding to
the palette
start (int, optional) : a start slice index to apply when the column
data has factors with multiple levels. (default: 0)
end (int, optional) : an end slice index to apply when the column
data has factors with multiple levels. (default: None)
Returns:
dict
Added in version 1.1.1
'''
return field(field_name, CategoricalPatternMapper(patterns=patterns,
factors=factors,
start=start,
end=end)) | python | def factor_hatch(field_name, patterns, factors, start=0, end=None):
''' Create a ``DataSpec`` dict that applies a client-side
``CategoricalPatternMapper`` transformation to a ``ColumnDataSource``
column.
Args:
field_name (str) : a field name to configure ``DataSpec`` with
patterns (seq[string]) : a list of hatch patterns to use to map to
factors (seq) : a sequences of categorical factors corresponding to
the palette
start (int, optional) : a start slice index to apply when the column
data has factors with multiple levels. (default: 0)
end (int, optional) : an end slice index to apply when the column
data has factors with multiple levels. (default: None)
Returns:
dict
Added in version 1.1.1
'''
return field(field_name, CategoricalPatternMapper(patterns=patterns,
factors=factors,
start=start,
end=end)) | [
"def",
"factor_hatch",
"(",
"field_name",
",",
"patterns",
",",
"factors",
",",
"start",
"=",
"0",
",",
"end",
"=",
"None",
")",
":",
"return",
"field",
"(",
"field_name",
",",
"CategoricalPatternMapper",
"(",
"patterns",
"=",
"patterns",
",",
"factors",
"=",
"factors",
",",
"start",
"=",
"start",
",",
"end",
"=",
"end",
")",
")"
] | Create a ``DataSpec`` dict that applies a client-side
``CategoricalPatternMapper`` transformation to a ``ColumnDataSource``
column.
Args:
field_name (str) : a field name to configure ``DataSpec`` with
patterns (seq[string]) : a list of hatch patterns to use to map to
factors (seq) : a sequences of categorical factors corresponding to
the palette
start (int, optional) : a start slice index to apply when the column
data has factors with multiple levels. (default: 0)
end (int, optional) : an end slice index to apply when the column
data has factors with multiple levels. (default: None)
Returns:
dict
Added in version 1.1.1 | [
"Create",
"a",
"DataSpec",
"dict",
"that",
"applies",
"a",
"client",
"-",
"side",
"CategoricalPatternMapper",
"transformation",
"to",
"a",
"ColumnDataSource",
"column",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/transform.py#L127-L155 | train |
bokeh/bokeh | bokeh/transform.py | factor_mark | def factor_mark(field_name, markers, factors, start=0, end=None):
''' Create a ``DataSpec`` dict that applies a client-side
``CategoricalMarkerMapper`` transformation to a ``ColumnDataSource``
column.
.. note::
This transform is primarily only useful with ``scatter``, which
can be parameterized by glyph type.
Args:
field_name (str) : a field name to configure ``DataSpec`` with
markers (seq[string]) : a list of markers to use to map to
factors (seq) : a sequences of categorical factors corresponding to
the palette
start (int, optional) : a start slice index to apply when the column
data has factors with multiple levels. (default: 0)
end (int, optional) : an end slice index to apply when the column
data has factors with multiple levels. (default: None)
Returns:
dict
'''
return field(field_name, CategoricalMarkerMapper(markers=markers,
factors=factors,
start=start,
end=end)) | python | def factor_mark(field_name, markers, factors, start=0, end=None):
''' Create a ``DataSpec`` dict that applies a client-side
``CategoricalMarkerMapper`` transformation to a ``ColumnDataSource``
column.
.. note::
This transform is primarily only useful with ``scatter``, which
can be parameterized by glyph type.
Args:
field_name (str) : a field name to configure ``DataSpec`` with
markers (seq[string]) : a list of markers to use to map to
factors (seq) : a sequences of categorical factors corresponding to
the palette
start (int, optional) : a start slice index to apply when the column
data has factors with multiple levels. (default: 0)
end (int, optional) : an end slice index to apply when the column
data has factors with multiple levels. (default: None)
Returns:
dict
'''
return field(field_name, CategoricalMarkerMapper(markers=markers,
factors=factors,
start=start,
end=end)) | [
"def",
"factor_mark",
"(",
"field_name",
",",
"markers",
",",
"factors",
",",
"start",
"=",
"0",
",",
"end",
"=",
"None",
")",
":",
"return",
"field",
"(",
"field_name",
",",
"CategoricalMarkerMapper",
"(",
"markers",
"=",
"markers",
",",
"factors",
"=",
"factors",
",",
"start",
"=",
"start",
",",
"end",
"=",
"end",
")",
")"
] | Create a ``DataSpec`` dict that applies a client-side
``CategoricalMarkerMapper`` transformation to a ``ColumnDataSource``
column.
.. note::
This transform is primarily only useful with ``scatter``, which
can be parameterized by glyph type.
Args:
field_name (str) : a field name to configure ``DataSpec`` with
markers (seq[string]) : a list of markers to use to map to
factors (seq) : a sequences of categorical factors corresponding to
the palette
start (int, optional) : a start slice index to apply when the column
data has factors with multiple levels. (default: 0)
end (int, optional) : an end slice index to apply when the column
data has factors with multiple levels. (default: None)
Returns:
dict | [
"Create",
"a",
"DataSpec",
"dict",
"that",
"applies",
"a",
"client",
"-",
"side",
"CategoricalMarkerMapper",
"transformation",
"to",
"a",
"ColumnDataSource",
"column",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/transform.py#L157-L187 | train |
bokeh/bokeh | bokeh/transform.py | jitter | def jitter(field_name, width, mean=0, distribution="uniform", range=None):
''' Create a ``DataSpec`` dict that applies a client-side ``Jitter``
transformation to a ``ColumnDataSource`` column.
Args:
field_name (str) : a field name to configure ``DataSpec`` with
width (float) : the width of the random distribution to apply
mean (float, optional) : an offset to apply (default: 0)
distribution (str, optional) : ``"uniform"`` or ``"normal"``
(default: ``"uniform"``)
range (Range, optional) : a range to use for computing synthetic
coordinates when necessary, e.g. a ``FactorRange`` when the
column data is categorical (default: None)
Returns:
dict
'''
return field(field_name, Jitter(mean=mean,
width=width,
distribution=distribution,
range=range)) | python | def jitter(field_name, width, mean=0, distribution="uniform", range=None):
''' Create a ``DataSpec`` dict that applies a client-side ``Jitter``
transformation to a ``ColumnDataSource`` column.
Args:
field_name (str) : a field name to configure ``DataSpec`` with
width (float) : the width of the random distribution to apply
mean (float, optional) : an offset to apply (default: 0)
distribution (str, optional) : ``"uniform"`` or ``"normal"``
(default: ``"uniform"``)
range (Range, optional) : a range to use for computing synthetic
coordinates when necessary, e.g. a ``FactorRange`` when the
column data is categorical (default: None)
Returns:
dict
'''
return field(field_name, Jitter(mean=mean,
width=width,
distribution=distribution,
range=range)) | [
"def",
"jitter",
"(",
"field_name",
",",
"width",
",",
"mean",
"=",
"0",
",",
"distribution",
"=",
"\"uniform\"",
",",
"range",
"=",
"None",
")",
":",
"return",
"field",
"(",
"field_name",
",",
"Jitter",
"(",
"mean",
"=",
"mean",
",",
"width",
"=",
"width",
",",
"distribution",
"=",
"distribution",
",",
"range",
"=",
"range",
")",
")"
] | Create a ``DataSpec`` dict that applies a client-side ``Jitter``
transformation to a ``ColumnDataSource`` column.
Args:
field_name (str) : a field name to configure ``DataSpec`` with
width (float) : the width of the random distribution to apply
mean (float, optional) : an offset to apply (default: 0)
distribution (str, optional) : ``"uniform"`` or ``"normal"``
(default: ``"uniform"``)
range (Range, optional) : a range to use for computing synthetic
coordinates when necessary, e.g. a ``FactorRange`` when the
column data is categorical (default: None)
Returns:
dict | [
"Create",
"a",
"DataSpec",
"dict",
"that",
"applies",
"a",
"client",
"-",
"side",
"Jitter",
"transformation",
"to",
"a",
"ColumnDataSource",
"column",
"."
] | dc8cf49e4e4302fd38537ad089ece81fbcca4737 | https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/transform.py#L189-L214 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.