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/server/tornado.py
BokehTornado.start
def start(self): ''' Start the Bokeh Server application. Starting the Bokeh Server Tornado application will run periodic callbacks for stats logging, cleanup, pinging, etc. Additionally, any startup hooks defined by the configured Bokeh applications will be run. ''' self._stats_job.start() if self._mem_job is not None: self._mem_job.start() self._cleanup_job.start() if self._ping_job is not None: self._ping_job.start() for context in self._applications.values(): context.run_load_hook()
python
def start(self): ''' Start the Bokeh Server application. Starting the Bokeh Server Tornado application will run periodic callbacks for stats logging, cleanup, pinging, etc. Additionally, any startup hooks defined by the configured Bokeh applications will be run. ''' self._stats_job.start() if self._mem_job is not None: self._mem_job.start() self._cleanup_job.start() if self._ping_job is not None: self._ping_job.start() for context in self._applications.values(): context.run_load_hook()
[ "def", "start", "(", "self", ")", ":", "self", ".", "_stats_job", ".", "start", "(", ")", "if", "self", ".", "_mem_job", "is", "not", "None", ":", "self", ".", "_mem_job", ".", "start", "(", ")", "self", ".", "_cleanup_job", ".", "start", "(", ")", "if", "self", ".", "_ping_job", "is", "not", "None", ":", "self", ".", "_ping_job", ".", "start", "(", ")", "for", "context", "in", "self", ".", "_applications", ".", "values", "(", ")", ":", "context", ".", "run_load_hook", "(", ")" ]
Start the Bokeh Server application. Starting the Bokeh Server Tornado application will run periodic callbacks for stats logging, cleanup, pinging, etc. Additionally, any startup hooks defined by the configured Bokeh applications will be run.
[ "Start", "the", "Bokeh", "Server", "application", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/tornado.py#L425-L441
train
bokeh/bokeh
bokeh/server/tornado.py
BokehTornado.stop
def stop(self, wait=True): ''' Stop the Bokeh Server application. Args: wait (bool): whether to wait for orderly cleanup (default: True) Returns: None ''' # TODO should probably close all connections and shut down all sessions here for context in self._applications.values(): context.run_unload_hook() self._stats_job.stop() if self._mem_job is not None: self._mem_job.stop() self._cleanup_job.stop() if self._ping_job is not None: self._ping_job.stop() self._clients.clear()
python
def stop(self, wait=True): ''' Stop the Bokeh Server application. Args: wait (bool): whether to wait for orderly cleanup (default: True) Returns: None ''' # TODO should probably close all connections and shut down all sessions here for context in self._applications.values(): context.run_unload_hook() self._stats_job.stop() if self._mem_job is not None: self._mem_job.stop() self._cleanup_job.stop() if self._ping_job is not None: self._ping_job.stop() self._clients.clear()
[ "def", "stop", "(", "self", ",", "wait", "=", "True", ")", ":", "# TODO should probably close all connections and shut down all sessions here", "for", "context", "in", "self", ".", "_applications", ".", "values", "(", ")", ":", "context", ".", "run_unload_hook", "(", ")", "self", ".", "_stats_job", ".", "stop", "(", ")", "if", "self", ".", "_mem_job", "is", "not", "None", ":", "self", ".", "_mem_job", ".", "stop", "(", ")", "self", ".", "_cleanup_job", ".", "stop", "(", ")", "if", "self", ".", "_ping_job", "is", "not", "None", ":", "self", ".", "_ping_job", ".", "stop", "(", ")", "self", ".", "_clients", ".", "clear", "(", ")" ]
Stop the Bokeh Server application. Args: wait (bool): whether to wait for orderly cleanup (default: True) Returns: None
[ "Stop", "the", "Bokeh", "Server", "application", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/tornado.py#L443-L465
train
bokeh/bokeh
bokeh/server/tornado.py
BokehTornado.get_session
def get_session(self, app_path, session_id): ''' Get an active a session by name application path and session ID. Args: app_path (str) : The configured application path for the application to return a session for. session_id (str) : The session ID of the session to retrieve. Returns: ServerSession ''' if app_path not in self._applications: raise ValueError("Application %s does not exist on this server" % app_path) return self._applications[app_path].get_session(session_id)
python
def get_session(self, app_path, session_id): ''' Get an active a session by name application path and session ID. Args: app_path (str) : The configured application path for the application to return a session for. session_id (str) : The session ID of the session to retrieve. Returns: ServerSession ''' if app_path not in self._applications: raise ValueError("Application %s does not exist on this server" % app_path) return self._applications[app_path].get_session(session_id)
[ "def", "get_session", "(", "self", ",", "app_path", ",", "session_id", ")", ":", "if", "app_path", "not", "in", "self", ".", "_applications", ":", "raise", "ValueError", "(", "\"Application %s does not exist on this server\"", "%", "app_path", ")", "return", "self", ".", "_applications", "[", "app_path", "]", ".", "get_session", "(", "session_id", ")" ]
Get an active a session by name application path and session ID. Args: app_path (str) : The configured application path for the application to return a session for. session_id (str) : The session ID of the session to retrieve. Returns: ServerSession
[ "Get", "an", "active", "a", "session", "by", "name", "application", "path", "and", "session", "ID", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/tornado.py#L476-L493
train
bokeh/bokeh
bokeh/server/tornado.py
BokehTornado.get_sessions
def get_sessions(self, app_path): ''' Gets all currently active sessions for an application. Args: app_path (str) : The configured application path for the application to return sessions for. Returns: list[ServerSession] ''' if app_path not in self._applications: raise ValueError("Application %s does not exist on this server" % app_path) return list(self._applications[app_path].sessions)
python
def get_sessions(self, app_path): ''' Gets all currently active sessions for an application. Args: app_path (str) : The configured application path for the application to return sessions for. Returns: list[ServerSession] ''' if app_path not in self._applications: raise ValueError("Application %s does not exist on this server" % app_path) return list(self._applications[app_path].sessions)
[ "def", "get_sessions", "(", "self", ",", "app_path", ")", ":", "if", "app_path", "not", "in", "self", ".", "_applications", ":", "raise", "ValueError", "(", "\"Application %s does not exist on this server\"", "%", "app_path", ")", "return", "list", "(", "self", ".", "_applications", "[", "app_path", "]", ".", "sessions", ")" ]
Gets all currently active sessions for an application. Args: app_path (str) : The configured application path for the application to return sessions for. Returns: list[ServerSession]
[ "Gets", "all", "currently", "active", "sessions", "for", "an", "application", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/tornado.py#L495-L509
train
bokeh/bokeh
bokeh/core/validation/decorators.py
_validator
def _validator(code_or_name, validator_type): ''' Internal shared implementation to handle both error and warning validation checks. Args: code code_or_name (int or str) : a defined error code or custom message validator_type (str) : either "error" or "warning" Returns: validation decorator ''' if validator_type == "error": from .errors import codes from .errors import EXT elif validator_type == "warning": from .warnings import codes from .warnings import EXT else: pass # TODO (bev) ValueError? def decorator(func): def wrapper(*args, **kw): extra = func(*args, **kw) if extra is None: return [] if isinstance(code_or_name, string_types): code = EXT name = codes[code][0] + ":" + code_or_name else: code = code_or_name name = codes[code][0] text = codes[code][1] return [(code, name, text, extra)] wrapper.validator_type = validator_type return wrapper return decorator
python
def _validator(code_or_name, validator_type): ''' Internal shared implementation to handle both error and warning validation checks. Args: code code_or_name (int or str) : a defined error code or custom message validator_type (str) : either "error" or "warning" Returns: validation decorator ''' if validator_type == "error": from .errors import codes from .errors import EXT elif validator_type == "warning": from .warnings import codes from .warnings import EXT else: pass # TODO (bev) ValueError? def decorator(func): def wrapper(*args, **kw): extra = func(*args, **kw) if extra is None: return [] if isinstance(code_or_name, string_types): code = EXT name = codes[code][0] + ":" + code_or_name else: code = code_or_name name = codes[code][0] text = codes[code][1] return [(code, name, text, extra)] wrapper.validator_type = validator_type return wrapper return decorator
[ "def", "_validator", "(", "code_or_name", ",", "validator_type", ")", ":", "if", "validator_type", "==", "\"error\"", ":", "from", ".", "errors", "import", "codes", "from", ".", "errors", "import", "EXT", "elif", "validator_type", "==", "\"warning\"", ":", "from", ".", "warnings", "import", "codes", "from", ".", "warnings", "import", "EXT", "else", ":", "pass", "# TODO (bev) ValueError?", "def", "decorator", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "extra", "=", "func", "(", "*", "args", ",", "*", "*", "kw", ")", "if", "extra", "is", "None", ":", "return", "[", "]", "if", "isinstance", "(", "code_or_name", ",", "string_types", ")", ":", "code", "=", "EXT", "name", "=", "codes", "[", "code", "]", "[", "0", "]", "+", "\":\"", "+", "code_or_name", "else", ":", "code", "=", "code_or_name", "name", "=", "codes", "[", "code", "]", "[", "0", "]", "text", "=", "codes", "[", "code", "]", "[", "1", "]", "return", "[", "(", "code", ",", "name", ",", "text", ",", "extra", ")", "]", "wrapper", ".", "validator_type", "=", "validator_type", "return", "wrapper", "return", "decorator" ]
Internal shared implementation to handle both error and warning validation checks. Args: code code_or_name (int or str) : a defined error code or custom message validator_type (str) : either "error" or "warning" Returns: validation decorator
[ "Internal", "shared", "implementation", "to", "handle", "both", "error", "and", "warning", "validation", "checks", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/validation/decorators.py#L44-L80
train
bokeh/bokeh
bokeh/core/query.py
find
def find(objs, selector, context=None): ''' Query a collection of Bokeh models and yield any that match the a selector. Args: obj (Model) : object to test selector (JSON-like) : query selector context (dict) : kwargs to supply callable query attributes Yields: Model : objects that match the query Queries are specified as selectors similar to MongoDB style query selectors, as described for :func:`~bokeh.core.query.match`. Examples: .. code-block:: python # find all objects with type Grid find(p.references(), {'type': Grid}) # find all objects with type Grid or Axis find(p.references(), {OR: [ {'type': Grid}, {'type': Axis} ]}) # same query, using IN operator find(p.references(), {'type': {IN: [Grid, Axis]}}) # find all plot objects on the 'left' layout of the Plot # here layout is a method that takes a plot as context find(p.references(), {'layout': 'left'}, {'plot': p}) ''' return (obj for obj in objs if match(obj, selector, context))
python
def find(objs, selector, context=None): ''' Query a collection of Bokeh models and yield any that match the a selector. Args: obj (Model) : object to test selector (JSON-like) : query selector context (dict) : kwargs to supply callable query attributes Yields: Model : objects that match the query Queries are specified as selectors similar to MongoDB style query selectors, as described for :func:`~bokeh.core.query.match`. Examples: .. code-block:: python # find all objects with type Grid find(p.references(), {'type': Grid}) # find all objects with type Grid or Axis find(p.references(), {OR: [ {'type': Grid}, {'type': Axis} ]}) # same query, using IN operator find(p.references(), {'type': {IN: [Grid, Axis]}}) # find all plot objects on the 'left' layout of the Plot # here layout is a method that takes a plot as context find(p.references(), {'layout': 'left'}, {'plot': p}) ''' return (obj for obj in objs if match(obj, selector, context))
[ "def", "find", "(", "objs", ",", "selector", ",", "context", "=", "None", ")", ":", "return", "(", "obj", "for", "obj", "in", "objs", "if", "match", "(", "obj", ",", "selector", ",", "context", ")", ")" ]
Query a collection of Bokeh models and yield any that match the a selector. Args: obj (Model) : object to test selector (JSON-like) : query selector context (dict) : kwargs to supply callable query attributes Yields: Model : objects that match the query Queries are specified as selectors similar to MongoDB style query selectors, as described for :func:`~bokeh.core.query.match`. Examples: .. code-block:: python # find all objects with type Grid find(p.references(), {'type': Grid}) # find all objects with type Grid or Axis find(p.references(), {OR: [ {'type': Grid}, {'type': Axis} ]}) # same query, using IN operator find(p.references(), {'type': {IN: [Grid, Axis]}}) # find all plot objects on the 'left' layout of the Plot # here layout is a method that takes a plot as context find(p.references(), {'layout': 'left'}, {'plot': p})
[ "Query", "a", "collection", "of", "Bokeh", "models", "and", "yield", "any", "that", "match", "the", "a", "selector", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/query.py#L52-L87
train
bokeh/bokeh
bokeh/core/query.py
match
def match(obj, selector, context=None): ''' Test whether a given Bokeh model matches a given selector. Args: obj (Model) : object to test selector (JSON-like) : query selector context (dict) : kwargs to supply callable query attributes Returns: bool : True if the object matches, False otherwise In general, the selectors have the form: .. code-block:: python { attrname : predicate } Where a predicate is constructed from the operators ``EQ``, ``GT``, etc. and is used to compare against values of model attributes named ``attrname``. For example: .. code-block:: python >>> from bokeh.plotting import figure >>> p = figure(plot_width=400) >>> match(p, {'plot_width': {EQ: 400}}) True >>> match(p, {'plot_width': {GT: 500}}) False There are two selector keys that are handled especially. The first is 'type', which will do an isinstance check: .. code-block:: python >>> from bokeh.plotting import figure >>> from bokeh.models import Axis >>> p = figure() >>> match(p.xaxis[0], {'type': Axis}) True >>> match(p.title, {'type': Axis}) False There is also a ``'tags'`` attribute that ``Model`` objects have, that is a list of user-supplied values. The ``'tags'`` selector key can be used to query against this list of tags. An object matches if any of the tags in the selector match any of the tags on the object: .. code-block:: python >>> from bokeh.plotting import figure >>> p = figure(tags = ["my plot", 10]) >>> match(p, {'tags': "my plot"}) True >>> match(p, {'tags': ["my plot", 10]}) True >>> match(p, {'tags': ["foo"]}) False ''' context = context or {} for key, val in selector.items(): # test attributes if isinstance(key, string_types): # special case 'type' if key == "type": # type supports IN, check for that first if isinstance(val, dict) and list(val.keys()) == [IN]: if not any(isinstance(obj, x) for x in val[IN]): return False # otherwise just check the type of the object against val elif not isinstance(obj, val): return False # special case 'tag' elif key == 'tags': if isinstance(val, string_types): if val not in obj.tags: return False else: try: if not set(val) & set(obj.tags): return False except TypeError: if val not in obj.tags: return False # if the object doesn't have the attr, it doesn't match elif not hasattr(obj, key): return False # if the value to check is a dict, recurse else: attr = getattr(obj, key) if callable(attr): try: if not attr(val, **context): return False except: return False elif isinstance(val, dict): if not match(attr, val, context): return False else: if attr != val: return False # test OR conditionals elif key is OR: if not _or(obj, val): return False # test operands elif key in _operators: if not _operators[key](obj, val): return False else: raise ValueError("malformed query selector") return True
python
def match(obj, selector, context=None): ''' Test whether a given Bokeh model matches a given selector. Args: obj (Model) : object to test selector (JSON-like) : query selector context (dict) : kwargs to supply callable query attributes Returns: bool : True if the object matches, False otherwise In general, the selectors have the form: .. code-block:: python { attrname : predicate } Where a predicate is constructed from the operators ``EQ``, ``GT``, etc. and is used to compare against values of model attributes named ``attrname``. For example: .. code-block:: python >>> from bokeh.plotting import figure >>> p = figure(plot_width=400) >>> match(p, {'plot_width': {EQ: 400}}) True >>> match(p, {'plot_width': {GT: 500}}) False There are two selector keys that are handled especially. The first is 'type', which will do an isinstance check: .. code-block:: python >>> from bokeh.plotting import figure >>> from bokeh.models import Axis >>> p = figure() >>> match(p.xaxis[0], {'type': Axis}) True >>> match(p.title, {'type': Axis}) False There is also a ``'tags'`` attribute that ``Model`` objects have, that is a list of user-supplied values. The ``'tags'`` selector key can be used to query against this list of tags. An object matches if any of the tags in the selector match any of the tags on the object: .. code-block:: python >>> from bokeh.plotting import figure >>> p = figure(tags = ["my plot", 10]) >>> match(p, {'tags': "my plot"}) True >>> match(p, {'tags': ["my plot", 10]}) True >>> match(p, {'tags': ["foo"]}) False ''' context = context or {} for key, val in selector.items(): # test attributes if isinstance(key, string_types): # special case 'type' if key == "type": # type supports IN, check for that first if isinstance(val, dict) and list(val.keys()) == [IN]: if not any(isinstance(obj, x) for x in val[IN]): return False # otherwise just check the type of the object against val elif not isinstance(obj, val): return False # special case 'tag' elif key == 'tags': if isinstance(val, string_types): if val not in obj.tags: return False else: try: if not set(val) & set(obj.tags): return False except TypeError: if val not in obj.tags: return False # if the object doesn't have the attr, it doesn't match elif not hasattr(obj, key): return False # if the value to check is a dict, recurse else: attr = getattr(obj, key) if callable(attr): try: if not attr(val, **context): return False except: return False elif isinstance(val, dict): if not match(attr, val, context): return False else: if attr != val: return False # test OR conditionals elif key is OR: if not _or(obj, val): return False # test operands elif key in _operators: if not _operators[key](obj, val): return False else: raise ValueError("malformed query selector") return True
[ "def", "match", "(", "obj", ",", "selector", ",", "context", "=", "None", ")", ":", "context", "=", "context", "or", "{", "}", "for", "key", ",", "val", "in", "selector", ".", "items", "(", ")", ":", "# test attributes", "if", "isinstance", "(", "key", ",", "string_types", ")", ":", "# special case 'type'", "if", "key", "==", "\"type\"", ":", "# type supports IN, check for that first", "if", "isinstance", "(", "val", ",", "dict", ")", "and", "list", "(", "val", ".", "keys", "(", ")", ")", "==", "[", "IN", "]", ":", "if", "not", "any", "(", "isinstance", "(", "obj", ",", "x", ")", "for", "x", "in", "val", "[", "IN", "]", ")", ":", "return", "False", "# otherwise just check the type of the object against val", "elif", "not", "isinstance", "(", "obj", ",", "val", ")", ":", "return", "False", "# special case 'tag'", "elif", "key", "==", "'tags'", ":", "if", "isinstance", "(", "val", ",", "string_types", ")", ":", "if", "val", "not", "in", "obj", ".", "tags", ":", "return", "False", "else", ":", "try", ":", "if", "not", "set", "(", "val", ")", "&", "set", "(", "obj", ".", "tags", ")", ":", "return", "False", "except", "TypeError", ":", "if", "val", "not", "in", "obj", ".", "tags", ":", "return", "False", "# if the object doesn't have the attr, it doesn't match", "elif", "not", "hasattr", "(", "obj", ",", "key", ")", ":", "return", "False", "# if the value to check is a dict, recurse", "else", ":", "attr", "=", "getattr", "(", "obj", ",", "key", ")", "if", "callable", "(", "attr", ")", ":", "try", ":", "if", "not", "attr", "(", "val", ",", "*", "*", "context", ")", ":", "return", "False", "except", ":", "return", "False", "elif", "isinstance", "(", "val", ",", "dict", ")", ":", "if", "not", "match", "(", "attr", ",", "val", ",", "context", ")", ":", "return", "False", "else", ":", "if", "attr", "!=", "val", ":", "return", "False", "# test OR conditionals", "elif", "key", "is", "OR", ":", "if", "not", "_or", "(", "obj", ",", "val", ")", ":", "return", "False", "# test operands", "elif", "key", "in", "_operators", ":", "if", "not", "_operators", "[", "key", "]", "(", "obj", ",", "val", ")", ":", "return", "False", "else", ":", "raise", "ValueError", "(", "\"malformed query selector\"", ")", "return", "True" ]
Test whether a given Bokeh model matches a given selector. Args: obj (Model) : object to test selector (JSON-like) : query selector context (dict) : kwargs to supply callable query attributes Returns: bool : True if the object matches, False otherwise In general, the selectors have the form: .. code-block:: python { attrname : predicate } Where a predicate is constructed from the operators ``EQ``, ``GT``, etc. and is used to compare against values of model attributes named ``attrname``. For example: .. code-block:: python >>> from bokeh.plotting import figure >>> p = figure(plot_width=400) >>> match(p, {'plot_width': {EQ: 400}}) True >>> match(p, {'plot_width': {GT: 500}}) False There are two selector keys that are handled especially. The first is 'type', which will do an isinstance check: .. code-block:: python >>> from bokeh.plotting import figure >>> from bokeh.models import Axis >>> p = figure() >>> match(p.xaxis[0], {'type': Axis}) True >>> match(p.title, {'type': Axis}) False There is also a ``'tags'`` attribute that ``Model`` objects have, that is a list of user-supplied values. The ``'tags'`` selector key can be used to query against this list of tags. An object matches if any of the tags in the selector match any of the tags on the object: .. code-block:: python >>> from bokeh.plotting import figure >>> p = figure(tags = ["my plot", 10]) >>> match(p, {'tags': "my plot"}) True >>> match(p, {'tags': ["my plot", 10]}) True >>> match(p, {'tags': ["foo"]}) False
[ "Test", "whether", "a", "given", "Bokeh", "model", "matches", "a", "given", "selector", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/query.py#L89-L211
train
bokeh/bokeh
bokeh/sphinxext/bokeh_gallery.py
setup
def setup(app): ''' Required Sphinx extension setup function. ''' app.add_config_value('bokeh_gallery_dir', join("docs", "gallery"), 'html') app.connect('config-inited', config_inited_handler) app.add_directive('bokeh-gallery', BokehGalleryDirective)
python
def setup(app): ''' Required Sphinx extension setup function. ''' app.add_config_value('bokeh_gallery_dir', join("docs", "gallery"), 'html') app.connect('config-inited', config_inited_handler) app.add_directive('bokeh-gallery', BokehGalleryDirective)
[ "def", "setup", "(", "app", ")", ":", "app", ".", "add_config_value", "(", "'bokeh_gallery_dir'", ",", "join", "(", "\"docs\"", ",", "\"gallery\"", ")", ",", "'html'", ")", "app", ".", "connect", "(", "'config-inited'", ",", "config_inited_handler", ")", "app", ".", "add_directive", "(", "'bokeh-gallery'", ",", "BokehGalleryDirective", ")" ]
Required Sphinx extension setup function.
[ "Required", "Sphinx", "extension", "setup", "function", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/sphinxext/bokeh_gallery.py#L124-L128
train
bokeh/bokeh
bokeh/io/util.py
default_filename
def default_filename(ext): ''' Generate a default filename with a given extension, attempting to use the filename of the currently running process, if possible. If the filename of the current process is not available (or would not be writable), then a temporary file with the given extension is returned. Args: ext (str) : the desired extension for the filename Returns: str Raises: RuntimeError If the extensions requested is ".py" ''' if ext == "py": raise RuntimeError("asked for a default filename with 'py' extension") filename = detect_current_filename() if filename is None: return temp_filename(ext) basedir = dirname(filename) or getcwd() if _no_access(basedir) or _shares_exec_prefix(basedir): return temp_filename(ext) name, _ = splitext(basename(filename)) return join(basedir, name + "." + ext)
python
def default_filename(ext): ''' Generate a default filename with a given extension, attempting to use the filename of the currently running process, if possible. If the filename of the current process is not available (or would not be writable), then a temporary file with the given extension is returned. Args: ext (str) : the desired extension for the filename Returns: str Raises: RuntimeError If the extensions requested is ".py" ''' if ext == "py": raise RuntimeError("asked for a default filename with 'py' extension") filename = detect_current_filename() if filename is None: return temp_filename(ext) basedir = dirname(filename) or getcwd() if _no_access(basedir) or _shares_exec_prefix(basedir): return temp_filename(ext) name, _ = splitext(basename(filename)) return join(basedir, name + "." + ext)
[ "def", "default_filename", "(", "ext", ")", ":", "if", "ext", "==", "\"py\"", ":", "raise", "RuntimeError", "(", "\"asked for a default filename with 'py' extension\"", ")", "filename", "=", "detect_current_filename", "(", ")", "if", "filename", "is", "None", ":", "return", "temp_filename", "(", "ext", ")", "basedir", "=", "dirname", "(", "filename", ")", "or", "getcwd", "(", ")", "if", "_no_access", "(", "basedir", ")", "or", "_shares_exec_prefix", "(", "basedir", ")", ":", "return", "temp_filename", "(", "ext", ")", "name", ",", "_", "=", "splitext", "(", "basename", "(", "filename", ")", ")", "return", "join", "(", "basedir", ",", "name", "+", "\".\"", "+", "ext", ")" ]
Generate a default filename with a given extension, attempting to use the filename of the currently running process, if possible. If the filename of the current process is not available (or would not be writable), then a temporary file with the given extension is returned. Args: ext (str) : the desired extension for the filename Returns: str Raises: RuntimeError If the extensions requested is ".py"
[ "Generate", "a", "default", "filename", "with", "a", "given", "extension", "attempting", "to", "use", "the", "filename", "of", "the", "currently", "running", "process", "if", "possible", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/util.py#L50-L82
train
bokeh/bokeh
bokeh/io/util.py
detect_current_filename
def detect_current_filename(): ''' Attempt to return the filename of the currently running Python process Returns None if the filename cannot be detected. ''' import inspect filename = None frame = inspect.currentframe() try: while frame.f_back and frame.f_globals.get('name') != '__main__': frame = frame.f_back filename = frame.f_globals.get('__file__') finally: del frame return filename
python
def detect_current_filename(): ''' Attempt to return the filename of the currently running Python process Returns None if the filename cannot be detected. ''' import inspect filename = None frame = inspect.currentframe() try: while frame.f_back and frame.f_globals.get('name') != '__main__': frame = frame.f_back filename = frame.f_globals.get('__file__') finally: del frame return filename
[ "def", "detect_current_filename", "(", ")", ":", "import", "inspect", "filename", "=", "None", "frame", "=", "inspect", ".", "currentframe", "(", ")", "try", ":", "while", "frame", ".", "f_back", "and", "frame", ".", "f_globals", ".", "get", "(", "'name'", ")", "!=", "'__main__'", ":", "frame", "=", "frame", ".", "f_back", "filename", "=", "frame", ".", "f_globals", ".", "get", "(", "'__file__'", ")", "finally", ":", "del", "frame", "return", "filename" ]
Attempt to return the filename of the currently running Python process Returns None if the filename cannot be detected.
[ "Attempt", "to", "return", "the", "filename", "of", "the", "currently", "running", "Python", "process" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/util.py#L84-L101
train
bokeh/bokeh
bokeh/io/util.py
_no_access
def _no_access(basedir): ''' Return True if the given base dir is not accessible or writeable ''' import os return not os.access(basedir, os.W_OK | os.X_OK)
python
def _no_access(basedir): ''' Return True if the given base dir is not accessible or writeable ''' import os return not os.access(basedir, os.W_OK | os.X_OK)
[ "def", "_no_access", "(", "basedir", ")", ":", "import", "os", "return", "not", "os", ".", "access", "(", "basedir", ",", "os", ".", "W_OK", "|", "os", ".", "X_OK", ")" ]
Return True if the given base dir is not accessible or writeable
[ "Return", "True", "if", "the", "given", "base", "dir", "is", "not", "accessible", "or", "writeable" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/util.py#L113-L118
train
bokeh/bokeh
bokeh/io/util.py
_shares_exec_prefix
def _shares_exec_prefix(basedir): ''' Whether a give base directory is on the system exex prefix ''' import sys prefix = sys.exec_prefix return (prefix is not None and basedir.startswith(prefix))
python
def _shares_exec_prefix(basedir): ''' Whether a give base directory is on the system exex prefix ''' import sys prefix = sys.exec_prefix return (prefix is not None and basedir.startswith(prefix))
[ "def", "_shares_exec_prefix", "(", "basedir", ")", ":", "import", "sys", "prefix", "=", "sys", ".", "exec_prefix", "return", "(", "prefix", "is", "not", "None", "and", "basedir", ".", "startswith", "(", "prefix", ")", ")" ]
Whether a give base directory is on the system exex prefix
[ "Whether", "a", "give", "base", "directory", "is", "on", "the", "system", "exex", "prefix" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/util.py#L120-L126
train
bokeh/bokeh
bokeh/sphinxext/bokeh_palette_group.py
setup
def setup(app): ''' Required Sphinx extension setup function. ''' app.add_node(bokeh_palette_group, html=(html_visit_bokeh_palette_group, None)) app.add_directive('bokeh-palette-group', BokehPaletteGroupDirective)
python
def setup(app): ''' Required Sphinx extension setup function. ''' app.add_node(bokeh_palette_group, html=(html_visit_bokeh_palette_group, None)) app.add_directive('bokeh-palette-group', BokehPaletteGroupDirective)
[ "def", "setup", "(", "app", ")", ":", "app", ".", "add_node", "(", "bokeh_palette_group", ",", "html", "=", "(", "html_visit_bokeh_palette_group", ",", "None", ")", ")", "app", ".", "add_directive", "(", "'bokeh-palette-group'", ",", "BokehPaletteGroupDirective", ")" ]
Required Sphinx extension setup function.
[ "Required", "Sphinx", "extension", "setup", "function", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/sphinxext/bokeh_palette_group.py#L100-L103
train
bokeh/bokeh
bokeh/command/subcommands/file_output.py
FileOutputSubcommand.other_args
def other_args(cls): ''' Return args for ``-o`` / ``--output`` to specify where output should be written, and for a ``--args`` to pass on any additional command line args to the subcommand. Subclasses should append these to their class ``args``. Example: .. code-block:: python class Foo(FileOutputSubcommand): args = ( FileOutputSubcommand.files_arg("FOO"), # more args for Foo ) + FileOutputSubcommand.other_args() ''' return ( (('-o', '--output'), dict( metavar='FILENAME', action='append', type=str, help="Name of the output file or - for standard output." )), ('--args', dict( metavar='COMMAND-LINE-ARGS', nargs=argparse.REMAINDER, help="Any command line arguments remaining are passed on to the application handler", )), )
python
def other_args(cls): ''' Return args for ``-o`` / ``--output`` to specify where output should be written, and for a ``--args`` to pass on any additional command line args to the subcommand. Subclasses should append these to their class ``args``. Example: .. code-block:: python class Foo(FileOutputSubcommand): args = ( FileOutputSubcommand.files_arg("FOO"), # more args for Foo ) + FileOutputSubcommand.other_args() ''' return ( (('-o', '--output'), dict( metavar='FILENAME', action='append', type=str, help="Name of the output file or - for standard output." )), ('--args', dict( metavar='COMMAND-LINE-ARGS', nargs=argparse.REMAINDER, help="Any command line arguments remaining are passed on to the application handler", )), )
[ "def", "other_args", "(", "cls", ")", ":", "return", "(", "(", "(", "'-o'", ",", "'--output'", ")", ",", "dict", "(", "metavar", "=", "'FILENAME'", ",", "action", "=", "'append'", ",", "type", "=", "str", ",", "help", "=", "\"Name of the output file or - for standard output.\"", ")", ")", ",", "(", "'--args'", ",", "dict", "(", "metavar", "=", "'COMMAND-LINE-ARGS'", ",", "nargs", "=", "argparse", ".", "REMAINDER", ",", "help", "=", "\"Any command line arguments remaining are passed on to the application handler\"", ",", ")", ")", ",", ")" ]
Return args for ``-o`` / ``--output`` to specify where output should be written, and for a ``--args`` to pass on any additional command line args to the subcommand. Subclasses should append these to their class ``args``. Example: .. code-block:: python class Foo(FileOutputSubcommand): args = ( FileOutputSubcommand.files_arg("FOO"), # more args for Foo ) + FileOutputSubcommand.other_args()
[ "Return", "args", "for", "-", "o", "/", "--", "output", "to", "specify", "where", "output", "should", "be", "written", "and", "for", "a", "--", "args", "to", "pass", "on", "any", "additional", "command", "line", "args", "to", "the", "subcommand", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/command/subcommands/file_output.py#L89-L124
train
bokeh/bokeh
bokeh/plotting/helpers.py
_pop_colors_and_alpha
def _pop_colors_and_alpha(glyphclass, kwargs, prefix="", default_alpha=1.0): """ Given a kwargs dict, a prefix, and a default value, looks for different color and alpha fields of the given prefix, and fills in the default value if it doesn't exist. """ result = dict() # TODO: The need to do this and the complexity of managing this kind of # thing throughout the codebase really suggests that we need to have # a real stylesheet class, where defaults and Types can declaratively # substitute for this kind of imperative logic. color = kwargs.pop(prefix + "color", get_default_color()) for argname in ("fill_color", "line_color"): if argname not in glyphclass.properties(): continue result[argname] = kwargs.pop(prefix + argname, color) # NOTE: text fill color should really always default to black, hard coding # this here now until the stylesheet solution exists if "text_color" in glyphclass.properties(): result["text_color"] = kwargs.pop(prefix + "text_color", "black") alpha = kwargs.pop(prefix + "alpha", default_alpha) for argname in ("fill_alpha", "line_alpha", "text_alpha"): if argname not in glyphclass.properties(): continue result[argname] = kwargs.pop(prefix + argname, alpha) return result
python
def _pop_colors_and_alpha(glyphclass, kwargs, prefix="", default_alpha=1.0): """ Given a kwargs dict, a prefix, and a default value, looks for different color and alpha fields of the given prefix, and fills in the default value if it doesn't exist. """ result = dict() # TODO: The need to do this and the complexity of managing this kind of # thing throughout the codebase really suggests that we need to have # a real stylesheet class, where defaults and Types can declaratively # substitute for this kind of imperative logic. color = kwargs.pop(prefix + "color", get_default_color()) for argname in ("fill_color", "line_color"): if argname not in glyphclass.properties(): continue result[argname] = kwargs.pop(prefix + argname, color) # NOTE: text fill color should really always default to black, hard coding # this here now until the stylesheet solution exists if "text_color" in glyphclass.properties(): result["text_color"] = kwargs.pop(prefix + "text_color", "black") alpha = kwargs.pop(prefix + "alpha", default_alpha) for argname in ("fill_alpha", "line_alpha", "text_alpha"): if argname not in glyphclass.properties(): continue result[argname] = kwargs.pop(prefix + argname, alpha) return result
[ "def", "_pop_colors_and_alpha", "(", "glyphclass", ",", "kwargs", ",", "prefix", "=", "\"\"", ",", "default_alpha", "=", "1.0", ")", ":", "result", "=", "dict", "(", ")", "# TODO: The need to do this and the complexity of managing this kind of", "# thing throughout the codebase really suggests that we need to have", "# a real stylesheet class, where defaults and Types can declaratively", "# substitute for this kind of imperative logic.", "color", "=", "kwargs", ".", "pop", "(", "prefix", "+", "\"color\"", ",", "get_default_color", "(", ")", ")", "for", "argname", "in", "(", "\"fill_color\"", ",", "\"line_color\"", ")", ":", "if", "argname", "not", "in", "glyphclass", ".", "properties", "(", ")", ":", "continue", "result", "[", "argname", "]", "=", "kwargs", ".", "pop", "(", "prefix", "+", "argname", ",", "color", ")", "# NOTE: text fill color should really always default to black, hard coding", "# this here now until the stylesheet solution exists", "if", "\"text_color\"", "in", "glyphclass", ".", "properties", "(", ")", ":", "result", "[", "\"text_color\"", "]", "=", "kwargs", ".", "pop", "(", "prefix", "+", "\"text_color\"", ",", "\"black\"", ")", "alpha", "=", "kwargs", ".", "pop", "(", "prefix", "+", "\"alpha\"", ",", "default_alpha", ")", "for", "argname", "in", "(", "\"fill_alpha\"", ",", "\"line_alpha\"", ",", "\"text_alpha\"", ")", ":", "if", "argname", "not", "in", "glyphclass", ".", "properties", "(", ")", ":", "continue", "result", "[", "argname", "]", "=", "kwargs", ".", "pop", "(", "prefix", "+", "argname", ",", "alpha", ")", "return", "result" ]
Given a kwargs dict, a prefix, and a default value, looks for different color and alpha fields of the given prefix, and fills in the default value if it doesn't exist.
[ "Given", "a", "kwargs", "dict", "a", "prefix", "and", "a", "default", "value", "looks", "for", "different", "color", "and", "alpha", "fields", "of", "the", "given", "prefix", "and", "fills", "in", "the", "default", "value", "if", "it", "doesn", "t", "exist", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/plotting/helpers.py#L286-L315
train
bokeh/bokeh
bokeh/plotting/helpers.py
_tool_from_string
def _tool_from_string(name): """ Takes a string and returns a corresponding `Tool` instance. """ known_tools = sorted(_known_tools.keys()) if name in known_tools: tool_fn = _known_tools[name] if isinstance(tool_fn, string_types): tool_fn = _known_tools[tool_fn] return tool_fn() else: matches, text = difflib.get_close_matches(name.lower(), known_tools), "similar" if not matches: matches, text = known_tools, "possible" raise ValueError("unexpected tool name '%s', %s tools are %s" % (name, text, nice_join(matches)))
python
def _tool_from_string(name): """ Takes a string and returns a corresponding `Tool` instance. """ known_tools = sorted(_known_tools.keys()) if name in known_tools: tool_fn = _known_tools[name] if isinstance(tool_fn, string_types): tool_fn = _known_tools[tool_fn] return tool_fn() else: matches, text = difflib.get_close_matches(name.lower(), known_tools), "similar" if not matches: matches, text = known_tools, "possible" raise ValueError("unexpected tool name '%s', %s tools are %s" % (name, text, nice_join(matches)))
[ "def", "_tool_from_string", "(", "name", ")", ":", "known_tools", "=", "sorted", "(", "_known_tools", ".", "keys", "(", ")", ")", "if", "name", "in", "known_tools", ":", "tool_fn", "=", "_known_tools", "[", "name", "]", "if", "isinstance", "(", "tool_fn", ",", "string_types", ")", ":", "tool_fn", "=", "_known_tools", "[", "tool_fn", "]", "return", "tool_fn", "(", ")", "else", ":", "matches", ",", "text", "=", "difflib", ".", "get_close_matches", "(", "name", ".", "lower", "(", ")", ",", "known_tools", ")", ",", "\"similar\"", "if", "not", "matches", ":", "matches", ",", "text", "=", "known_tools", ",", "\"possible\"", "raise", "ValueError", "(", "\"unexpected tool name '%s', %s tools are %s\"", "%", "(", "name", ",", "text", ",", "nice_join", "(", "matches", ")", ")", ")" ]
Takes a string and returns a corresponding `Tool` instance.
[ "Takes", "a", "string", "and", "returns", "a", "corresponding", "Tool", "instance", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/plotting/helpers.py#L544-L561
train
bokeh/bokeh
bokeh/plotting/helpers.py
_process_tools_arg
def _process_tools_arg(plot, tools, tooltips=None): """ Adds tools to the plot object Args: plot (Plot): instance of a plot object tools (seq[Tool or str]|str): list of tool types or string listing the tool names. Those are converted using the _tool_from_string function. I.e.: `wheel_zoom,box_zoom,reset`. tooltips (string or seq[tuple[str, str]], optional): tooltips to use to configure a HoverTool Returns: list of Tools objects added to plot, map of supplied string names to tools """ tool_objs = [] tool_map = {} temp_tool_str = "" repeated_tools = [] if isinstance(tools, (list, tuple)): for tool in tools: if isinstance(tool, Tool): tool_objs.append(tool) elif isinstance(tool, string_types): temp_tool_str += tool + ',' else: raise ValueError("tool should be a string or an instance of Tool class") tools = temp_tool_str for tool in re.split(r"\s*,\s*", tools.strip()): # re.split will return empty strings; ignore them. if tool == "": continue tool_obj = _tool_from_string(tool) tool_objs.append(tool_obj) tool_map[tool] = tool_obj for typename, group in itertools.groupby( sorted(tool.__class__.__name__ for tool in tool_objs)): if len(list(group)) > 1: repeated_tools.append(typename) if repeated_tools: warnings.warn("%s are being repeated" % ",".join(repeated_tools)) if tooltips is not None: for tool_obj in tool_objs: if isinstance(tool_obj, HoverTool): tool_obj.tooltips = tooltips break else: tool_objs.append(HoverTool(tooltips=tooltips)) return tool_objs, tool_map
python
def _process_tools_arg(plot, tools, tooltips=None): """ Adds tools to the plot object Args: plot (Plot): instance of a plot object tools (seq[Tool or str]|str): list of tool types or string listing the tool names. Those are converted using the _tool_from_string function. I.e.: `wheel_zoom,box_zoom,reset`. tooltips (string or seq[tuple[str, str]], optional): tooltips to use to configure a HoverTool Returns: list of Tools objects added to plot, map of supplied string names to tools """ tool_objs = [] tool_map = {} temp_tool_str = "" repeated_tools = [] if isinstance(tools, (list, tuple)): for tool in tools: if isinstance(tool, Tool): tool_objs.append(tool) elif isinstance(tool, string_types): temp_tool_str += tool + ',' else: raise ValueError("tool should be a string or an instance of Tool class") tools = temp_tool_str for tool in re.split(r"\s*,\s*", tools.strip()): # re.split will return empty strings; ignore them. if tool == "": continue tool_obj = _tool_from_string(tool) tool_objs.append(tool_obj) tool_map[tool] = tool_obj for typename, group in itertools.groupby( sorted(tool.__class__.__name__ for tool in tool_objs)): if len(list(group)) > 1: repeated_tools.append(typename) if repeated_tools: warnings.warn("%s are being repeated" % ",".join(repeated_tools)) if tooltips is not None: for tool_obj in tool_objs: if isinstance(tool_obj, HoverTool): tool_obj.tooltips = tooltips break else: tool_objs.append(HoverTool(tooltips=tooltips)) return tool_objs, tool_map
[ "def", "_process_tools_arg", "(", "plot", ",", "tools", ",", "tooltips", "=", "None", ")", ":", "tool_objs", "=", "[", "]", "tool_map", "=", "{", "}", "temp_tool_str", "=", "\"\"", "repeated_tools", "=", "[", "]", "if", "isinstance", "(", "tools", ",", "(", "list", ",", "tuple", ")", ")", ":", "for", "tool", "in", "tools", ":", "if", "isinstance", "(", "tool", ",", "Tool", ")", ":", "tool_objs", ".", "append", "(", "tool", ")", "elif", "isinstance", "(", "tool", ",", "string_types", ")", ":", "temp_tool_str", "+=", "tool", "+", "','", "else", ":", "raise", "ValueError", "(", "\"tool should be a string or an instance of Tool class\"", ")", "tools", "=", "temp_tool_str", "for", "tool", "in", "re", ".", "split", "(", "r\"\\s*,\\s*\"", ",", "tools", ".", "strip", "(", ")", ")", ":", "# re.split will return empty strings; ignore them.", "if", "tool", "==", "\"\"", ":", "continue", "tool_obj", "=", "_tool_from_string", "(", "tool", ")", "tool_objs", ".", "append", "(", "tool_obj", ")", "tool_map", "[", "tool", "]", "=", "tool_obj", "for", "typename", ",", "group", "in", "itertools", ".", "groupby", "(", "sorted", "(", "tool", ".", "__class__", ".", "__name__", "for", "tool", "in", "tool_objs", ")", ")", ":", "if", "len", "(", "list", "(", "group", ")", ")", ">", "1", ":", "repeated_tools", ".", "append", "(", "typename", ")", "if", "repeated_tools", ":", "warnings", ".", "warn", "(", "\"%s are being repeated\"", "%", "\",\"", ".", "join", "(", "repeated_tools", ")", ")", "if", "tooltips", "is", "not", "None", ":", "for", "tool_obj", "in", "tool_objs", ":", "if", "isinstance", "(", "tool_obj", ",", "HoverTool", ")", ":", "tool_obj", ".", "tooltips", "=", "tooltips", "break", "else", ":", "tool_objs", ".", "append", "(", "HoverTool", "(", "tooltips", "=", "tooltips", ")", ")", "return", "tool_objs", ",", "tool_map" ]
Adds tools to the plot object Args: plot (Plot): instance of a plot object tools (seq[Tool or str]|str): list of tool types or string listing the tool names. Those are converted using the _tool_from_string function. I.e.: `wheel_zoom,box_zoom,reset`. tooltips (string or seq[tuple[str, str]], optional): tooltips to use to configure a HoverTool Returns: list of Tools objects added to plot, map of supplied string names to tools
[ "Adds", "tools", "to", "the", "plot", "object" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/plotting/helpers.py#L584-L638
train
bokeh/bokeh
bokeh/plotting/helpers.py
_process_active_tools
def _process_active_tools(toolbar, tool_map, active_drag, active_inspect, active_scroll, active_tap): """ Adds tools to the plot object Args: toolbar (Toolbar): instance of a Toolbar object tools_map (dict[str]|Tool): tool_map from _process_tools_arg active_drag (str or Tool): the tool to set active for drag active_inspect (str or Tool): the tool to set active for inspect active_scroll (str or Tool): the tool to set active for scroll active_tap (str or Tool): the tool to set active for tap Returns: None Note: This function sets properties on Toolbar """ if active_drag in ['auto', None] or isinstance(active_drag, Tool): toolbar.active_drag = active_drag elif active_drag in tool_map: toolbar.active_drag = tool_map[active_drag] else: raise ValueError("Got unknown %r for 'active_drag', which was not a string supplied in 'tools' argument" % active_drag) if active_inspect in ['auto', None] or isinstance(active_inspect, Tool) or all(isinstance(t, Tool) for t in active_inspect): toolbar.active_inspect = active_inspect elif active_inspect in tool_map: toolbar.active_inspect = tool_map[active_inspect] else: raise ValueError("Got unknown %r for 'active_inspect', which was not a string supplied in 'tools' argument" % active_scroll) if active_scroll in ['auto', None] or isinstance(active_scroll, Tool): toolbar.active_scroll = active_scroll elif active_scroll in tool_map: toolbar.active_scroll = tool_map[active_scroll] else: raise ValueError("Got unknown %r for 'active_scroll', which was not a string supplied in 'tools' argument" % active_scroll) if active_tap in ['auto', None] or isinstance(active_tap, Tool): toolbar.active_tap = active_tap elif active_tap in tool_map: toolbar.active_tap = tool_map[active_tap] else: raise ValueError("Got unknown %r for 'active_tap', which was not a string supplied in 'tools' argument" % active_tap)
python
def _process_active_tools(toolbar, tool_map, active_drag, active_inspect, active_scroll, active_tap): """ Adds tools to the plot object Args: toolbar (Toolbar): instance of a Toolbar object tools_map (dict[str]|Tool): tool_map from _process_tools_arg active_drag (str or Tool): the tool to set active for drag active_inspect (str or Tool): the tool to set active for inspect active_scroll (str or Tool): the tool to set active for scroll active_tap (str or Tool): the tool to set active for tap Returns: None Note: This function sets properties on Toolbar """ if active_drag in ['auto', None] or isinstance(active_drag, Tool): toolbar.active_drag = active_drag elif active_drag in tool_map: toolbar.active_drag = tool_map[active_drag] else: raise ValueError("Got unknown %r for 'active_drag', which was not a string supplied in 'tools' argument" % active_drag) if active_inspect in ['auto', None] or isinstance(active_inspect, Tool) or all(isinstance(t, Tool) for t in active_inspect): toolbar.active_inspect = active_inspect elif active_inspect in tool_map: toolbar.active_inspect = tool_map[active_inspect] else: raise ValueError("Got unknown %r for 'active_inspect', which was not a string supplied in 'tools' argument" % active_scroll) if active_scroll in ['auto', None] or isinstance(active_scroll, Tool): toolbar.active_scroll = active_scroll elif active_scroll in tool_map: toolbar.active_scroll = tool_map[active_scroll] else: raise ValueError("Got unknown %r for 'active_scroll', which was not a string supplied in 'tools' argument" % active_scroll) if active_tap in ['auto', None] or isinstance(active_tap, Tool): toolbar.active_tap = active_tap elif active_tap in tool_map: toolbar.active_tap = tool_map[active_tap] else: raise ValueError("Got unknown %r for 'active_tap', which was not a string supplied in 'tools' argument" % active_tap)
[ "def", "_process_active_tools", "(", "toolbar", ",", "tool_map", ",", "active_drag", ",", "active_inspect", ",", "active_scroll", ",", "active_tap", ")", ":", "if", "active_drag", "in", "[", "'auto'", ",", "None", "]", "or", "isinstance", "(", "active_drag", ",", "Tool", ")", ":", "toolbar", ".", "active_drag", "=", "active_drag", "elif", "active_drag", "in", "tool_map", ":", "toolbar", ".", "active_drag", "=", "tool_map", "[", "active_drag", "]", "else", ":", "raise", "ValueError", "(", "\"Got unknown %r for 'active_drag', which was not a string supplied in 'tools' argument\"", "%", "active_drag", ")", "if", "active_inspect", "in", "[", "'auto'", ",", "None", "]", "or", "isinstance", "(", "active_inspect", ",", "Tool", ")", "or", "all", "(", "isinstance", "(", "t", ",", "Tool", ")", "for", "t", "in", "active_inspect", ")", ":", "toolbar", ".", "active_inspect", "=", "active_inspect", "elif", "active_inspect", "in", "tool_map", ":", "toolbar", ".", "active_inspect", "=", "tool_map", "[", "active_inspect", "]", "else", ":", "raise", "ValueError", "(", "\"Got unknown %r for 'active_inspect', which was not a string supplied in 'tools' argument\"", "%", "active_scroll", ")", "if", "active_scroll", "in", "[", "'auto'", ",", "None", "]", "or", "isinstance", "(", "active_scroll", ",", "Tool", ")", ":", "toolbar", ".", "active_scroll", "=", "active_scroll", "elif", "active_scroll", "in", "tool_map", ":", "toolbar", ".", "active_scroll", "=", "tool_map", "[", "active_scroll", "]", "else", ":", "raise", "ValueError", "(", "\"Got unknown %r for 'active_scroll', which was not a string supplied in 'tools' argument\"", "%", "active_scroll", ")", "if", "active_tap", "in", "[", "'auto'", ",", "None", "]", "or", "isinstance", "(", "active_tap", ",", "Tool", ")", ":", "toolbar", ".", "active_tap", "=", "active_tap", "elif", "active_tap", "in", "tool_map", ":", "toolbar", ".", "active_tap", "=", "tool_map", "[", "active_tap", "]", "else", ":", "raise", "ValueError", "(", "\"Got unknown %r for 'active_tap', which was not a string supplied in 'tools' argument\"", "%", "active_tap", ")" ]
Adds tools to the plot object Args: toolbar (Toolbar): instance of a Toolbar object tools_map (dict[str]|Tool): tool_map from _process_tools_arg active_drag (str or Tool): the tool to set active for drag active_inspect (str or Tool): the tool to set active for inspect active_scroll (str or Tool): the tool to set active for scroll active_tap (str or Tool): the tool to set active for tap Returns: None Note: This function sets properties on Toolbar
[ "Adds", "tools", "to", "the", "plot", "object" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/plotting/helpers.py#L641-L684
train
bokeh/bokeh
bokeh/models/callbacks.py
CustomJS.from_py_func
def from_py_func(cls, func): """ Create a ``CustomJS`` instance from a Python function. The function is translated to JavaScript using PScript. """ from bokeh.util.deprecation import deprecated deprecated("'from_py_func' is deprecated and will be removed in an eventual 2.0 release. " "Use CustomJS directly instead.") if not isinstance(func, FunctionType): raise ValueError('CustomJS.from_py_func needs function object.') pscript = import_required('pscript', 'To use Python functions for CustomJS, you need PScript ' + '("conda install -c conda-forge pscript" or "pip install pscript")') # Collect default values default_values = func.__defaults__ # Python 2.6+ default_names = func.__code__.co_varnames[:len(default_values)] args = dict(zip(default_names, default_values)) args.pop('window', None) # Clear window, so we use the global window object # Get JS code, we could rip out the function def, or just # call the function. We do the latter. code = pscript.py2js(func, 'cb') + 'cb(%s);\n' % ', '.join(default_names) return cls(code=code, args=args)
python
def from_py_func(cls, func): """ Create a ``CustomJS`` instance from a Python function. The function is translated to JavaScript using PScript. """ from bokeh.util.deprecation import deprecated deprecated("'from_py_func' is deprecated and will be removed in an eventual 2.0 release. " "Use CustomJS directly instead.") if not isinstance(func, FunctionType): raise ValueError('CustomJS.from_py_func needs function object.') pscript = import_required('pscript', 'To use Python functions for CustomJS, you need PScript ' + '("conda install -c conda-forge pscript" or "pip install pscript")') # Collect default values default_values = func.__defaults__ # Python 2.6+ default_names = func.__code__.co_varnames[:len(default_values)] args = dict(zip(default_names, default_values)) args.pop('window', None) # Clear window, so we use the global window object # Get JS code, we could rip out the function def, or just # call the function. We do the latter. code = pscript.py2js(func, 'cb') + 'cb(%s);\n' % ', '.join(default_names) return cls(code=code, args=args)
[ "def", "from_py_func", "(", "cls", ",", "func", ")", ":", "from", "bokeh", ".", "util", ".", "deprecation", "import", "deprecated", "deprecated", "(", "\"'from_py_func' is deprecated and will be removed in an eventual 2.0 release. \"", "\"Use CustomJS directly instead.\"", ")", "if", "not", "isinstance", "(", "func", ",", "FunctionType", ")", ":", "raise", "ValueError", "(", "'CustomJS.from_py_func needs function object.'", ")", "pscript", "=", "import_required", "(", "'pscript'", ",", "'To use Python functions for CustomJS, you need PScript '", "+", "'(\"conda install -c conda-forge pscript\" or \"pip install pscript\")'", ")", "# Collect default values", "default_values", "=", "func", ".", "__defaults__", "# Python 2.6+", "default_names", "=", "func", ".", "__code__", ".", "co_varnames", "[", ":", "len", "(", "default_values", ")", "]", "args", "=", "dict", "(", "zip", "(", "default_names", ",", "default_values", ")", ")", "args", ".", "pop", "(", "'window'", ",", "None", ")", "# Clear window, so we use the global window object", "# Get JS code, we could rip out the function def, or just", "# call the function. We do the latter.", "code", "=", "pscript", ".", "py2js", "(", "func", ",", "'cb'", ")", "+", "'cb(%s);\\n'", "%", "', '", ".", "join", "(", "default_names", ")", "return", "cls", "(", "code", "=", "code", ",", "args", "=", "args", ")" ]
Create a ``CustomJS`` instance from a Python function. The function is translated to JavaScript using PScript.
[ "Create", "a", "CustomJS", "instance", "from", "a", "Python", "function", ".", "The", "function", "is", "translated", "to", "JavaScript", "using", "PScript", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/callbacks.py#L85-L106
train
bokeh/bokeh
bokeh/client/websocket.py
WebSocketClientConnectionWrapper.write_message
def write_message(self, message, binary=False, locked=True): ''' Write a message to the websocket after obtaining the appropriate Bokeh Document lock. ''' def write_message_unlocked(): if self._socket.protocol is None: # Tornado is maybe supposed to do this, but in fact it # tries to do _socket.protocol.write_message when protocol # is None and throws AttributeError or something. So avoid # trying to write to the closed socket. There doesn't seem # to be an obvious public function to check if the socket # is closed. raise WebSocketError("Connection to the server has been closed") future = self._socket.write_message(message, binary) # don't yield this future or we're blocking on ourselves! raise gen.Return(future) if locked: with (yield self.write_lock.acquire()): write_message_unlocked() else: write_message_unlocked()
python
def write_message(self, message, binary=False, locked=True): ''' Write a message to the websocket after obtaining the appropriate Bokeh Document lock. ''' def write_message_unlocked(): if self._socket.protocol is None: # Tornado is maybe supposed to do this, but in fact it # tries to do _socket.protocol.write_message when protocol # is None and throws AttributeError or something. So avoid # trying to write to the closed socket. There doesn't seem # to be an obvious public function to check if the socket # is closed. raise WebSocketError("Connection to the server has been closed") future = self._socket.write_message(message, binary) # don't yield this future or we're blocking on ourselves! raise gen.Return(future) if locked: with (yield self.write_lock.acquire()): write_message_unlocked() else: write_message_unlocked()
[ "def", "write_message", "(", "self", ",", "message", ",", "binary", "=", "False", ",", "locked", "=", "True", ")", ":", "def", "write_message_unlocked", "(", ")", ":", "if", "self", ".", "_socket", ".", "protocol", "is", "None", ":", "# Tornado is maybe supposed to do this, but in fact it", "# tries to do _socket.protocol.write_message when protocol", "# is None and throws AttributeError or something. So avoid", "# trying to write to the closed socket. There doesn't seem", "# to be an obvious public function to check if the socket", "# is closed.", "raise", "WebSocketError", "(", "\"Connection to the server has been closed\"", ")", "future", "=", "self", ".", "_socket", ".", "write_message", "(", "message", ",", "binary", ")", "# don't yield this future or we're blocking on ourselves!", "raise", "gen", ".", "Return", "(", "future", ")", "if", "locked", ":", "with", "(", "yield", "self", ".", "write_lock", ".", "acquire", "(", ")", ")", ":", "write_message_unlocked", "(", ")", "else", ":", "write_message_unlocked", "(", ")" ]
Write a message to the websocket after obtaining the appropriate Bokeh Document lock.
[ "Write", "a", "message", "to", "the", "websocket", "after", "obtaining", "the", "appropriate", "Bokeh", "Document", "lock", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/client/websocket.py#L62-L86
train
bokeh/bokeh
bokeh/resources.py
BaseResources._collect_external_resources
def _collect_external_resources(self, resource_attr): """ Collect external resources set on resource_attr attribute of all models.""" external_resources = [] for _, cls in sorted(Model.model_class_reverse_map.items(), key=lambda arg: arg[0]): external = getattr(cls, resource_attr, None) if isinstance(external, string_types): if external not in external_resources: external_resources.append(external) elif isinstance(external, list): for e in external: if e not in external_resources: external_resources.append(e) return external_resources
python
def _collect_external_resources(self, resource_attr): """ Collect external resources set on resource_attr attribute of all models.""" external_resources = [] for _, cls in sorted(Model.model_class_reverse_map.items(), key=lambda arg: arg[0]): external = getattr(cls, resource_attr, None) if isinstance(external, string_types): if external not in external_resources: external_resources.append(external) elif isinstance(external, list): for e in external: if e not in external_resources: external_resources.append(e) return external_resources
[ "def", "_collect_external_resources", "(", "self", ",", "resource_attr", ")", ":", "external_resources", "=", "[", "]", "for", "_", ",", "cls", "in", "sorted", "(", "Model", ".", "model_class_reverse_map", ".", "items", "(", ")", ",", "key", "=", "lambda", "arg", ":", "arg", "[", "0", "]", ")", ":", "external", "=", "getattr", "(", "cls", ",", "resource_attr", ",", "None", ")", "if", "isinstance", "(", "external", ",", "string_types", ")", ":", "if", "external", "not", "in", "external_resources", ":", "external_resources", ".", "append", "(", "external", ")", "elif", "isinstance", "(", "external", ",", "list", ")", ":", "for", "e", "in", "external", ":", "if", "e", "not", "in", "external_resources", ":", "external_resources", ".", "append", "(", "e", ")", "return", "external_resources" ]
Collect external resources set on resource_attr attribute of all models.
[ "Collect", "external", "resources", "set", "on", "resource_attr", "attribute", "of", "all", "models", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/resources.py#L155-L171
train
bokeh/bokeh
bokeh/settings.py
_Settings.py_log_level
def py_log_level(self, default='none'): ''' Set the log level for python Bokeh code. ''' level = self._get_str("PY_LOG_LEVEL", default, "debug") LEVELS = {'trace': logging.TRACE, 'debug': logging.DEBUG, 'info' : logging.INFO, 'warn' : logging.WARNING, 'error': logging.ERROR, 'fatal': logging.CRITICAL, 'none' : None} return LEVELS[level]
python
def py_log_level(self, default='none'): ''' Set the log level for python Bokeh code. ''' level = self._get_str("PY_LOG_LEVEL", default, "debug") LEVELS = {'trace': logging.TRACE, 'debug': logging.DEBUG, 'info' : logging.INFO, 'warn' : logging.WARNING, 'error': logging.ERROR, 'fatal': logging.CRITICAL, 'none' : None} return LEVELS[level]
[ "def", "py_log_level", "(", "self", ",", "default", "=", "'none'", ")", ":", "level", "=", "self", ".", "_get_str", "(", "\"PY_LOG_LEVEL\"", ",", "default", ",", "\"debug\"", ")", "LEVELS", "=", "{", "'trace'", ":", "logging", ".", "TRACE", ",", "'debug'", ":", "logging", ".", "DEBUG", ",", "'info'", ":", "logging", ".", "INFO", ",", "'warn'", ":", "logging", ".", "WARNING", ",", "'error'", ":", "logging", ".", "ERROR", ",", "'fatal'", ":", "logging", ".", "CRITICAL", ",", "'none'", ":", "None", "}", "return", "LEVELS", "[", "level", "]" ]
Set the log level for python Bokeh code.
[ "Set", "the", "log", "level", "for", "python", "Bokeh", "code", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/settings.py#L275-L287
train
bokeh/bokeh
bokeh/settings.py
_Settings.secret_key_bytes
def secret_key_bytes(self): ''' Return the secret_key, converted to bytes and cached. ''' if not hasattr(self, '_secret_key_bytes'): key = self.secret_key() if key is None: self._secret_key_bytes = None else: self._secret_key_bytes = codecs.encode(key, "utf-8") return self._secret_key_bytes
python
def secret_key_bytes(self): ''' Return the secret_key, converted to bytes and cached. ''' if not hasattr(self, '_secret_key_bytes'): key = self.secret_key() if key is None: self._secret_key_bytes = None else: self._secret_key_bytes = codecs.encode(key, "utf-8") return self._secret_key_bytes
[ "def", "secret_key_bytes", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_secret_key_bytes'", ")", ":", "key", "=", "self", ".", "secret_key", "(", ")", "if", "key", "is", "None", ":", "self", ".", "_secret_key_bytes", "=", "None", "else", ":", "self", ".", "_secret_key_bytes", "=", "codecs", ".", "encode", "(", "key", ",", "\"utf-8\"", ")", "return", "self", ".", "_secret_key_bytes" ]
Return the secret_key, converted to bytes and cached.
[ "Return", "the", "secret_key", "converted", "to", "bytes", "and", "cached", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/settings.py#L315-L325
train
bokeh/bokeh
bokeh/settings.py
_Settings.bokehjssrcdir
def bokehjssrcdir(self): ''' The absolute path of the BokehJS source code in the installed Bokeh source tree. ''' if self._is_dev or self.debugjs: bokehjssrcdir = abspath(join(ROOT_DIR, '..', 'bokehjs', 'src')) if isdir(bokehjssrcdir): return bokehjssrcdir return None
python
def bokehjssrcdir(self): ''' The absolute path of the BokehJS source code in the installed Bokeh source tree. ''' if self._is_dev or self.debugjs: bokehjssrcdir = abspath(join(ROOT_DIR, '..', 'bokehjs', 'src')) if isdir(bokehjssrcdir): return bokehjssrcdir return None
[ "def", "bokehjssrcdir", "(", "self", ")", ":", "if", "self", ".", "_is_dev", "or", "self", ".", "debugjs", ":", "bokehjssrcdir", "=", "abspath", "(", "join", "(", "ROOT_DIR", ",", "'..'", ",", "'bokehjs'", ",", "'src'", ")", ")", "if", "isdir", "(", "bokehjssrcdir", ")", ":", "return", "bokehjssrcdir", "return", "None" ]
The absolute path of the BokehJS source code in the installed Bokeh source tree.
[ "The", "absolute", "path", "of", "the", "BokehJS", "source", "code", "in", "the", "installed", "Bokeh", "source", "tree", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/settings.py#L344-L355
train
bokeh/bokeh
bokeh/settings.py
_Settings.css_files
def css_files(self): ''' The CSS files in the BokehJS directory. ''' bokehjsdir = self.bokehjsdir() js_files = [] for root, dirnames, files in os.walk(bokehjsdir): for fname in files: if fname.endswith(".css"): js_files.append(join(root, fname)) return js_files
python
def css_files(self): ''' The CSS files in the BokehJS directory. ''' bokehjsdir = self.bokehjsdir() js_files = [] for root, dirnames, files in os.walk(bokehjsdir): for fname in files: if fname.endswith(".css"): js_files.append(join(root, fname)) return js_files
[ "def", "css_files", "(", "self", ")", ":", "bokehjsdir", "=", "self", ".", "bokehjsdir", "(", ")", "js_files", "=", "[", "]", "for", "root", ",", "dirnames", ",", "files", "in", "os", ".", "walk", "(", "bokehjsdir", ")", ":", "for", "fname", "in", "files", ":", "if", "fname", ".", "endswith", "(", "\".css\"", ")", ":", "js_files", ".", "append", "(", "join", "(", "root", ",", "fname", ")", ")", "return", "js_files" ]
The CSS files in the BokehJS directory.
[ "The", "CSS", "files", "in", "the", "BokehJS", "directory", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/settings.py#L375-L385
train
bokeh/bokeh
bokeh/core/json_encoder.py
serialize_json
def serialize_json(obj, pretty=None, indent=None, **kwargs): ''' Return a serialized JSON representation of objects, suitable to send to BokehJS. This function is typically used to serialize single python objects in the manner expected by BokehJS. In particular, many datetime values are automatically normalized to an expected format. Some Bokeh objects can also be passed, but note that Bokeh models are typically properly serialized in the context of an entire Bokeh document. The resulting JSON always has sorted keys. By default. the output is as compact as possible unless pretty output or indentation is requested. Args: obj (obj) : the object to serialize to JSON format pretty (bool, optional) : Whether to generate prettified output. If ``True``, spaces are added after added after separators, and indentation and newlines are applied. (default: False) Pretty output can also be enabled with the environment variable ``BOKEH_PRETTY``, which overrides this argument, if set. indent (int or None, optional) : Amount of indentation to use in generated JSON output. If ``None`` then no indentation is used, unless pretty output is enabled, in which case two spaces are used. (default: None) Any additional keyword arguments are passed to ``json.dumps``, except for some that are computed internally, and cannot be overridden: * allow_nan * indent * separators * sort_keys Examples: .. code-block:: python >>> data = dict(b=np.datetime64('2017-01-01'), a = np.arange(3)) >>>print(serialize_json(data)) {"a":[0,1,2],"b":1483228800000.0} >>> print(serialize_json(data, pretty=True)) { "a": [ 0, 1, 2 ], "b": 1483228800000.0 } ''' # these args to json.dumps are computed internally and should not be passed along for name in ['allow_nan', 'separators', 'sort_keys']: if name in kwargs: raise ValueError("The value of %r is computed internally, overriding is not permissable." % name) if pretty is None: pretty = settings.pretty(False) if pretty: separators=(",", ": ") else: separators=(",", ":") if pretty and indent is None: indent = 2 return json.dumps(obj, cls=BokehJSONEncoder, allow_nan=False, indent=indent, separators=separators, sort_keys=True, **kwargs)
python
def serialize_json(obj, pretty=None, indent=None, **kwargs): ''' Return a serialized JSON representation of objects, suitable to send to BokehJS. This function is typically used to serialize single python objects in the manner expected by BokehJS. In particular, many datetime values are automatically normalized to an expected format. Some Bokeh objects can also be passed, but note that Bokeh models are typically properly serialized in the context of an entire Bokeh document. The resulting JSON always has sorted keys. By default. the output is as compact as possible unless pretty output or indentation is requested. Args: obj (obj) : the object to serialize to JSON format pretty (bool, optional) : Whether to generate prettified output. If ``True``, spaces are added after added after separators, and indentation and newlines are applied. (default: False) Pretty output can also be enabled with the environment variable ``BOKEH_PRETTY``, which overrides this argument, if set. indent (int or None, optional) : Amount of indentation to use in generated JSON output. If ``None`` then no indentation is used, unless pretty output is enabled, in which case two spaces are used. (default: None) Any additional keyword arguments are passed to ``json.dumps``, except for some that are computed internally, and cannot be overridden: * allow_nan * indent * separators * sort_keys Examples: .. code-block:: python >>> data = dict(b=np.datetime64('2017-01-01'), a = np.arange(3)) >>>print(serialize_json(data)) {"a":[0,1,2],"b":1483228800000.0} >>> print(serialize_json(data, pretty=True)) { "a": [ 0, 1, 2 ], "b": 1483228800000.0 } ''' # these args to json.dumps are computed internally and should not be passed along for name in ['allow_nan', 'separators', 'sort_keys']: if name in kwargs: raise ValueError("The value of %r is computed internally, overriding is not permissable." % name) if pretty is None: pretty = settings.pretty(False) if pretty: separators=(",", ": ") else: separators=(",", ":") if pretty and indent is None: indent = 2 return json.dumps(obj, cls=BokehJSONEncoder, allow_nan=False, indent=indent, separators=separators, sort_keys=True, **kwargs)
[ "def", "serialize_json", "(", "obj", ",", "pretty", "=", "None", ",", "indent", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# these args to json.dumps are computed internally and should not be passed along", "for", "name", "in", "[", "'allow_nan'", ",", "'separators'", ",", "'sort_keys'", "]", ":", "if", "name", "in", "kwargs", ":", "raise", "ValueError", "(", "\"The value of %r is computed internally, overriding is not permissable.\"", "%", "name", ")", "if", "pretty", "is", "None", ":", "pretty", "=", "settings", ".", "pretty", "(", "False", ")", "if", "pretty", ":", "separators", "=", "(", "\",\"", ",", "\": \"", ")", "else", ":", "separators", "=", "(", "\",\"", ",", "\":\"", ")", "if", "pretty", "and", "indent", "is", "None", ":", "indent", "=", "2", "return", "json", ".", "dumps", "(", "obj", ",", "cls", "=", "BokehJSONEncoder", ",", "allow_nan", "=", "False", ",", "indent", "=", "indent", ",", "separators", "=", "separators", ",", "sort_keys", "=", "True", ",", "*", "*", "kwargs", ")" ]
Return a serialized JSON representation of objects, suitable to send to BokehJS. This function is typically used to serialize single python objects in the manner expected by BokehJS. In particular, many datetime values are automatically normalized to an expected format. Some Bokeh objects can also be passed, but note that Bokeh models are typically properly serialized in the context of an entire Bokeh document. The resulting JSON always has sorted keys. By default. the output is as compact as possible unless pretty output or indentation is requested. Args: obj (obj) : the object to serialize to JSON format pretty (bool, optional) : Whether to generate prettified output. If ``True``, spaces are added after added after separators, and indentation and newlines are applied. (default: False) Pretty output can also be enabled with the environment variable ``BOKEH_PRETTY``, which overrides this argument, if set. indent (int or None, optional) : Amount of indentation to use in generated JSON output. If ``None`` then no indentation is used, unless pretty output is enabled, in which case two spaces are used. (default: None) Any additional keyword arguments are passed to ``json.dumps``, except for some that are computed internally, and cannot be overridden: * allow_nan * indent * separators * sort_keys Examples: .. code-block:: python >>> data = dict(b=np.datetime64('2017-01-01'), a = np.arange(3)) >>>print(serialize_json(data)) {"a":[0,1,2],"b":1483228800000.0} >>> print(serialize_json(data, pretty=True)) { "a": [ 0, 1, 2 ], "b": 1483228800000.0 }
[ "Return", "a", "serialized", "JSON", "representation", "of", "objects", "suitable", "to", "send", "to", "BokehJS", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/json_encoder.py#L85-L161
train
bokeh/bokeh
bokeh/core/json_encoder.py
BokehJSONEncoder.transform_python_types
def transform_python_types(self, obj): ''' Handle special scalars such as (Python, NumPy, or Pandas) datetimes, or Decimal values. Args: obj (obj) : The object to encode. Anything not specifically handled in this method is passed on to the default system JSON encoder. ''' # date/time values that get serialized as milliseconds if is_datetime_type(obj): return convert_datetime_type(obj) if is_timedelta_type(obj): return convert_timedelta_type(obj) # slice objects elif isinstance(obj, slice): return dict(start=obj.start, stop=obj.stop, step=obj.step) # NumPy scalars elif np.issubdtype(type(obj), np.floating): return float(obj) elif np.issubdtype(type(obj), np.integer): return int(obj) elif np.issubdtype(type(obj), np.bool_): return bool(obj) # Decimal values elif isinstance(obj, decimal.Decimal): return float(obj) # RelativeDelta gets serialized as a dict elif rd and isinstance(obj, rd.relativedelta): return dict(years=obj.years, months=obj.months, days=obj.days, hours=obj.hours, minutes=obj.minutes, seconds=obj.seconds, microseconds=obj.microseconds) else: return super(BokehJSONEncoder, self).default(obj)
python
def transform_python_types(self, obj): ''' Handle special scalars such as (Python, NumPy, or Pandas) datetimes, or Decimal values. Args: obj (obj) : The object to encode. Anything not specifically handled in this method is passed on to the default system JSON encoder. ''' # date/time values that get serialized as milliseconds if is_datetime_type(obj): return convert_datetime_type(obj) if is_timedelta_type(obj): return convert_timedelta_type(obj) # slice objects elif isinstance(obj, slice): return dict(start=obj.start, stop=obj.stop, step=obj.step) # NumPy scalars elif np.issubdtype(type(obj), np.floating): return float(obj) elif np.issubdtype(type(obj), np.integer): return int(obj) elif np.issubdtype(type(obj), np.bool_): return bool(obj) # Decimal values elif isinstance(obj, decimal.Decimal): return float(obj) # RelativeDelta gets serialized as a dict elif rd and isinstance(obj, rd.relativedelta): return dict(years=obj.years, months=obj.months, days=obj.days, hours=obj.hours, minutes=obj.minutes, seconds=obj.seconds, microseconds=obj.microseconds) else: return super(BokehJSONEncoder, self).default(obj)
[ "def", "transform_python_types", "(", "self", ",", "obj", ")", ":", "# date/time values that get serialized as milliseconds", "if", "is_datetime_type", "(", "obj", ")", ":", "return", "convert_datetime_type", "(", "obj", ")", "if", "is_timedelta_type", "(", "obj", ")", ":", "return", "convert_timedelta_type", "(", "obj", ")", "# slice objects", "elif", "isinstance", "(", "obj", ",", "slice", ")", ":", "return", "dict", "(", "start", "=", "obj", ".", "start", ",", "stop", "=", "obj", ".", "stop", ",", "step", "=", "obj", ".", "step", ")", "# NumPy scalars", "elif", "np", ".", "issubdtype", "(", "type", "(", "obj", ")", ",", "np", ".", "floating", ")", ":", "return", "float", "(", "obj", ")", "elif", "np", ".", "issubdtype", "(", "type", "(", "obj", ")", ",", "np", ".", "integer", ")", ":", "return", "int", "(", "obj", ")", "elif", "np", ".", "issubdtype", "(", "type", "(", "obj", ")", ",", "np", ".", "bool_", ")", ":", "return", "bool", "(", "obj", ")", "# Decimal values", "elif", "isinstance", "(", "obj", ",", "decimal", ".", "Decimal", ")", ":", "return", "float", "(", "obj", ")", "# RelativeDelta gets serialized as a dict", "elif", "rd", "and", "isinstance", "(", "obj", ",", "rd", ".", "relativedelta", ")", ":", "return", "dict", "(", "years", "=", "obj", ".", "years", ",", "months", "=", "obj", ".", "months", ",", "days", "=", "obj", ".", "days", ",", "hours", "=", "obj", ".", "hours", ",", "minutes", "=", "obj", ".", "minutes", ",", "seconds", "=", "obj", ".", "seconds", ",", "microseconds", "=", "obj", ".", "microseconds", ")", "else", ":", "return", "super", "(", "BokehJSONEncoder", ",", "self", ")", ".", "default", "(", "obj", ")" ]
Handle special scalars such as (Python, NumPy, or Pandas) datetimes, or Decimal values. Args: obj (obj) : The object to encode. Anything not specifically handled in this method is passed on to the default system JSON encoder.
[ "Handle", "special", "scalars", "such", "as", "(", "Python", "NumPy", "or", "Pandas", ")", "datetimes", "or", "Decimal", "values", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/json_encoder.py#L173-L219
train
bokeh/bokeh
bokeh/core/json_encoder.py
BokehJSONEncoder.default
def default(self, obj): ''' The required ``default`` method for ``JSONEncoder`` subclasses. Args: obj (obj) : The object to encode. Anything not specifically handled in this method is passed on to the default system JSON encoder. ''' from ..model import Model from ..colors import Color from .has_props import HasProps # array types -- use force_list here, only binary # encoding CDS columns for now if pd and isinstance(obj, (pd.Series, pd.Index)): return transform_series(obj, force_list=True) elif isinstance(obj, np.ndarray): return transform_array(obj, force_list=True) elif isinstance(obj, collections.deque): return list(map(self.default, obj)) elif isinstance(obj, Model): return obj.ref elif isinstance(obj, HasProps): return obj.properties_with_values(include_defaults=False) elif isinstance(obj, Color): return obj.to_css() else: return self.transform_python_types(obj)
python
def default(self, obj): ''' The required ``default`` method for ``JSONEncoder`` subclasses. Args: obj (obj) : The object to encode. Anything not specifically handled in this method is passed on to the default system JSON encoder. ''' from ..model import Model from ..colors import Color from .has_props import HasProps # array types -- use force_list here, only binary # encoding CDS columns for now if pd and isinstance(obj, (pd.Series, pd.Index)): return transform_series(obj, force_list=True) elif isinstance(obj, np.ndarray): return transform_array(obj, force_list=True) elif isinstance(obj, collections.deque): return list(map(self.default, obj)) elif isinstance(obj, Model): return obj.ref elif isinstance(obj, HasProps): return obj.properties_with_values(include_defaults=False) elif isinstance(obj, Color): return obj.to_css() else: return self.transform_python_types(obj)
[ "def", "default", "(", "self", ",", "obj", ")", ":", "from", ".", ".", "model", "import", "Model", "from", ".", ".", "colors", "import", "Color", "from", ".", "has_props", "import", "HasProps", "# array types -- use force_list here, only binary", "# encoding CDS columns for now", "if", "pd", "and", "isinstance", "(", "obj", ",", "(", "pd", ".", "Series", ",", "pd", ".", "Index", ")", ")", ":", "return", "transform_series", "(", "obj", ",", "force_list", "=", "True", ")", "elif", "isinstance", "(", "obj", ",", "np", ".", "ndarray", ")", ":", "return", "transform_array", "(", "obj", ",", "force_list", "=", "True", ")", "elif", "isinstance", "(", "obj", ",", "collections", ".", "deque", ")", ":", "return", "list", "(", "map", "(", "self", ".", "default", ",", "obj", ")", ")", "elif", "isinstance", "(", "obj", ",", "Model", ")", ":", "return", "obj", ".", "ref", "elif", "isinstance", "(", "obj", ",", "HasProps", ")", ":", "return", "obj", ".", "properties_with_values", "(", "include_defaults", "=", "False", ")", "elif", "isinstance", "(", "obj", ",", "Color", ")", ":", "return", "obj", ".", "to_css", "(", ")", "else", ":", "return", "self", ".", "transform_python_types", "(", "obj", ")" ]
The required ``default`` method for ``JSONEncoder`` subclasses. Args: obj (obj) : The object to encode. Anything not specifically handled in this method is passed on to the default system JSON encoder.
[ "The", "required", "default", "method", "for", "JSONEncoder", "subclasses", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/json_encoder.py#L221-L252
train
bokeh/bokeh
bokeh/application/application.py
Application.add
def add(self, handler): ''' Add a handler to the pipeline used to initialize new documents. Args: handler (Handler) : a handler for this Application to use to process Documents ''' self._handlers.append(handler) # make sure there is at most one static path static_paths = set(h.static_path() for h in self.handlers) static_paths.discard(None) if len(static_paths) > 1: raise RuntimeError("More than one static path requested for app: %r" % list(static_paths)) elif len(static_paths) == 1: self._static_path = static_paths.pop() else: self._static_path = None
python
def add(self, handler): ''' Add a handler to the pipeline used to initialize new documents. Args: handler (Handler) : a handler for this Application to use to process Documents ''' self._handlers.append(handler) # make sure there is at most one static path static_paths = set(h.static_path() for h in self.handlers) static_paths.discard(None) if len(static_paths) > 1: raise RuntimeError("More than one static path requested for app: %r" % list(static_paths)) elif len(static_paths) == 1: self._static_path = static_paths.pop() else: self._static_path = None
[ "def", "add", "(", "self", ",", "handler", ")", ":", "self", ".", "_handlers", ".", "append", "(", "handler", ")", "# make sure there is at most one static path", "static_paths", "=", "set", "(", "h", ".", "static_path", "(", ")", "for", "h", "in", "self", ".", "handlers", ")", "static_paths", ".", "discard", "(", "None", ")", "if", "len", "(", "static_paths", ")", ">", "1", ":", "raise", "RuntimeError", "(", "\"More than one static path requested for app: %r\"", "%", "list", "(", "static_paths", ")", ")", "elif", "len", "(", "static_paths", ")", "==", "1", ":", "self", ".", "_static_path", "=", "static_paths", ".", "pop", "(", ")", "else", ":", "self", ".", "_static_path", "=", "None" ]
Add a handler to the pipeline used to initialize new documents. Args: handler (Handler) : a handler for this Application to use to process Documents
[ "Add", "a", "handler", "to", "the", "pipeline", "used", "to", "initialize", "new", "documents", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/application/application.py#L142-L160
train
bokeh/bokeh
bokeh/application/application.py
Application.initialize_document
def initialize_document(self, doc): ''' Fills in a new document using the Application's handlers. ''' for h in self._handlers: # TODO (havocp) we need to check the 'failed' flag on each handler # and build a composite error display. In develop mode, we want to # somehow get these errors to the client. h.modify_document(doc) if h.failed: log.error("Error running application handler %r: %s %s ", h, h.error, h.error_detail) if settings.perform_document_validation(): doc.validate()
python
def initialize_document(self, doc): ''' Fills in a new document using the Application's handlers. ''' for h in self._handlers: # TODO (havocp) we need to check the 'failed' flag on each handler # and build a composite error display. In develop mode, we want to # somehow get these errors to the client. h.modify_document(doc) if h.failed: log.error("Error running application handler %r: %s %s ", h, h.error, h.error_detail) if settings.perform_document_validation(): doc.validate()
[ "def", "initialize_document", "(", "self", ",", "doc", ")", ":", "for", "h", "in", "self", ".", "_handlers", ":", "# TODO (havocp) we need to check the 'failed' flag on each handler", "# and build a composite error display. In develop mode, we want to", "# somehow get these errors to the client.", "h", ".", "modify_document", "(", "doc", ")", "if", "h", ".", "failed", ":", "log", ".", "error", "(", "\"Error running application handler %r: %s %s \"", ",", "h", ",", "h", ".", "error", ",", "h", ".", "error_detail", ")", "if", "settings", ".", "perform_document_validation", "(", ")", ":", "doc", ".", "validate", "(", ")" ]
Fills in a new document using the Application's handlers.
[ "Fills", "in", "a", "new", "document", "using", "the", "Application", "s", "handlers", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/application/application.py#L170-L183
train
bokeh/bokeh
bokeh/application/application.py
Application.on_session_created
def on_session_created(self, session_context): ''' Invoked to execute code when a new session is created. This method calls ``on_session_created`` on each handler, in order, with the session context passed as the only argument. May return a ``Future`` which will delay session creation until the ``Future`` completes. ''' for h in self._handlers: result = h.on_session_created(session_context) yield yield_for_all_futures(result) raise gen.Return(None)
python
def on_session_created(self, session_context): ''' Invoked to execute code when a new session is created. This method calls ``on_session_created`` on each handler, in order, with the session context passed as the only argument. May return a ``Future`` which will delay session creation until the ``Future`` completes. ''' for h in self._handlers: result = h.on_session_created(session_context) yield yield_for_all_futures(result) raise gen.Return(None)
[ "def", "on_session_created", "(", "self", ",", "session_context", ")", ":", "for", "h", "in", "self", ".", "_handlers", ":", "result", "=", "h", ".", "on_session_created", "(", "session_context", ")", "yield", "yield_for_all_futures", "(", "result", ")", "raise", "gen", ".", "Return", "(", "None", ")" ]
Invoked to execute code when a new session is created. This method calls ``on_session_created`` on each handler, in order, with the session context passed as the only argument. May return a ``Future`` which will delay session creation until the ``Future`` completes.
[ "Invoked", "to", "execute", "code", "when", "a", "new", "session", "is", "created", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/application/application.py#L211-L224
train
bokeh/bokeh
bokeh/models/plots.py
_select_helper
def _select_helper(args, kwargs): """ Allow flexible selector syntax. Returns: dict """ if len(args) > 1: raise TypeError("select accepts at most ONE positional argument.") if len(args) > 0 and len(kwargs) > 0: raise TypeError("select accepts EITHER a positional argument, OR keyword arguments (not both).") if len(args) == 0 and len(kwargs) == 0: raise TypeError("select requires EITHER a positional argument, OR keyword arguments.") if args: arg = args[0] if isinstance(arg, dict): selector = arg elif isinstance(arg, string_types): selector = dict(name=arg) elif isinstance(arg, type) and issubclass(arg, Model): selector = {"type": arg} else: raise TypeError("selector must be a dictionary, string or plot object.") elif 'selector' in kwargs: if len(kwargs) == 1: selector = kwargs['selector'] else: raise TypeError("when passing 'selector' keyword arg, not other keyword args may be present") else: selector = kwargs return selector
python
def _select_helper(args, kwargs): """ Allow flexible selector syntax. Returns: dict """ if len(args) > 1: raise TypeError("select accepts at most ONE positional argument.") if len(args) > 0 and len(kwargs) > 0: raise TypeError("select accepts EITHER a positional argument, OR keyword arguments (not both).") if len(args) == 0 and len(kwargs) == 0: raise TypeError("select requires EITHER a positional argument, OR keyword arguments.") if args: arg = args[0] if isinstance(arg, dict): selector = arg elif isinstance(arg, string_types): selector = dict(name=arg) elif isinstance(arg, type) and issubclass(arg, Model): selector = {"type": arg} else: raise TypeError("selector must be a dictionary, string or plot object.") elif 'selector' in kwargs: if len(kwargs) == 1: selector = kwargs['selector'] else: raise TypeError("when passing 'selector' keyword arg, not other keyword args may be present") else: selector = kwargs return selector
[ "def", "_select_helper", "(", "args", ",", "kwargs", ")", ":", "if", "len", "(", "args", ")", ">", "1", ":", "raise", "TypeError", "(", "\"select accepts at most ONE positional argument.\"", ")", "if", "len", "(", "args", ")", ">", "0", "and", "len", "(", "kwargs", ")", ">", "0", ":", "raise", "TypeError", "(", "\"select accepts EITHER a positional argument, OR keyword arguments (not both).\"", ")", "if", "len", "(", "args", ")", "==", "0", "and", "len", "(", "kwargs", ")", "==", "0", ":", "raise", "TypeError", "(", "\"select requires EITHER a positional argument, OR keyword arguments.\"", ")", "if", "args", ":", "arg", "=", "args", "[", "0", "]", "if", "isinstance", "(", "arg", ",", "dict", ")", ":", "selector", "=", "arg", "elif", "isinstance", "(", "arg", ",", "string_types", ")", ":", "selector", "=", "dict", "(", "name", "=", "arg", ")", "elif", "isinstance", "(", "arg", ",", "type", ")", "and", "issubclass", "(", "arg", ",", "Model", ")", ":", "selector", "=", "{", "\"type\"", ":", "arg", "}", "else", ":", "raise", "TypeError", "(", "\"selector must be a dictionary, string or plot object.\"", ")", "elif", "'selector'", "in", "kwargs", ":", "if", "len", "(", "kwargs", ")", "==", "1", ":", "selector", "=", "kwargs", "[", "'selector'", "]", "else", ":", "raise", "TypeError", "(", "\"when passing 'selector' keyword arg, not other keyword args may be present\"", ")", "else", ":", "selector", "=", "kwargs", "return", "selector" ]
Allow flexible selector syntax. Returns: dict
[ "Allow", "flexible", "selector", "syntax", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/plots.py#L759-L795
train
bokeh/bokeh
bokeh/models/plots.py
Plot.select
def select(self, *args, **kwargs): ''' Query this object and all of its references for objects that match the given selector. There are a few different ways to call the ``select`` method. The most general is to supply a JSON-like query dictionary as the single argument or as keyword arguments: Args: selector (JSON-like) : some sample text Keyword Arguments: kwargs : query dict key/values as keyword arguments Additionally, for compatibility with ``Model.select``, a selector dict may be passed as ``selector`` keyword argument, in which case the value of ``kwargs['selector']`` is used for the query. For convenience, queries on just names can be made by supplying the ``name`` string as the single parameter: Args: name (str) : the name to query on Also queries on just type can be made simply by supplying the ``Model`` subclass as the single parameter: Args: type (Model) : the type to query on Returns: seq[Model] Examples: .. code-block:: python # These three are equivalent p.select(selector={"type": HoverTool}) p.select({"type": HoverTool}) p.select(HoverTool) # These two are also equivalent p.select({"name": "mycircle"}) p.select("mycircle") # Keyword arguments can be supplied in place of selector dict p.select({"name": "foo", "type": HoverTool}) p.select(name="foo", type=HoverTool) ''' selector = _select_helper(args, kwargs) # Want to pass selector that is a dictionary return _list_attr_splat(find(self.references(), selector, {'plot': self}))
python
def select(self, *args, **kwargs): ''' Query this object and all of its references for objects that match the given selector. There are a few different ways to call the ``select`` method. The most general is to supply a JSON-like query dictionary as the single argument or as keyword arguments: Args: selector (JSON-like) : some sample text Keyword Arguments: kwargs : query dict key/values as keyword arguments Additionally, for compatibility with ``Model.select``, a selector dict may be passed as ``selector`` keyword argument, in which case the value of ``kwargs['selector']`` is used for the query. For convenience, queries on just names can be made by supplying the ``name`` string as the single parameter: Args: name (str) : the name to query on Also queries on just type can be made simply by supplying the ``Model`` subclass as the single parameter: Args: type (Model) : the type to query on Returns: seq[Model] Examples: .. code-block:: python # These three are equivalent p.select(selector={"type": HoverTool}) p.select({"type": HoverTool}) p.select(HoverTool) # These two are also equivalent p.select({"name": "mycircle"}) p.select("mycircle") # Keyword arguments can be supplied in place of selector dict p.select({"name": "foo", "type": HoverTool}) p.select(name="foo", type=HoverTool) ''' selector = _select_helper(args, kwargs) # Want to pass selector that is a dictionary return _list_attr_splat(find(self.references(), selector, {'plot': self}))
[ "def", "select", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "selector", "=", "_select_helper", "(", "args", ",", "kwargs", ")", "# Want to pass selector that is a dictionary", "return", "_list_attr_splat", "(", "find", "(", "self", ".", "references", "(", ")", ",", "selector", ",", "{", "'plot'", ":", "self", "}", ")", ")" ]
Query this object and all of its references for objects that match the given selector. There are a few different ways to call the ``select`` method. The most general is to supply a JSON-like query dictionary as the single argument or as keyword arguments: Args: selector (JSON-like) : some sample text Keyword Arguments: kwargs : query dict key/values as keyword arguments Additionally, for compatibility with ``Model.select``, a selector dict may be passed as ``selector`` keyword argument, in which case the value of ``kwargs['selector']`` is used for the query. For convenience, queries on just names can be made by supplying the ``name`` string as the single parameter: Args: name (str) : the name to query on Also queries on just type can be made simply by supplying the ``Model`` subclass as the single parameter: Args: type (Model) : the type to query on Returns: seq[Model] Examples: .. code-block:: python # These three are equivalent p.select(selector={"type": HoverTool}) p.select({"type": HoverTool}) p.select(HoverTool) # These two are also equivalent p.select({"name": "mycircle"}) p.select("mycircle") # Keyword arguments can be supplied in place of selector dict p.select({"name": "foo", "type": HoverTool}) p.select(name="foo", type=HoverTool)
[ "Query", "this", "object", "and", "all", "of", "its", "references", "for", "objects", "that", "match", "the", "given", "selector", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/plots.py#L69-L124
train
bokeh/bokeh
bokeh/models/plots.py
Plot.legend
def legend(self): ''' Splattable list of :class:`~bokeh.models.annotations.Legend` objects. ''' panels = self.above + self.below + self.left + self.right + self.center legends = [obj for obj in panels if isinstance(obj, Legend)] return _legend_attr_splat(legends)
python
def legend(self): ''' Splattable list of :class:`~bokeh.models.annotations.Legend` objects. ''' panels = self.above + self.below + self.left + self.right + self.center legends = [obj for obj in panels if isinstance(obj, Legend)] return _legend_attr_splat(legends)
[ "def", "legend", "(", "self", ")", ":", "panels", "=", "self", ".", "above", "+", "self", ".", "below", "+", "self", ".", "left", "+", "self", ".", "right", "+", "self", ".", "center", "legends", "=", "[", "obj", "for", "obj", "in", "panels", "if", "isinstance", "(", "obj", ",", "Legend", ")", "]", "return", "_legend_attr_splat", "(", "legends", ")" ]
Splattable list of :class:`~bokeh.models.annotations.Legend` objects.
[ "Splattable", "list", "of", ":", "class", ":", "~bokeh", ".", "models", ".", "annotations", ".", "Legend", "objects", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/plots.py#L181-L187
train
bokeh/bokeh
bokeh/models/plots.py
Plot.hover
def hover(self): ''' Splattable list of :class:`~bokeh.models.tools.HoverTool` objects. ''' hovers = [obj for obj in self.tools if isinstance(obj, HoverTool)] return _list_attr_splat(hovers)
python
def hover(self): ''' Splattable list of :class:`~bokeh.models.tools.HoverTool` objects. ''' hovers = [obj for obj in self.tools if isinstance(obj, HoverTool)] return _list_attr_splat(hovers)
[ "def", "hover", "(", "self", ")", ":", "hovers", "=", "[", "obj", "for", "obj", "in", "self", ".", "tools", "if", "isinstance", "(", "obj", ",", "HoverTool", ")", "]", "return", "_list_attr_splat", "(", "hovers", ")" ]
Splattable list of :class:`~bokeh.models.tools.HoverTool` objects.
[ "Splattable", "list", "of", ":", "class", ":", "~bokeh", ".", "models", ".", "tools", ".", "HoverTool", "objects", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/plots.py#L190-L195
train
bokeh/bokeh
bokeh/models/plots.py
Plot.add_layout
def add_layout(self, obj, place='center'): ''' Adds an object to the plot in a specified place. Args: obj (Renderer) : the object to add to the Plot place (str, optional) : where to add the object (default: 'center') Valid places are: 'left', 'right', 'above', 'below', 'center'. Returns: None ''' valid_places = ['left', 'right', 'above', 'below', 'center'] if place not in valid_places: raise ValueError( "Invalid place '%s' specified. Valid place values are: %s" % (place, nice_join(valid_places)) ) getattr(self, place).append(obj)
python
def add_layout(self, obj, place='center'): ''' Adds an object to the plot in a specified place. Args: obj (Renderer) : the object to add to the Plot place (str, optional) : where to add the object (default: 'center') Valid places are: 'left', 'right', 'above', 'below', 'center'. Returns: None ''' valid_places = ['left', 'right', 'above', 'below', 'center'] if place not in valid_places: raise ValueError( "Invalid place '%s' specified. Valid place values are: %s" % (place, nice_join(valid_places)) ) getattr(self, place).append(obj)
[ "def", "add_layout", "(", "self", ",", "obj", ",", "place", "=", "'center'", ")", ":", "valid_places", "=", "[", "'left'", ",", "'right'", ",", "'above'", ",", "'below'", ",", "'center'", "]", "if", "place", "not", "in", "valid_places", ":", "raise", "ValueError", "(", "\"Invalid place '%s' specified. Valid place values are: %s\"", "%", "(", "place", ",", "nice_join", "(", "valid_places", ")", ")", ")", "getattr", "(", "self", ",", "place", ")", ".", "append", "(", "obj", ")" ]
Adds an object to the plot in a specified place. Args: obj (Renderer) : the object to add to the Plot place (str, optional) : where to add the object (default: 'center') Valid places are: 'left', 'right', 'above', 'below', 'center'. Returns: None
[ "Adds", "an", "object", "to", "the", "plot", "in", "a", "specified", "place", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/plots.py#L230-L248
train
bokeh/bokeh
bokeh/models/plots.py
Plot.add_tools
def add_tools(self, *tools): ''' Adds tools to the plot. Args: *tools (Tool) : the tools to add to the Plot Returns: None ''' for tool in tools: if not isinstance(tool, Tool): raise ValueError("All arguments to add_tool must be Tool subclasses.") self.toolbar.tools.append(tool)
python
def add_tools(self, *tools): ''' Adds tools to the plot. Args: *tools (Tool) : the tools to add to the Plot Returns: None ''' for tool in tools: if not isinstance(tool, Tool): raise ValueError("All arguments to add_tool must be Tool subclasses.") self.toolbar.tools.append(tool)
[ "def", "add_tools", "(", "self", ",", "*", "tools", ")", ":", "for", "tool", "in", "tools", ":", "if", "not", "isinstance", "(", "tool", ",", "Tool", ")", ":", "raise", "ValueError", "(", "\"All arguments to add_tool must be Tool subclasses.\"", ")", "self", ".", "toolbar", ".", "tools", ".", "append", "(", "tool", ")" ]
Adds tools to the plot. Args: *tools (Tool) : the tools to add to the Plot Returns: None
[ "Adds", "tools", "to", "the", "plot", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/plots.py#L250-L264
train
bokeh/bokeh
bokeh/models/plots.py
Plot.add_glyph
def add_glyph(self, source_or_glyph, glyph=None, **kw): ''' Adds a glyph to the plot with associated data sources and ranges. This function will take care of creating and configuring a Glyph object, and then add it to the plot's list of renderers. Args: source (DataSource) : a data source for the glyphs to all use glyph (Glyph) : the glyph to add to the Plot Keyword Arguments: Any additional keyword arguments are passed on as-is to the Glyph initializer. Returns: GlyphRenderer ''' if glyph is not None: source = source_or_glyph else: source, glyph = ColumnDataSource(), source_or_glyph if not isinstance(source, DataSource): raise ValueError("'source' argument to add_glyph() must be DataSource subclass") if not isinstance(glyph, Glyph): raise ValueError("'glyph' argument to add_glyph() must be Glyph subclass") g = GlyphRenderer(data_source=source, glyph=glyph, **kw) self.renderers.append(g) return g
python
def add_glyph(self, source_or_glyph, glyph=None, **kw): ''' Adds a glyph to the plot with associated data sources and ranges. This function will take care of creating and configuring a Glyph object, and then add it to the plot's list of renderers. Args: source (DataSource) : a data source for the glyphs to all use glyph (Glyph) : the glyph to add to the Plot Keyword Arguments: Any additional keyword arguments are passed on as-is to the Glyph initializer. Returns: GlyphRenderer ''' if glyph is not None: source = source_or_glyph else: source, glyph = ColumnDataSource(), source_or_glyph if not isinstance(source, DataSource): raise ValueError("'source' argument to add_glyph() must be DataSource subclass") if not isinstance(glyph, Glyph): raise ValueError("'glyph' argument to add_glyph() must be Glyph subclass") g = GlyphRenderer(data_source=source, glyph=glyph, **kw) self.renderers.append(g) return g
[ "def", "add_glyph", "(", "self", ",", "source_or_glyph", ",", "glyph", "=", "None", ",", "*", "*", "kw", ")", ":", "if", "glyph", "is", "not", "None", ":", "source", "=", "source_or_glyph", "else", ":", "source", ",", "glyph", "=", "ColumnDataSource", "(", ")", ",", "source_or_glyph", "if", "not", "isinstance", "(", "source", ",", "DataSource", ")", ":", "raise", "ValueError", "(", "\"'source' argument to add_glyph() must be DataSource subclass\"", ")", "if", "not", "isinstance", "(", "glyph", ",", "Glyph", ")", ":", "raise", "ValueError", "(", "\"'glyph' argument to add_glyph() must be Glyph subclass\"", ")", "g", "=", "GlyphRenderer", "(", "data_source", "=", "source", ",", "glyph", "=", "glyph", ",", "*", "*", "kw", ")", "self", ".", "renderers", ".", "append", "(", "g", ")", "return", "g" ]
Adds a glyph to the plot with associated data sources and ranges. This function will take care of creating and configuring a Glyph object, and then add it to the plot's list of renderers. Args: source (DataSource) : a data source for the glyphs to all use glyph (Glyph) : the glyph to add to the Plot Keyword Arguments: Any additional keyword arguments are passed on as-is to the Glyph initializer. Returns: GlyphRenderer
[ "Adds", "a", "glyph", "to", "the", "plot", "with", "associated", "data", "sources", "and", "ranges", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/plots.py#L266-L298
train
bokeh/bokeh
bokeh/models/plots.py
Plot.add_tile
def add_tile(self, tile_source, **kw): ''' Adds new ``TileRenderer`` into ``Plot.renderers`` Args: tile_source (TileSource) : a tile source instance which contain tileset configuration Keyword Arguments: Additional keyword arguments are passed on as-is to the tile renderer Returns: TileRenderer : TileRenderer ''' tile_renderer = TileRenderer(tile_source=tile_source, **kw) self.renderers.append(tile_renderer) return tile_renderer
python
def add_tile(self, tile_source, **kw): ''' Adds new ``TileRenderer`` into ``Plot.renderers`` Args: tile_source (TileSource) : a tile source instance which contain tileset configuration Keyword Arguments: Additional keyword arguments are passed on as-is to the tile renderer Returns: TileRenderer : TileRenderer ''' tile_renderer = TileRenderer(tile_source=tile_source, **kw) self.renderers.append(tile_renderer) return tile_renderer
[ "def", "add_tile", "(", "self", ",", "tile_source", ",", "*", "*", "kw", ")", ":", "tile_renderer", "=", "TileRenderer", "(", "tile_source", "=", "tile_source", ",", "*", "*", "kw", ")", "self", ".", "renderers", ".", "append", "(", "tile_renderer", ")", "return", "tile_renderer" ]
Adds new ``TileRenderer`` into ``Plot.renderers`` Args: tile_source (TileSource) : a tile source instance which contain tileset configuration Keyword Arguments: Additional keyword arguments are passed on as-is to the tile renderer Returns: TileRenderer : TileRenderer
[ "Adds", "new", "TileRenderer", "into", "Plot", ".", "renderers" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/plots.py#L300-L315
train
bokeh/bokeh
bokeh/layouts.py
row
def row(*args, **kwargs): """ Create a row of Bokeh Layout objects. Forces all objects to have the same sizing_mode, which is required for complex layouts to work. Args: children (list of :class:`~bokeh.models.layouts.LayoutDOM` ): A list of instances for the row. Can be any of the following - :class:`~bokeh.models.plots.Plot`, :class:`~bokeh.models.widgets.widget.Widget`, :class:`~bokeh.models.layouts.Row`, :class:`~bokeh.models.layouts.Column`, :class:`~bokeh.models.tools.ToolbarBox`, :class:`~bokeh.models.layouts.Spacer`. sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How will the items in the layout resize to fill the available space. Default is ``"fixed"``. For more information on the different modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode` description on :class:`~bokeh.models.layouts.LayoutDOM`. Returns: Row: A row of LayoutDOM objects all with the same sizing_mode. Examples: >>> row([plot_1, plot_2]) >>> row(children=[widget_box_1, plot_1], sizing_mode='stretch_both') """ sizing_mode = kwargs.pop('sizing_mode', None) children = kwargs.pop('children', None) children = _handle_children(*args, children=children) row_children = [] for item in children: if isinstance(item, LayoutDOM): if sizing_mode is not None and _has_auto_sizing(item): item.sizing_mode = sizing_mode row_children.append(item) else: raise ValueError("""Only LayoutDOM items can be inserted into a row. Tried to insert: %s of type %s""" % (item, type(item))) return Row(children=row_children, sizing_mode=sizing_mode, **kwargs)
python
def row(*args, **kwargs): """ Create a row of Bokeh Layout objects. Forces all objects to have the same sizing_mode, which is required for complex layouts to work. Args: children (list of :class:`~bokeh.models.layouts.LayoutDOM` ): A list of instances for the row. Can be any of the following - :class:`~bokeh.models.plots.Plot`, :class:`~bokeh.models.widgets.widget.Widget`, :class:`~bokeh.models.layouts.Row`, :class:`~bokeh.models.layouts.Column`, :class:`~bokeh.models.tools.ToolbarBox`, :class:`~bokeh.models.layouts.Spacer`. sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How will the items in the layout resize to fill the available space. Default is ``"fixed"``. For more information on the different modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode` description on :class:`~bokeh.models.layouts.LayoutDOM`. Returns: Row: A row of LayoutDOM objects all with the same sizing_mode. Examples: >>> row([plot_1, plot_2]) >>> row(children=[widget_box_1, plot_1], sizing_mode='stretch_both') """ sizing_mode = kwargs.pop('sizing_mode', None) children = kwargs.pop('children', None) children = _handle_children(*args, children=children) row_children = [] for item in children: if isinstance(item, LayoutDOM): if sizing_mode is not None and _has_auto_sizing(item): item.sizing_mode = sizing_mode row_children.append(item) else: raise ValueError("""Only LayoutDOM items can be inserted into a row. Tried to insert: %s of type %s""" % (item, type(item))) return Row(children=row_children, sizing_mode=sizing_mode, **kwargs)
[ "def", "row", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "sizing_mode", "=", "kwargs", ".", "pop", "(", "'sizing_mode'", ",", "None", ")", "children", "=", "kwargs", ".", "pop", "(", "'children'", ",", "None", ")", "children", "=", "_handle_children", "(", "*", "args", ",", "children", "=", "children", ")", "row_children", "=", "[", "]", "for", "item", "in", "children", ":", "if", "isinstance", "(", "item", ",", "LayoutDOM", ")", ":", "if", "sizing_mode", "is", "not", "None", "and", "_has_auto_sizing", "(", "item", ")", ":", "item", ".", "sizing_mode", "=", "sizing_mode", "row_children", ".", "append", "(", "item", ")", "else", ":", "raise", "ValueError", "(", "\"\"\"Only LayoutDOM items can be inserted into a row. Tried to insert: %s of type %s\"\"\"", "%", "(", "item", ",", "type", "(", "item", ")", ")", ")", "return", "Row", "(", "children", "=", "row_children", ",", "sizing_mode", "=", "sizing_mode", ",", "*", "*", "kwargs", ")" ]
Create a row of Bokeh Layout objects. Forces all objects to have the same sizing_mode, which is required for complex layouts to work. Args: children (list of :class:`~bokeh.models.layouts.LayoutDOM` ): A list of instances for the row. Can be any of the following - :class:`~bokeh.models.plots.Plot`, :class:`~bokeh.models.widgets.widget.Widget`, :class:`~bokeh.models.layouts.Row`, :class:`~bokeh.models.layouts.Column`, :class:`~bokeh.models.tools.ToolbarBox`, :class:`~bokeh.models.layouts.Spacer`. sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How will the items in the layout resize to fill the available space. Default is ``"fixed"``. For more information on the different modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode` description on :class:`~bokeh.models.layouts.LayoutDOM`. Returns: Row: A row of LayoutDOM objects all with the same sizing_mode. Examples: >>> row([plot_1, plot_2]) >>> row(children=[widget_box_1, plot_1], sizing_mode='stretch_both')
[ "Create", "a", "row", "of", "Bokeh", "Layout", "objects", ".", "Forces", "all", "objects", "to", "have", "the", "same", "sizing_mode", "which", "is", "required", "for", "complex", "layouts", "to", "work", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/layouts.py#L55-L97
train
bokeh/bokeh
bokeh/layouts.py
column
def column(*args, **kwargs): """ Create a column of Bokeh Layout objects. Forces all objects to have the same sizing_mode, which is required for complex layouts to work. Args: children (list of :class:`~bokeh.models.layouts.LayoutDOM` ): A list of instances for the column. Can be any of the following - :class:`~bokeh.models.plots.Plot`, :class:`~bokeh.models.widgets.widget.Widget`, :class:`~bokeh.models.layouts.Row`, :class:`~bokeh.models.layouts.Column`, :class:`~bokeh.models.tools.ToolbarBox`, :class:`~bokeh.models.layouts.Spacer`. sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How will the items in the layout resize to fill the available space. Default is ``"fixed"``. For more information on the different modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode` description on :class:`~bokeh.models.layouts.LayoutDOM`. Returns: Column: A column of LayoutDOM objects all with the same sizing_mode. Examples: >>> column([plot_1, plot_2]) >>> column(children=[widget_1, plot_1], sizing_mode='stretch_both') """ sizing_mode = kwargs.pop('sizing_mode', None) children = kwargs.pop('children', None) children = _handle_children(*args, children=children) col_children = [] for item in children: if isinstance(item, LayoutDOM): if sizing_mode is not None and _has_auto_sizing(item): item.sizing_mode = sizing_mode col_children.append(item) else: raise ValueError("""Only LayoutDOM items can be inserted into a column. Tried to insert: %s of type %s""" % (item, type(item))) return Column(children=col_children, sizing_mode=sizing_mode, **kwargs)
python
def column(*args, **kwargs): """ Create a column of Bokeh Layout objects. Forces all objects to have the same sizing_mode, which is required for complex layouts to work. Args: children (list of :class:`~bokeh.models.layouts.LayoutDOM` ): A list of instances for the column. Can be any of the following - :class:`~bokeh.models.plots.Plot`, :class:`~bokeh.models.widgets.widget.Widget`, :class:`~bokeh.models.layouts.Row`, :class:`~bokeh.models.layouts.Column`, :class:`~bokeh.models.tools.ToolbarBox`, :class:`~bokeh.models.layouts.Spacer`. sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How will the items in the layout resize to fill the available space. Default is ``"fixed"``. For more information on the different modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode` description on :class:`~bokeh.models.layouts.LayoutDOM`. Returns: Column: A column of LayoutDOM objects all with the same sizing_mode. Examples: >>> column([plot_1, plot_2]) >>> column(children=[widget_1, plot_1], sizing_mode='stretch_both') """ sizing_mode = kwargs.pop('sizing_mode', None) children = kwargs.pop('children', None) children = _handle_children(*args, children=children) col_children = [] for item in children: if isinstance(item, LayoutDOM): if sizing_mode is not None and _has_auto_sizing(item): item.sizing_mode = sizing_mode col_children.append(item) else: raise ValueError("""Only LayoutDOM items can be inserted into a column. Tried to insert: %s of type %s""" % (item, type(item))) return Column(children=col_children, sizing_mode=sizing_mode, **kwargs)
[ "def", "column", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "sizing_mode", "=", "kwargs", ".", "pop", "(", "'sizing_mode'", ",", "None", ")", "children", "=", "kwargs", ".", "pop", "(", "'children'", ",", "None", ")", "children", "=", "_handle_children", "(", "*", "args", ",", "children", "=", "children", ")", "col_children", "=", "[", "]", "for", "item", "in", "children", ":", "if", "isinstance", "(", "item", ",", "LayoutDOM", ")", ":", "if", "sizing_mode", "is", "not", "None", "and", "_has_auto_sizing", "(", "item", ")", ":", "item", ".", "sizing_mode", "=", "sizing_mode", "col_children", ".", "append", "(", "item", ")", "else", ":", "raise", "ValueError", "(", "\"\"\"Only LayoutDOM items can be inserted into a column. Tried to insert: %s of type %s\"\"\"", "%", "(", "item", ",", "type", "(", "item", ")", ")", ")", "return", "Column", "(", "children", "=", "col_children", ",", "sizing_mode", "=", "sizing_mode", ",", "*", "*", "kwargs", ")" ]
Create a column of Bokeh Layout objects. Forces all objects to have the same sizing_mode, which is required for complex layouts to work. Args: children (list of :class:`~bokeh.models.layouts.LayoutDOM` ): A list of instances for the column. Can be any of the following - :class:`~bokeh.models.plots.Plot`, :class:`~bokeh.models.widgets.widget.Widget`, :class:`~bokeh.models.layouts.Row`, :class:`~bokeh.models.layouts.Column`, :class:`~bokeh.models.tools.ToolbarBox`, :class:`~bokeh.models.layouts.Spacer`. sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How will the items in the layout resize to fill the available space. Default is ``"fixed"``. For more information on the different modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode` description on :class:`~bokeh.models.layouts.LayoutDOM`. Returns: Column: A column of LayoutDOM objects all with the same sizing_mode. Examples: >>> column([plot_1, plot_2]) >>> column(children=[widget_1, plot_1], sizing_mode='stretch_both')
[ "Create", "a", "column", "of", "Bokeh", "Layout", "objects", ".", "Forces", "all", "objects", "to", "have", "the", "same", "sizing_mode", "which", "is", "required", "for", "complex", "layouts", "to", "work", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/layouts.py#L100-L142
train
bokeh/bokeh
bokeh/layouts.py
widgetbox
def widgetbox(*args, **kwargs): """ Create a column of bokeh widgets with predefined styling. Args: children (list of :class:`~bokeh.models.widgets.widget.Widget`): A list of widgets. sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How will the items in the layout resize to fill the available space. Default is ``"fixed"``. For more information on the different modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode` description on :class:`~bokeh.models.layouts.LayoutDOM`. Returns: WidgetBox: A column layout of widget instances all with the same ``sizing_mode``. Examples: >>> widgetbox([button, select]) >>> widgetbox(children=[slider], sizing_mode='scale_width') """ sizing_mode = kwargs.pop('sizing_mode', None) children = kwargs.pop('children', None) children = _handle_children(*args, children=children) col_children = [] for item in children: if isinstance(item, LayoutDOM): if sizing_mode is not None and _has_auto_sizing(item): item.sizing_mode = sizing_mode col_children.append(item) else: raise ValueError("""Only LayoutDOM items can be inserted into a widget box. Tried to insert: %s of type %s""" % (item, type(item))) return WidgetBox(children=col_children, sizing_mode=sizing_mode, **kwargs)
python
def widgetbox(*args, **kwargs): """ Create a column of bokeh widgets with predefined styling. Args: children (list of :class:`~bokeh.models.widgets.widget.Widget`): A list of widgets. sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How will the items in the layout resize to fill the available space. Default is ``"fixed"``. For more information on the different modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode` description on :class:`~bokeh.models.layouts.LayoutDOM`. Returns: WidgetBox: A column layout of widget instances all with the same ``sizing_mode``. Examples: >>> widgetbox([button, select]) >>> widgetbox(children=[slider], sizing_mode='scale_width') """ sizing_mode = kwargs.pop('sizing_mode', None) children = kwargs.pop('children', None) children = _handle_children(*args, children=children) col_children = [] for item in children: if isinstance(item, LayoutDOM): if sizing_mode is not None and _has_auto_sizing(item): item.sizing_mode = sizing_mode col_children.append(item) else: raise ValueError("""Only LayoutDOM items can be inserted into a widget box. Tried to insert: %s of type %s""" % (item, type(item))) return WidgetBox(children=col_children, sizing_mode=sizing_mode, **kwargs)
[ "def", "widgetbox", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "sizing_mode", "=", "kwargs", ".", "pop", "(", "'sizing_mode'", ",", "None", ")", "children", "=", "kwargs", ".", "pop", "(", "'children'", ",", "None", ")", "children", "=", "_handle_children", "(", "*", "args", ",", "children", "=", "children", ")", "col_children", "=", "[", "]", "for", "item", "in", "children", ":", "if", "isinstance", "(", "item", ",", "LayoutDOM", ")", ":", "if", "sizing_mode", "is", "not", "None", "and", "_has_auto_sizing", "(", "item", ")", ":", "item", ".", "sizing_mode", "=", "sizing_mode", "col_children", ".", "append", "(", "item", ")", "else", ":", "raise", "ValueError", "(", "\"\"\"Only LayoutDOM items can be inserted into a widget box. Tried to insert: %s of type %s\"\"\"", "%", "(", "item", ",", "type", "(", "item", ")", ")", ")", "return", "WidgetBox", "(", "children", "=", "col_children", ",", "sizing_mode", "=", "sizing_mode", ",", "*", "*", "kwargs", ")" ]
Create a column of bokeh widgets with predefined styling. Args: children (list of :class:`~bokeh.models.widgets.widget.Widget`): A list of widgets. sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How will the items in the layout resize to fill the available space. Default is ``"fixed"``. For more information on the different modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode` description on :class:`~bokeh.models.layouts.LayoutDOM`. Returns: WidgetBox: A column layout of widget instances all with the same ``sizing_mode``. Examples: >>> widgetbox([button, select]) >>> widgetbox(children=[slider], sizing_mode='scale_width')
[ "Create", "a", "column", "of", "bokeh", "widgets", "with", "predefined", "styling", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/layouts.py#L145-L179
train
bokeh/bokeh
bokeh/layouts.py
layout
def layout(*args, **kwargs): """ Create a grid-based arrangement of Bokeh Layout objects. Args: children (list of lists of :class:`~bokeh.models.layouts.LayoutDOM` ): A list of lists of instances for a grid layout. Can be any of the following - :class:`~bokeh.models.plots.Plot`, :class:`~bokeh.models.widgets.widget.Widget`, :class:`~bokeh.models.layouts.Row`, :class:`~bokeh.models.layouts.Column`, :class:`~bokeh.models.tools.ToolbarBox`, :class:`~bokeh.models.layouts.Spacer`. sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How will the items in the layout resize to fill the available space. Default is ``"fixed"``. For more information on the different modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode` description on :class:`~bokeh.models.layouts.LayoutDOM`. Returns: Column: A column of ``Row`` layouts of the children, all with the same sizing_mode. Examples: >>> layout([[plot_1, plot_2], [plot_3, plot_4]]) >>> layout( children=[ [widget_1, plot_1], [slider], [widget_2, plot_2, plot_3] ], sizing_mode='fixed', ) """ sizing_mode = kwargs.pop('sizing_mode', None) children = kwargs.pop('children', None) children = _handle_children(*args, children=children) # Make the grid return _create_grid(children, sizing_mode)
python
def layout(*args, **kwargs): """ Create a grid-based arrangement of Bokeh Layout objects. Args: children (list of lists of :class:`~bokeh.models.layouts.LayoutDOM` ): A list of lists of instances for a grid layout. Can be any of the following - :class:`~bokeh.models.plots.Plot`, :class:`~bokeh.models.widgets.widget.Widget`, :class:`~bokeh.models.layouts.Row`, :class:`~bokeh.models.layouts.Column`, :class:`~bokeh.models.tools.ToolbarBox`, :class:`~bokeh.models.layouts.Spacer`. sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How will the items in the layout resize to fill the available space. Default is ``"fixed"``. For more information on the different modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode` description on :class:`~bokeh.models.layouts.LayoutDOM`. Returns: Column: A column of ``Row`` layouts of the children, all with the same sizing_mode. Examples: >>> layout([[plot_1, plot_2], [plot_3, plot_4]]) >>> layout( children=[ [widget_1, plot_1], [slider], [widget_2, plot_2, plot_3] ], sizing_mode='fixed', ) """ sizing_mode = kwargs.pop('sizing_mode', None) children = kwargs.pop('children', None) children = _handle_children(*args, children=children) # Make the grid return _create_grid(children, sizing_mode)
[ "def", "layout", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "sizing_mode", "=", "kwargs", ".", "pop", "(", "'sizing_mode'", ",", "None", ")", "children", "=", "kwargs", ".", "pop", "(", "'children'", ",", "None", ")", "children", "=", "_handle_children", "(", "*", "args", ",", "children", "=", "children", ")", "# Make the grid", "return", "_create_grid", "(", "children", ",", "sizing_mode", ")" ]
Create a grid-based arrangement of Bokeh Layout objects. Args: children (list of lists of :class:`~bokeh.models.layouts.LayoutDOM` ): A list of lists of instances for a grid layout. Can be any of the following - :class:`~bokeh.models.plots.Plot`, :class:`~bokeh.models.widgets.widget.Widget`, :class:`~bokeh.models.layouts.Row`, :class:`~bokeh.models.layouts.Column`, :class:`~bokeh.models.tools.ToolbarBox`, :class:`~bokeh.models.layouts.Spacer`. sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How will the items in the layout resize to fill the available space. Default is ``"fixed"``. For more information on the different modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode` description on :class:`~bokeh.models.layouts.LayoutDOM`. Returns: Column: A column of ``Row`` layouts of the children, all with the same sizing_mode. Examples: >>> layout([[plot_1, plot_2], [plot_3, plot_4]]) >>> layout( children=[ [widget_1, plot_1], [slider], [widget_2, plot_2, plot_3] ], sizing_mode='fixed', )
[ "Create", "a", "grid", "-", "based", "arrangement", "of", "Bokeh", "Layout", "objects", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/layouts.py#L182-L222
train
bokeh/bokeh
bokeh/layouts.py
gridplot
def gridplot(children, sizing_mode=None, toolbar_location='above', ncols=None, plot_width=None, plot_height=None, toolbar_options=None, merge_tools=True): ''' Create a grid of plots rendered on separate canvases. The ``gridplot`` function builds a single toolbar for all the plots in the grid. ``gridplot`` is designed to layout a set of plots. For general grid layout, use the :func:`~bokeh.layouts.layout` function. Args: children (list of lists of :class:`~bokeh.models.plots.Plot` ): An array of plots to display in a grid, given as a list of lists of Plot objects. To leave a position in the grid empty, pass None for that position in the children list. OR list of :class:`~bokeh.models.plots.Plot` if called with ncols. OR an instance of GridSpec. sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How will the items in the layout resize to fill the available space. Default is ``"fixed"``. For more information on the different modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode` description on :class:`~bokeh.models.layouts.LayoutDOM`. toolbar_location (``above``, ``below``, ``left``, ``right`` ): Where the toolbar will be located, with respect to the grid. Default is ``above``. If set to None, no toolbar will be attached to the grid. ncols (int, optional): Specify the number of columns you would like in your grid. You must only pass an un-nested list of plots (as opposed to a list of lists of plots) when using ncols. plot_width (int, optional): The width you would like all your plots to be plot_height (int, optional): The height you would like all your plots to be. toolbar_options (dict, optional) : A dictionary of options that will be used to construct the grid's toolbar (an instance of :class:`~bokeh.models.tools.ToolbarBox`). If none is supplied, ToolbarBox's defaults will be used. merge_tools (``True``, ``False``): Combine tools from all child plots into a single toolbar. Returns: Row or Column: A row or column containing the grid toolbar and the grid of plots (depending on whether the toolbar is left/right or above/below. The grid is always a Column of Rows of plots. Examples: >>> gridplot([[plot_1, plot_2], [plot_3, plot_4]]) >>> gridplot([plot_1, plot_2, plot_3, plot_4], ncols=2, plot_width=200, plot_height=100) >>> gridplot( children=[[plot_1, plot_2], [None, plot_3]], toolbar_location='right' sizing_mode='fixed', toolbar_options=dict(logo='gray') ) ''' if toolbar_options is None: toolbar_options = {} if toolbar_location: if not hasattr(Location, toolbar_location): raise ValueError("Invalid value of toolbar_location: %s" % toolbar_location) children = _handle_children(children=children) if ncols: if any(isinstance(child, list) for child in children): raise ValueError("Cannot provide a nested list when using ncols") children = list(_chunks(children, ncols)) # Additional children set-up for grid plot if not children: children = [] # Make the grid tools = [] items = [] for y, row in enumerate(children): for x, item in enumerate(row): if item is None: continue elif isinstance(item, LayoutDOM): if merge_tools: for plot in item.select(dict(type=Plot)): tools += plot.toolbar.tools plot.toolbar_location = None if isinstance(item, Plot): if plot_width is not None: item.plot_width = plot_width if plot_height is not None: item.plot_height = plot_height if sizing_mode is not None and _has_auto_sizing(item): item.sizing_mode = sizing_mode items.append((item, y, x)) else: raise ValueError("Only LayoutDOM items can be inserted into a grid") if not merge_tools or not toolbar_location: return GridBox(children=items, sizing_mode=sizing_mode) grid = GridBox(children=items) proxy = ProxyToolbar(tools=tools, **toolbar_options) toolbar = ToolbarBox(toolbar=proxy, toolbar_location=toolbar_location) if toolbar_location == 'above': return Column(children=[toolbar, grid], sizing_mode=sizing_mode) elif toolbar_location == 'below': return Column(children=[grid, toolbar], sizing_mode=sizing_mode) elif toolbar_location == 'left': return Row(children=[toolbar, grid], sizing_mode=sizing_mode) elif toolbar_location == 'right': return Row(children=[grid, toolbar], sizing_mode=sizing_mode)
python
def gridplot(children, sizing_mode=None, toolbar_location='above', ncols=None, plot_width=None, plot_height=None, toolbar_options=None, merge_tools=True): ''' Create a grid of plots rendered on separate canvases. The ``gridplot`` function builds a single toolbar for all the plots in the grid. ``gridplot`` is designed to layout a set of plots. For general grid layout, use the :func:`~bokeh.layouts.layout` function. Args: children (list of lists of :class:`~bokeh.models.plots.Plot` ): An array of plots to display in a grid, given as a list of lists of Plot objects. To leave a position in the grid empty, pass None for that position in the children list. OR list of :class:`~bokeh.models.plots.Plot` if called with ncols. OR an instance of GridSpec. sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How will the items in the layout resize to fill the available space. Default is ``"fixed"``. For more information on the different modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode` description on :class:`~bokeh.models.layouts.LayoutDOM`. toolbar_location (``above``, ``below``, ``left``, ``right`` ): Where the toolbar will be located, with respect to the grid. Default is ``above``. If set to None, no toolbar will be attached to the grid. ncols (int, optional): Specify the number of columns you would like in your grid. You must only pass an un-nested list of plots (as opposed to a list of lists of plots) when using ncols. plot_width (int, optional): The width you would like all your plots to be plot_height (int, optional): The height you would like all your plots to be. toolbar_options (dict, optional) : A dictionary of options that will be used to construct the grid's toolbar (an instance of :class:`~bokeh.models.tools.ToolbarBox`). If none is supplied, ToolbarBox's defaults will be used. merge_tools (``True``, ``False``): Combine tools from all child plots into a single toolbar. Returns: Row or Column: A row or column containing the grid toolbar and the grid of plots (depending on whether the toolbar is left/right or above/below. The grid is always a Column of Rows of plots. Examples: >>> gridplot([[plot_1, plot_2], [plot_3, plot_4]]) >>> gridplot([plot_1, plot_2, plot_3, plot_4], ncols=2, plot_width=200, plot_height=100) >>> gridplot( children=[[plot_1, plot_2], [None, plot_3]], toolbar_location='right' sizing_mode='fixed', toolbar_options=dict(logo='gray') ) ''' if toolbar_options is None: toolbar_options = {} if toolbar_location: if not hasattr(Location, toolbar_location): raise ValueError("Invalid value of toolbar_location: %s" % toolbar_location) children = _handle_children(children=children) if ncols: if any(isinstance(child, list) for child in children): raise ValueError("Cannot provide a nested list when using ncols") children = list(_chunks(children, ncols)) # Additional children set-up for grid plot if not children: children = [] # Make the grid tools = [] items = [] for y, row in enumerate(children): for x, item in enumerate(row): if item is None: continue elif isinstance(item, LayoutDOM): if merge_tools: for plot in item.select(dict(type=Plot)): tools += plot.toolbar.tools plot.toolbar_location = None if isinstance(item, Plot): if plot_width is not None: item.plot_width = plot_width if plot_height is not None: item.plot_height = plot_height if sizing_mode is not None and _has_auto_sizing(item): item.sizing_mode = sizing_mode items.append((item, y, x)) else: raise ValueError("Only LayoutDOM items can be inserted into a grid") if not merge_tools or not toolbar_location: return GridBox(children=items, sizing_mode=sizing_mode) grid = GridBox(children=items) proxy = ProxyToolbar(tools=tools, **toolbar_options) toolbar = ToolbarBox(toolbar=proxy, toolbar_location=toolbar_location) if toolbar_location == 'above': return Column(children=[toolbar, grid], sizing_mode=sizing_mode) elif toolbar_location == 'below': return Column(children=[grid, toolbar], sizing_mode=sizing_mode) elif toolbar_location == 'left': return Row(children=[toolbar, grid], sizing_mode=sizing_mode) elif toolbar_location == 'right': return Row(children=[grid, toolbar], sizing_mode=sizing_mode)
[ "def", "gridplot", "(", "children", ",", "sizing_mode", "=", "None", ",", "toolbar_location", "=", "'above'", ",", "ncols", "=", "None", ",", "plot_width", "=", "None", ",", "plot_height", "=", "None", ",", "toolbar_options", "=", "None", ",", "merge_tools", "=", "True", ")", ":", "if", "toolbar_options", "is", "None", ":", "toolbar_options", "=", "{", "}", "if", "toolbar_location", ":", "if", "not", "hasattr", "(", "Location", ",", "toolbar_location", ")", ":", "raise", "ValueError", "(", "\"Invalid value of toolbar_location: %s\"", "%", "toolbar_location", ")", "children", "=", "_handle_children", "(", "children", "=", "children", ")", "if", "ncols", ":", "if", "any", "(", "isinstance", "(", "child", ",", "list", ")", "for", "child", "in", "children", ")", ":", "raise", "ValueError", "(", "\"Cannot provide a nested list when using ncols\"", ")", "children", "=", "list", "(", "_chunks", "(", "children", ",", "ncols", ")", ")", "# Additional children set-up for grid plot", "if", "not", "children", ":", "children", "=", "[", "]", "# Make the grid", "tools", "=", "[", "]", "items", "=", "[", "]", "for", "y", ",", "row", "in", "enumerate", "(", "children", ")", ":", "for", "x", ",", "item", "in", "enumerate", "(", "row", ")", ":", "if", "item", "is", "None", ":", "continue", "elif", "isinstance", "(", "item", ",", "LayoutDOM", ")", ":", "if", "merge_tools", ":", "for", "plot", "in", "item", ".", "select", "(", "dict", "(", "type", "=", "Plot", ")", ")", ":", "tools", "+=", "plot", ".", "toolbar", ".", "tools", "plot", ".", "toolbar_location", "=", "None", "if", "isinstance", "(", "item", ",", "Plot", ")", ":", "if", "plot_width", "is", "not", "None", ":", "item", ".", "plot_width", "=", "plot_width", "if", "plot_height", "is", "not", "None", ":", "item", ".", "plot_height", "=", "plot_height", "if", "sizing_mode", "is", "not", "None", "and", "_has_auto_sizing", "(", "item", ")", ":", "item", ".", "sizing_mode", "=", "sizing_mode", "items", ".", "append", "(", "(", "item", ",", "y", ",", "x", ")", ")", "else", ":", "raise", "ValueError", "(", "\"Only LayoutDOM items can be inserted into a grid\"", ")", "if", "not", "merge_tools", "or", "not", "toolbar_location", ":", "return", "GridBox", "(", "children", "=", "items", ",", "sizing_mode", "=", "sizing_mode", ")", "grid", "=", "GridBox", "(", "children", "=", "items", ")", "proxy", "=", "ProxyToolbar", "(", "tools", "=", "tools", ",", "*", "*", "toolbar_options", ")", "toolbar", "=", "ToolbarBox", "(", "toolbar", "=", "proxy", ",", "toolbar_location", "=", "toolbar_location", ")", "if", "toolbar_location", "==", "'above'", ":", "return", "Column", "(", "children", "=", "[", "toolbar", ",", "grid", "]", ",", "sizing_mode", "=", "sizing_mode", ")", "elif", "toolbar_location", "==", "'below'", ":", "return", "Column", "(", "children", "=", "[", "grid", ",", "toolbar", "]", ",", "sizing_mode", "=", "sizing_mode", ")", "elif", "toolbar_location", "==", "'left'", ":", "return", "Row", "(", "children", "=", "[", "toolbar", ",", "grid", "]", ",", "sizing_mode", "=", "sizing_mode", ")", "elif", "toolbar_location", "==", "'right'", ":", "return", "Row", "(", "children", "=", "[", "grid", ",", "toolbar", "]", ",", "sizing_mode", "=", "sizing_mode", ")" ]
Create a grid of plots rendered on separate canvases. The ``gridplot`` function builds a single toolbar for all the plots in the grid. ``gridplot`` is designed to layout a set of plots. For general grid layout, use the :func:`~bokeh.layouts.layout` function. Args: children (list of lists of :class:`~bokeh.models.plots.Plot` ): An array of plots to display in a grid, given as a list of lists of Plot objects. To leave a position in the grid empty, pass None for that position in the children list. OR list of :class:`~bokeh.models.plots.Plot` if called with ncols. OR an instance of GridSpec. sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How will the items in the layout resize to fill the available space. Default is ``"fixed"``. For more information on the different modes see :attr:`~bokeh.models.layouts.LayoutDOM.sizing_mode` description on :class:`~bokeh.models.layouts.LayoutDOM`. toolbar_location (``above``, ``below``, ``left``, ``right`` ): Where the toolbar will be located, with respect to the grid. Default is ``above``. If set to None, no toolbar will be attached to the grid. ncols (int, optional): Specify the number of columns you would like in your grid. You must only pass an un-nested list of plots (as opposed to a list of lists of plots) when using ncols. plot_width (int, optional): The width you would like all your plots to be plot_height (int, optional): The height you would like all your plots to be. toolbar_options (dict, optional) : A dictionary of options that will be used to construct the grid's toolbar (an instance of :class:`~bokeh.models.tools.ToolbarBox`). If none is supplied, ToolbarBox's defaults will be used. merge_tools (``True``, ``False``): Combine tools from all child plots into a single toolbar. Returns: Row or Column: A row or column containing the grid toolbar and the grid of plots (depending on whether the toolbar is left/right or above/below. The grid is always a Column of Rows of plots. Examples: >>> gridplot([[plot_1, plot_2], [plot_3, plot_4]]) >>> gridplot([plot_1, plot_2, plot_3, plot_4], ncols=2, plot_width=200, plot_height=100) >>> gridplot( children=[[plot_1, plot_2], [None, plot_3]], toolbar_location='right' sizing_mode='fixed', toolbar_options=dict(logo='gray') )
[ "Create", "a", "grid", "of", "plots", "rendered", "on", "separate", "canvases", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/layouts.py#L224-L340
train
bokeh/bokeh
bokeh/layouts.py
grid
def grid(children=[], sizing_mode=None, nrows=None, ncols=None): """ Conveniently create a grid of layoutable objects. Grids are created by using ``GridBox`` model. This gives the most control over the layout of a grid, but is also tedious and may result in unreadable code in practical applications. ``grid()`` function remedies this by reducing the level of control, but in turn providing a more convenient API. Supported patterns: 1. Nested lists of layoutable objects. Assumes the top-level list represents a column and alternates between rows and columns in subsequent nesting levels. One can use ``None`` for padding purpose. >>> grid([p1, [[p2, p3], p4]]) GridBox(children=[ (p1, 0, 0, 1, 2), (p2, 1, 0, 1, 1), (p3, 2, 0, 1, 1), (p4, 1, 1, 2, 1), ]) 2. Nested ``Row`` and ``Column`` instances. Similar to the first pattern, just instead of using nested lists, it uses nested ``Row`` and ``Column`` models. This can be much more readable that the former. Note, however, that only models that don't have ``sizing_mode`` set are used. >>> grid(column(p1, row(column(p2, p3), p4))) GridBox(children=[ (p1, 0, 0, 1, 2), (p2, 1, 0, 1, 1), (p3, 2, 0, 1, 1), (p4, 1, 1, 2, 1), ]) 3. Flat list of layoutable objects. This requires ``nrows`` and/or ``ncols`` to be set. The input list will be rearranged into a 2D array accordingly. One can use ``None`` for padding purpose. >>> grid([p1, p2, p3, p4], ncols=2) GridBox(children=[ (p1, 0, 0, 1, 1), (p2, 0, 1, 1, 1), (p3, 1, 0, 1, 1), (p4, 1, 1, 1, 1), ]) """ row = namedtuple("row", ["children"]) col = namedtuple("col", ["children"]) def flatten(layout): Item = namedtuple("Item", ["layout", "r0", "c0", "r1", "c1"]) Grid = namedtuple("Grid", ["nrows", "ncols", "items"]) def gcd(a, b): a, b = abs(a), abs(b) while b != 0: a, b = b, a % b return a def lcm(a, *rest): for b in rest: a = (a*b) // gcd(a, b) return a nonempty = lambda child: child.nrows != 0 and child.ncols != 0 def _flatten(layout): if isinstance(layout, row): children = list(filter(nonempty, map(_flatten, layout.children))) if not children: return Grid(0, 0, []) nrows = lcm(*[ child.nrows for child in children ]) ncols = sum([ child.ncols for child in children ]) items = [] offset = 0 for child in children: factor = nrows//child.nrows for (layout, r0, c0, r1, c1) in child.items: items.append((layout, factor*r0, c0 + offset, factor*r1, c1 + offset)) offset += child.ncols return Grid(nrows, ncols, items) elif isinstance(layout, col): children = list(filter(nonempty, map(_flatten, layout.children))) if not children: return Grid(0, 0, []) nrows = sum([ child.nrows for child in children ]) ncols = lcm(*[ child.ncols for child in children ]) items = [] offset = 0 for child in children: factor = ncols//child.ncols for (layout, r0, c0, r1, c1) in child.items: items.append((layout, r0 + offset, factor*c0, r1 + offset, factor*c1)) offset += child.nrows return Grid(nrows, ncols, items) else: return Grid(1, 1, [Item(layout, 0, 0, 1, 1)]) grid = _flatten(layout) children = [] for (layout, r0, c0, r1, c1) in grid.items: if layout is not None: children.append((layout, r0, c0, r1 - r0, c1 - c0)) return GridBox(children=children) if isinstance(children, list): if nrows is not None or ncols is not None: N = len(children) if ncols is None: ncols = math.ceil(N/nrows) layout = col([ row(children[i:i+ncols]) for i in range(0, N, ncols) ]) else: def traverse(children, level=0): if isinstance(children, list): container = col if level % 2 == 0 else row return container([ traverse(child, level+1) for child in children ]) else: return children layout = traverse(children) elif isinstance(children, LayoutDOM): def is_usable(child): return _has_auto_sizing(child) and child.spacing == 0 def traverse(item, top_level=False): if isinstance(item, Box) and (top_level or is_usable(item)): container = col if isinstance(item, Column) else row return container(list(map(traverse, item.children))) else: return item layout = traverse(children, top_level=True) elif isinstance(children, string_types): raise NotImplementedError else: raise ValueError("expected a list, string or model") grid = flatten(layout) if sizing_mode is not None: grid.sizing_mode = sizing_mode for child in grid.children: layout = child[0] if _has_auto_sizing(layout): layout.sizing_mode = sizing_mode return grid
python
def grid(children=[], sizing_mode=None, nrows=None, ncols=None): """ Conveniently create a grid of layoutable objects. Grids are created by using ``GridBox`` model. This gives the most control over the layout of a grid, but is also tedious and may result in unreadable code in practical applications. ``grid()`` function remedies this by reducing the level of control, but in turn providing a more convenient API. Supported patterns: 1. Nested lists of layoutable objects. Assumes the top-level list represents a column and alternates between rows and columns in subsequent nesting levels. One can use ``None`` for padding purpose. >>> grid([p1, [[p2, p3], p4]]) GridBox(children=[ (p1, 0, 0, 1, 2), (p2, 1, 0, 1, 1), (p3, 2, 0, 1, 1), (p4, 1, 1, 2, 1), ]) 2. Nested ``Row`` and ``Column`` instances. Similar to the first pattern, just instead of using nested lists, it uses nested ``Row`` and ``Column`` models. This can be much more readable that the former. Note, however, that only models that don't have ``sizing_mode`` set are used. >>> grid(column(p1, row(column(p2, p3), p4))) GridBox(children=[ (p1, 0, 0, 1, 2), (p2, 1, 0, 1, 1), (p3, 2, 0, 1, 1), (p4, 1, 1, 2, 1), ]) 3. Flat list of layoutable objects. This requires ``nrows`` and/or ``ncols`` to be set. The input list will be rearranged into a 2D array accordingly. One can use ``None`` for padding purpose. >>> grid([p1, p2, p3, p4], ncols=2) GridBox(children=[ (p1, 0, 0, 1, 1), (p2, 0, 1, 1, 1), (p3, 1, 0, 1, 1), (p4, 1, 1, 1, 1), ]) """ row = namedtuple("row", ["children"]) col = namedtuple("col", ["children"]) def flatten(layout): Item = namedtuple("Item", ["layout", "r0", "c0", "r1", "c1"]) Grid = namedtuple("Grid", ["nrows", "ncols", "items"]) def gcd(a, b): a, b = abs(a), abs(b) while b != 0: a, b = b, a % b return a def lcm(a, *rest): for b in rest: a = (a*b) // gcd(a, b) return a nonempty = lambda child: child.nrows != 0 and child.ncols != 0 def _flatten(layout): if isinstance(layout, row): children = list(filter(nonempty, map(_flatten, layout.children))) if not children: return Grid(0, 0, []) nrows = lcm(*[ child.nrows for child in children ]) ncols = sum([ child.ncols for child in children ]) items = [] offset = 0 for child in children: factor = nrows//child.nrows for (layout, r0, c0, r1, c1) in child.items: items.append((layout, factor*r0, c0 + offset, factor*r1, c1 + offset)) offset += child.ncols return Grid(nrows, ncols, items) elif isinstance(layout, col): children = list(filter(nonempty, map(_flatten, layout.children))) if not children: return Grid(0, 0, []) nrows = sum([ child.nrows for child in children ]) ncols = lcm(*[ child.ncols for child in children ]) items = [] offset = 0 for child in children: factor = ncols//child.ncols for (layout, r0, c0, r1, c1) in child.items: items.append((layout, r0 + offset, factor*c0, r1 + offset, factor*c1)) offset += child.nrows return Grid(nrows, ncols, items) else: return Grid(1, 1, [Item(layout, 0, 0, 1, 1)]) grid = _flatten(layout) children = [] for (layout, r0, c0, r1, c1) in grid.items: if layout is not None: children.append((layout, r0, c0, r1 - r0, c1 - c0)) return GridBox(children=children) if isinstance(children, list): if nrows is not None or ncols is not None: N = len(children) if ncols is None: ncols = math.ceil(N/nrows) layout = col([ row(children[i:i+ncols]) for i in range(0, N, ncols) ]) else: def traverse(children, level=0): if isinstance(children, list): container = col if level % 2 == 0 else row return container([ traverse(child, level+1) for child in children ]) else: return children layout = traverse(children) elif isinstance(children, LayoutDOM): def is_usable(child): return _has_auto_sizing(child) and child.spacing == 0 def traverse(item, top_level=False): if isinstance(item, Box) and (top_level or is_usable(item)): container = col if isinstance(item, Column) else row return container(list(map(traverse, item.children))) else: return item layout = traverse(children, top_level=True) elif isinstance(children, string_types): raise NotImplementedError else: raise ValueError("expected a list, string or model") grid = flatten(layout) if sizing_mode is not None: grid.sizing_mode = sizing_mode for child in grid.children: layout = child[0] if _has_auto_sizing(layout): layout.sizing_mode = sizing_mode return grid
[ "def", "grid", "(", "children", "=", "[", "]", ",", "sizing_mode", "=", "None", ",", "nrows", "=", "None", ",", "ncols", "=", "None", ")", ":", "row", "=", "namedtuple", "(", "\"row\"", ",", "[", "\"children\"", "]", ")", "col", "=", "namedtuple", "(", "\"col\"", ",", "[", "\"children\"", "]", ")", "def", "flatten", "(", "layout", ")", ":", "Item", "=", "namedtuple", "(", "\"Item\"", ",", "[", "\"layout\"", ",", "\"r0\"", ",", "\"c0\"", ",", "\"r1\"", ",", "\"c1\"", "]", ")", "Grid", "=", "namedtuple", "(", "\"Grid\"", ",", "[", "\"nrows\"", ",", "\"ncols\"", ",", "\"items\"", "]", ")", "def", "gcd", "(", "a", ",", "b", ")", ":", "a", ",", "b", "=", "abs", "(", "a", ")", ",", "abs", "(", "b", ")", "while", "b", "!=", "0", ":", "a", ",", "b", "=", "b", ",", "a", "%", "b", "return", "a", "def", "lcm", "(", "a", ",", "*", "rest", ")", ":", "for", "b", "in", "rest", ":", "a", "=", "(", "a", "*", "b", ")", "//", "gcd", "(", "a", ",", "b", ")", "return", "a", "nonempty", "=", "lambda", "child", ":", "child", ".", "nrows", "!=", "0", "and", "child", ".", "ncols", "!=", "0", "def", "_flatten", "(", "layout", ")", ":", "if", "isinstance", "(", "layout", ",", "row", ")", ":", "children", "=", "list", "(", "filter", "(", "nonempty", ",", "map", "(", "_flatten", ",", "layout", ".", "children", ")", ")", ")", "if", "not", "children", ":", "return", "Grid", "(", "0", ",", "0", ",", "[", "]", ")", "nrows", "=", "lcm", "(", "*", "[", "child", ".", "nrows", "for", "child", "in", "children", "]", ")", "ncols", "=", "sum", "(", "[", "child", ".", "ncols", "for", "child", "in", "children", "]", ")", "items", "=", "[", "]", "offset", "=", "0", "for", "child", "in", "children", ":", "factor", "=", "nrows", "//", "child", ".", "nrows", "for", "(", "layout", ",", "r0", ",", "c0", ",", "r1", ",", "c1", ")", "in", "child", ".", "items", ":", "items", ".", "append", "(", "(", "layout", ",", "factor", "*", "r0", ",", "c0", "+", "offset", ",", "factor", "*", "r1", ",", "c1", "+", "offset", ")", ")", "offset", "+=", "child", ".", "ncols", "return", "Grid", "(", "nrows", ",", "ncols", ",", "items", ")", "elif", "isinstance", "(", "layout", ",", "col", ")", ":", "children", "=", "list", "(", "filter", "(", "nonempty", ",", "map", "(", "_flatten", ",", "layout", ".", "children", ")", ")", ")", "if", "not", "children", ":", "return", "Grid", "(", "0", ",", "0", ",", "[", "]", ")", "nrows", "=", "sum", "(", "[", "child", ".", "nrows", "for", "child", "in", "children", "]", ")", "ncols", "=", "lcm", "(", "*", "[", "child", ".", "ncols", "for", "child", "in", "children", "]", ")", "items", "=", "[", "]", "offset", "=", "0", "for", "child", "in", "children", ":", "factor", "=", "ncols", "//", "child", ".", "ncols", "for", "(", "layout", ",", "r0", ",", "c0", ",", "r1", ",", "c1", ")", "in", "child", ".", "items", ":", "items", ".", "append", "(", "(", "layout", ",", "r0", "+", "offset", ",", "factor", "*", "c0", ",", "r1", "+", "offset", ",", "factor", "*", "c1", ")", ")", "offset", "+=", "child", ".", "nrows", "return", "Grid", "(", "nrows", ",", "ncols", ",", "items", ")", "else", ":", "return", "Grid", "(", "1", ",", "1", ",", "[", "Item", "(", "layout", ",", "0", ",", "0", ",", "1", ",", "1", ")", "]", ")", "grid", "=", "_flatten", "(", "layout", ")", "children", "=", "[", "]", "for", "(", "layout", ",", "r0", ",", "c0", ",", "r1", ",", "c1", ")", "in", "grid", ".", "items", ":", "if", "layout", "is", "not", "None", ":", "children", ".", "append", "(", "(", "layout", ",", "r0", ",", "c0", ",", "r1", "-", "r0", ",", "c1", "-", "c0", ")", ")", "return", "GridBox", "(", "children", "=", "children", ")", "if", "isinstance", "(", "children", ",", "list", ")", ":", "if", "nrows", "is", "not", "None", "or", "ncols", "is", "not", "None", ":", "N", "=", "len", "(", "children", ")", "if", "ncols", "is", "None", ":", "ncols", "=", "math", ".", "ceil", "(", "N", "/", "nrows", ")", "layout", "=", "col", "(", "[", "row", "(", "children", "[", "i", ":", "i", "+", "ncols", "]", ")", "for", "i", "in", "range", "(", "0", ",", "N", ",", "ncols", ")", "]", ")", "else", ":", "def", "traverse", "(", "children", ",", "level", "=", "0", ")", ":", "if", "isinstance", "(", "children", ",", "list", ")", ":", "container", "=", "col", "if", "level", "%", "2", "==", "0", "else", "row", "return", "container", "(", "[", "traverse", "(", "child", ",", "level", "+", "1", ")", "for", "child", "in", "children", "]", ")", "else", ":", "return", "children", "layout", "=", "traverse", "(", "children", ")", "elif", "isinstance", "(", "children", ",", "LayoutDOM", ")", ":", "def", "is_usable", "(", "child", ")", ":", "return", "_has_auto_sizing", "(", "child", ")", "and", "child", ".", "spacing", "==", "0", "def", "traverse", "(", "item", ",", "top_level", "=", "False", ")", ":", "if", "isinstance", "(", "item", ",", "Box", ")", "and", "(", "top_level", "or", "is_usable", "(", "item", ")", ")", ":", "container", "=", "col", "if", "isinstance", "(", "item", ",", "Column", ")", "else", "row", "return", "container", "(", "list", "(", "map", "(", "traverse", ",", "item", ".", "children", ")", ")", ")", "else", ":", "return", "item", "layout", "=", "traverse", "(", "children", ",", "top_level", "=", "True", ")", "elif", "isinstance", "(", "children", ",", "string_types", ")", ":", "raise", "NotImplementedError", "else", ":", "raise", "ValueError", "(", "\"expected a list, string or model\"", ")", "grid", "=", "flatten", "(", "layout", ")", "if", "sizing_mode", "is", "not", "None", ":", "grid", ".", "sizing_mode", "=", "sizing_mode", "for", "child", "in", "grid", ".", "children", ":", "layout", "=", "child", "[", "0", "]", "if", "_has_auto_sizing", "(", "layout", ")", ":", "layout", ".", "sizing_mode", "=", "sizing_mode", "return", "grid" ]
Conveniently create a grid of layoutable objects. Grids are created by using ``GridBox`` model. This gives the most control over the layout of a grid, but is also tedious and may result in unreadable code in practical applications. ``grid()`` function remedies this by reducing the level of control, but in turn providing a more convenient API. Supported patterns: 1. Nested lists of layoutable objects. Assumes the top-level list represents a column and alternates between rows and columns in subsequent nesting levels. One can use ``None`` for padding purpose. >>> grid([p1, [[p2, p3], p4]]) GridBox(children=[ (p1, 0, 0, 1, 2), (p2, 1, 0, 1, 1), (p3, 2, 0, 1, 1), (p4, 1, 1, 2, 1), ]) 2. Nested ``Row`` and ``Column`` instances. Similar to the first pattern, just instead of using nested lists, it uses nested ``Row`` and ``Column`` models. This can be much more readable that the former. Note, however, that only models that don't have ``sizing_mode`` set are used. >>> grid(column(p1, row(column(p2, p3), p4))) GridBox(children=[ (p1, 0, 0, 1, 2), (p2, 1, 0, 1, 1), (p3, 2, 0, 1, 1), (p4, 1, 1, 2, 1), ]) 3. Flat list of layoutable objects. This requires ``nrows`` and/or ``ncols`` to be set. The input list will be rearranged into a 2D array accordingly. One can use ``None`` for padding purpose. >>> grid([p1, p2, p3, p4], ncols=2) GridBox(children=[ (p1, 0, 0, 1, 1), (p2, 0, 1, 1, 1), (p3, 1, 0, 1, 1), (p4, 1, 1, 1, 1), ])
[ "Conveniently", "create", "a", "grid", "of", "layoutable", "objects", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/layouts.py#L342-L504
train
bokeh/bokeh
bokeh/layouts.py
_create_grid
def _create_grid(iterable, sizing_mode, layer=0): """Recursively create grid from input lists.""" return_list = [] for item in iterable: if isinstance(item, list): return_list.append(_create_grid(item, sizing_mode, layer+1)) elif isinstance(item, LayoutDOM): if sizing_mode is not None and _has_auto_sizing(item): item.sizing_mode = sizing_mode return_list.append(item) else: raise ValueError( """Only LayoutDOM items can be inserted into a layout. Tried to insert: %s of type %s""" % (item, type(item)) ) if layer % 2 == 0: return column(children=return_list, sizing_mode=sizing_mode) return row(children=return_list, sizing_mode=sizing_mode)
python
def _create_grid(iterable, sizing_mode, layer=0): """Recursively create grid from input lists.""" return_list = [] for item in iterable: if isinstance(item, list): return_list.append(_create_grid(item, sizing_mode, layer+1)) elif isinstance(item, LayoutDOM): if sizing_mode is not None and _has_auto_sizing(item): item.sizing_mode = sizing_mode return_list.append(item) else: raise ValueError( """Only LayoutDOM items can be inserted into a layout. Tried to insert: %s of type %s""" % (item, type(item)) ) if layer % 2 == 0: return column(children=return_list, sizing_mode=sizing_mode) return row(children=return_list, sizing_mode=sizing_mode)
[ "def", "_create_grid", "(", "iterable", ",", "sizing_mode", ",", "layer", "=", "0", ")", ":", "return_list", "=", "[", "]", "for", "item", "in", "iterable", ":", "if", "isinstance", "(", "item", ",", "list", ")", ":", "return_list", ".", "append", "(", "_create_grid", "(", "item", ",", "sizing_mode", ",", "layer", "+", "1", ")", ")", "elif", "isinstance", "(", "item", ",", "LayoutDOM", ")", ":", "if", "sizing_mode", "is", "not", "None", "and", "_has_auto_sizing", "(", "item", ")", ":", "item", ".", "sizing_mode", "=", "sizing_mode", "return_list", ".", "append", "(", "item", ")", "else", ":", "raise", "ValueError", "(", "\"\"\"Only LayoutDOM items can be inserted into a layout.\n Tried to insert: %s of type %s\"\"\"", "%", "(", "item", ",", "type", "(", "item", ")", ")", ")", "if", "layer", "%", "2", "==", "0", ":", "return", "column", "(", "children", "=", "return_list", ",", "sizing_mode", "=", "sizing_mode", ")", "return", "row", "(", "children", "=", "return_list", ",", "sizing_mode", "=", "sizing_mode", ")" ]
Recursively create grid from input lists.
[ "Recursively", "create", "grid", "from", "input", "lists", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/layouts.py#L593-L610
train
bokeh/bokeh
bokeh/layouts.py
_chunks
def _chunks(l, ncols): """Yield successive n-sized chunks from list, l.""" assert isinstance(ncols, int), "ncols must be an integer" for i in range(0, len(l), ncols): yield l[i: i+ncols]
python
def _chunks(l, ncols): """Yield successive n-sized chunks from list, l.""" assert isinstance(ncols, int), "ncols must be an integer" for i in range(0, len(l), ncols): yield l[i: i+ncols]
[ "def", "_chunks", "(", "l", ",", "ncols", ")", ":", "assert", "isinstance", "(", "ncols", ",", "int", ")", ",", "\"ncols must be an integer\"", "for", "i", "in", "range", "(", "0", ",", "len", "(", "l", ")", ",", "ncols", ")", ":", "yield", "l", "[", "i", ":", "i", "+", "ncols", "]" ]
Yield successive n-sized chunks from list, l.
[ "Yield", "successive", "n", "-", "sized", "chunks", "from", "list", "l", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/layouts.py#L613-L617
train
bokeh/bokeh
bokeh/document/locking.py
without_document_lock
def without_document_lock(func): ''' Wrap a callback function to execute without first obtaining the document lock. Args: func (callable) : The function to wrap Returns: callable : a function wrapped to execute without a |Document| lock. While inside an unlocked callback, it is completely *unsafe* to modify ``curdoc()``. The value of ``curdoc()`` inside the callback will be a specially wrapped version of |Document| that only allows safe operations, which are: * :func:`~bokeh.document.Document.add_next_tick_callback` * :func:`~bokeh.document.Document.remove_next_tick_callback` Only these may be used safely without taking the document lock. To make other changes to the document, you must add a next tick callback and make your changes to ``curdoc()`` from that second callback. Attempts to otherwise access or change the Document will result in an exception being raised. ''' @wraps(func) def wrapper(*args, **kw): return func(*args, **kw) wrapper.nolock = True return wrapper
python
def without_document_lock(func): ''' Wrap a callback function to execute without first obtaining the document lock. Args: func (callable) : The function to wrap Returns: callable : a function wrapped to execute without a |Document| lock. While inside an unlocked callback, it is completely *unsafe* to modify ``curdoc()``. The value of ``curdoc()`` inside the callback will be a specially wrapped version of |Document| that only allows safe operations, which are: * :func:`~bokeh.document.Document.add_next_tick_callback` * :func:`~bokeh.document.Document.remove_next_tick_callback` Only these may be used safely without taking the document lock. To make other changes to the document, you must add a next tick callback and make your changes to ``curdoc()`` from that second callback. Attempts to otherwise access or change the Document will result in an exception being raised. ''' @wraps(func) def wrapper(*args, **kw): return func(*args, **kw) wrapper.nolock = True return wrapper
[ "def", "without_document_lock", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kw", ")", "wrapper", ".", "nolock", "=", "True", "return", "wrapper" ]
Wrap a callback function to execute without first obtaining the document lock. Args: func (callable) : The function to wrap Returns: callable : a function wrapped to execute without a |Document| lock. While inside an unlocked callback, it is completely *unsafe* to modify ``curdoc()``. The value of ``curdoc()`` inside the callback will be a specially wrapped version of |Document| that only allows safe operations, which are: * :func:`~bokeh.document.Document.add_next_tick_callback` * :func:`~bokeh.document.Document.remove_next_tick_callback` Only these may be used safely without taking the document lock. To make other changes to the document, you must add a next tick callback and make your changes to ``curdoc()`` from that second callback. Attempts to otherwise access or change the Document will result in an exception being raised.
[ "Wrap", "a", "callback", "function", "to", "execute", "without", "first", "obtaining", "the", "document", "lock", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/locking.py#L43-L73
train
bokeh/bokeh
bokeh/embed/server.py
server_document
def server_document(url="default", relative_urls=False, resources="default", arguments=None): ''' Return a script tag that embeds content from a Bokeh server. Bokeh apps embedded using these methods will NOT set the browser window title. Args: url (str, optional) : A URL to a Bokeh application on a Bokeh server (default: "default") If ``"default"`` the default URL ``{DEFAULT_SERVER_HTTP_URL}`` will be used. relative_urls (bool, optional) : Whether to use relative URLs for resources. If ``True`` the links generated for resources such a BokehJS JavaScript and CSS will be relative links. This should normally be set to ``False``, but must be set to ``True`` in situations where only relative URLs will work. E.g. when running the Bokeh behind reverse-proxies under certain configurations resources (str) : A string specifying what resources need to be loaded along with the document. If ``default`` then the default JS/CSS bokeh files will be loaded. If None then none of the resource files will be loaded. This is useful if you prefer to serve those resource files via other means (e.g. from a caching server). Be careful, however, that the resource files you'll load separately are of the same version as that of the server's, otherwise the rendering may not work correctly. arguments (dict[str, str], optional) : A dictionary of key/values to be passed as HTTP request arguments to Bokeh application code (default: None) Returns: A ``<script>`` tag that will embed content from a Bokeh Server. ''' url = _clean_url(url) app_path = _get_app_path(url) elementid = make_id() src_path = _src_path(url, elementid) src_path += _process_app_path(app_path) src_path += _process_relative_urls(relative_urls, url) src_path += _process_resources(resources) src_path += _process_arguments(arguments) tag = AUTOLOAD_TAG.render( src_path = src_path, app_path = app_path, elementid = elementid, ) return encode_utf8(tag)
python
def server_document(url="default", relative_urls=False, resources="default", arguments=None): ''' Return a script tag that embeds content from a Bokeh server. Bokeh apps embedded using these methods will NOT set the browser window title. Args: url (str, optional) : A URL to a Bokeh application on a Bokeh server (default: "default") If ``"default"`` the default URL ``{DEFAULT_SERVER_HTTP_URL}`` will be used. relative_urls (bool, optional) : Whether to use relative URLs for resources. If ``True`` the links generated for resources such a BokehJS JavaScript and CSS will be relative links. This should normally be set to ``False``, but must be set to ``True`` in situations where only relative URLs will work. E.g. when running the Bokeh behind reverse-proxies under certain configurations resources (str) : A string specifying what resources need to be loaded along with the document. If ``default`` then the default JS/CSS bokeh files will be loaded. If None then none of the resource files will be loaded. This is useful if you prefer to serve those resource files via other means (e.g. from a caching server). Be careful, however, that the resource files you'll load separately are of the same version as that of the server's, otherwise the rendering may not work correctly. arguments (dict[str, str], optional) : A dictionary of key/values to be passed as HTTP request arguments to Bokeh application code (default: None) Returns: A ``<script>`` tag that will embed content from a Bokeh Server. ''' url = _clean_url(url) app_path = _get_app_path(url) elementid = make_id() src_path = _src_path(url, elementid) src_path += _process_app_path(app_path) src_path += _process_relative_urls(relative_urls, url) src_path += _process_resources(resources) src_path += _process_arguments(arguments) tag = AUTOLOAD_TAG.render( src_path = src_path, app_path = app_path, elementid = elementid, ) return encode_utf8(tag)
[ "def", "server_document", "(", "url", "=", "\"default\"", ",", "relative_urls", "=", "False", ",", "resources", "=", "\"default\"", ",", "arguments", "=", "None", ")", ":", "url", "=", "_clean_url", "(", "url", ")", "app_path", "=", "_get_app_path", "(", "url", ")", "elementid", "=", "make_id", "(", ")", "src_path", "=", "_src_path", "(", "url", ",", "elementid", ")", "src_path", "+=", "_process_app_path", "(", "app_path", ")", "src_path", "+=", "_process_relative_urls", "(", "relative_urls", ",", "url", ")", "src_path", "+=", "_process_resources", "(", "resources", ")", "src_path", "+=", "_process_arguments", "(", "arguments", ")", "tag", "=", "AUTOLOAD_TAG", ".", "render", "(", "src_path", "=", "src_path", ",", "app_path", "=", "app_path", ",", "elementid", "=", "elementid", ",", ")", "return", "encode_utf8", "(", "tag", ")" ]
Return a script tag that embeds content from a Bokeh server. Bokeh apps embedded using these methods will NOT set the browser window title. Args: url (str, optional) : A URL to a Bokeh application on a Bokeh server (default: "default") If ``"default"`` the default URL ``{DEFAULT_SERVER_HTTP_URL}`` will be used. relative_urls (bool, optional) : Whether to use relative URLs for resources. If ``True`` the links generated for resources such a BokehJS JavaScript and CSS will be relative links. This should normally be set to ``False``, but must be set to ``True`` in situations where only relative URLs will work. E.g. when running the Bokeh behind reverse-proxies under certain configurations resources (str) : A string specifying what resources need to be loaded along with the document. If ``default`` then the default JS/CSS bokeh files will be loaded. If None then none of the resource files will be loaded. This is useful if you prefer to serve those resource files via other means (e.g. from a caching server). Be careful, however, that the resource files you'll load separately are of the same version as that of the server's, otherwise the rendering may not work correctly. arguments (dict[str, str], optional) : A dictionary of key/values to be passed as HTTP request arguments to Bokeh application code (default: None) Returns: A ``<script>`` tag that will embed content from a Bokeh Server.
[ "Return", "a", "script", "tag", "that", "embeds", "content", "from", "a", "Bokeh", "server", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/server.py#L51-L110
train
bokeh/bokeh
bokeh/embed/server.py
server_session
def server_session(model=None, session_id=None, url="default", relative_urls=False, resources="default"): ''' Return a script tag that embeds content from a specific existing session on a Bokeh server. This function is typically only useful for serving from a a specific session that was previously created using the ``bokeh.client`` API. Bokeh apps embedded using these methods will NOT set the browser window title. .. note:: Typically you will not want to save or re-use the output of this function for different or multiple page loads. Args: model (Model or None, optional) : The object to render from the session, or None. (default: None) If None, the entire document will be rendered. session_id (str) : A server session ID url (str, optional) : A URL to a Bokeh application on a Bokeh server (default: "default") If ``"default"`` the default URL ``{DEFAULT_SERVER_HTTP_URL}`` will be used. relative_urls (bool, optional) : Whether to use relative URLs for resources. If ``True`` the links generated for resources such a BokehJS JavaScript and CSS will be relative links. This should normally be set to ``False``, but must be set to ``True`` in situations where only relative URLs will work. E.g. when running the Bokeh behind reverse-proxies under certain configurations resources (str) : A string specifying what resources need to be loaded along with the document. If ``default`` then the default JS/CSS bokeh files will be loaded. If None then none of the resource files will be loaded. This is useful if you prefer to serve those resource files via other means (e.g. from a caching server). Be careful, however, that the resource files you'll load separately are of the same version as that of the server's, otherwise the rendering may not work correctly. Returns: A ``<script>`` tag that will embed content from a Bokeh Server. .. warning:: It is typically a bad idea to re-use the same ``session_id`` for every page load. This is likely to create scalability and security problems, and will cause "shared Google doc" behavior, which is probably not desired. ''' if session_id is None: raise ValueError("Must supply a session_id") url = _clean_url(url) app_path = _get_app_path(url) elementid = make_id() modelid = "" if model is None else model.id src_path = _src_path(url, elementid) src_path += _process_app_path(app_path) src_path += _process_relative_urls(relative_urls, url) src_path += _process_session_id(session_id) src_path += _process_resources(resources) tag = AUTOLOAD_TAG.render( src_path = src_path, app_path = app_path, elementid = elementid, modelid = modelid, ) return encode_utf8(tag)
python
def server_session(model=None, session_id=None, url="default", relative_urls=False, resources="default"): ''' Return a script tag that embeds content from a specific existing session on a Bokeh server. This function is typically only useful for serving from a a specific session that was previously created using the ``bokeh.client`` API. Bokeh apps embedded using these methods will NOT set the browser window title. .. note:: Typically you will not want to save or re-use the output of this function for different or multiple page loads. Args: model (Model or None, optional) : The object to render from the session, or None. (default: None) If None, the entire document will be rendered. session_id (str) : A server session ID url (str, optional) : A URL to a Bokeh application on a Bokeh server (default: "default") If ``"default"`` the default URL ``{DEFAULT_SERVER_HTTP_URL}`` will be used. relative_urls (bool, optional) : Whether to use relative URLs for resources. If ``True`` the links generated for resources such a BokehJS JavaScript and CSS will be relative links. This should normally be set to ``False``, but must be set to ``True`` in situations where only relative URLs will work. E.g. when running the Bokeh behind reverse-proxies under certain configurations resources (str) : A string specifying what resources need to be loaded along with the document. If ``default`` then the default JS/CSS bokeh files will be loaded. If None then none of the resource files will be loaded. This is useful if you prefer to serve those resource files via other means (e.g. from a caching server). Be careful, however, that the resource files you'll load separately are of the same version as that of the server's, otherwise the rendering may not work correctly. Returns: A ``<script>`` tag that will embed content from a Bokeh Server. .. warning:: It is typically a bad idea to re-use the same ``session_id`` for every page load. This is likely to create scalability and security problems, and will cause "shared Google doc" behavior, which is probably not desired. ''' if session_id is None: raise ValueError("Must supply a session_id") url = _clean_url(url) app_path = _get_app_path(url) elementid = make_id() modelid = "" if model is None else model.id src_path = _src_path(url, elementid) src_path += _process_app_path(app_path) src_path += _process_relative_urls(relative_urls, url) src_path += _process_session_id(session_id) src_path += _process_resources(resources) tag = AUTOLOAD_TAG.render( src_path = src_path, app_path = app_path, elementid = elementid, modelid = modelid, ) return encode_utf8(tag)
[ "def", "server_session", "(", "model", "=", "None", ",", "session_id", "=", "None", ",", "url", "=", "\"default\"", ",", "relative_urls", "=", "False", ",", "resources", "=", "\"default\"", ")", ":", "if", "session_id", "is", "None", ":", "raise", "ValueError", "(", "\"Must supply a session_id\"", ")", "url", "=", "_clean_url", "(", "url", ")", "app_path", "=", "_get_app_path", "(", "url", ")", "elementid", "=", "make_id", "(", ")", "modelid", "=", "\"\"", "if", "model", "is", "None", "else", "model", ".", "id", "src_path", "=", "_src_path", "(", "url", ",", "elementid", ")", "src_path", "+=", "_process_app_path", "(", "app_path", ")", "src_path", "+=", "_process_relative_urls", "(", "relative_urls", ",", "url", ")", "src_path", "+=", "_process_session_id", "(", "session_id", ")", "src_path", "+=", "_process_resources", "(", "resources", ")", "tag", "=", "AUTOLOAD_TAG", ".", "render", "(", "src_path", "=", "src_path", ",", "app_path", "=", "app_path", ",", "elementid", "=", "elementid", ",", "modelid", "=", "modelid", ",", ")", "return", "encode_utf8", "(", "tag", ")" ]
Return a script tag that embeds content from a specific existing session on a Bokeh server. This function is typically only useful for serving from a a specific session that was previously created using the ``bokeh.client`` API. Bokeh apps embedded using these methods will NOT set the browser window title. .. note:: Typically you will not want to save or re-use the output of this function for different or multiple page loads. Args: model (Model or None, optional) : The object to render from the session, or None. (default: None) If None, the entire document will be rendered. session_id (str) : A server session ID url (str, optional) : A URL to a Bokeh application on a Bokeh server (default: "default") If ``"default"`` the default URL ``{DEFAULT_SERVER_HTTP_URL}`` will be used. relative_urls (bool, optional) : Whether to use relative URLs for resources. If ``True`` the links generated for resources such a BokehJS JavaScript and CSS will be relative links. This should normally be set to ``False``, but must be set to ``True`` in situations where only relative URLs will work. E.g. when running the Bokeh behind reverse-proxies under certain configurations resources (str) : A string specifying what resources need to be loaded along with the document. If ``default`` then the default JS/CSS bokeh files will be loaded. If None then none of the resource files will be loaded. This is useful if you prefer to serve those resource files via other means (e.g. from a caching server). Be careful, however, that the resource files you'll load separately are of the same version as that of the server's, otherwise the rendering may not work correctly. Returns: A ``<script>`` tag that will embed content from a Bokeh Server. .. warning:: It is typically a bad idea to re-use the same ``session_id`` for every page load. This is likely to create scalability and security problems, and will cause "shared Google doc" behavior, which is probably not desired.
[ "Return", "a", "script", "tag", "that", "embeds", "content", "from", "a", "specific", "existing", "session", "on", "a", "Bokeh", "server", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/server.py#L112-L194
train
bokeh/bokeh
bokeh/embed/server.py
_clean_url
def _clean_url(url): ''' Produce a canonical Bokeh server URL. Args: url (str) A URL to clean, or "defatul". If "default" then the ``BOKEH_SERVER_HTTP_URL`` will be returned. Returns: str ''' if url == 'default': url = DEFAULT_SERVER_HTTP_URL if url.startswith("ws"): raise ValueError("url should be the http or https URL for the server, not the websocket URL") return url.rstrip("/")
python
def _clean_url(url): ''' Produce a canonical Bokeh server URL. Args: url (str) A URL to clean, or "defatul". If "default" then the ``BOKEH_SERVER_HTTP_URL`` will be returned. Returns: str ''' if url == 'default': url = DEFAULT_SERVER_HTTP_URL if url.startswith("ws"): raise ValueError("url should be the http or https URL for the server, not the websocket URL") return url.rstrip("/")
[ "def", "_clean_url", "(", "url", ")", ":", "if", "url", "==", "'default'", ":", "url", "=", "DEFAULT_SERVER_HTTP_URL", "if", "url", ".", "startswith", "(", "\"ws\"", ")", ":", "raise", "ValueError", "(", "\"url should be the http or https URL for the server, not the websocket URL\"", ")", "return", "url", ".", "rstrip", "(", "\"/\"", ")" ]
Produce a canonical Bokeh server URL. Args: url (str) A URL to clean, or "defatul". If "default" then the ``BOKEH_SERVER_HTTP_URL`` will be returned. Returns: str
[ "Produce", "a", "canonical", "Bokeh", "server", "URL", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/server.py#L236-L254
train
bokeh/bokeh
bokeh/embed/server.py
_get_app_path
def _get_app_path(url): ''' Extract the app path from a Bokeh server URL Args: url (str) : Returns: str ''' app_path = urlparse(url).path.rstrip("/") if not app_path.startswith("/"): app_path = "/" + app_path return app_path
python
def _get_app_path(url): ''' Extract the app path from a Bokeh server URL Args: url (str) : Returns: str ''' app_path = urlparse(url).path.rstrip("/") if not app_path.startswith("/"): app_path = "/" + app_path return app_path
[ "def", "_get_app_path", "(", "url", ")", ":", "app_path", "=", "urlparse", "(", "url", ")", ".", "path", ".", "rstrip", "(", "\"/\"", ")", "if", "not", "app_path", ".", "startswith", "(", "\"/\"", ")", ":", "app_path", "=", "\"/\"", "+", "app_path", "return", "app_path" ]
Extract the app path from a Bokeh server URL Args: url (str) : Returns: str
[ "Extract", "the", "app", "path", "from", "a", "Bokeh", "server", "URL" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/server.py#L256-L269
train
bokeh/bokeh
bokeh/embed/server.py
_process_arguments
def _process_arguments(arguments): ''' Return user-supplied HTML arguments to add to a Bokeh server URL. Args: arguments (dict[str, object]) : Key/value pairs to add to the URL Returns: str ''' if arguments is None: return "" result = "" for key, value in arguments.items(): if not key.startswith("bokeh-"): result += "&{}={}".format(quote_plus(str(key)), quote_plus(str(value))) return result
python
def _process_arguments(arguments): ''' Return user-supplied HTML arguments to add to a Bokeh server URL. Args: arguments (dict[str, object]) : Key/value pairs to add to the URL Returns: str ''' if arguments is None: return "" result = "" for key, value in arguments.items(): if not key.startswith("bokeh-"): result += "&{}={}".format(quote_plus(str(key)), quote_plus(str(value))) return result
[ "def", "_process_arguments", "(", "arguments", ")", ":", "if", "arguments", "is", "None", ":", "return", "\"\"", "result", "=", "\"\"", "for", "key", ",", "value", "in", "arguments", ".", "items", "(", ")", ":", "if", "not", "key", ".", "startswith", "(", "\"bokeh-\"", ")", ":", "result", "+=", "\"&{}={}\"", ".", "format", "(", "quote_plus", "(", "str", "(", "key", ")", ")", ",", "quote_plus", "(", "str", "(", "value", ")", ")", ")", "return", "result" ]
Return user-supplied HTML arguments to add to a Bokeh server URL. Args: arguments (dict[str, object]) : Key/value pairs to add to the URL Returns: str
[ "Return", "user", "-", "supplied", "HTML", "arguments", "to", "add", "to", "a", "Bokeh", "server", "URL", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/server.py#L271-L287
train
bokeh/bokeh
bokeh/server/views/ws.py
WSHandler.check_origin
def check_origin(self, origin): ''' Implement a check_origin policy for Tornado to call. The supplied origin will be compared to the Bokeh server whitelist. If the origin is not allow, an error will be logged and ``False`` will be returned. Args: origin (str) : The URL of the connection origin Returns: bool, True if the connection is allowed, False otherwise ''' from ..util import check_whitelist parsed_origin = urlparse(origin) origin_host = parsed_origin.netloc.lower() allowed_hosts = self.application.websocket_origins if settings.allowed_ws_origin(): allowed_hosts = set(settings.allowed_ws_origin()) allowed = check_whitelist(origin_host, allowed_hosts) if allowed: return True else: log.error("Refusing websocket connection from Origin '%s'; \ use --allow-websocket-origin=%s or set BOKEH_ALLOW_WS_ORIGIN=%s to permit this; currently we allow origins %r", origin, origin_host, origin_host, allowed_hosts) return False
python
def check_origin(self, origin): ''' Implement a check_origin policy for Tornado to call. The supplied origin will be compared to the Bokeh server whitelist. If the origin is not allow, an error will be logged and ``False`` will be returned. Args: origin (str) : The URL of the connection origin Returns: bool, True if the connection is allowed, False otherwise ''' from ..util import check_whitelist parsed_origin = urlparse(origin) origin_host = parsed_origin.netloc.lower() allowed_hosts = self.application.websocket_origins if settings.allowed_ws_origin(): allowed_hosts = set(settings.allowed_ws_origin()) allowed = check_whitelist(origin_host, allowed_hosts) if allowed: return True else: log.error("Refusing websocket connection from Origin '%s'; \ use --allow-websocket-origin=%s or set BOKEH_ALLOW_WS_ORIGIN=%s to permit this; currently we allow origins %r", origin, origin_host, origin_host, allowed_hosts) return False
[ "def", "check_origin", "(", "self", ",", "origin", ")", ":", "from", ".", ".", "util", "import", "check_whitelist", "parsed_origin", "=", "urlparse", "(", "origin", ")", "origin_host", "=", "parsed_origin", ".", "netloc", ".", "lower", "(", ")", "allowed_hosts", "=", "self", ".", "application", ".", "websocket_origins", "if", "settings", ".", "allowed_ws_origin", "(", ")", ":", "allowed_hosts", "=", "set", "(", "settings", ".", "allowed_ws_origin", "(", ")", ")", "allowed", "=", "check_whitelist", "(", "origin_host", ",", "allowed_hosts", ")", "if", "allowed", ":", "return", "True", "else", ":", "log", ".", "error", "(", "\"Refusing websocket connection from Origin '%s'; \\\n use --allow-websocket-origin=%s or set BOKEH_ALLOW_WS_ORIGIN=%s to permit this; currently we allow origins %r\"", ",", "origin", ",", "origin_host", ",", "origin_host", ",", "allowed_hosts", ")", "return", "False" ]
Implement a check_origin policy for Tornado to call. The supplied origin will be compared to the Bokeh server whitelist. If the origin is not allow, an error will be logged and ``False`` will be returned. Args: origin (str) : The URL of the connection origin Returns: bool, True if the connection is allowed, False otherwise
[ "Implement", "a", "check_origin", "policy", "for", "Tornado", "to", "call", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/views/ws.py#L79-L108
train
bokeh/bokeh
bokeh/server/views/ws.py
WSHandler.open
def open(self): ''' Initialize a connection to a client. Returns: None ''' log.info('WebSocket connection opened') proto_version = self.get_argument("bokeh-protocol-version", default=None) if proto_version is None: self.close() raise ProtocolError("No bokeh-protocol-version specified") session_id = self.get_argument("bokeh-session-id", default=None) if session_id is None: self.close() raise ProtocolError("No bokeh-session-id specified") if not check_session_id_signature(session_id, signed=self.application.sign_sessions, secret_key=self.application.secret_key): log.error("Session id had invalid signature: %r", session_id) raise ProtocolError("Invalid session ID") def on_fully_opened(future): e = future.exception() if e is not None: # this isn't really an error (unless we have a # bug), it just means a client disconnected # immediately, most likely. log.debug("Failed to fully open connection %r", e) future = self._async_open(session_id, proto_version) self.application.io_loop.add_future(future, on_fully_opened)
python
def open(self): ''' Initialize a connection to a client. Returns: None ''' log.info('WebSocket connection opened') proto_version = self.get_argument("bokeh-protocol-version", default=None) if proto_version is None: self.close() raise ProtocolError("No bokeh-protocol-version specified") session_id = self.get_argument("bokeh-session-id", default=None) if session_id is None: self.close() raise ProtocolError("No bokeh-session-id specified") if not check_session_id_signature(session_id, signed=self.application.sign_sessions, secret_key=self.application.secret_key): log.error("Session id had invalid signature: %r", session_id) raise ProtocolError("Invalid session ID") def on_fully_opened(future): e = future.exception() if e is not None: # this isn't really an error (unless we have a # bug), it just means a client disconnected # immediately, most likely. log.debug("Failed to fully open connection %r", e) future = self._async_open(session_id, proto_version) self.application.io_loop.add_future(future, on_fully_opened)
[ "def", "open", "(", "self", ")", ":", "log", ".", "info", "(", "'WebSocket connection opened'", ")", "proto_version", "=", "self", ".", "get_argument", "(", "\"bokeh-protocol-version\"", ",", "default", "=", "None", ")", "if", "proto_version", "is", "None", ":", "self", ".", "close", "(", ")", "raise", "ProtocolError", "(", "\"No bokeh-protocol-version specified\"", ")", "session_id", "=", "self", ".", "get_argument", "(", "\"bokeh-session-id\"", ",", "default", "=", "None", ")", "if", "session_id", "is", "None", ":", "self", ".", "close", "(", ")", "raise", "ProtocolError", "(", "\"No bokeh-session-id specified\"", ")", "if", "not", "check_session_id_signature", "(", "session_id", ",", "signed", "=", "self", ".", "application", ".", "sign_sessions", ",", "secret_key", "=", "self", ".", "application", ".", "secret_key", ")", ":", "log", ".", "error", "(", "\"Session id had invalid signature: %r\"", ",", "session_id", ")", "raise", "ProtocolError", "(", "\"Invalid session ID\"", ")", "def", "on_fully_opened", "(", "future", ")", ":", "e", "=", "future", ".", "exception", "(", ")", "if", "e", "is", "not", "None", ":", "# this isn't really an error (unless we have a", "# bug), it just means a client disconnected", "# immediately, most likely.", "log", ".", "debug", "(", "\"Failed to fully open connection %r\"", ",", "e", ")", "future", "=", "self", ".", "_async_open", "(", "session_id", ",", "proto_version", ")", "self", ".", "application", ".", "io_loop", ".", "add_future", "(", "future", ",", "on_fully_opened", ")" ]
Initialize a connection to a client. Returns: None
[ "Initialize", "a", "connection", "to", "a", "client", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/views/ws.py#L110-L144
train
bokeh/bokeh
bokeh/server/views/ws.py
WSHandler._async_open
def _async_open(self, session_id, proto_version): ''' Perform the specific steps needed to open a connection to a Bokeh session Specifically, this method coordinates: * Getting a session for a session ID (creating a new one if needed) * Creating a protocol receiver and hander * Opening a new ServerConnection and sending it an ACK Args: session_id (str) : A session ID to for a session to connect to If no session exists with the given ID, a new session is made proto_version (str): The protocol version requested by the connecting client. Returns: None ''' try: yield self.application_context.create_session_if_needed(session_id, self.request) session = self.application_context.get_session(session_id) protocol = Protocol(proto_version) self.receiver = Receiver(protocol) log.debug("Receiver created for %r", protocol) self.handler = ProtocolHandler() log.debug("ProtocolHandler created for %r", protocol) self.connection = self.application.new_connection(protocol, self, self.application_context, session) log.info("ServerConnection created") except ProtocolError as e: log.error("Could not create new server session, reason: %s", e) self.close() raise e msg = self.connection.protocol.create('ACK') yield self.send_message(msg) raise gen.Return(None)
python
def _async_open(self, session_id, proto_version): ''' Perform the specific steps needed to open a connection to a Bokeh session Specifically, this method coordinates: * Getting a session for a session ID (creating a new one if needed) * Creating a protocol receiver and hander * Opening a new ServerConnection and sending it an ACK Args: session_id (str) : A session ID to for a session to connect to If no session exists with the given ID, a new session is made proto_version (str): The protocol version requested by the connecting client. Returns: None ''' try: yield self.application_context.create_session_if_needed(session_id, self.request) session = self.application_context.get_session(session_id) protocol = Protocol(proto_version) self.receiver = Receiver(protocol) log.debug("Receiver created for %r", protocol) self.handler = ProtocolHandler() log.debug("ProtocolHandler created for %r", protocol) self.connection = self.application.new_connection(protocol, self, self.application_context, session) log.info("ServerConnection created") except ProtocolError as e: log.error("Could not create new server session, reason: %s", e) self.close() raise e msg = self.connection.protocol.create('ACK') yield self.send_message(msg) raise gen.Return(None)
[ "def", "_async_open", "(", "self", ",", "session_id", ",", "proto_version", ")", ":", "try", ":", "yield", "self", ".", "application_context", ".", "create_session_if_needed", "(", "session_id", ",", "self", ".", "request", ")", "session", "=", "self", ".", "application_context", ".", "get_session", "(", "session_id", ")", "protocol", "=", "Protocol", "(", "proto_version", ")", "self", ".", "receiver", "=", "Receiver", "(", "protocol", ")", "log", ".", "debug", "(", "\"Receiver created for %r\"", ",", "protocol", ")", "self", ".", "handler", "=", "ProtocolHandler", "(", ")", "log", ".", "debug", "(", "\"ProtocolHandler created for %r\"", ",", "protocol", ")", "self", ".", "connection", "=", "self", ".", "application", ".", "new_connection", "(", "protocol", ",", "self", ",", "self", ".", "application_context", ",", "session", ")", "log", ".", "info", "(", "\"ServerConnection created\"", ")", "except", "ProtocolError", "as", "e", ":", "log", ".", "error", "(", "\"Could not create new server session, reason: %s\"", ",", "e", ")", "self", ".", "close", "(", ")", "raise", "e", "msg", "=", "self", ".", "connection", ".", "protocol", ".", "create", "(", "'ACK'", ")", "yield", "self", ".", "send_message", "(", "msg", ")", "raise", "gen", ".", "Return", "(", "None", ")" ]
Perform the specific steps needed to open a connection to a Bokeh session Specifically, this method coordinates: * Getting a session for a session ID (creating a new one if needed) * Creating a protocol receiver and hander * Opening a new ServerConnection and sending it an ACK Args: session_id (str) : A session ID to for a session to connect to If no session exists with the given ID, a new session is made proto_version (str): The protocol version requested by the connecting client. Returns: None
[ "Perform", "the", "specific", "steps", "needed", "to", "open", "a", "connection", "to", "a", "Bokeh", "session" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/views/ws.py#L147-L191
train
bokeh/bokeh
bokeh/server/views/ws.py
WSHandler.on_message
def on_message(self, fragment): ''' Process an individual wire protocol fragment. The websocket RFC specifies opcodes for distinguishing text frames from binary frames. Tornado passes us either a text or binary string depending on that opcode, we have to look at the type of the fragment to see what we got. Args: fragment (unicode or bytes) : wire fragment to process ''' # We shouldn't throw exceptions from on_message because the caller is # just Tornado and it doesn't know what to do with them other than # report them as an unhandled Future try: message = yield self._receive(fragment) except Exception as e: # If you go look at self._receive, it's catching the # expected error types... here we have something weird. log.error("Unhandled exception receiving a message: %r: %r", e, fragment, exc_info=True) self._internal_error("server failed to parse a message") try: if message: if _message_test_port is not None: _message_test_port.received.append(message) work = yield self._handle(message) if work: yield self._schedule(work) except Exception as e: log.error("Handler or its work threw an exception: %r: %r", e, message, exc_info=True) self._internal_error("server failed to handle a message") raise gen.Return(None)
python
def on_message(self, fragment): ''' Process an individual wire protocol fragment. The websocket RFC specifies opcodes for distinguishing text frames from binary frames. Tornado passes us either a text or binary string depending on that opcode, we have to look at the type of the fragment to see what we got. Args: fragment (unicode or bytes) : wire fragment to process ''' # We shouldn't throw exceptions from on_message because the caller is # just Tornado and it doesn't know what to do with them other than # report them as an unhandled Future try: message = yield self._receive(fragment) except Exception as e: # If you go look at self._receive, it's catching the # expected error types... here we have something weird. log.error("Unhandled exception receiving a message: %r: %r", e, fragment, exc_info=True) self._internal_error("server failed to parse a message") try: if message: if _message_test_port is not None: _message_test_port.received.append(message) work = yield self._handle(message) if work: yield self._schedule(work) except Exception as e: log.error("Handler or its work threw an exception: %r: %r", e, message, exc_info=True) self._internal_error("server failed to handle a message") raise gen.Return(None)
[ "def", "on_message", "(", "self", ",", "fragment", ")", ":", "# We shouldn't throw exceptions from on_message because the caller is", "# just Tornado and it doesn't know what to do with them other than", "# report them as an unhandled Future", "try", ":", "message", "=", "yield", "self", ".", "_receive", "(", "fragment", ")", "except", "Exception", "as", "e", ":", "# If you go look at self._receive, it's catching the", "# expected error types... here we have something weird.", "log", ".", "error", "(", "\"Unhandled exception receiving a message: %r: %r\"", ",", "e", ",", "fragment", ",", "exc_info", "=", "True", ")", "self", ".", "_internal_error", "(", "\"server failed to parse a message\"", ")", "try", ":", "if", "message", ":", "if", "_message_test_port", "is", "not", "None", ":", "_message_test_port", ".", "received", ".", "append", "(", "message", ")", "work", "=", "yield", "self", ".", "_handle", "(", "message", ")", "if", "work", ":", "yield", "self", ".", "_schedule", "(", "work", ")", "except", "Exception", "as", "e", ":", "log", ".", "error", "(", "\"Handler or its work threw an exception: %r: %r\"", ",", "e", ",", "message", ",", "exc_info", "=", "True", ")", "self", ".", "_internal_error", "(", "\"server failed to handle a message\"", ")", "raise", "gen", ".", "Return", "(", "None", ")" ]
Process an individual wire protocol fragment. The websocket RFC specifies opcodes for distinguishing text frames from binary frames. Tornado passes us either a text or binary string depending on that opcode, we have to look at the type of the fragment to see what we got. Args: fragment (unicode or bytes) : wire fragment to process
[ "Process", "an", "individual", "wire", "protocol", "fragment", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/views/ws.py#L194-L230
train
bokeh/bokeh
bokeh/server/views/ws.py
WSHandler.send_message
def send_message(self, message): ''' Send a Bokeh Server protocol message to the connected client. Args: message (Message) : a message to send ''' try: if _message_test_port is not None: _message_test_port.sent.append(message) yield message.send(self) except (WebSocketClosedError, StreamClosedError): # Tornado 4.x may raise StreamClosedError # on_close() is / will be called anyway log.warning("Failed sending message as connection was closed") raise gen.Return(None)
python
def send_message(self, message): ''' Send a Bokeh Server protocol message to the connected client. Args: message (Message) : a message to send ''' try: if _message_test_port is not None: _message_test_port.sent.append(message) yield message.send(self) except (WebSocketClosedError, StreamClosedError): # Tornado 4.x may raise StreamClosedError # on_close() is / will be called anyway log.warning("Failed sending message as connection was closed") raise gen.Return(None)
[ "def", "send_message", "(", "self", ",", "message", ")", ":", "try", ":", "if", "_message_test_port", "is", "not", "None", ":", "_message_test_port", ".", "sent", ".", "append", "(", "message", ")", "yield", "message", ".", "send", "(", "self", ")", "except", "(", "WebSocketClosedError", ",", "StreamClosedError", ")", ":", "# Tornado 4.x may raise StreamClosedError", "# on_close() is / will be called anyway", "log", ".", "warning", "(", "\"Failed sending message as connection was closed\"", ")", "raise", "gen", ".", "Return", "(", "None", ")" ]
Send a Bokeh Server protocol message to the connected client. Args: message (Message) : a message to send
[ "Send", "a", "Bokeh", "Server", "protocol", "message", "to", "the", "connected", "client", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/views/ws.py#L243-L257
train
bokeh/bokeh
bokeh/server/views/ws.py
WSHandler.write_message
def write_message(self, message, binary=False, locked=True): ''' Override parent write_message with a version that acquires a write lock before writing. ''' if locked: with (yield self.write_lock.acquire()): yield super(WSHandler, self).write_message(message, binary) else: yield super(WSHandler, self).write_message(message, binary)
python
def write_message(self, message, binary=False, locked=True): ''' Override parent write_message with a version that acquires a write lock before writing. ''' if locked: with (yield self.write_lock.acquire()): yield super(WSHandler, self).write_message(message, binary) else: yield super(WSHandler, self).write_message(message, binary)
[ "def", "write_message", "(", "self", ",", "message", ",", "binary", "=", "False", ",", "locked", "=", "True", ")", ":", "if", "locked", ":", "with", "(", "yield", "self", ".", "write_lock", ".", "acquire", "(", ")", ")", ":", "yield", "super", "(", "WSHandler", ",", "self", ")", ".", "write_message", "(", "message", ",", "binary", ")", "else", ":", "yield", "super", "(", "WSHandler", ",", "self", ")", ".", "write_message", "(", "message", ",", "binary", ")" ]
Override parent write_message with a version that acquires a write lock before writing.
[ "Override", "parent", "write_message", "with", "a", "version", "that", "acquires", "a", "write", "lock", "before", "writing", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/views/ws.py#L260-L269
train
bokeh/bokeh
bokeh/server/views/ws.py
WSHandler.on_close
def on_close(self): ''' Clean up when the connection is closed. ''' log.info('WebSocket connection closed: code=%s, reason=%r', self.close_code, self.close_reason) if self.connection is not None: self.application.client_lost(self.connection)
python
def on_close(self): ''' Clean up when the connection is closed. ''' log.info('WebSocket connection closed: code=%s, reason=%r', self.close_code, self.close_reason) if self.connection is not None: self.application.client_lost(self.connection)
[ "def", "on_close", "(", "self", ")", ":", "log", ".", "info", "(", "'WebSocket connection closed: code=%s, reason=%r'", ",", "self", ".", "close_code", ",", "self", ".", "close_reason", ")", "if", "self", ".", "connection", "is", "not", "None", ":", "self", ".", "application", ".", "client_lost", "(", "self", ".", "connection", ")" ]
Clean up when the connection is closed.
[ "Clean", "up", "when", "the", "connection", "is", "closed", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/views/ws.py#L271-L277
train
bokeh/bokeh
bokeh/embed/bundle.py
bundle_for_objs_and_resources
def bundle_for_objs_and_resources(objs, resources): ''' Generate rendered CSS and JS resources suitable for the given collection of Bokeh objects Args: objs (seq[Model or Document]) : resources (BaseResources or tuple[BaseResources]) Returns: tuple ''' if isinstance(resources, BaseResources): js_resources = css_resources = resources elif isinstance(resources, tuple) and len(resources) == 2 and all(r is None or isinstance(r, BaseResources) for r in resources): js_resources, css_resources = resources if js_resources and not css_resources: warn('No Bokeh CSS Resources provided to template. If required you will need to provide them manually.') if css_resources and not js_resources: warn('No Bokeh JS Resources provided to template. If required you will need to provide them manually.') else: raise ValueError("expected Resources or a pair of optional Resources, got %r" % resources) from copy import deepcopy # XXX: force all components on server and in notebook, because we don't know in advance what will be used use_widgets = _use_widgets(objs) if objs else True use_tables = _use_tables(objs) if objs else True use_gl = _use_gl(objs) if objs else True if js_resources: js_resources = deepcopy(js_resources) if not use_widgets and "bokeh-widgets" in js_resources.js_components: js_resources.js_components.remove("bokeh-widgets") if not use_tables and "bokeh-tables" in js_resources.js_components: js_resources.js_components.remove("bokeh-tables") if not use_gl and "bokeh-gl" in js_resources.js_components: js_resources.js_components.remove("bokeh-gl") bokeh_js = js_resources.render_js() else: bokeh_js = None models = [ obj.__class__ for obj in _all_objs(objs) ] if objs else None custom_bundle = bundle_models(models) if custom_bundle is not None: custom_bundle = wrap_in_script_tag(custom_bundle) if bokeh_js is not None: bokeh_js += "\n" + custom_bundle else: bokeh_js = custom_bundle if css_resources: css_resources = deepcopy(css_resources) if not use_widgets and "bokeh-widgets" in css_resources.css_components: css_resources.css_components.remove("bokeh-widgets") if not use_tables and "bokeh-tables" in css_resources.css_components: css_resources.css_components.remove("bokeh-tables") bokeh_css = css_resources.render_css() else: bokeh_css = None return bokeh_js, bokeh_css
python
def bundle_for_objs_and_resources(objs, resources): ''' Generate rendered CSS and JS resources suitable for the given collection of Bokeh objects Args: objs (seq[Model or Document]) : resources (BaseResources or tuple[BaseResources]) Returns: tuple ''' if isinstance(resources, BaseResources): js_resources = css_resources = resources elif isinstance(resources, tuple) and len(resources) == 2 and all(r is None or isinstance(r, BaseResources) for r in resources): js_resources, css_resources = resources if js_resources and not css_resources: warn('No Bokeh CSS Resources provided to template. If required you will need to provide them manually.') if css_resources and not js_resources: warn('No Bokeh JS Resources provided to template. If required you will need to provide them manually.') else: raise ValueError("expected Resources or a pair of optional Resources, got %r" % resources) from copy import deepcopy # XXX: force all components on server and in notebook, because we don't know in advance what will be used use_widgets = _use_widgets(objs) if objs else True use_tables = _use_tables(objs) if objs else True use_gl = _use_gl(objs) if objs else True if js_resources: js_resources = deepcopy(js_resources) if not use_widgets and "bokeh-widgets" in js_resources.js_components: js_resources.js_components.remove("bokeh-widgets") if not use_tables and "bokeh-tables" in js_resources.js_components: js_resources.js_components.remove("bokeh-tables") if not use_gl and "bokeh-gl" in js_resources.js_components: js_resources.js_components.remove("bokeh-gl") bokeh_js = js_resources.render_js() else: bokeh_js = None models = [ obj.__class__ for obj in _all_objs(objs) ] if objs else None custom_bundle = bundle_models(models) if custom_bundle is not None: custom_bundle = wrap_in_script_tag(custom_bundle) if bokeh_js is not None: bokeh_js += "\n" + custom_bundle else: bokeh_js = custom_bundle if css_resources: css_resources = deepcopy(css_resources) if not use_widgets and "bokeh-widgets" in css_resources.css_components: css_resources.css_components.remove("bokeh-widgets") if not use_tables and "bokeh-tables" in css_resources.css_components: css_resources.css_components.remove("bokeh-tables") bokeh_css = css_resources.render_css() else: bokeh_css = None return bokeh_js, bokeh_css
[ "def", "bundle_for_objs_and_resources", "(", "objs", ",", "resources", ")", ":", "if", "isinstance", "(", "resources", ",", "BaseResources", ")", ":", "js_resources", "=", "css_resources", "=", "resources", "elif", "isinstance", "(", "resources", ",", "tuple", ")", "and", "len", "(", "resources", ")", "==", "2", "and", "all", "(", "r", "is", "None", "or", "isinstance", "(", "r", ",", "BaseResources", ")", "for", "r", "in", "resources", ")", ":", "js_resources", ",", "css_resources", "=", "resources", "if", "js_resources", "and", "not", "css_resources", ":", "warn", "(", "'No Bokeh CSS Resources provided to template. If required you will need to provide them manually.'", ")", "if", "css_resources", "and", "not", "js_resources", ":", "warn", "(", "'No Bokeh JS Resources provided to template. If required you will need to provide them manually.'", ")", "else", ":", "raise", "ValueError", "(", "\"expected Resources or a pair of optional Resources, got %r\"", "%", "resources", ")", "from", "copy", "import", "deepcopy", "# XXX: force all components on server and in notebook, because we don't know in advance what will be used", "use_widgets", "=", "_use_widgets", "(", "objs", ")", "if", "objs", "else", "True", "use_tables", "=", "_use_tables", "(", "objs", ")", "if", "objs", "else", "True", "use_gl", "=", "_use_gl", "(", "objs", ")", "if", "objs", "else", "True", "if", "js_resources", ":", "js_resources", "=", "deepcopy", "(", "js_resources", ")", "if", "not", "use_widgets", "and", "\"bokeh-widgets\"", "in", "js_resources", ".", "js_components", ":", "js_resources", ".", "js_components", ".", "remove", "(", "\"bokeh-widgets\"", ")", "if", "not", "use_tables", "and", "\"bokeh-tables\"", "in", "js_resources", ".", "js_components", ":", "js_resources", ".", "js_components", ".", "remove", "(", "\"bokeh-tables\"", ")", "if", "not", "use_gl", "and", "\"bokeh-gl\"", "in", "js_resources", ".", "js_components", ":", "js_resources", ".", "js_components", ".", "remove", "(", "\"bokeh-gl\"", ")", "bokeh_js", "=", "js_resources", ".", "render_js", "(", ")", "else", ":", "bokeh_js", "=", "None", "models", "=", "[", "obj", ".", "__class__", "for", "obj", "in", "_all_objs", "(", "objs", ")", "]", "if", "objs", "else", "None", "custom_bundle", "=", "bundle_models", "(", "models", ")", "if", "custom_bundle", "is", "not", "None", ":", "custom_bundle", "=", "wrap_in_script_tag", "(", "custom_bundle", ")", "if", "bokeh_js", "is", "not", "None", ":", "bokeh_js", "+=", "\"\\n\"", "+", "custom_bundle", "else", ":", "bokeh_js", "=", "custom_bundle", "if", "css_resources", ":", "css_resources", "=", "deepcopy", "(", "css_resources", ")", "if", "not", "use_widgets", "and", "\"bokeh-widgets\"", "in", "css_resources", ".", "css_components", ":", "css_resources", ".", "css_components", ".", "remove", "(", "\"bokeh-widgets\"", ")", "if", "not", "use_tables", "and", "\"bokeh-tables\"", "in", "css_resources", ".", "css_components", ":", "css_resources", ".", "css_components", ".", "remove", "(", "\"bokeh-tables\"", ")", "bokeh_css", "=", "css_resources", ".", "render_css", "(", ")", "else", ":", "bokeh_css", "=", "None", "return", "bokeh_js", ",", "bokeh_css" ]
Generate rendered CSS and JS resources suitable for the given collection of Bokeh objects Args: objs (seq[Model or Document]) : resources (BaseResources or tuple[BaseResources]) Returns: tuple
[ "Generate", "rendered", "CSS", "and", "JS", "resources", "suitable", "for", "the", "given", "collection", "of", "Bokeh", "objects" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/bundle.py#L50-L116
train
bokeh/bokeh
bokeh/embed/bundle.py
_any
def _any(objs, query): ''' Whether any of a collection of objects satisfies a given query predicate Args: objs (seq[Model or Document]) : query (callable) Returns: True, if ``query(obj)`` is True for some object in ``objs``, else False ''' for obj in objs: if isinstance(obj, Document): if _any(obj.roots, query): return True else: if any(query(ref) for ref in obj.references()): return True else: return False
python
def _any(objs, query): ''' Whether any of a collection of objects satisfies a given query predicate Args: objs (seq[Model or Document]) : query (callable) Returns: True, if ``query(obj)`` is True for some object in ``objs``, else False ''' for obj in objs: if isinstance(obj, Document): if _any(obj.roots, query): return True else: if any(query(ref) for ref in obj.references()): return True else: return False
[ "def", "_any", "(", "objs", ",", "query", ")", ":", "for", "obj", "in", "objs", ":", "if", "isinstance", "(", "obj", ",", "Document", ")", ":", "if", "_any", "(", "obj", ".", "roots", ",", "query", ")", ":", "return", "True", "else", ":", "if", "any", "(", "query", "(", "ref", ")", "for", "ref", "in", "obj", ".", "references", "(", ")", ")", ":", "return", "True", "else", ":", "return", "False" ]
Whether any of a collection of objects satisfies a given query predicate Args: objs (seq[Model or Document]) : query (callable) Returns: True, if ``query(obj)`` is True for some object in ``objs``, else False
[ "Whether", "any", "of", "a", "collection", "of", "objects", "satisfies", "a", "given", "query", "predicate" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/bundle.py#L134-L154
train
bokeh/bokeh
bokeh/embed/bundle.py
_use_gl
def _use_gl(objs): ''' Whether a collection of Bokeh objects contains a plot requesting WebGL Args: objs (seq[Model or Document]) : Returns: bool ''' from ..models.plots import Plot return _any(objs, lambda obj: isinstance(obj, Plot) and obj.output_backend == "webgl")
python
def _use_gl(objs): ''' Whether a collection of Bokeh objects contains a plot requesting WebGL Args: objs (seq[Model or Document]) : Returns: bool ''' from ..models.plots import Plot return _any(objs, lambda obj: isinstance(obj, Plot) and obj.output_backend == "webgl")
[ "def", "_use_gl", "(", "objs", ")", ":", "from", ".", ".", "models", ".", "plots", "import", "Plot", "return", "_any", "(", "objs", ",", "lambda", "obj", ":", "isinstance", "(", "obj", ",", "Plot", ")", "and", "obj", ".", "output_backend", "==", "\"webgl\"", ")" ]
Whether a collection of Bokeh objects contains a plot requesting WebGL Args: objs (seq[Model or Document]) : Returns: bool
[ "Whether", "a", "collection", "of", "Bokeh", "objects", "contains", "a", "plot", "requesting", "WebGL" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/bundle.py#L156-L167
train
bokeh/bokeh
bokeh/embed/bundle.py
_use_tables
def _use_tables(objs): ''' Whether a collection of Bokeh objects contains a TableWidget Args: objs (seq[Model or Document]) : Returns: bool ''' from ..models.widgets import TableWidget return _any(objs, lambda obj: isinstance(obj, TableWidget))
python
def _use_tables(objs): ''' Whether a collection of Bokeh objects contains a TableWidget Args: objs (seq[Model or Document]) : Returns: bool ''' from ..models.widgets import TableWidget return _any(objs, lambda obj: isinstance(obj, TableWidget))
[ "def", "_use_tables", "(", "objs", ")", ":", "from", ".", ".", "models", ".", "widgets", "import", "TableWidget", "return", "_any", "(", "objs", ",", "lambda", "obj", ":", "isinstance", "(", "obj", ",", "TableWidget", ")", ")" ]
Whether a collection of Bokeh objects contains a TableWidget Args: objs (seq[Model or Document]) : Returns: bool
[ "Whether", "a", "collection", "of", "Bokeh", "objects", "contains", "a", "TableWidget" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/bundle.py#L169-L180
train
bokeh/bokeh
bokeh/embed/bundle.py
_use_widgets
def _use_widgets(objs): ''' Whether a collection of Bokeh objects contains a any Widget Args: objs (seq[Model or Document]) : Returns: bool ''' from ..models.widgets import Widget return _any(objs, lambda obj: isinstance(obj, Widget))
python
def _use_widgets(objs): ''' Whether a collection of Bokeh objects contains a any Widget Args: objs (seq[Model or Document]) : Returns: bool ''' from ..models.widgets import Widget return _any(objs, lambda obj: isinstance(obj, Widget))
[ "def", "_use_widgets", "(", "objs", ")", ":", "from", ".", ".", "models", ".", "widgets", "import", "Widget", "return", "_any", "(", "objs", ",", "lambda", "obj", ":", "isinstance", "(", "obj", ",", "Widget", ")", ")" ]
Whether a collection of Bokeh objects contains a any Widget Args: objs (seq[Model or Document]) : Returns: bool
[ "Whether", "a", "collection", "of", "Bokeh", "objects", "contains", "a", "any", "Widget" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/bundle.py#L182-L193
train
bokeh/bokeh
bokeh/core/property/descriptors.py
PropertyDescriptor.add_prop_descriptor_to_class
def add_prop_descriptor_to_class(self, class_name, new_class_attrs, names_with_refs, container_names, dataspecs): ''' ``MetaHasProps`` calls this during class creation as it iterates over properties to add, to update its registry of new properties. The parameters passed in are mutable and this function is expected to update them accordingly. Args: class_name (str) : name of the class this descriptor is added to new_class_attrs(dict[str, PropertyDescriptor]) : mapping of attribute names to PropertyDescriptor that this function will update names_with_refs (set[str]) : set of all property names for properties that also have references, that this function will update container_names (set[str]) : set of all property names for properties that are container props, that this function will update dataspecs(dict[str, PropertyDescriptor]) : mapping of attribute names to PropertyDescriptor for DataSpec properties that this function will update Return: None ''' from .bases import ContainerProperty from .dataspec import DataSpec name = self.name if name in new_class_attrs: raise RuntimeError("Two property generators both created %s.%s" % (class_name, name)) new_class_attrs[name] = self if self.has_ref: names_with_refs.add(name) if isinstance(self, BasicPropertyDescriptor): if isinstance(self.property, ContainerProperty): container_names.add(name) if isinstance(self.property, DataSpec): dataspecs[name] = self
python
def add_prop_descriptor_to_class(self, class_name, new_class_attrs, names_with_refs, container_names, dataspecs): ''' ``MetaHasProps`` calls this during class creation as it iterates over properties to add, to update its registry of new properties. The parameters passed in are mutable and this function is expected to update them accordingly. Args: class_name (str) : name of the class this descriptor is added to new_class_attrs(dict[str, PropertyDescriptor]) : mapping of attribute names to PropertyDescriptor that this function will update names_with_refs (set[str]) : set of all property names for properties that also have references, that this function will update container_names (set[str]) : set of all property names for properties that are container props, that this function will update dataspecs(dict[str, PropertyDescriptor]) : mapping of attribute names to PropertyDescriptor for DataSpec properties that this function will update Return: None ''' from .bases import ContainerProperty from .dataspec import DataSpec name = self.name if name in new_class_attrs: raise RuntimeError("Two property generators both created %s.%s" % (class_name, name)) new_class_attrs[name] = self if self.has_ref: names_with_refs.add(name) if isinstance(self, BasicPropertyDescriptor): if isinstance(self.property, ContainerProperty): container_names.add(name) if isinstance(self.property, DataSpec): dataspecs[name] = self
[ "def", "add_prop_descriptor_to_class", "(", "self", ",", "class_name", ",", "new_class_attrs", ",", "names_with_refs", ",", "container_names", ",", "dataspecs", ")", ":", "from", ".", "bases", "import", "ContainerProperty", "from", ".", "dataspec", "import", "DataSpec", "name", "=", "self", ".", "name", "if", "name", "in", "new_class_attrs", ":", "raise", "RuntimeError", "(", "\"Two property generators both created %s.%s\"", "%", "(", "class_name", ",", "name", ")", ")", "new_class_attrs", "[", "name", "]", "=", "self", "if", "self", ".", "has_ref", ":", "names_with_refs", ".", "add", "(", "name", ")", "if", "isinstance", "(", "self", ",", "BasicPropertyDescriptor", ")", ":", "if", "isinstance", "(", "self", ".", "property", ",", "ContainerProperty", ")", ":", "container_names", ".", "add", "(", "name", ")", "if", "isinstance", "(", "self", ".", "property", ",", "DataSpec", ")", ":", "dataspecs", "[", "name", "]", "=", "self" ]
``MetaHasProps`` calls this during class creation as it iterates over properties to add, to update its registry of new properties. The parameters passed in are mutable and this function is expected to update them accordingly. Args: class_name (str) : name of the class this descriptor is added to new_class_attrs(dict[str, PropertyDescriptor]) : mapping of attribute names to PropertyDescriptor that this function will update names_with_refs (set[str]) : set of all property names for properties that also have references, that this function will update container_names (set[str]) : set of all property names for properties that are container props, that this function will update dataspecs(dict[str, PropertyDescriptor]) : mapping of attribute names to PropertyDescriptor for DataSpec properties that this function will update Return: None
[ "MetaHasProps", "calls", "this", "during", "class", "creation", "as", "it", "iterates", "over", "properties", "to", "add", "to", "update", "its", "registry", "of", "new", "properties", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L221-L267
train
bokeh/bokeh
bokeh/core/property/descriptors.py
PropertyDescriptor.serializable_value
def serializable_value(self, obj): ''' Produce the value as it should be serialized. Sometimes it is desirable for the serialized value to differ from the ``__get__`` in order for the ``__get__`` value to appear simpler for user or developer convenience. Args: obj (HasProps) : the object to get the serialized attribute for Returns: JSON-like ''' value = self.__get__(obj, obj.__class__) return self.property.serialize_value(value)
python
def serializable_value(self, obj): ''' Produce the value as it should be serialized. Sometimes it is desirable for the serialized value to differ from the ``__get__`` in order for the ``__get__`` value to appear simpler for user or developer convenience. Args: obj (HasProps) : the object to get the serialized attribute for Returns: JSON-like ''' value = self.__get__(obj, obj.__class__) return self.property.serialize_value(value)
[ "def", "serializable_value", "(", "self", ",", "obj", ")", ":", "value", "=", "self", ".", "__get__", "(", "obj", ",", "obj", ".", "__class__", ")", "return", "self", ".", "property", ".", "serialize_value", "(", "value", ")" ]
Produce the value as it should be serialized. Sometimes it is desirable for the serialized value to differ from the ``__get__`` in order for the ``__get__`` value to appear simpler for user or developer convenience. Args: obj (HasProps) : the object to get the serialized attribute for Returns: JSON-like
[ "Produce", "the", "value", "as", "it", "should", "be", "serialized", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L281-L296
train
bokeh/bokeh
bokeh/core/property/descriptors.py
PropertyDescriptor.set_from_json
def set_from_json(self, obj, json, models=None, setter=None): '''Sets the value of this property from a JSON value. Args: obj: (HasProps) : instance to set the property value on 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. (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 ''' self._internal_set(obj, json, setter=setter)
python
def set_from_json(self, obj, json, models=None, setter=None): '''Sets the value of this property from a JSON value. Args: obj: (HasProps) : instance to set the property value on 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. (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 ''' self._internal_set(obj, json, setter=setter)
[ "def", "set_from_json", "(", "self", ",", "obj", ",", "json", ",", "models", "=", "None", ",", "setter", "=", "None", ")", ":", "self", ".", "_internal_set", "(", "obj", ",", "json", ",", "setter", "=", "setter", ")" ]
Sets the value of this property from a JSON value. Args: obj: (HasProps) : instance to set the property value on 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. (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
[ "Sets", "the", "value", "of", "this", "property", "from", "a", "JSON", "value", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L298-L327
train
bokeh/bokeh
bokeh/core/property/descriptors.py
BasicPropertyDescriptor.instance_default
def instance_default(self, obj): ''' Get the default value that will be used for a specific instance. Args: obj (HasProps) : The instance to get the default value for. Returns: object ''' return self.property.themed_default(obj.__class__, self.name, obj.themed_values())
python
def instance_default(self, obj): ''' Get the default value that will be used for a specific instance. Args: obj (HasProps) : The instance to get the default value for. Returns: object ''' return self.property.themed_default(obj.__class__, self.name, obj.themed_values())
[ "def", "instance_default", "(", "self", ",", "obj", ")", ":", "return", "self", ".", "property", ".", "themed_default", "(", "obj", ".", "__class__", ",", "self", ".", "name", ",", "obj", ".", "themed_values", "(", ")", ")" ]
Get the default value that will be used for a specific instance. Args: obj (HasProps) : The instance to get the default value for. Returns: object
[ "Get", "the", "default", "value", "that", "will", "be", "used", "for", "a", "specific", "instance", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L577-L587
train
bokeh/bokeh
bokeh/core/property/descriptors.py
BasicPropertyDescriptor.set_from_json
def set_from_json(self, obj, json, models=None, setter=None): ''' Sets the value of this property from a JSON value. This method first Args: obj (HasProps) : json (JSON-dict) : models(seq[Model], optional) : 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 ''' return super(BasicPropertyDescriptor, self).set_from_json(obj, self.property.from_json(json, models), models, setter)
python
def set_from_json(self, obj, json, models=None, setter=None): ''' Sets the value of this property from a JSON value. This method first Args: obj (HasProps) : json (JSON-dict) : models(seq[Model], optional) : 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 ''' return super(BasicPropertyDescriptor, self).set_from_json(obj, self.property.from_json(json, models), models, setter)
[ "def", "set_from_json", "(", "self", ",", "obj", ",", "json", ",", "models", "=", "None", ",", "setter", "=", "None", ")", ":", "return", "super", "(", "BasicPropertyDescriptor", ",", "self", ")", ".", "set_from_json", "(", "obj", ",", "self", ".", "property", ".", "from_json", "(", "json", ",", "models", ")", ",", "models", ",", "setter", ")" ]
Sets the value of this property from a JSON value. This method first Args: obj (HasProps) : json (JSON-dict) : models(seq[Model], optional) : 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
[ "Sets", "the", "value", "of", "this", "property", "from", "a", "JSON", "value", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L589-L618
train
bokeh/bokeh
bokeh/core/property/descriptors.py
BasicPropertyDescriptor.trigger_if_changed
def trigger_if_changed(self, obj, old): ''' Send a change event notification if the property is set to a value is not equal to ``old``. Args: obj (HasProps) The object the property is being set on. old (obj) : The previous value of the property to compare Returns: None ''' new_value = self.__get__(obj, obj.__class__) if not self.property.matches(old, new_value): self._trigger(obj, old, new_value)
python
def trigger_if_changed(self, obj, old): ''' Send a change event notification if the property is set to a value is not equal to ``old``. Args: obj (HasProps) The object the property is being set on. old (obj) : The previous value of the property to compare Returns: None ''' new_value = self.__get__(obj, obj.__class__) if not self.property.matches(old, new_value): self._trigger(obj, old, new_value)
[ "def", "trigger_if_changed", "(", "self", ",", "obj", ",", "old", ")", ":", "new_value", "=", "self", ".", "__get__", "(", "obj", ",", "obj", ".", "__class__", ")", "if", "not", "self", ".", "property", ".", "matches", "(", "old", ",", "new_value", ")", ":", "self", ".", "_trigger", "(", "obj", ",", "old", ",", "new_value", ")" ]
Send a change event notification if the property is set to a value is not equal to ``old``. Args: obj (HasProps) The object the property is being set on. old (obj) : The previous value of the property to compare Returns: None
[ "Send", "a", "change", "event", "notification", "if", "the", "property", "is", "set", "to", "a", "value", "is", "not", "equal", "to", "old", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L620-L637
train
bokeh/bokeh
bokeh/core/property/descriptors.py
BasicPropertyDescriptor._get
def _get(self, obj): ''' Internal implementation of instance attribute access for the ``BasicPropertyDescriptor`` getter. If the value has not been explicitly set by a user, return that value. Otherwise, return the default. Args: obj (HasProps) : the instance to get a value of this property for Returns: object Raises: RuntimeError If the |HasProps| instance has not yet been initialized, or if this descriptor is on a class that is not a |HasProps|. ''' if not hasattr(obj, '_property_values'): raise RuntimeError("Cannot get a property value '%s' from a %s instance before HasProps.__init__" % (self.name, obj.__class__.__name__)) if self.name not in obj._property_values: return self._get_default(obj) else: return obj._property_values[self.name]
python
def _get(self, obj): ''' Internal implementation of instance attribute access for the ``BasicPropertyDescriptor`` getter. If the value has not been explicitly set by a user, return that value. Otherwise, return the default. Args: obj (HasProps) : the instance to get a value of this property for Returns: object Raises: RuntimeError If the |HasProps| instance has not yet been initialized, or if this descriptor is on a class that is not a |HasProps|. ''' if not hasattr(obj, '_property_values'): raise RuntimeError("Cannot get a property value '%s' from a %s instance before HasProps.__init__" % (self.name, obj.__class__.__name__)) if self.name not in obj._property_values: return self._get_default(obj) else: return obj._property_values[self.name]
[ "def", "_get", "(", "self", ",", "obj", ")", ":", "if", "not", "hasattr", "(", "obj", ",", "'_property_values'", ")", ":", "raise", "RuntimeError", "(", "\"Cannot get a property value '%s' from a %s instance before HasProps.__init__\"", "%", "(", "self", ".", "name", ",", "obj", ".", "__class__", ".", "__name__", ")", ")", "if", "self", ".", "name", "not", "in", "obj", ".", "_property_values", ":", "return", "self", ".", "_get_default", "(", "obj", ")", "else", ":", "return", "obj", ".", "_property_values", "[", "self", ".", "name", "]" ]
Internal implementation of instance attribute access for the ``BasicPropertyDescriptor`` getter. If the value has not been explicitly set by a user, return that value. Otherwise, return the default. Args: obj (HasProps) : the instance to get a value of this property for Returns: object Raises: RuntimeError If the |HasProps| instance has not yet been initialized, or if this descriptor is on a class that is not a |HasProps|.
[ "Internal", "implementation", "of", "instance", "attribute", "access", "for", "the", "BasicPropertyDescriptor", "getter", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L671-L697
train
bokeh/bokeh
bokeh/core/property/descriptors.py
BasicPropertyDescriptor._get_default
def _get_default(self, obj): ''' Internal implementation of instance attribute access for default values. Handles bookeeping around |PropertyContainer| value, etc. ''' if self.name in obj._property_values: # this shouldn't happen because we should have checked before _get_default() raise RuntimeError("Bokeh internal error, does not handle the case of self.name already in _property_values") is_themed = obj.themed_values() is not None and self.name in obj.themed_values() default = self.instance_default(obj) if is_themed: unstable_dict = obj._unstable_themed_values else: unstable_dict = obj._unstable_default_values if self.name in unstable_dict: return unstable_dict[self.name] if self.property._may_have_unstable_default(): if isinstance(default, PropertyValueContainer): default._register_owner(obj, self) unstable_dict[self.name] = default return default
python
def _get_default(self, obj): ''' Internal implementation of instance attribute access for default values. Handles bookeeping around |PropertyContainer| value, etc. ''' if self.name in obj._property_values: # this shouldn't happen because we should have checked before _get_default() raise RuntimeError("Bokeh internal error, does not handle the case of self.name already in _property_values") is_themed = obj.themed_values() is not None and self.name in obj.themed_values() default = self.instance_default(obj) if is_themed: unstable_dict = obj._unstable_themed_values else: unstable_dict = obj._unstable_default_values if self.name in unstable_dict: return unstable_dict[self.name] if self.property._may_have_unstable_default(): if isinstance(default, PropertyValueContainer): default._register_owner(obj, self) unstable_dict[self.name] = default return default
[ "def", "_get_default", "(", "self", ",", "obj", ")", ":", "if", "self", ".", "name", "in", "obj", ".", "_property_values", ":", "# this shouldn't happen because we should have checked before _get_default()", "raise", "RuntimeError", "(", "\"Bokeh internal error, does not handle the case of self.name already in _property_values\"", ")", "is_themed", "=", "obj", ".", "themed_values", "(", ")", "is", "not", "None", "and", "self", ".", "name", "in", "obj", ".", "themed_values", "(", ")", "default", "=", "self", ".", "instance_default", "(", "obj", ")", "if", "is_themed", ":", "unstable_dict", "=", "obj", ".", "_unstable_themed_values", "else", ":", "unstable_dict", "=", "obj", ".", "_unstable_default_values", "if", "self", ".", "name", "in", "unstable_dict", ":", "return", "unstable_dict", "[", "self", ".", "name", "]", "if", "self", ".", "property", ".", "_may_have_unstable_default", "(", ")", ":", "if", "isinstance", "(", "default", ",", "PropertyValueContainer", ")", ":", "default", ".", "_register_owner", "(", "obj", ",", "self", ")", "unstable_dict", "[", "self", ".", "name", "]", "=", "default", "return", "default" ]
Internal implementation of instance attribute access for default values. Handles bookeeping around |PropertyContainer| value, etc.
[ "Internal", "implementation", "of", "instance", "attribute", "access", "for", "default", "values", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L699-L727
train
bokeh/bokeh
bokeh/core/property/descriptors.py
BasicPropertyDescriptor._internal_set
def _internal_set(self, obj, value, hint=None, setter=None): ''' Internal implementation to set property values, that is used by __set__, set_from_json, etc. Delegate to the |Property| instance to prepare the value appropriately, then `set. Args: obj (HasProps) The object the property is being set on. old (obj) : The previous value of the property to compare hint (event hint or None, optional) An optional update event hint, e.g. ``ColumnStreamedEvent`` (default: None) Update event hints are usually used at times when better update performance can be obtained by special-casing in some way (e.g. streaming or patching column data sources) setter (ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. (default: None) In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. Returns: None ''' value = self.property.prepare_value(obj, self.name, value) old = self.__get__(obj, obj.__class__) self._real_set(obj, old, value, hint=hint, setter=setter)
python
def _internal_set(self, obj, value, hint=None, setter=None): ''' Internal implementation to set property values, that is used by __set__, set_from_json, etc. Delegate to the |Property| instance to prepare the value appropriately, then `set. Args: obj (HasProps) The object the property is being set on. old (obj) : The previous value of the property to compare hint (event hint or None, optional) An optional update event hint, e.g. ``ColumnStreamedEvent`` (default: None) Update event hints are usually used at times when better update performance can be obtained by special-casing in some way (e.g. streaming or patching column data sources) setter (ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. (default: None) In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. Returns: None ''' value = self.property.prepare_value(obj, self.name, value) old = self.__get__(obj, obj.__class__) self._real_set(obj, old, value, hint=hint, setter=setter)
[ "def", "_internal_set", "(", "self", ",", "obj", ",", "value", ",", "hint", "=", "None", ",", "setter", "=", "None", ")", ":", "value", "=", "self", ".", "property", ".", "prepare_value", "(", "obj", ",", "self", ".", "name", ",", "value", ")", "old", "=", "self", ".", "__get__", "(", "obj", ",", "obj", ".", "__class__", ")", "self", ".", "_real_set", "(", "obj", ",", "old", ",", "value", ",", "hint", "=", "hint", ",", "setter", "=", "setter", ")" ]
Internal implementation to set property values, that is used by __set__, set_from_json, etc. Delegate to the |Property| instance to prepare the value appropriately, then `set. Args: obj (HasProps) The object the property is being set on. old (obj) : The previous value of the property to compare hint (event hint or None, optional) An optional update event hint, e.g. ``ColumnStreamedEvent`` (default: None) Update event hints are usually used at times when better update performance can be obtained by special-casing in some way (e.g. streaming or patching column data sources) setter (ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. (default: None) In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. Returns: None
[ "Internal", "implementation", "to", "set", "property", "values", "that", "is", "used", "by", "__set__", "set_from_json", "etc", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L729-L769
train
bokeh/bokeh
bokeh/core/property/descriptors.py
BasicPropertyDescriptor._real_set
def _real_set(self, obj, old, value, hint=None, setter=None): ''' Internal implementation helper to set property values. This function handles bookkeeping around noting whether values have been explicitly set, etc. Args: obj (HasProps) The object the property is being set on. old (obj) : The previous value of the property to compare hint (event hint or None, optional) An optional update event hint, e.g. ``ColumnStreamedEvent`` (default: None) Update event hints are usually used at times when better update performance can be obtained by special-casing in some way (e.g. streaming or patching column data sources) setter (ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. (default: None) In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. Returns: None ''' # Normally we want a "no-op" if the new value and old value are identical # but some hinted events are in-place. This check will allow those cases # to continue on to the notification machinery if self.property.matches(value, old) and (hint is None): return was_set = self.name in obj._property_values # "old" is the logical old value, but it may not be the actual current # attribute value if our value was mutated behind our back and we got # _notify_mutated. if was_set: old_attr_value = obj._property_values[self.name] else: old_attr_value = old if old_attr_value is not value: if isinstance(old_attr_value, PropertyValueContainer): old_attr_value._unregister_owner(obj, self) if isinstance(value, PropertyValueContainer): value._register_owner(obj, self) if self.name in obj._unstable_themed_values: del obj._unstable_themed_values[self.name] if self.name in obj._unstable_default_values: del obj._unstable_default_values[self.name] obj._property_values[self.name] = value # for notification purposes, "old" should be the logical old self._trigger(obj, old, value, hint=hint, setter=setter)
python
def _real_set(self, obj, old, value, hint=None, setter=None): ''' Internal implementation helper to set property values. This function handles bookkeeping around noting whether values have been explicitly set, etc. Args: obj (HasProps) The object the property is being set on. old (obj) : The previous value of the property to compare hint (event hint or None, optional) An optional update event hint, e.g. ``ColumnStreamedEvent`` (default: None) Update event hints are usually used at times when better update performance can be obtained by special-casing in some way (e.g. streaming or patching column data sources) setter (ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. (default: None) In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. Returns: None ''' # Normally we want a "no-op" if the new value and old value are identical # but some hinted events are in-place. This check will allow those cases # to continue on to the notification machinery if self.property.matches(value, old) and (hint is None): return was_set = self.name in obj._property_values # "old" is the logical old value, but it may not be the actual current # attribute value if our value was mutated behind our back and we got # _notify_mutated. if was_set: old_attr_value = obj._property_values[self.name] else: old_attr_value = old if old_attr_value is not value: if isinstance(old_attr_value, PropertyValueContainer): old_attr_value._unregister_owner(obj, self) if isinstance(value, PropertyValueContainer): value._register_owner(obj, self) if self.name in obj._unstable_themed_values: del obj._unstable_themed_values[self.name] if self.name in obj._unstable_default_values: del obj._unstable_default_values[self.name] obj._property_values[self.name] = value # for notification purposes, "old" should be the logical old self._trigger(obj, old, value, hint=hint, setter=setter)
[ "def", "_real_set", "(", "self", ",", "obj", ",", "old", ",", "value", ",", "hint", "=", "None", ",", "setter", "=", "None", ")", ":", "# Normally we want a \"no-op\" if the new value and old value are identical", "# but some hinted events are in-place. This check will allow those cases", "# to continue on to the notification machinery", "if", "self", ".", "property", ".", "matches", "(", "value", ",", "old", ")", "and", "(", "hint", "is", "None", ")", ":", "return", "was_set", "=", "self", ".", "name", "in", "obj", ".", "_property_values", "# \"old\" is the logical old value, but it may not be the actual current", "# attribute value if our value was mutated behind our back and we got", "# _notify_mutated.", "if", "was_set", ":", "old_attr_value", "=", "obj", ".", "_property_values", "[", "self", ".", "name", "]", "else", ":", "old_attr_value", "=", "old", "if", "old_attr_value", "is", "not", "value", ":", "if", "isinstance", "(", "old_attr_value", ",", "PropertyValueContainer", ")", ":", "old_attr_value", ".", "_unregister_owner", "(", "obj", ",", "self", ")", "if", "isinstance", "(", "value", ",", "PropertyValueContainer", ")", ":", "value", ".", "_register_owner", "(", "obj", ",", "self", ")", "if", "self", ".", "name", "in", "obj", ".", "_unstable_themed_values", ":", "del", "obj", ".", "_unstable_themed_values", "[", "self", ".", "name", "]", "if", "self", ".", "name", "in", "obj", ".", "_unstable_default_values", ":", "del", "obj", ".", "_unstable_default_values", "[", "self", ".", "name", "]", "obj", ".", "_property_values", "[", "self", ".", "name", "]", "=", "value", "# for notification purposes, \"old\" should be the logical old", "self", ".", "_trigger", "(", "obj", ",", "old", ",", "value", ",", "hint", "=", "hint", ",", "setter", "=", "setter", ")" ]
Internal implementation helper to set property values. This function handles bookkeeping around noting whether values have been explicitly set, etc. Args: obj (HasProps) The object the property is being set on. old (obj) : The previous value of the property to compare hint (event hint or None, optional) An optional update event hint, e.g. ``ColumnStreamedEvent`` (default: None) Update event hints are usually used at times when better update performance can be obtained by special-casing in some way (e.g. streaming or patching column data sources) setter (ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. (default: None) In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. Returns: None
[ "Internal", "implementation", "helper", "to", "set", "property", "values", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L771-L838
train
bokeh/bokeh
bokeh/core/property/descriptors.py
BasicPropertyDescriptor._notify_mutated
def _notify_mutated(self, obj, old, hint=None): ''' A method to call when a container is mutated "behind our back" and we detect it with our |PropertyContainer| wrappers. Args: obj (HasProps) : The object who's container value was mutated old (object) : The "old" value of the container In this case, somewhat weirdly, ``old`` is a copy and the new value should already be set unless we change it due to validation. hint (event hint or None, optional) An optional update event hint, e.g. ``ColumnStreamedEvent`` (default: None) Update event hints are usually used at times when better update performance can be obtained by special-casing in some way (e.g. streaming or patching column data sources) Returns: None ''' value = self.__get__(obj, obj.__class__) # re-validate because the contents of 'old' have changed, # in some cases this could give us a new object for the value value = self.property.prepare_value(obj, self.name, value) self._real_set(obj, old, value, hint=hint)
python
def _notify_mutated(self, obj, old, hint=None): ''' A method to call when a container is mutated "behind our back" and we detect it with our |PropertyContainer| wrappers. Args: obj (HasProps) : The object who's container value was mutated old (object) : The "old" value of the container In this case, somewhat weirdly, ``old`` is a copy and the new value should already be set unless we change it due to validation. hint (event hint or None, optional) An optional update event hint, e.g. ``ColumnStreamedEvent`` (default: None) Update event hints are usually used at times when better update performance can be obtained by special-casing in some way (e.g. streaming or patching column data sources) Returns: None ''' value = self.__get__(obj, obj.__class__) # re-validate because the contents of 'old' have changed, # in some cases this could give us a new object for the value value = self.property.prepare_value(obj, self.name, value) self._real_set(obj, old, value, hint=hint)
[ "def", "_notify_mutated", "(", "self", ",", "obj", ",", "old", ",", "hint", "=", "None", ")", ":", "value", "=", "self", ".", "__get__", "(", "obj", ",", "obj", ".", "__class__", ")", "# re-validate because the contents of 'old' have changed,", "# in some cases this could give us a new object for the value", "value", "=", "self", ".", "property", ".", "prepare_value", "(", "obj", ",", "self", ".", "name", ",", "value", ")", "self", ".", "_real_set", "(", "obj", ",", "old", ",", "value", ",", "hint", "=", "hint", ")" ]
A method to call when a container is mutated "behind our back" and we detect it with our |PropertyContainer| wrappers. Args: obj (HasProps) : The object who's container value was mutated old (object) : The "old" value of the container In this case, somewhat weirdly, ``old`` is a copy and the new value should already be set unless we change it due to validation. hint (event hint or None, optional) An optional update event hint, e.g. ``ColumnStreamedEvent`` (default: None) Update event hints are usually used at times when better update performance can be obtained by special-casing in some way (e.g. streaming or patching column data sources) Returns: None
[ "A", "method", "to", "call", "when", "a", "container", "is", "mutated", "behind", "our", "back", "and", "we", "detect", "it", "with", "our", "|PropertyContainer|", "wrappers", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L842-L875
train
bokeh/bokeh
bokeh/core/property/descriptors.py
BasicPropertyDescriptor._trigger
def _trigger(self, obj, old, value, hint=None, setter=None): ''' Unconditionally send a change event notification for the property. Args: obj (HasProps) The object the property is being set on. old (obj) : The previous value of the property new (obj) : The new value of the property hint (event hint or None, optional) An optional update event hint, e.g. ``ColumnStreamedEvent`` (default: None) Update event hints are usually used at times when better update performance can be obtained by special-casing in some way (e.g. streaming or patching column data sources) setter (ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. (default: None) In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. Returns: None ''' if hasattr(obj, 'trigger'): obj.trigger(self.name, old, value, hint, setter)
python
def _trigger(self, obj, old, value, hint=None, setter=None): ''' Unconditionally send a change event notification for the property. Args: obj (HasProps) The object the property is being set on. old (obj) : The previous value of the property new (obj) : The new value of the property hint (event hint or None, optional) An optional update event hint, e.g. ``ColumnStreamedEvent`` (default: None) Update event hints are usually used at times when better update performance can be obtained by special-casing in some way (e.g. streaming or patching column data sources) setter (ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. (default: None) In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. Returns: None ''' if hasattr(obj, 'trigger'): obj.trigger(self.name, old, value, hint, setter)
[ "def", "_trigger", "(", "self", ",", "obj", ",", "old", ",", "value", ",", "hint", "=", "None", ",", "setter", "=", "None", ")", ":", "if", "hasattr", "(", "obj", ",", "'trigger'", ")", ":", "obj", ".", "trigger", "(", "self", ".", "name", ",", "old", ",", "value", ",", "hint", ",", "setter", ")" ]
Unconditionally send a change event notification for the property. Args: obj (HasProps) The object the property is being set on. old (obj) : The previous value of the property new (obj) : The new value of the property hint (event hint or None, optional) An optional update event hint, e.g. ``ColumnStreamedEvent`` (default: None) Update event hints are usually used at times when better update performance can be obtained by special-casing in some way (e.g. streaming or patching column data sources) setter (ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. (default: None) In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. Returns: None
[ "Unconditionally", "send", "a", "change", "event", "notification", "for", "the", "property", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L877-L915
train
bokeh/bokeh
bokeh/core/property/descriptors.py
DataSpecPropertyDescriptor.set_from_json
def set_from_json(self, obj, json, models=None, setter=None): ''' Sets the value of this property from a JSON value. This method first Args: obj (HasProps) : json (JSON-dict) : models(seq[Model], optional) : setter (ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. (default: None) In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. Returns: None ''' if isinstance(json, dict): # we want to try to keep the "format" of the data spec as string, dict, or number, # assuming the serialized dict is compatible with that. old = getattr(obj, self.name) if old is not None: try: self.property._type.validate(old, False) if 'value' in json: json = json['value'] except ValueError: if isinstance(old, string_types) and 'field' in json: json = json['field'] # leave it as a dict if 'old' was a dict super(DataSpecPropertyDescriptor, self).set_from_json(obj, json, models, setter)
python
def set_from_json(self, obj, json, models=None, setter=None): ''' Sets the value of this property from a JSON value. This method first Args: obj (HasProps) : json (JSON-dict) : models(seq[Model], optional) : setter (ClientSession or ServerSession or None, optional) : This is used to prevent "boomerang" updates to Bokeh apps. (default: None) In the context of a Bokeh server application, incoming updates to properties will be annotated with the session that is doing the updating. This value is propagated through any subsequent change notifications that the update triggers. The session can compare the event setter to itself, and suppress any updates that originate from itself. Returns: None ''' if isinstance(json, dict): # we want to try to keep the "format" of the data spec as string, dict, or number, # assuming the serialized dict is compatible with that. old = getattr(obj, self.name) if old is not None: try: self.property._type.validate(old, False) if 'value' in json: json = json['value'] except ValueError: if isinstance(old, string_types) and 'field' in json: json = json['field'] # leave it as a dict if 'old' was a dict super(DataSpecPropertyDescriptor, self).set_from_json(obj, json, models, setter)
[ "def", "set_from_json", "(", "self", ",", "obj", ",", "json", ",", "models", "=", "None", ",", "setter", "=", "None", ")", ":", "if", "isinstance", "(", "json", ",", "dict", ")", ":", "# we want to try to keep the \"format\" of the data spec as string, dict, or number,", "# assuming the serialized dict is compatible with that.", "old", "=", "getattr", "(", "obj", ",", "self", ".", "name", ")", "if", "old", "is", "not", "None", ":", "try", ":", "self", ".", "property", ".", "_type", ".", "validate", "(", "old", ",", "False", ")", "if", "'value'", "in", "json", ":", "json", "=", "json", "[", "'value'", "]", "except", "ValueError", ":", "if", "isinstance", "(", "old", ",", "string_types", ")", "and", "'field'", "in", "json", ":", "json", "=", "json", "[", "'field'", "]", "# leave it as a dict if 'old' was a dict", "super", "(", "DataSpecPropertyDescriptor", ",", "self", ")", ".", "set_from_json", "(", "obj", ",", "json", ",", "models", ",", "setter", ")" ]
Sets the value of this property from a JSON value. This method first Args: obj (HasProps) : json (JSON-dict) : models(seq[Model], optional) : 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
[ "Sets", "the", "value", "of", "this", "property", "from", "a", "JSON", "value", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L987-L1028
train
bokeh/bokeh
bokeh/core/property/descriptors.py
UnitsSpecPropertyDescriptor.set_from_json
def set_from_json(self, obj, json, models=None, setter=None): ''' Sets the value of this property from a JSON value. This method first separately extracts and removes any ``units`` field in the JSON, and sets the associated units property directly. The remaining JSON is then passed to the superclass ``set_from_json`` to be handled. Args: obj: (HasProps) : instance to set the property value on 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. (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 ''' json = self._extract_units(obj, json) super(UnitsSpecPropertyDescriptor, self).set_from_json(obj, json, models, setter)
python
def set_from_json(self, obj, json, models=None, setter=None): ''' Sets the value of this property from a JSON value. This method first separately extracts and removes any ``units`` field in the JSON, and sets the associated units property directly. The remaining JSON is then passed to the superclass ``set_from_json`` to be handled. Args: obj: (HasProps) : instance to set the property value on 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. (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 ''' json = self._extract_units(obj, json) super(UnitsSpecPropertyDescriptor, self).set_from_json(obj, json, models, setter)
[ "def", "set_from_json", "(", "self", ",", "obj", ",", "json", ",", "models", "=", "None", ",", "setter", "=", "None", ")", ":", "json", "=", "self", ".", "_extract_units", "(", "obj", ",", "json", ")", "super", "(", "UnitsSpecPropertyDescriptor", ",", "self", ")", ".", "set_from_json", "(", "obj", ",", "json", ",", "models", ",", "setter", ")" ]
Sets the value of this property from a JSON value. This method first separately extracts and removes any ``units`` field in the JSON, and sets the associated units property directly. The remaining JSON is then passed to the superclass ``set_from_json`` to be handled. Args: obj: (HasProps) : instance to set the property value on 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. (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
[ "Sets", "the", "value", "of", "this", "property", "from", "a", "JSON", "value", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L1091-L1126
train
bokeh/bokeh
bokeh/core/property/descriptors.py
UnitsSpecPropertyDescriptor._extract_units
def _extract_units(self, obj, value): ''' Internal helper for dealing with units associated units properties when setting values on |UnitsSpec| properties. When ``value`` is a dict, this function may mutate the value of the associated units property. Args: obj (HasProps) : instance to update units spec property value for value (obj) : new value to set for the property Returns: copy of ``value``, with 'units' key and value removed when applicable ''' if isinstance(value, dict): if 'units' in value: value = copy(value) # so we can modify it units = value.pop("units", None) if units: self.units_prop.__set__(obj, units) return value
python
def _extract_units(self, obj, value): ''' Internal helper for dealing with units associated units properties when setting values on |UnitsSpec| properties. When ``value`` is a dict, this function may mutate the value of the associated units property. Args: obj (HasProps) : instance to update units spec property value for value (obj) : new value to set for the property Returns: copy of ``value``, with 'units' key and value removed when applicable ''' if isinstance(value, dict): if 'units' in value: value = copy(value) # so we can modify it units = value.pop("units", None) if units: self.units_prop.__set__(obj, units) return value
[ "def", "_extract_units", "(", "self", ",", "obj", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "if", "'units'", "in", "value", ":", "value", "=", "copy", "(", "value", ")", "# so we can modify it", "units", "=", "value", ".", "pop", "(", "\"units\"", ",", "None", ")", "if", "units", ":", "self", ".", "units_prop", ".", "__set__", "(", "obj", ",", "units", ")", "return", "value" ]
Internal helper for dealing with units associated units properties when setting values on |UnitsSpec| properties. When ``value`` is a dict, this function may mutate the value of the associated units property. Args: obj (HasProps) : instance to update units spec property value for value (obj) : new value to set for the property Returns: copy of ``value``, with 'units' key and value removed when applicable
[ "Internal", "helper", "for", "dealing", "with", "units", "associated", "units", "properties", "when", "setting", "values", "on", "|UnitsSpec|", "properties", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/descriptors.py#L1128-L1150
train
bokeh/bokeh
bokeh/io/notebook.py
install_notebook_hook
def install_notebook_hook(notebook_type, load, show_doc, show_app, overwrite=False): ''' Install a new notebook display hook. Bokeh comes with support for Jupyter notebooks built-in. However, there are other kinds of notebooks in use by different communities. This function provides a mechanism for other projects to instruct Bokeh how to display content in other notebooks. This function is primarily of use to developers wishing to integrate Bokeh with new notebook types. Args: notebook_type (str) : A name for the notebook type, e.e. ``'Jupyter'`` or ``'Zeppelin'`` If the name has previously been installed, a ``RuntimeError`` will be raised, unless ``overwrite=True`` load (callable) : A function for loading BokehJS in a notebook type. The function will be called with the following arguments: .. code-block:: python load( resources, # A Resources object for how to load BokehJS verbose, # Whether to display verbose loading banner hide_banner, # Whether to hide the output banner entirely load_timeout # Time after which to report a load fail error ) show_doc (callable) : A function for displaying Bokeh standalone documents in the notebook type. This function will be called with the following arguments: .. code-block:: python show_doc( obj, # the Bokeh object to display state, # current bokeh.io "state" notebook_handle # whether a notebook handle was requested ) If the notebook platform is capable of supporting in-place updates to plots then this function may return an opaque notebook handle that can be used for that purpose. The handle will be returned by ``show()``, and can be used by as appropriate to update plots, etc. by additional functions in the library that installed the hooks. show_app (callable) : A function for displaying Bokeh applications in the notebook type. This function will be called with the following arguments: .. code-block:: python show_app( app, # the Bokeh Application to display state, # current bokeh.io "state" notebook_url, # URL to the current active notebook page **kw # any backend-specific keywords passed as-is ) overwrite (bool, optional) : Whether to allow an existing hook to be overwritten by a new definition (default: False) Returns: None Raises: RuntimeError If ``notebook_type`` is already installed and ``overwrite=False`` ''' if notebook_type in _HOOKS and not overwrite: raise RuntimeError("hook for notebook type %r already exists" % notebook_type) _HOOKS[notebook_type] = dict(load=load, doc=show_doc, app=show_app)
python
def install_notebook_hook(notebook_type, load, show_doc, show_app, overwrite=False): ''' Install a new notebook display hook. Bokeh comes with support for Jupyter notebooks built-in. However, there are other kinds of notebooks in use by different communities. This function provides a mechanism for other projects to instruct Bokeh how to display content in other notebooks. This function is primarily of use to developers wishing to integrate Bokeh with new notebook types. Args: notebook_type (str) : A name for the notebook type, e.e. ``'Jupyter'`` or ``'Zeppelin'`` If the name has previously been installed, a ``RuntimeError`` will be raised, unless ``overwrite=True`` load (callable) : A function for loading BokehJS in a notebook type. The function will be called with the following arguments: .. code-block:: python load( resources, # A Resources object for how to load BokehJS verbose, # Whether to display verbose loading banner hide_banner, # Whether to hide the output banner entirely load_timeout # Time after which to report a load fail error ) show_doc (callable) : A function for displaying Bokeh standalone documents in the notebook type. This function will be called with the following arguments: .. code-block:: python show_doc( obj, # the Bokeh object to display state, # current bokeh.io "state" notebook_handle # whether a notebook handle was requested ) If the notebook platform is capable of supporting in-place updates to plots then this function may return an opaque notebook handle that can be used for that purpose. The handle will be returned by ``show()``, and can be used by as appropriate to update plots, etc. by additional functions in the library that installed the hooks. show_app (callable) : A function for displaying Bokeh applications in the notebook type. This function will be called with the following arguments: .. code-block:: python show_app( app, # the Bokeh Application to display state, # current bokeh.io "state" notebook_url, # URL to the current active notebook page **kw # any backend-specific keywords passed as-is ) overwrite (bool, optional) : Whether to allow an existing hook to be overwritten by a new definition (default: False) Returns: None Raises: RuntimeError If ``notebook_type`` is already installed and ``overwrite=False`` ''' if notebook_type in _HOOKS and not overwrite: raise RuntimeError("hook for notebook type %r already exists" % notebook_type) _HOOKS[notebook_type] = dict(load=load, doc=show_doc, app=show_app)
[ "def", "install_notebook_hook", "(", "notebook_type", ",", "load", ",", "show_doc", ",", "show_app", ",", "overwrite", "=", "False", ")", ":", "if", "notebook_type", "in", "_HOOKS", "and", "not", "overwrite", ":", "raise", "RuntimeError", "(", "\"hook for notebook type %r already exists\"", "%", "notebook_type", ")", "_HOOKS", "[", "notebook_type", "]", "=", "dict", "(", "load", "=", "load", ",", "doc", "=", "show_doc", ",", "app", "=", "show_app", ")" ]
Install a new notebook display hook. Bokeh comes with support for Jupyter notebooks built-in. However, there are other kinds of notebooks in use by different communities. This function provides a mechanism for other projects to instruct Bokeh how to display content in other notebooks. This function is primarily of use to developers wishing to integrate Bokeh with new notebook types. Args: notebook_type (str) : A name for the notebook type, e.e. ``'Jupyter'`` or ``'Zeppelin'`` If the name has previously been installed, a ``RuntimeError`` will be raised, unless ``overwrite=True`` load (callable) : A function for loading BokehJS in a notebook type. The function will be called with the following arguments: .. code-block:: python load( resources, # A Resources object for how to load BokehJS verbose, # Whether to display verbose loading banner hide_banner, # Whether to hide the output banner entirely load_timeout # Time after which to report a load fail error ) show_doc (callable) : A function for displaying Bokeh standalone documents in the notebook type. This function will be called with the following arguments: .. code-block:: python show_doc( obj, # the Bokeh object to display state, # current bokeh.io "state" notebook_handle # whether a notebook handle was requested ) If the notebook platform is capable of supporting in-place updates to plots then this function may return an opaque notebook handle that can be used for that purpose. The handle will be returned by ``show()``, and can be used by as appropriate to update plots, etc. by additional functions in the library that installed the hooks. show_app (callable) : A function for displaying Bokeh applications in the notebook type. This function will be called with the following arguments: .. code-block:: python show_app( app, # the Bokeh Application to display state, # current bokeh.io "state" notebook_url, # URL to the current active notebook page **kw # any backend-specific keywords passed as-is ) overwrite (bool, optional) : Whether to allow an existing hook to be overwritten by a new definition (default: False) Returns: None Raises: RuntimeError If ``notebook_type`` is already installed and ``overwrite=False``
[ "Install", "a", "new", "notebook", "display", "hook", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/notebook.py#L112-L189
train
bokeh/bokeh
bokeh/io/notebook.py
push_notebook
def push_notebook(document=None, state=None, handle=None): ''' Update Bokeh plots in a Jupyter notebook output cells with new data or property values. When working the the notebook, the ``show`` function can be passed the argument ``notebook_handle=True``, which will cause it to return a handle object that can be used to update the Bokeh output later. When ``push_notebook`` is called, any property updates (e.g. plot titles or data source values, etc.) since the last call to ``push_notebook`` or the original ``show`` call are applied to the Bokeh output in the previously rendered Jupyter output cell. Several example notebooks can be found in the GitHub repository in the :bokeh-tree:`examples/howto/notebook_comms` directory. Args: document (Document, optional) : A :class:`~bokeh.document.Document` to push from. If None, uses ``curdoc()``. (default: None) state (State, optional) : A :class:`State` object. If None, then the current default state (set by ``output_file``, etc.) is used. (default: None) Returns: None Examples: Typical usage is typically similar to this: .. code-block:: python from bokeh.plotting import figure from bokeh.io import output_notebook, push_notebook, show output_notebook() plot = figure() plot.circle([1,2,3], [4,6,5]) handle = show(plot, notebook_handle=True) # Update the plot title in the earlier cell plot.title.text = "New Title" push_notebook(handle=handle) ''' from ..protocol import Protocol if state is None: state = curstate() if not document: document = state.document if not document: warn("No document to push") return if handle is None: handle = state.last_comms_handle if not handle: warn("Cannot find a last shown plot to update. Call output_notebook() and show(..., notebook_handle=True) before push_notebook()") return events = list(handle.doc._held_events) # This is to avoid having an exception raised for attempting to create a # PATCH-DOC with no events. In the notebook, we just want to silently # ignore calls to push_notebook when there are no new events if len(events) == 0: return handle.doc._held_events = [] msg = Protocol("1.0").create("PATCH-DOC", events) handle.comms.send(msg.header_json) handle.comms.send(msg.metadata_json) handle.comms.send(msg.content_json) for header, payload in msg.buffers: handle.comms.send(json.dumps(header)) handle.comms.send(buffers=[payload])
python
def push_notebook(document=None, state=None, handle=None): ''' Update Bokeh plots in a Jupyter notebook output cells with new data or property values. When working the the notebook, the ``show`` function can be passed the argument ``notebook_handle=True``, which will cause it to return a handle object that can be used to update the Bokeh output later. When ``push_notebook`` is called, any property updates (e.g. plot titles or data source values, etc.) since the last call to ``push_notebook`` or the original ``show`` call are applied to the Bokeh output in the previously rendered Jupyter output cell. Several example notebooks can be found in the GitHub repository in the :bokeh-tree:`examples/howto/notebook_comms` directory. Args: document (Document, optional) : A :class:`~bokeh.document.Document` to push from. If None, uses ``curdoc()``. (default: None) state (State, optional) : A :class:`State` object. If None, then the current default state (set by ``output_file``, etc.) is used. (default: None) Returns: None Examples: Typical usage is typically similar to this: .. code-block:: python from bokeh.plotting import figure from bokeh.io import output_notebook, push_notebook, show output_notebook() plot = figure() plot.circle([1,2,3], [4,6,5]) handle = show(plot, notebook_handle=True) # Update the plot title in the earlier cell plot.title.text = "New Title" push_notebook(handle=handle) ''' from ..protocol import Protocol if state is None: state = curstate() if not document: document = state.document if not document: warn("No document to push") return if handle is None: handle = state.last_comms_handle if not handle: warn("Cannot find a last shown plot to update. Call output_notebook() and show(..., notebook_handle=True) before push_notebook()") return events = list(handle.doc._held_events) # This is to avoid having an exception raised for attempting to create a # PATCH-DOC with no events. In the notebook, we just want to silently # ignore calls to push_notebook when there are no new events if len(events) == 0: return handle.doc._held_events = [] msg = Protocol("1.0").create("PATCH-DOC", events) handle.comms.send(msg.header_json) handle.comms.send(msg.metadata_json) handle.comms.send(msg.content_json) for header, payload in msg.buffers: handle.comms.send(json.dumps(header)) handle.comms.send(buffers=[payload])
[ "def", "push_notebook", "(", "document", "=", "None", ",", "state", "=", "None", ",", "handle", "=", "None", ")", ":", "from", ".", ".", "protocol", "import", "Protocol", "if", "state", "is", "None", ":", "state", "=", "curstate", "(", ")", "if", "not", "document", ":", "document", "=", "state", ".", "document", "if", "not", "document", ":", "warn", "(", "\"No document to push\"", ")", "return", "if", "handle", "is", "None", ":", "handle", "=", "state", ".", "last_comms_handle", "if", "not", "handle", ":", "warn", "(", "\"Cannot find a last shown plot to update. Call output_notebook() and show(..., notebook_handle=True) before push_notebook()\"", ")", "return", "events", "=", "list", "(", "handle", ".", "doc", ".", "_held_events", ")", "# This is to avoid having an exception raised for attempting to create a", "# PATCH-DOC with no events. In the notebook, we just want to silently", "# ignore calls to push_notebook when there are no new events", "if", "len", "(", "events", ")", "==", "0", ":", "return", "handle", ".", "doc", ".", "_held_events", "=", "[", "]", "msg", "=", "Protocol", "(", "\"1.0\"", ")", ".", "create", "(", "\"PATCH-DOC\"", ",", "events", ")", "handle", ".", "comms", ".", "send", "(", "msg", ".", "header_json", ")", "handle", ".", "comms", ".", "send", "(", "msg", ".", "metadata_json", ")", "handle", ".", "comms", ".", "send", "(", "msg", ".", "content_json", ")", "for", "header", ",", "payload", "in", "msg", ".", "buffers", ":", "handle", ".", "comms", ".", "send", "(", "json", ".", "dumps", "(", "header", ")", ")", "handle", ".", "comms", ".", "send", "(", "buffers", "=", "[", "payload", "]", ")" ]
Update Bokeh plots in a Jupyter notebook output cells with new data or property values. When working the the notebook, the ``show`` function can be passed the argument ``notebook_handle=True``, which will cause it to return a handle object that can be used to update the Bokeh output later. When ``push_notebook`` is called, any property updates (e.g. plot titles or data source values, etc.) since the last call to ``push_notebook`` or the original ``show`` call are applied to the Bokeh output in the previously rendered Jupyter output cell. Several example notebooks can be found in the GitHub repository in the :bokeh-tree:`examples/howto/notebook_comms` directory. Args: document (Document, optional) : A :class:`~bokeh.document.Document` to push from. If None, uses ``curdoc()``. (default: None) state (State, optional) : A :class:`State` object. If None, then the current default state (set by ``output_file``, etc.) is used. (default: None) Returns: None Examples: Typical usage is typically similar to this: .. code-block:: python from bokeh.plotting import figure from bokeh.io import output_notebook, push_notebook, show output_notebook() plot = figure() plot.circle([1,2,3], [4,6,5]) handle = show(plot, notebook_handle=True) # Update the plot title in the earlier cell plot.title.text = "New Title" push_notebook(handle=handle)
[ "Update", "Bokeh", "plots", "in", "a", "Jupyter", "notebook", "output", "cells", "with", "new", "data", "or", "property", "values", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/notebook.py#L191-L275
train
bokeh/bokeh
bokeh/io/notebook.py
run_notebook_hook
def run_notebook_hook(notebook_type, action, *args, **kw): ''' Run an installed notebook hook with supplied arguments. Args: noteboook_type (str) : Name of an existing installed notebook hook actions (str) : Name of the hook action to execute, ``'doc'`` or ``'app'`` All other arguments and keyword arguments are passed to the hook action exactly as supplied. Returns: Result of the hook action, as-is Raises: RuntimeError If the hook or specific action is not installed ''' if notebook_type not in _HOOKS: raise RuntimeError("no display hook installed for notebook type %r" % notebook_type) if _HOOKS[notebook_type][action] is None: raise RuntimeError("notebook hook for %r did not install %r action" % notebook_type, action) return _HOOKS[notebook_type][action](*args, **kw)
python
def run_notebook_hook(notebook_type, action, *args, **kw): ''' Run an installed notebook hook with supplied arguments. Args: noteboook_type (str) : Name of an existing installed notebook hook actions (str) : Name of the hook action to execute, ``'doc'`` or ``'app'`` All other arguments and keyword arguments are passed to the hook action exactly as supplied. Returns: Result of the hook action, as-is Raises: RuntimeError If the hook or specific action is not installed ''' if notebook_type not in _HOOKS: raise RuntimeError("no display hook installed for notebook type %r" % notebook_type) if _HOOKS[notebook_type][action] is None: raise RuntimeError("notebook hook for %r did not install %r action" % notebook_type, action) return _HOOKS[notebook_type][action](*args, **kw)
[ "def", "run_notebook_hook", "(", "notebook_type", ",", "action", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "if", "notebook_type", "not", "in", "_HOOKS", ":", "raise", "RuntimeError", "(", "\"no display hook installed for notebook type %r\"", "%", "notebook_type", ")", "if", "_HOOKS", "[", "notebook_type", "]", "[", "action", "]", "is", "None", ":", "raise", "RuntimeError", "(", "\"notebook hook for %r did not install %r action\"", "%", "notebook_type", ",", "action", ")", "return", "_HOOKS", "[", "notebook_type", "]", "[", "action", "]", "(", "*", "args", ",", "*", "*", "kw", ")" ]
Run an installed notebook hook with supplied arguments. Args: noteboook_type (str) : Name of an existing installed notebook hook actions (str) : Name of the hook action to execute, ``'doc'`` or ``'app'`` All other arguments and keyword arguments are passed to the hook action exactly as supplied. Returns: Result of the hook action, as-is Raises: RuntimeError If the hook or specific action is not installed
[ "Run", "an", "installed", "notebook", "hook", "with", "supplied", "arguments", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/notebook.py#L277-L302
train
bokeh/bokeh
bokeh/io/notebook.py
destroy_server
def destroy_server(server_id): ''' Given a UUID id of a div removed or replaced in the Jupyter notebook, destroy the corresponding server sessions and stop it. ''' server = curstate().uuid_to_server.get(server_id, None) if server is None: log.debug("No server instance found for uuid: %r" % server_id) return try: for session in server.get_sessions(): session.destroy() server.stop() del curstate().uuid_to_server[server_id] except Exception as e: log.debug("Could not destroy server for id %r: %s" % (server_id, e))
python
def destroy_server(server_id): ''' Given a UUID id of a div removed or replaced in the Jupyter notebook, destroy the corresponding server sessions and stop it. ''' server = curstate().uuid_to_server.get(server_id, None) if server is None: log.debug("No server instance found for uuid: %r" % server_id) return try: for session in server.get_sessions(): session.destroy() server.stop() del curstate().uuid_to_server[server_id] except Exception as e: log.debug("Could not destroy server for id %r: %s" % (server_id, e))
[ "def", "destroy_server", "(", "server_id", ")", ":", "server", "=", "curstate", "(", ")", ".", "uuid_to_server", ".", "get", "(", "server_id", ",", "None", ")", "if", "server", "is", "None", ":", "log", ".", "debug", "(", "\"No server instance found for uuid: %r\"", "%", "server_id", ")", "return", "try", ":", "for", "session", "in", "server", ".", "get_sessions", "(", ")", ":", "session", ".", "destroy", "(", ")", "server", ".", "stop", "(", ")", "del", "curstate", "(", ")", ".", "uuid_to_server", "[", "server_id", "]", "except", "Exception", "as", "e", ":", "log", ".", "debug", "(", "\"Could not destroy server for id %r: %s\"", "%", "(", "server_id", ",", "e", ")", ")" ]
Given a UUID id of a div removed or replaced in the Jupyter notebook, destroy the corresponding server sessions and stop it.
[ "Given", "a", "UUID", "id", "of", "a", "div", "removed", "or", "replaced", "in", "the", "Jupyter", "notebook", "destroy", "the", "corresponding", "server", "sessions", "and", "stop", "it", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/notebook.py#L308-L325
train
bokeh/bokeh
bokeh/io/notebook.py
load_notebook
def load_notebook(resources=None, verbose=False, hide_banner=False, load_timeout=5000): ''' Prepare the IPython notebook for displaying Bokeh plots. Args: resources (Resource, optional) : how and where to load BokehJS from (default: CDN) verbose (bool, optional) : whether to report detailed settings (default: False) hide_banner (bool, optional): whether to hide the Bokeh banner (default: False) load_timeout (int, optional) : Timeout in milliseconds when plots assume load timed out (default: 5000) .. warning:: Clearing the output cell containing the published BokehJS resources HTML code may cause Bokeh CSS styling to be removed. Returns: None ''' global _NOTEBOOK_LOADED from .. import __version__ from ..core.templates import NOTEBOOK_LOAD from ..util.serialization import make_id from ..resources import CDN from ..util.compiler import bundle_all_models if resources is None: resources = CDN if not hide_banner: if resources.mode == 'inline': js_info = 'inline' css_info = 'inline' else: js_info = resources.js_files[0] if len(resources.js_files) == 1 else resources.js_files css_info = resources.css_files[0] if len(resources.css_files) == 1 else resources.css_files warnings = ["Warning: " + msg['text'] for msg in resources.messages if msg['type'] == 'warn'] if _NOTEBOOK_LOADED and verbose: warnings.append('Warning: BokehJS previously loaded') element_id = make_id() html = NOTEBOOK_LOAD.render( element_id = element_id, verbose = verbose, js_info = js_info, css_info = css_info, bokeh_version = __version__, warnings = warnings, ) else: element_id = None _NOTEBOOK_LOADED = resources custom_models_js = bundle_all_models() or "" nb_js = _loading_js(resources, element_id, custom_models_js, load_timeout, register_mime=True) jl_js = _loading_js(resources, element_id, custom_models_js, load_timeout, register_mime=False) if not hide_banner: publish_display_data({'text/html': html}) publish_display_data({ JS_MIME_TYPE : nb_js, LOAD_MIME_TYPE : jl_js })
python
def load_notebook(resources=None, verbose=False, hide_banner=False, load_timeout=5000): ''' Prepare the IPython notebook for displaying Bokeh plots. Args: resources (Resource, optional) : how and where to load BokehJS from (default: CDN) verbose (bool, optional) : whether to report detailed settings (default: False) hide_banner (bool, optional): whether to hide the Bokeh banner (default: False) load_timeout (int, optional) : Timeout in milliseconds when plots assume load timed out (default: 5000) .. warning:: Clearing the output cell containing the published BokehJS resources HTML code may cause Bokeh CSS styling to be removed. Returns: None ''' global _NOTEBOOK_LOADED from .. import __version__ from ..core.templates import NOTEBOOK_LOAD from ..util.serialization import make_id from ..resources import CDN from ..util.compiler import bundle_all_models if resources is None: resources = CDN if not hide_banner: if resources.mode == 'inline': js_info = 'inline' css_info = 'inline' else: js_info = resources.js_files[0] if len(resources.js_files) == 1 else resources.js_files css_info = resources.css_files[0] if len(resources.css_files) == 1 else resources.css_files warnings = ["Warning: " + msg['text'] for msg in resources.messages if msg['type'] == 'warn'] if _NOTEBOOK_LOADED and verbose: warnings.append('Warning: BokehJS previously loaded') element_id = make_id() html = NOTEBOOK_LOAD.render( element_id = element_id, verbose = verbose, js_info = js_info, css_info = css_info, bokeh_version = __version__, warnings = warnings, ) else: element_id = None _NOTEBOOK_LOADED = resources custom_models_js = bundle_all_models() or "" nb_js = _loading_js(resources, element_id, custom_models_js, load_timeout, register_mime=True) jl_js = _loading_js(resources, element_id, custom_models_js, load_timeout, register_mime=False) if not hide_banner: publish_display_data({'text/html': html}) publish_display_data({ JS_MIME_TYPE : nb_js, LOAD_MIME_TYPE : jl_js })
[ "def", "load_notebook", "(", "resources", "=", "None", ",", "verbose", "=", "False", ",", "hide_banner", "=", "False", ",", "load_timeout", "=", "5000", ")", ":", "global", "_NOTEBOOK_LOADED", "from", ".", ".", "import", "__version__", "from", ".", ".", "core", ".", "templates", "import", "NOTEBOOK_LOAD", "from", ".", ".", "util", ".", "serialization", "import", "make_id", "from", ".", ".", "resources", "import", "CDN", "from", ".", ".", "util", ".", "compiler", "import", "bundle_all_models", "if", "resources", "is", "None", ":", "resources", "=", "CDN", "if", "not", "hide_banner", ":", "if", "resources", ".", "mode", "==", "'inline'", ":", "js_info", "=", "'inline'", "css_info", "=", "'inline'", "else", ":", "js_info", "=", "resources", ".", "js_files", "[", "0", "]", "if", "len", "(", "resources", ".", "js_files", ")", "==", "1", "else", "resources", ".", "js_files", "css_info", "=", "resources", ".", "css_files", "[", "0", "]", "if", "len", "(", "resources", ".", "css_files", ")", "==", "1", "else", "resources", ".", "css_files", "warnings", "=", "[", "\"Warning: \"", "+", "msg", "[", "'text'", "]", "for", "msg", "in", "resources", ".", "messages", "if", "msg", "[", "'type'", "]", "==", "'warn'", "]", "if", "_NOTEBOOK_LOADED", "and", "verbose", ":", "warnings", ".", "append", "(", "'Warning: BokehJS previously loaded'", ")", "element_id", "=", "make_id", "(", ")", "html", "=", "NOTEBOOK_LOAD", ".", "render", "(", "element_id", "=", "element_id", ",", "verbose", "=", "verbose", ",", "js_info", "=", "js_info", ",", "css_info", "=", "css_info", ",", "bokeh_version", "=", "__version__", ",", "warnings", "=", "warnings", ",", ")", "else", ":", "element_id", "=", "None", "_NOTEBOOK_LOADED", "=", "resources", "custom_models_js", "=", "bundle_all_models", "(", ")", "or", "\"\"", "nb_js", "=", "_loading_js", "(", "resources", ",", "element_id", ",", "custom_models_js", ",", "load_timeout", ",", "register_mime", "=", "True", ")", "jl_js", "=", "_loading_js", "(", "resources", ",", "element_id", ",", "custom_models_js", ",", "load_timeout", ",", "register_mime", "=", "False", ")", "if", "not", "hide_banner", ":", "publish_display_data", "(", "{", "'text/html'", ":", "html", "}", ")", "publish_display_data", "(", "{", "JS_MIME_TYPE", ":", "nb_js", ",", "LOAD_MIME_TYPE", ":", "jl_js", "}", ")" ]
Prepare the IPython notebook for displaying Bokeh plots. Args: resources (Resource, optional) : how and where to load BokehJS from (default: CDN) verbose (bool, optional) : whether to report detailed settings (default: False) hide_banner (bool, optional): whether to hide the Bokeh banner (default: False) load_timeout (int, optional) : Timeout in milliseconds when plots assume load timed out (default: 5000) .. warning:: Clearing the output cell containing the published BokehJS resources HTML code may cause Bokeh CSS styling to be removed. Returns: None
[ "Prepare", "the", "IPython", "notebook", "for", "displaying", "Bokeh", "plots", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/notebook.py#L348-L423
train
bokeh/bokeh
bokeh/io/notebook.py
show_app
def show_app(app, state, notebook_url, port=0, **kw): ''' Embed a Bokeh server application in a Jupyter Notebook output cell. Args: app (Application or callable) : A Bokeh Application to embed inline in a Jupyter notebook. state (State) : ** Unused ** notebook_url (str or callable) : The URL of the notebook server that is running the embedded app. If ``notebook_url`` is a string, the value string is parsed to construct the origin and full server URLs. If notebook_url is a callable, it must accept one parameter, which will be the server port, or None. If passed a port, the callable must generate the server URL, otherwise if passed None, it must generate the origin URL for the server. port (int) : A port for the embedded server will listen on. By default the port is 0, which results in the server listening on a random dynamic port. Any additional keyword arguments are passed to :class:`~bokeh.server.Server` (added in version 1.1) Returns: None ''' logging.basicConfig() from tornado.ioloop import IOLoop from ..server.server import Server loop = IOLoop.current() if callable(notebook_url): origin = notebook_url(None) else: origin = _origin_url(notebook_url) server = Server({"/": app}, io_loop=loop, port=port, allow_websocket_origin=[origin], **kw) server_id = uuid4().hex curstate().uuid_to_server[server_id] = server server.start() if callable(notebook_url): url = notebook_url(server.port) else: url = _server_url(notebook_url, server.port) logging.debug("Server URL is %s" % url) logging.debug("Origin URL is %s" % origin) from ..embed import server_document script = server_document(url, resources=None) publish_display_data({ HTML_MIME_TYPE: script, EXEC_MIME_TYPE: "" }, metadata={ EXEC_MIME_TYPE: {"server_id": server_id} })
python
def show_app(app, state, notebook_url, port=0, **kw): ''' Embed a Bokeh server application in a Jupyter Notebook output cell. Args: app (Application or callable) : A Bokeh Application to embed inline in a Jupyter notebook. state (State) : ** Unused ** notebook_url (str or callable) : The URL of the notebook server that is running the embedded app. If ``notebook_url`` is a string, the value string is parsed to construct the origin and full server URLs. If notebook_url is a callable, it must accept one parameter, which will be the server port, or None. If passed a port, the callable must generate the server URL, otherwise if passed None, it must generate the origin URL for the server. port (int) : A port for the embedded server will listen on. By default the port is 0, which results in the server listening on a random dynamic port. Any additional keyword arguments are passed to :class:`~bokeh.server.Server` (added in version 1.1) Returns: None ''' logging.basicConfig() from tornado.ioloop import IOLoop from ..server.server import Server loop = IOLoop.current() if callable(notebook_url): origin = notebook_url(None) else: origin = _origin_url(notebook_url) server = Server({"/": app}, io_loop=loop, port=port, allow_websocket_origin=[origin], **kw) server_id = uuid4().hex curstate().uuid_to_server[server_id] = server server.start() if callable(notebook_url): url = notebook_url(server.port) else: url = _server_url(notebook_url, server.port) logging.debug("Server URL is %s" % url) logging.debug("Origin URL is %s" % origin) from ..embed import server_document script = server_document(url, resources=None) publish_display_data({ HTML_MIME_TYPE: script, EXEC_MIME_TYPE: "" }, metadata={ EXEC_MIME_TYPE: {"server_id": server_id} })
[ "def", "show_app", "(", "app", ",", "state", ",", "notebook_url", ",", "port", "=", "0", ",", "*", "*", "kw", ")", ":", "logging", ".", "basicConfig", "(", ")", "from", "tornado", ".", "ioloop", "import", "IOLoop", "from", ".", ".", "server", ".", "server", "import", "Server", "loop", "=", "IOLoop", ".", "current", "(", ")", "if", "callable", "(", "notebook_url", ")", ":", "origin", "=", "notebook_url", "(", "None", ")", "else", ":", "origin", "=", "_origin_url", "(", "notebook_url", ")", "server", "=", "Server", "(", "{", "\"/\"", ":", "app", "}", ",", "io_loop", "=", "loop", ",", "port", "=", "port", ",", "allow_websocket_origin", "=", "[", "origin", "]", ",", "*", "*", "kw", ")", "server_id", "=", "uuid4", "(", ")", ".", "hex", "curstate", "(", ")", ".", "uuid_to_server", "[", "server_id", "]", "=", "server", "server", ".", "start", "(", ")", "if", "callable", "(", "notebook_url", ")", ":", "url", "=", "notebook_url", "(", "server", ".", "port", ")", "else", ":", "url", "=", "_server_url", "(", "notebook_url", ",", "server", ".", "port", ")", "logging", ".", "debug", "(", "\"Server URL is %s\"", "%", "url", ")", "logging", ".", "debug", "(", "\"Origin URL is %s\"", "%", "origin", ")", "from", ".", ".", "embed", "import", "server_document", "script", "=", "server_document", "(", "url", ",", "resources", "=", "None", ")", "publish_display_data", "(", "{", "HTML_MIME_TYPE", ":", "script", ",", "EXEC_MIME_TYPE", ":", "\"\"", "}", ",", "metadata", "=", "{", "EXEC_MIME_TYPE", ":", "{", "\"server_id\"", ":", "server_id", "}", "}", ")" ]
Embed a Bokeh server application in a Jupyter Notebook output cell. Args: app (Application or callable) : A Bokeh Application to embed inline in a Jupyter notebook. state (State) : ** Unused ** notebook_url (str or callable) : The URL of the notebook server that is running the embedded app. If ``notebook_url`` is a string, the value string is parsed to construct the origin and full server URLs. If notebook_url is a callable, it must accept one parameter, which will be the server port, or None. If passed a port, the callable must generate the server URL, otherwise if passed None, it must generate the origin URL for the server. port (int) : A port for the embedded server will listen on. By default the port is 0, which results in the server listening on a random dynamic port. Any additional keyword arguments are passed to :class:`~bokeh.server.Server` (added in version 1.1) Returns: None
[ "Embed", "a", "Bokeh", "server", "application", "in", "a", "Jupyter", "Notebook", "output", "cell", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/notebook.py#L433-L501
train
bokeh/bokeh
bokeh/colors/color.py
Color.clamp
def clamp(value, maximum=None): ''' Clamp numeric values to be non-negative, an optionally, less than a given maximum. Args: value (float) : A number to clamp. maximum (float, optional) : A max bound to to clamp to. If None, there is no upper bound, and values are only clamped to be non-negative. (default: None) Returns: float ''' value = max(value, 0) if maximum is not None: return min(value, maximum) else: return value
python
def clamp(value, maximum=None): ''' Clamp numeric values to be non-negative, an optionally, less than a given maximum. Args: value (float) : A number to clamp. maximum (float, optional) : A max bound to to clamp to. If None, there is no upper bound, and values are only clamped to be non-negative. (default: None) Returns: float ''' value = max(value, 0) if maximum is not None: return min(value, maximum) else: return value
[ "def", "clamp", "(", "value", ",", "maximum", "=", "None", ")", ":", "value", "=", "max", "(", "value", ",", "0", ")", "if", "maximum", "is", "not", "None", ":", "return", "min", "(", "value", ",", "maximum", ")", "else", ":", "return", "value" ]
Clamp numeric values to be non-negative, an optionally, less than a given maximum. Args: value (float) : A number to clamp. maximum (float, optional) : A max bound to to clamp to. If None, there is no upper bound, and values are only clamped to be non-negative. (default: None) Returns: float
[ "Clamp", "numeric", "values", "to", "be", "non", "-", "negative", "an", "optionally", "less", "than", "a", "given", "maximum", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/colors/color.py#L50-L71
train
bokeh/bokeh
bokeh/colors/color.py
Color.darken
def darken(self, amount): ''' Darken (reduce the luminance) of this color. Args: amount (float) : Amount to reduce the luminance by (clamped above zero) Returns: Color ''' hsl = self.to_hsl() hsl.l = self.clamp(hsl.l - amount) return self.from_hsl(hsl)
python
def darken(self, amount): ''' Darken (reduce the luminance) of this color. Args: amount (float) : Amount to reduce the luminance by (clamped above zero) Returns: Color ''' hsl = self.to_hsl() hsl.l = self.clamp(hsl.l - amount) return self.from_hsl(hsl)
[ "def", "darken", "(", "self", ",", "amount", ")", ":", "hsl", "=", "self", ".", "to_hsl", "(", ")", "hsl", ".", "l", "=", "self", ".", "clamp", "(", "hsl", ".", "l", "-", "amount", ")", "return", "self", ".", "from_hsl", "(", "hsl", ")" ]
Darken (reduce the luminance) of this color. Args: amount (float) : Amount to reduce the luminance by (clamped above zero) Returns: Color
[ "Darken", "(", "reduce", "the", "luminance", ")", "of", "this", "color", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/colors/color.py#L81-L94
train
bokeh/bokeh
bokeh/colors/color.py
Color.lighten
def lighten(self, amount): ''' Lighten (increase the luminance) of this color. Args: amount (float) : Amount to increase the luminance by (clamped above zero) Returns: Color ''' hsl = self.to_hsl() hsl.l = self.clamp(hsl.l + amount, 1) return self.from_hsl(hsl)
python
def lighten(self, amount): ''' Lighten (increase the luminance) of this color. Args: amount (float) : Amount to increase the luminance by (clamped above zero) Returns: Color ''' hsl = self.to_hsl() hsl.l = self.clamp(hsl.l + amount, 1) return self.from_hsl(hsl)
[ "def", "lighten", "(", "self", ",", "amount", ")", ":", "hsl", "=", "self", ".", "to_hsl", "(", ")", "hsl", ".", "l", "=", "self", ".", "clamp", "(", "hsl", ".", "l", "+", "amount", ",", "1", ")", "return", "self", ".", "from_hsl", "(", "hsl", ")" ]
Lighten (increase the luminance) of this color. Args: amount (float) : Amount to increase the luminance by (clamped above zero) Returns: Color
[ "Lighten", "(", "increase", "the", "luminance", ")", "of", "this", "color", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/colors/color.py#L129-L142
train
bokeh/bokeh
bokeh/models/widgets/buttons.py
Toggle.on_click
def on_click(self, handler): """ Set up a handler for button state changes (clicks). Args: handler (func) : handler function to call when button is toggled. Returns: None """ self.on_change('active', lambda attr, old, new: handler(new))
python
def on_click(self, handler): """ Set up a handler for button state changes (clicks). Args: handler (func) : handler function to call when button is toggled. Returns: None """ self.on_change('active', lambda attr, old, new: handler(new))
[ "def", "on_click", "(", "self", ",", "handler", ")", ":", "self", ".", "on_change", "(", "'active'", ",", "lambda", "attr", ",", "old", ",", "new", ":", "handler", "(", "new", ")", ")" ]
Set up a handler for button state changes (clicks). Args: handler (func) : handler function to call when button is toggled. Returns: None
[ "Set", "up", "a", "handler", "for", "button", "state", "changes", "(", "clicks", ")", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/widgets/buttons.py#L129-L139
train
bokeh/bokeh
bokeh/models/widgets/buttons.py
Dropdown.on_click
def on_click(self, handler): ''' Set up a handler for button or menu item clicks. Args: handler (func) : handler function to call when button is activated. Returns: None ''' self.on_event(ButtonClick, handler) self.on_event(MenuItemClick, handler)
python
def on_click(self, handler): ''' Set up a handler for button or menu item clicks. Args: handler (func) : handler function to call when button is activated. Returns: None ''' self.on_event(ButtonClick, handler) self.on_event(MenuItemClick, handler)
[ "def", "on_click", "(", "self", ",", "handler", ")", ":", "self", ".", "on_event", "(", "ButtonClick", ",", "handler", ")", "self", ".", "on_event", "(", "MenuItemClick", ",", "handler", ")" ]
Set up a handler for button or menu item clicks. Args: handler (func) : handler function to call when button is activated. Returns: None
[ "Set", "up", "a", "handler", "for", "button", "or", "menu", "item", "clicks", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/widgets/buttons.py#L160-L171
train
bokeh/bokeh
bokeh/models/widgets/buttons.py
Dropdown.js_on_click
def js_on_click(self, handler): ''' Set up a JavaScript handler for button or menu item clicks. ''' self.js_on_event(ButtonClick, handler) self.js_on_event(MenuItemClick, handler)
python
def js_on_click(self, handler): ''' Set up a JavaScript handler for button or menu item clicks. ''' self.js_on_event(ButtonClick, handler) self.js_on_event(MenuItemClick, handler)
[ "def", "js_on_click", "(", "self", ",", "handler", ")", ":", "self", ".", "js_on_event", "(", "ButtonClick", ",", "handler", ")", "self", ".", "js_on_event", "(", "MenuItemClick", ",", "handler", ")" ]
Set up a JavaScript handler for button or menu item clicks.
[ "Set", "up", "a", "JavaScript", "handler", "for", "button", "or", "menu", "item", "clicks", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/widgets/buttons.py#L173-L176
train
bokeh/bokeh
bokeh/util/dependencies.py
import_optional
def import_optional(mod_name): ''' Attempt to import an optional dependency. Silently returns None if the requested module is not available. Args: mod_name (str) : name of the optional module to try to import Returns: imported module or None, if import fails ''' try: return import_module(mod_name) except ImportError: pass except Exception: msg = "Failed to import optional module `{}`".format(mod_name) log.exception(msg)
python
def import_optional(mod_name): ''' Attempt to import an optional dependency. Silently returns None if the requested module is not available. Args: mod_name (str) : name of the optional module to try to import Returns: imported module or None, if import fails ''' try: return import_module(mod_name) except ImportError: pass except Exception: msg = "Failed to import optional module `{}`".format(mod_name) log.exception(msg)
[ "def", "import_optional", "(", "mod_name", ")", ":", "try", ":", "return", "import_module", "(", "mod_name", ")", "except", "ImportError", ":", "pass", "except", "Exception", ":", "msg", "=", "\"Failed to import optional module `{}`\"", ".", "format", "(", "mod_name", ")", "log", ".", "exception", "(", "msg", ")" ]
Attempt to import an optional dependency. Silently returns None if the requested module is not available. Args: mod_name (str) : name of the optional module to try to import Returns: imported module or None, if import fails
[ "Attempt", "to", "import", "an", "optional", "dependency", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/dependencies.py#L50-L68
train
bokeh/bokeh
bokeh/util/dependencies.py
detect_phantomjs
def detect_phantomjs(version='2.1'): ''' Detect if PhantomJS is avaiable in PATH, at a minimum version. Args: version (str, optional) : Required minimum version for PhantomJS (mostly for testing) Returns: str, path to PhantomJS ''' if settings.phantomjs_path() is not None: phantomjs_path = settings.phantomjs_path() else: if hasattr(shutil, "which"): phantomjs_path = shutil.which("phantomjs") or "phantomjs" else: # Python 2 relies on Environment variable in PATH - attempt to use as follows phantomjs_path = "phantomjs" try: proc = Popen([phantomjs_path, "--version"], stdout=PIPE, stderr=PIPE) proc.wait() out = proc.communicate() if len(out[1]) > 0: raise RuntimeError('Error encountered in PhantomJS detection: %r' % out[1].decode('utf8')) required = V(version) installed = V(out[0].decode('utf8')) if installed < required: raise RuntimeError('PhantomJS version to old. Version>=%s required, installed: %s' % (required, installed)) except OSError: raise RuntimeError('PhantomJS is not present in PATH or BOKEH_PHANTOMJS_PATH. Try "conda install phantomjs" or \ "npm install -g phantomjs-prebuilt"') return phantomjs_path
python
def detect_phantomjs(version='2.1'): ''' Detect if PhantomJS is avaiable in PATH, at a minimum version. Args: version (str, optional) : Required minimum version for PhantomJS (mostly for testing) Returns: str, path to PhantomJS ''' if settings.phantomjs_path() is not None: phantomjs_path = settings.phantomjs_path() else: if hasattr(shutil, "which"): phantomjs_path = shutil.which("phantomjs") or "phantomjs" else: # Python 2 relies on Environment variable in PATH - attempt to use as follows phantomjs_path = "phantomjs" try: proc = Popen([phantomjs_path, "--version"], stdout=PIPE, stderr=PIPE) proc.wait() out = proc.communicate() if len(out[1]) > 0: raise RuntimeError('Error encountered in PhantomJS detection: %r' % out[1].decode('utf8')) required = V(version) installed = V(out[0].decode('utf8')) if installed < required: raise RuntimeError('PhantomJS version to old. Version>=%s required, installed: %s' % (required, installed)) except OSError: raise RuntimeError('PhantomJS is not present in PATH or BOKEH_PHANTOMJS_PATH. Try "conda install phantomjs" or \ "npm install -g phantomjs-prebuilt"') return phantomjs_path
[ "def", "detect_phantomjs", "(", "version", "=", "'2.1'", ")", ":", "if", "settings", ".", "phantomjs_path", "(", ")", "is", "not", "None", ":", "phantomjs_path", "=", "settings", ".", "phantomjs_path", "(", ")", "else", ":", "if", "hasattr", "(", "shutil", ",", "\"which\"", ")", ":", "phantomjs_path", "=", "shutil", ".", "which", "(", "\"phantomjs\"", ")", "or", "\"phantomjs\"", "else", ":", "# Python 2 relies on Environment variable in PATH - attempt to use as follows", "phantomjs_path", "=", "\"phantomjs\"", "try", ":", "proc", "=", "Popen", "(", "[", "phantomjs_path", ",", "\"--version\"", "]", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ")", "proc", ".", "wait", "(", ")", "out", "=", "proc", ".", "communicate", "(", ")", "if", "len", "(", "out", "[", "1", "]", ")", ">", "0", ":", "raise", "RuntimeError", "(", "'Error encountered in PhantomJS detection: %r'", "%", "out", "[", "1", "]", ".", "decode", "(", "'utf8'", ")", ")", "required", "=", "V", "(", "version", ")", "installed", "=", "V", "(", "out", "[", "0", "]", ".", "decode", "(", "'utf8'", ")", ")", "if", "installed", "<", "required", ":", "raise", "RuntimeError", "(", "'PhantomJS version to old. Version>=%s required, installed: %s'", "%", "(", "required", ",", "installed", ")", ")", "except", "OSError", ":", "raise", "RuntimeError", "(", "'PhantomJS is not present in PATH or BOKEH_PHANTOMJS_PATH. Try \"conda install phantomjs\" or \\\n \"npm install -g phantomjs-prebuilt\"'", ")", "return", "phantomjs_path" ]
Detect if PhantomJS is avaiable in PATH, at a minimum version. Args: version (str, optional) : Required minimum version for PhantomJS (mostly for testing) Returns: str, path to PhantomJS
[ "Detect", "if", "PhantomJS", "is", "avaiable", "in", "PATH", "at", "a", "minimum", "version", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/dependencies.py#L91-L128
train
bokeh/bokeh
bokeh/protocol/receiver.py
Receiver.consume
def consume(self, fragment): ''' Consume individual protocol message fragments. Args: fragment (``JSON``) : A message fragment to assemble. When a complete message is assembled, the receiver state will reset to begin consuming a new message. ''' self._current_consumer(fragment) raise gen.Return(self._message)
python
def consume(self, fragment): ''' Consume individual protocol message fragments. Args: fragment (``JSON``) : A message fragment to assemble. When a complete message is assembled, the receiver state will reset to begin consuming a new message. ''' self._current_consumer(fragment) raise gen.Return(self._message)
[ "def", "consume", "(", "self", ",", "fragment", ")", ":", "self", ".", "_current_consumer", "(", "fragment", ")", "raise", "gen", ".", "Return", "(", "self", ".", "_message", ")" ]
Consume individual protocol message fragments. Args: fragment (``JSON``) : A message fragment to assemble. When a complete message is assembled, the receiver state will reset to begin consuming a new message.
[ "Consume", "individual", "protocol", "message", "fragments", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/protocol/receiver.py#L108-L119
train
bokeh/bokeh
bokeh/sphinxext/bokeh_autodoc.py
setup
def setup(app): ''' Required Sphinx extension setup function. ''' app.add_autodocumenter(ColorDocumenter) app.add_autodocumenter(EnumDocumenter) app.add_autodocumenter(PropDocumenter) app.add_autodocumenter(ModelDocumenter)
python
def setup(app): ''' Required Sphinx extension setup function. ''' app.add_autodocumenter(ColorDocumenter) app.add_autodocumenter(EnumDocumenter) app.add_autodocumenter(PropDocumenter) app.add_autodocumenter(ModelDocumenter)
[ "def", "setup", "(", "app", ")", ":", "app", ".", "add_autodocumenter", "(", "ColorDocumenter", ")", "app", ".", "add_autodocumenter", "(", "EnumDocumenter", ")", "app", ".", "add_autodocumenter", "(", "PropDocumenter", ")", "app", ".", "add_autodocumenter", "(", "ModelDocumenter", ")" ]
Required Sphinx extension setup function.
[ "Required", "Sphinx", "extension", "setup", "function", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/sphinxext/bokeh_autodoc.py#L107-L112
train
bokeh/bokeh
bokeh/driving.py
bounce
def bounce(sequence): ''' Return a driver function that can advance a "bounced" sequence of values. .. code-block:: none seq = [0, 1, 2, 3] # bounce(seq) => [0, 1, 2, 3, 3, 2, 1, 0, 0, 1, 2, ...] Args: sequence (seq) : a sequence of values for the driver to bounce ''' N = len(sequence) def f(i): div, mod = divmod(i, N) if div % 2 == 0: return sequence[mod] else: return sequence[N-mod-1] return partial(force, sequence=_advance(f))
python
def bounce(sequence): ''' Return a driver function that can advance a "bounced" sequence of values. .. code-block:: none seq = [0, 1, 2, 3] # bounce(seq) => [0, 1, 2, 3, 3, 2, 1, 0, 0, 1, 2, ...] Args: sequence (seq) : a sequence of values for the driver to bounce ''' N = len(sequence) def f(i): div, mod = divmod(i, N) if div % 2 == 0: return sequence[mod] else: return sequence[N-mod-1] return partial(force, sequence=_advance(f))
[ "def", "bounce", "(", "sequence", ")", ":", "N", "=", "len", "(", "sequence", ")", "def", "f", "(", "i", ")", ":", "div", ",", "mod", "=", "divmod", "(", "i", ",", "N", ")", "if", "div", "%", "2", "==", "0", ":", "return", "sequence", "[", "mod", "]", "else", ":", "return", "sequence", "[", "N", "-", "mod", "-", "1", "]", "return", "partial", "(", "force", ",", "sequence", "=", "_advance", "(", "f", ")", ")" ]
Return a driver function that can advance a "bounced" sequence of values. .. code-block:: none seq = [0, 1, 2, 3] # bounce(seq) => [0, 1, 2, 3, 3, 2, 1, 0, 0, 1, 2, ...] Args: sequence (seq) : a sequence of values for the driver to bounce
[ "Return", "a", "driver", "function", "that", "can", "advance", "a", "bounced", "sequence", "of", "values", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/driving.py#L73-L94
train
bokeh/bokeh
bokeh/driving.py
cosine
def cosine(w, A=1, phi=0, offset=0): ''' Return a driver function that can advance a sequence of cosine values. .. code-block:: none value = A * cos(w*i + phi) + offset Args: w (float) : a frequency for the cosine driver A (float) : an amplitude for the cosine driver phi (float) : a phase offset to start the cosine driver with offset (float) : a global offset to add to the driver values ''' from math import cos def f(i): return A * cos(w*i + phi) + offset return partial(force, sequence=_advance(f))
python
def cosine(w, A=1, phi=0, offset=0): ''' Return a driver function that can advance a sequence of cosine values. .. code-block:: none value = A * cos(w*i + phi) + offset Args: w (float) : a frequency for the cosine driver A (float) : an amplitude for the cosine driver phi (float) : a phase offset to start the cosine driver with offset (float) : a global offset to add to the driver values ''' from math import cos def f(i): return A * cos(w*i + phi) + offset return partial(force, sequence=_advance(f))
[ "def", "cosine", "(", "w", ",", "A", "=", "1", ",", "phi", "=", "0", ",", "offset", "=", "0", ")", ":", "from", "math", "import", "cos", "def", "f", "(", "i", ")", ":", "return", "A", "*", "cos", "(", "w", "*", "i", "+", "phi", ")", "+", "offset", "return", "partial", "(", "force", ",", "sequence", "=", "_advance", "(", "f", ")", ")" ]
Return a driver function that can advance a sequence of cosine values. .. code-block:: none value = A * cos(w*i + phi) + offset Args: w (float) : a frequency for the cosine driver A (float) : an amplitude for the cosine driver phi (float) : a phase offset to start the cosine driver with offset (float) : a global offset to add to the driver values
[ "Return", "a", "driver", "function", "that", "can", "advance", "a", "sequence", "of", "cosine", "values", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/driving.py#L96-L113
train
bokeh/bokeh
bokeh/driving.py
linear
def linear(m=1, b=0): ''' Return a driver function that can advance a sequence of linear values. .. code-block:: none value = m * i + b Args: m (float) : a slope for the linear driver x (float) : an offset for the linear driver ''' def f(i): return m * i + b return partial(force, sequence=_advance(f))
python
def linear(m=1, b=0): ''' Return a driver function that can advance a sequence of linear values. .. code-block:: none value = m * i + b Args: m (float) : a slope for the linear driver x (float) : an offset for the linear driver ''' def f(i): return m * i + b return partial(force, sequence=_advance(f))
[ "def", "linear", "(", "m", "=", "1", ",", "b", "=", "0", ")", ":", "def", "f", "(", "i", ")", ":", "return", "m", "*", "i", "+", "b", "return", "partial", "(", "force", ",", "sequence", "=", "_advance", "(", "f", ")", ")" ]
Return a driver function that can advance a sequence of linear values. .. code-block:: none value = m * i + b Args: m (float) : a slope for the linear driver x (float) : an offset for the linear driver
[ "Return", "a", "driver", "function", "that", "can", "advance", "a", "sequence", "of", "linear", "values", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/driving.py#L137-L151
train
bokeh/bokeh
bokeh/driving.py
repeat
def repeat(sequence): ''' Return a driver function that can advance a repeated of values. .. code-block:: none seq = [0, 1, 2, 3] # repeat(seq) => [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, ...] Args: sequence (seq) : a sequence of values for the driver to bounce ''' N = len(sequence) def f(i): return sequence[i%N] return partial(force, sequence=_advance(f))
python
def repeat(sequence): ''' Return a driver function that can advance a repeated of values. .. code-block:: none seq = [0, 1, 2, 3] # repeat(seq) => [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, ...] Args: sequence (seq) : a sequence of values for the driver to bounce ''' N = len(sequence) def f(i): return sequence[i%N] return partial(force, sequence=_advance(f))
[ "def", "repeat", "(", "sequence", ")", ":", "N", "=", "len", "(", "sequence", ")", "def", "f", "(", "i", ")", ":", "return", "sequence", "[", "i", "%", "N", "]", "return", "partial", "(", "force", ",", "sequence", "=", "_advance", "(", "f", ")", ")" ]
Return a driver function that can advance a repeated of values. .. code-block:: none seq = [0, 1, 2, 3] # repeat(seq) => [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, ...] Args: sequence (seq) : a sequence of values for the driver to bounce
[ "Return", "a", "driver", "function", "that", "can", "advance", "a", "repeated", "of", "values", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/driving.py#L153-L169
train