id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
30,500
bokeh/bokeh
bokeh/document/document.py
Document.unhold
def unhold(self): ''' Turn off any active document hold and apply any collected events. Returns: None ''' # no-op if we are already no holding if self._hold is None: return self._hold = None events = list(self._held_events) self._held_events = [] for event in events: self._trigger_on_change(event)
python
def unhold(self): ''' Turn off any active document hold and apply any collected events. Returns: None ''' # no-op if we are already no holding if self._hold is None: return self._hold = None events = list(self._held_events) self._held_events = [] for event in events: self._trigger_on_change(event)
[ "def", "unhold", "(", "self", ")", ":", "# no-op if we are already no holding", "if", "self", ".", "_hold", "is", "None", ":", "return", "self", ".", "_hold", "=", "None", "events", "=", "list", "(", "self", ".", "_held_events", ")", "self", ".", "_held_ev...
Turn off any active document hold and apply any collected events. Returns: None
[ "Turn", "off", "any", "active", "document", "hold", "and", "apply", "any", "collected", "events", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L637-L652
30,501
bokeh/bokeh
bokeh/document/document.py
Document.on_change
def on_change(self, *callbacks): ''' Provide callbacks to invoke if the document or any Model reachable from its roots changes. ''' for callback in callbacks: if callback in self._callbacks: continue _check_callback(callback, ('event',)) self._callbacks[callback] = callback
python
def on_change(self, *callbacks): ''' Provide callbacks to invoke if the document or any Model reachable from its roots changes. ''' for callback in callbacks: if callback in self._callbacks: continue _check_callback(callback, ('event',)) self._callbacks[callback] = callback
[ "def", "on_change", "(", "self", ",", "*", "callbacks", ")", ":", "for", "callback", "in", "callbacks", ":", "if", "callback", "in", "self", ".", "_callbacks", ":", "continue", "_check_callback", "(", "callback", ",", "(", "'event'", ",", ")", ")", "self...
Provide callbacks to invoke if the document or any Model reachable from its roots changes.
[ "Provide", "callbacks", "to", "invoke", "if", "the", "document", "or", "any", "Model", "reachable", "from", "its", "roots", "changes", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L654-L665
30,502
bokeh/bokeh
bokeh/document/document.py
Document.on_session_destroyed
def on_session_destroyed(self, *callbacks): ''' Provide callbacks to invoke when the session serving the Document is destroyed ''' for callback in callbacks: _check_callback(callback, ('session_context',)) self._session_destroyed_callbacks.add(callback)
python
def on_session_destroyed(self, *callbacks): ''' Provide callbacks to invoke when the session serving the Document is destroyed ''' for callback in callbacks: _check_callback(callback, ('session_context',)) self._session_destroyed_callbacks.add(callback)
[ "def", "on_session_destroyed", "(", "self", ",", "*", "callbacks", ")", ":", "for", "callback", "in", "callbacks", ":", "_check_callback", "(", "callback", ",", "(", "'session_context'", ",", ")", ")", "self", ".", "_session_destroyed_callbacks", ".", "add", "...
Provide callbacks to invoke when the session serving the Document is destroyed
[ "Provide", "callbacks", "to", "invoke", "when", "the", "session", "serving", "the", "Document", "is", "destroyed" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L671-L678
30,503
bokeh/bokeh
bokeh/document/document.py
Document.remove_root
def remove_root(self, model, setter=None): ''' Remove a model as root model from this Document. Changes to this model may still trigger ``on_change`` callbacks on this document, if the model is still referred to by other root models. Args: model (Model) : The model to add as a root of this document. 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. ''' if model not in self._roots: return # TODO (bev) ValueError? self._push_all_models_freeze() try: self._roots.remove(model) finally: self._pop_all_models_freeze() self._trigger_on_change(RootRemovedEvent(self, model, setter))
python
def remove_root(self, model, setter=None): ''' Remove a model as root model from this Document. Changes to this model may still trigger ``on_change`` callbacks on this document, if the model is still referred to by other root models. Args: model (Model) : The model to add as a root of this document. 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. ''' if model not in self._roots: return # TODO (bev) ValueError? self._push_all_models_freeze() try: self._roots.remove(model) finally: self._pop_all_models_freeze() self._trigger_on_change(RootRemovedEvent(self, model, setter))
[ "def", "remove_root", "(", "self", ",", "model", ",", "setter", "=", "None", ")", ":", "if", "model", "not", "in", "self", ".", "_roots", ":", "return", "# TODO (bev) ValueError?", "self", ".", "_push_all_models_freeze", "(", ")", "try", ":", "self", ".", ...
Remove a model as root model from this Document. Changes to this model may still trigger ``on_change`` callbacks on this document, if the model is still referred to by other root models. Args: model (Model) : The model to add as a root of this document. 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.
[ "Remove", "a", "model", "as", "root", "model", "from", "this", "Document", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L720-L750
30,504
bokeh/bokeh
bokeh/document/document.py
Document.replace_with_json
def replace_with_json(self, json): ''' Overwrite everything in this document with the JSON-encoded document. json (JSON-data) : A JSON-encoded document to overwrite this one. Returns: None ''' replacement = self.from_json(json) replacement._destructively_move(self)
python
def replace_with_json(self, json): ''' Overwrite everything in this document with the JSON-encoded document. json (JSON-data) : A JSON-encoded document to overwrite this one. Returns: None ''' replacement = self.from_json(json) replacement._destructively_move(self)
[ "def", "replace_with_json", "(", "self", ",", "json", ")", ":", "replacement", "=", "self", ".", "from_json", "(", "json", ")", "replacement", ".", "_destructively_move", "(", "self", ")" ]
Overwrite everything in this document with the JSON-encoded document. json (JSON-data) : A JSON-encoded document to overwrite this one. Returns: None
[ "Overwrite", "everything", "in", "this", "document", "with", "the", "JSON", "-", "encoded", "document", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L767-L779
30,505
bokeh/bokeh
bokeh/document/document.py
Document.select
def select(self, selector): ''' Query this document for objects that match the given selector. Args: selector (JSON-like query dictionary) : you can query by type or by name, e.g. ``{"type": HoverTool}``, ``{"name": "mycircle"}`` Returns: seq[Model] ''' if self._is_single_string_selector(selector, 'name'): # special-case optimization for by-name query return self._all_models_by_name.get_all(selector['name']) else: return find(self._all_models.values(), selector)
python
def select(self, selector): ''' Query this document for objects that match the given selector. Args: selector (JSON-like query dictionary) : you can query by type or by name, e.g. ``{"type": HoverTool}``, ``{"name": "mycircle"}`` Returns: seq[Model] ''' if self._is_single_string_selector(selector, 'name'): # special-case optimization for by-name query return self._all_models_by_name.get_all(selector['name']) else: return find(self._all_models.values(), selector)
[ "def", "select", "(", "self", ",", "selector", ")", ":", "if", "self", ".", "_is_single_string_selector", "(", "selector", ",", "'name'", ")", ":", "# special-case optimization for by-name query", "return", "self", ".", "_all_models_by_name", ".", "get_all", "(", ...
Query this document for objects that match the given selector. Args: selector (JSON-like query dictionary) : you can query by type or by name, e.g. ``{"type": HoverTool}``, ``{"name": "mycircle"}`` Returns: seq[Model]
[ "Query", "this", "document", "for", "objects", "that", "match", "the", "given", "selector", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L781-L796
30,506
bokeh/bokeh
bokeh/document/document.py
Document.select_one
def select_one(self, selector): ''' Query this document for objects that match the given selector. Raises an error if more than one object is found. Returns single matching object, or None if nothing is found Args: selector (JSON-like query dictionary) : you can query by type or by name, e.g. ``{"type": HoverTool}``, ``{"name": "mycircle"}`` Returns: Model or None ''' result = list(self.select(selector)) if len(result) > 1: raise ValueError("Found more than one model matching %s: %r" % (selector, result)) if len(result) == 0: return None return result[0]
python
def select_one(self, selector): ''' Query this document for objects that match the given selector. Raises an error if more than one object is found. Returns single matching object, or None if nothing is found Args: selector (JSON-like query dictionary) : you can query by type or by name, e.g. ``{"type": HoverTool}``, ``{"name": "mycircle"}`` Returns: Model or None ''' result = list(self.select(selector)) if len(result) > 1: raise ValueError("Found more than one model matching %s: %r" % (selector, result)) if len(result) == 0: return None return result[0]
[ "def", "select_one", "(", "self", ",", "selector", ")", ":", "result", "=", "list", "(", "self", ".", "select", "(", "selector", ")", ")", "if", "len", "(", "result", ")", ">", "1", ":", "raise", "ValueError", "(", "\"Found more than one model matching %s:...
Query this document for objects that match the given selector. Raises an error if more than one object is found. Returns single matching object, or None if nothing is found Args: selector (JSON-like query dictionary) : you can query by type or by name, e.g. ``{"type": HoverTool}``, ``{"name": "mycircle"}`` Returns: Model or None
[ "Query", "this", "document", "for", "objects", "that", "match", "the", "given", "selector", ".", "Raises", "an", "error", "if", "more", "than", "one", "object", "is", "found", ".", "Returns", "single", "matching", "object", "or", "None", "if", "nothing", "...
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L798-L816
30,507
bokeh/bokeh
bokeh/document/document.py
Document.to_json_string
def to_json_string(self, indent=None): ''' Convert the document to a JSON string. Args: indent (int or None, optional) : number of spaces to indent, or None to suppress all newlines and indentation (default: None) Returns: str ''' root_ids = [] for r in self._roots: root_ids.append(r.id) root_references = self._all_models.values() json = { 'title' : self.title, 'roots' : { 'root_ids' : root_ids, 'references' : references_json(root_references) }, 'version' : __version__ } return serialize_json(json, indent=indent)
python
def to_json_string(self, indent=None): ''' Convert the document to a JSON string. Args: indent (int or None, optional) : number of spaces to indent, or None to suppress all newlines and indentation (default: None) Returns: str ''' root_ids = [] for r in self._roots: root_ids.append(r.id) root_references = self._all_models.values() json = { 'title' : self.title, 'roots' : { 'root_ids' : root_ids, 'references' : references_json(root_references) }, 'version' : __version__ } return serialize_json(json, indent=indent)
[ "def", "to_json_string", "(", "self", ",", "indent", "=", "None", ")", ":", "root_ids", "=", "[", "]", "for", "r", "in", "self", ".", "_roots", ":", "root_ids", ".", "append", "(", "r", ".", "id", ")", "root_references", "=", "self", ".", "_all_model...
Convert the document to a JSON string. Args: indent (int or None, optional) : number of spaces to indent, or None to suppress all newlines and indentation (default: None) Returns: str
[ "Convert", "the", "document", "to", "a", "JSON", "string", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L848-L874
30,508
bokeh/bokeh
bokeh/document/document.py
Document.validate
def validate(self): ''' Perform integrity checks on the modes in this document. Returns: None ''' for r in self.roots: refs = r.references() check_integrity(refs)
python
def validate(self): ''' Perform integrity checks on the modes in this document. Returns: None ''' for r in self.roots: refs = r.references() check_integrity(refs)
[ "def", "validate", "(", "self", ")", ":", "for", "r", "in", "self", ".", "roots", ":", "refs", "=", "r", ".", "references", "(", ")", "check_integrity", "(", "refs", ")" ]
Perform integrity checks on the modes in this document. Returns: None
[ "Perform", "integrity", "checks", "on", "the", "modes", "in", "this", "document", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L876-L885
30,509
bokeh/bokeh
bokeh/document/document.py
Document._add_session_callback
def _add_session_callback(self, callback_obj, callback, one_shot, originator): ''' Internal implementation for adding session callbacks. Args: callback_obj (SessionCallback) : A session callback object that wraps a callable and is passed to ``trigger_on_change``. callback (callable) : A callable to execute when session events happen. one_shot (bool) : Whether the callback should immediately auto-remove itself after one execution. Returns: SessionCallback : passed in as ``callback_obj``. Raises: ValueError, if the callback has been previously added ''' if one_shot: @wraps(callback) def remove_then_invoke(*args, **kwargs): if callback_obj in self._session_callbacks: self._remove_session_callback(callback_obj, originator) return callback(*args, **kwargs) actual_callback = remove_then_invoke else: actual_callback = callback callback_obj._callback = self._wrap_with_self_as_curdoc(actual_callback) self._session_callbacks.add(callback_obj) self._callback_objs_by_callable[originator][callback].add(callback_obj) # emit event so the session is notified of the new callback self._trigger_on_change(SessionCallbackAdded(self, callback_obj)) return callback_obj
python
def _add_session_callback(self, callback_obj, callback, one_shot, originator): ''' Internal implementation for adding session callbacks. Args: callback_obj (SessionCallback) : A session callback object that wraps a callable and is passed to ``trigger_on_change``. callback (callable) : A callable to execute when session events happen. one_shot (bool) : Whether the callback should immediately auto-remove itself after one execution. Returns: SessionCallback : passed in as ``callback_obj``. Raises: ValueError, if the callback has been previously added ''' if one_shot: @wraps(callback) def remove_then_invoke(*args, **kwargs): if callback_obj in self._session_callbacks: self._remove_session_callback(callback_obj, originator) return callback(*args, **kwargs) actual_callback = remove_then_invoke else: actual_callback = callback callback_obj._callback = self._wrap_with_self_as_curdoc(actual_callback) self._session_callbacks.add(callback_obj) self._callback_objs_by_callable[originator][callback].add(callback_obj) # emit event so the session is notified of the new callback self._trigger_on_change(SessionCallbackAdded(self, callback_obj)) return callback_obj
[ "def", "_add_session_callback", "(", "self", ",", "callback_obj", ",", "callback", ",", "one_shot", ",", "originator", ")", ":", "if", "one_shot", ":", "@", "wraps", "(", "callback", ")", "def", "remove_then_invoke", "(", "*", "args", ",", "*", "*", "kwarg...
Internal implementation for adding session callbacks. Args: callback_obj (SessionCallback) : A session callback object that wraps a callable and is passed to ``trigger_on_change``. callback (callable) : A callable to execute when session events happen. one_shot (bool) : Whether the callback should immediately auto-remove itself after one execution. Returns: SessionCallback : passed in as ``callback_obj``. Raises: ValueError, if the callback has been previously added
[ "Internal", "implementation", "for", "adding", "session", "callbacks", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L889-L928
30,510
bokeh/bokeh
bokeh/document/document.py
Document._destructively_move
def _destructively_move(self, dest_doc): ''' Move all data in this doc to the dest_doc, leaving this doc empty. Args: dest_doc (Document) : The Bokeh document to populate with data from this one Returns: None ''' if dest_doc is self: raise RuntimeError("Attempted to overwrite a document with itself") dest_doc.clear() # we have to remove ALL roots before adding any # to the new doc or else models referenced from multiple # roots could be in both docs at once, which isn't allowed. roots = [] self._push_all_models_freeze() try: while self.roots: r = next(iter(self.roots)) self.remove_root(r) roots.append(r) finally: self._pop_all_models_freeze() for r in roots: if r.document is not None: raise RuntimeError("Somehow we didn't detach %r" % (r)) if len(self._all_models) != 0: raise RuntimeError("_all_models still had stuff in it: %r" % (self._all_models)) for r in roots: dest_doc.add_root(r) dest_doc.title = self.title
python
def _destructively_move(self, dest_doc): ''' Move all data in this doc to the dest_doc, leaving this doc empty. Args: dest_doc (Document) : The Bokeh document to populate with data from this one Returns: None ''' if dest_doc is self: raise RuntimeError("Attempted to overwrite a document with itself") dest_doc.clear() # we have to remove ALL roots before adding any # to the new doc or else models referenced from multiple # roots could be in both docs at once, which isn't allowed. roots = [] self._push_all_models_freeze() try: while self.roots: r = next(iter(self.roots)) self.remove_root(r) roots.append(r) finally: self._pop_all_models_freeze() for r in roots: if r.document is not None: raise RuntimeError("Somehow we didn't detach %r" % (r)) if len(self._all_models) != 0: raise RuntimeError("_all_models still had stuff in it: %r" % (self._all_models)) for r in roots: dest_doc.add_root(r) dest_doc.title = self.title
[ "def", "_destructively_move", "(", "self", ",", "dest_doc", ")", ":", "if", "dest_doc", "is", "self", ":", "raise", "RuntimeError", "(", "\"Attempted to overwrite a document with itself\"", ")", "dest_doc", ".", "clear", "(", ")", "# we have to remove ALL roots before a...
Move all data in this doc to the dest_doc, leaving this doc empty. Args: dest_doc (Document) : The Bokeh document to populate with data from this one Returns: None
[ "Move", "all", "data", "in", "this", "doc", "to", "the", "dest_doc", "leaving", "this", "doc", "empty", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L930-L966
30,511
bokeh/bokeh
bokeh/document/document.py
Document._notify_change
def _notify_change(self, model, attr, old, new, hint=None, setter=None, callback_invoker=None): ''' Called by Model when it changes ''' # if name changes, update by-name index if attr == 'name': if old is not None: self._all_models_by_name.remove_value(old, model) if new is not None: self._all_models_by_name.add_value(new, model) if hint is None: serializable_new = model.lookup(attr).serializable_value(model) else: serializable_new = None event = ModelChangedEvent(self, model, attr, old, new, serializable_new, hint, setter, callback_invoker) self._trigger_on_change(event)
python
def _notify_change(self, model, attr, old, new, hint=None, setter=None, callback_invoker=None): ''' Called by Model when it changes ''' # if name changes, update by-name index if attr == 'name': if old is not None: self._all_models_by_name.remove_value(old, model) if new is not None: self._all_models_by_name.add_value(new, model) if hint is None: serializable_new = model.lookup(attr).serializable_value(model) else: serializable_new = None event = ModelChangedEvent(self, model, attr, old, new, serializable_new, hint, setter, callback_invoker) self._trigger_on_change(event)
[ "def", "_notify_change", "(", "self", ",", "model", ",", "attr", ",", "old", ",", "new", ",", "hint", "=", "None", ",", "setter", "=", "None", ",", "callback_invoker", "=", "None", ")", ":", "# if name changes, update by-name index", "if", "attr", "==", "'...
Called by Model when it changes
[ "Called", "by", "Model", "when", "it", "changes" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L988-L1005
30,512
bokeh/bokeh
bokeh/document/document.py
Document._remove_session_callback
def _remove_session_callback(self, callback_obj, originator): ''' Remove a callback added earlier with ``add_periodic_callback``, ``add_timeout_callback``, or ``add_next_tick_callback``. Returns: None Raises: KeyError, if the callback was never added ''' try: callback_objs = [callback_obj] self._session_callbacks.remove(callback_obj) for cb, cb_objs in list(self._callback_objs_by_callable[originator].items()): try: cb_objs.remove(callback_obj) if not cb_objs: del self._callback_objs_by_callable[originator][cb] except KeyError: pass except KeyError: raise ValueError("callback already ran or was already removed, cannot be removed again") # emit event so the session is notified and can remove the callback for callback_obj in callback_objs: self._trigger_on_change(SessionCallbackRemoved(self, callback_obj))
python
def _remove_session_callback(self, callback_obj, originator): ''' Remove a callback added earlier with ``add_periodic_callback``, ``add_timeout_callback``, or ``add_next_tick_callback``. Returns: None Raises: KeyError, if the callback was never added ''' try: callback_objs = [callback_obj] self._session_callbacks.remove(callback_obj) for cb, cb_objs in list(self._callback_objs_by_callable[originator].items()): try: cb_objs.remove(callback_obj) if not cb_objs: del self._callback_objs_by_callable[originator][cb] except KeyError: pass except KeyError: raise ValueError("callback already ran or was already removed, cannot be removed again") # emit event so the session is notified and can remove the callback for callback_obj in callback_objs: self._trigger_on_change(SessionCallbackRemoved(self, callback_obj))
[ "def", "_remove_session_callback", "(", "self", ",", "callback_obj", ",", "originator", ")", ":", "try", ":", "callback_objs", "=", "[", "callback_obj", "]", "self", ".", "_session_callbacks", ".", "remove", "(", "callback_obj", ")", "for", "cb", ",", "cb_objs...
Remove a callback added earlier with ``add_periodic_callback``, ``add_timeout_callback``, or ``add_next_tick_callback``. Returns: None Raises: KeyError, if the callback was never added
[ "Remove", "a", "callback", "added", "earlier", "with", "add_periodic_callback", "add_timeout_callback", "or", "add_next_tick_callback", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/document/document.py#L1046-L1071
30,513
bokeh/bokeh
bokeh/util/callback_manager.py
_check_callback
def _check_callback(callback, fargs, what="Callback functions"): '''Bokeh-internal function to check callback signature''' sig = signature(callback) formatted_args = format_signature(sig) error_msg = what + " must have signature func(%s), got func%s" all_names, default_values = get_param_info(sig) nargs = len(all_names) - len(default_values) if nargs != len(fargs): raise ValueError(error_msg % (", ".join(fargs), formatted_args))
python
def _check_callback(callback, fargs, what="Callback functions"): '''Bokeh-internal function to check callback signature''' sig = signature(callback) formatted_args = format_signature(sig) error_msg = what + " must have signature func(%s), got func%s" all_names, default_values = get_param_info(sig) nargs = len(all_names) - len(default_values) if nargs != len(fargs): raise ValueError(error_msg % (", ".join(fargs), formatted_args))
[ "def", "_check_callback", "(", "callback", ",", "fargs", ",", "what", "=", "\"Callback functions\"", ")", ":", "sig", "=", "signature", "(", "callback", ")", "formatted_args", "=", "format_signature", "(", "sig", ")", "error_msg", "=", "what", "+", "\" must ha...
Bokeh-internal function to check callback signature
[ "Bokeh", "-", "internal", "function", "to", "check", "callback", "signature" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/callback_manager.py#L178-L188
30,514
bokeh/bokeh
bokeh/util/callback_manager.py
PropertyCallbackManager.remove_on_change
def remove_on_change(self, attr, *callbacks): ''' Remove a callback from this object ''' if len(callbacks) == 0: raise ValueError("remove_on_change takes an attribute name and one or more callbacks, got only one parameter") _callbacks = self._callbacks.setdefault(attr, []) for callback in callbacks: _callbacks.remove(callback)
python
def remove_on_change(self, attr, *callbacks): ''' Remove a callback from this object ''' if len(callbacks) == 0: raise ValueError("remove_on_change takes an attribute name and one or more callbacks, got only one parameter") _callbacks = self._callbacks.setdefault(attr, []) for callback in callbacks: _callbacks.remove(callback)
[ "def", "remove_on_change", "(", "self", ",", "attr", ",", "*", "callbacks", ")", ":", "if", "len", "(", "callbacks", ")", "==", "0", ":", "raise", "ValueError", "(", "\"remove_on_change takes an attribute name and one or more callbacks, got only one parameter\"", ")", ...
Remove a callback from this object
[ "Remove", "a", "callback", "from", "this", "object" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/callback_manager.py#L135-L141
30,515
bokeh/bokeh
bokeh/util/callback_manager.py
PropertyCallbackManager.trigger
def trigger(self, attr, old, new, hint=None, setter=None): ''' Trigger callbacks for ``attr`` on this object. Args: attr (str) : old (object) : new (object) : Returns: None ''' def invoke(): callbacks = self._callbacks.get(attr) if callbacks: for callback in callbacks: callback(attr, old, new) if hasattr(self, '_document') and self._document is not None: self._document._notify_change(self, attr, old, new, hint, setter, invoke) else: invoke()
python
def trigger(self, attr, old, new, hint=None, setter=None): ''' Trigger callbacks for ``attr`` on this object. Args: attr (str) : old (object) : new (object) : Returns: None ''' def invoke(): callbacks = self._callbacks.get(attr) if callbacks: for callback in callbacks: callback(attr, old, new) if hasattr(self, '_document') and self._document is not None: self._document._notify_change(self, attr, old, new, hint, setter, invoke) else: invoke()
[ "def", "trigger", "(", "self", ",", "attr", ",", "old", ",", "new", ",", "hint", "=", "None", ",", "setter", "=", "None", ")", ":", "def", "invoke", "(", ")", ":", "callbacks", "=", "self", ".", "_callbacks", ".", "get", "(", "attr", ")", "if", ...
Trigger callbacks for ``attr`` on this object. Args: attr (str) : old (object) : new (object) : Returns: None
[ "Trigger", "callbacks", "for", "attr", "on", "this", "object", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/callback_manager.py#L143-L163
30,516
bokeh/bokeh
bokeh/util/sampledata.py
download
def download(progress=True): ''' Download larger data sets for various Bokeh examples. ''' data_dir = external_data_dir(create=True) print("Using data directory: %s" % data_dir) s3 = 'https://bokeh-sampledata.s3.amazonaws.com' files = [ (s3, 'CGM.csv'), (s3, 'US_Counties.zip'), (s3, 'us_cities.json'), (s3, 'unemployment09.csv'), (s3, 'AAPL.csv'), (s3, 'FB.csv'), (s3, 'GOOG.csv'), (s3, 'IBM.csv'), (s3, 'MSFT.csv'), (s3, 'WPP2012_SA_DB03_POPULATION_QUINQUENNIAL.zip'), (s3, 'gapminder_fertility.csv'), (s3, 'gapminder_population.csv'), (s3, 'gapminder_life_expectancy.csv'), (s3, 'gapminder_regions.csv'), (s3, 'world_cities.zip'), (s3, 'airports.json'), (s3, 'movies.db.zip'), (s3, 'airports.csv'), (s3, 'routes.csv'), (s3, 'haarcascade_frontalface_default.xml'), ] for base_url, filename in files: _download_file(base_url, filename, data_dir, progress=progress)
python
def download(progress=True): ''' Download larger data sets for various Bokeh examples. ''' data_dir = external_data_dir(create=True) print("Using data directory: %s" % data_dir) s3 = 'https://bokeh-sampledata.s3.amazonaws.com' files = [ (s3, 'CGM.csv'), (s3, 'US_Counties.zip'), (s3, 'us_cities.json'), (s3, 'unemployment09.csv'), (s3, 'AAPL.csv'), (s3, 'FB.csv'), (s3, 'GOOG.csv'), (s3, 'IBM.csv'), (s3, 'MSFT.csv'), (s3, 'WPP2012_SA_DB03_POPULATION_QUINQUENNIAL.zip'), (s3, 'gapminder_fertility.csv'), (s3, 'gapminder_population.csv'), (s3, 'gapminder_life_expectancy.csv'), (s3, 'gapminder_regions.csv'), (s3, 'world_cities.zip'), (s3, 'airports.json'), (s3, 'movies.db.zip'), (s3, 'airports.csv'), (s3, 'routes.csv'), (s3, 'haarcascade_frontalface_default.xml'), ] for base_url, filename in files: _download_file(base_url, filename, data_dir, progress=progress)
[ "def", "download", "(", "progress", "=", "True", ")", ":", "data_dir", "=", "external_data_dir", "(", "create", "=", "True", ")", "print", "(", "\"Using data directory: %s\"", "%", "data_dir", ")", "s3", "=", "'https://bokeh-sampledata.s3.amazonaws.com'", "files", ...
Download larger data sets for various Bokeh examples.
[ "Download", "larger", "data", "sets", "for", "various", "Bokeh", "examples", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/util/sampledata.py#L49-L81
30,517
bokeh/bokeh
bokeh/command/bootstrap.py
main
def main(argv): ''' Execute the Bokeh command. Args: argv (seq[str]) : a list of command line arguments to process Returns: None The first item in ``argv`` is typically "bokeh", and the second should be the name of one of the available subcommands: * :ref:`html <bokeh.command.subcommands.html>` * :ref:`info <bokeh.command.subcommands.info>` * :ref:`json <bokeh.command.subcommands.json>` * :ref:`png <bokeh.command.subcommands.png>` * :ref:`sampledata <bokeh.command.subcommands.sampledata>` * :ref:`secret <bokeh.command.subcommands.secret>` * :ref:`serve <bokeh.command.subcommands.serve>` * :ref:`static <bokeh.command.subcommands.static>` * :ref:`svg <bokeh.command.subcommands.svg>` ''' if len(argv) == 1: die("ERROR: Must specify subcommand, one of: %s" % nice_join(x.name for x in subcommands.all)) parser = argparse.ArgumentParser( prog=argv[0], epilog="See '<command> --help' to read about a specific subcommand.") # we don't use settings.version() because the point of this option # is to report the actual version of Bokeh, while settings.version() # lets people change the version used for CDN for example. parser.add_argument('-v', '--version', action='version', version=__version__) subs = parser.add_subparsers(help="Sub-commands") for cls in subcommands.all: subparser = subs.add_parser(cls.name, help=cls.help) subcommand = cls(parser=subparser) subparser.set_defaults(invoke=subcommand.invoke) args = parser.parse_args(argv[1:]) try: args.invoke(args) except Exception as e: die("ERROR: " + str(e))
python
def main(argv): ''' Execute the Bokeh command. Args: argv (seq[str]) : a list of command line arguments to process Returns: None The first item in ``argv`` is typically "bokeh", and the second should be the name of one of the available subcommands: * :ref:`html <bokeh.command.subcommands.html>` * :ref:`info <bokeh.command.subcommands.info>` * :ref:`json <bokeh.command.subcommands.json>` * :ref:`png <bokeh.command.subcommands.png>` * :ref:`sampledata <bokeh.command.subcommands.sampledata>` * :ref:`secret <bokeh.command.subcommands.secret>` * :ref:`serve <bokeh.command.subcommands.serve>` * :ref:`static <bokeh.command.subcommands.static>` * :ref:`svg <bokeh.command.subcommands.svg>` ''' if len(argv) == 1: die("ERROR: Must specify subcommand, one of: %s" % nice_join(x.name for x in subcommands.all)) parser = argparse.ArgumentParser( prog=argv[0], epilog="See '<command> --help' to read about a specific subcommand.") # we don't use settings.version() because the point of this option # is to report the actual version of Bokeh, while settings.version() # lets people change the version used for CDN for example. parser.add_argument('-v', '--version', action='version', version=__version__) subs = parser.add_subparsers(help="Sub-commands") for cls in subcommands.all: subparser = subs.add_parser(cls.name, help=cls.help) subcommand = cls(parser=subparser) subparser.set_defaults(invoke=subcommand.invoke) args = parser.parse_args(argv[1:]) try: args.invoke(args) except Exception as e: die("ERROR: " + str(e))
[ "def", "main", "(", "argv", ")", ":", "if", "len", "(", "argv", ")", "==", "1", ":", "die", "(", "\"ERROR: Must specify subcommand, one of: %s\"", "%", "nice_join", "(", "x", ".", "name", "for", "x", "in", "subcommands", ".", "all", ")", ")", "parser", ...
Execute the Bokeh command. Args: argv (seq[str]) : a list of command line arguments to process Returns: None The first item in ``argv`` is typically "bokeh", and the second should be the name of one of the available subcommands: * :ref:`html <bokeh.command.subcommands.html>` * :ref:`info <bokeh.command.subcommands.info>` * :ref:`json <bokeh.command.subcommands.json>` * :ref:`png <bokeh.command.subcommands.png>` * :ref:`sampledata <bokeh.command.subcommands.sampledata>` * :ref:`secret <bokeh.command.subcommands.secret>` * :ref:`serve <bokeh.command.subcommands.serve>` * :ref:`static <bokeh.command.subcommands.static>` * :ref:`svg <bokeh.command.subcommands.svg>`
[ "Execute", "the", "Bokeh", "command", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/command/bootstrap.py#L69-L115
30,518
bokeh/bokeh
bokeh/io/showing.py
show
def show(obj, browser=None, new="tab", notebook_handle=False, notebook_url="localhost:8888", **kw): ''' Immediately display a Bokeh object or application. :func:`show` may be called multiple times in a single Jupyter notebook cell to display multiple objects. The objects are displayed in order. Args: obj (LayoutDOM or Application or callable) : A Bokeh object to display. Bokeh plots, widgets, layouts (i.e. rows and columns) may be passed to ``show`` in order to display them. When ``output_file`` has been called, the output will be to an HTML file, which is also opened in a new browser window or tab. When ``output_notebook`` has been called in a Jupyter notebook, the output will be inline in the associated notebook output cell. In a Jupyter notebook, a Bokeh application or callable may also be passed. A callable will be turned into an Application using a ``FunctionHandler``. The application will be run and displayed inline in the associated notebook output cell. browser (str, optional) : Specify the browser to use to open output files(default: None) For file output, the **browser** argument allows for specifying which browser to display in, e.g. "safari", "firefox", "opera", "windows-default". Not all platforms may support this option, see the documentation for the standard library webbrowser_ module for more information new (str, optional) : Specify the browser mode to use for output files (default: "tab") For file output, opens or raises the browser window showing the current output file. If **new** is 'tab', then opens a new tab. If **new** is 'window', then opens a new window. notebook_handle (bool, optional) : Whether to create a notebook interaction handle (default: False) For notebook output, toggles whether a handle which can be used with ``push_notebook`` is returned. Note that notebook handles only apply to standalone plots, layouts, etc. They do not apply when showing Applications in the notebook. notebook_url (URL, optional) : Location of the Jupyter notebook page (default: "localhost:8888") When showing Bokeh applications, the Bokeh server must be explicitly configured to allow connections originating from different URLs. This parameter defaults to the standard notebook host and port. If you are running on a different location, you will need to supply this value for the application to display properly. If no protocol is supplied in the URL, e.g. if it is of the form "localhost:8888", then "http" will be used. ``notebook_url`` can also be a function that takes one int for the bound server port. If the port is provided, the function needs to generate the full public URL to the bokeh server. If None is passed, the function is to generate the origin URL. Some parameters are only useful when certain output modes are active: * The ``browser`` and ``new`` parameters only apply when ``output_file`` is active. * The ``notebook_handle`` parameter only applies when ``output_notebook`` is active, and non-Application objects are being shown. It is only supported to Jupyter notebook, raise exception for other notebook types when it is True. * The ``notebook_url`` parameter only applies when showing Bokeh Applications in a Jupyter notebook. * Any additional keyword arguments are passed to :class:`~bokeh.server.Server` when showing a Bokeh app (added in version 1.1) Returns: When in a Jupyter notebook (with ``output_notebook`` enabled) and ``notebook_handle=True``, returns a handle that can be used by ``push_notebook``, None otherwise. .. _webbrowser: https://docs.python.org/2/library/webbrowser.html ''' state = curstate() is_application = getattr(obj, '_is_a_bokeh_application_class', False) if not (isinstance(obj, LayoutDOM) or is_application or callable(obj)): raise ValueError(_BAD_SHOW_MSG) # TODO (bev) check callable signature more thoroughly # This ugliness is to prevent importing bokeh.application (which would bring # in Tornado) just in order to show a non-server object if is_application or callable(obj): return run_notebook_hook(state.notebook_type, 'app', obj, state, notebook_url, **kw) return _show_with_state(obj, state, browser, new, notebook_handle=notebook_handle)
python
def show(obj, browser=None, new="tab", notebook_handle=False, notebook_url="localhost:8888", **kw): ''' Immediately display a Bokeh object or application. :func:`show` may be called multiple times in a single Jupyter notebook cell to display multiple objects. The objects are displayed in order. Args: obj (LayoutDOM or Application or callable) : A Bokeh object to display. Bokeh plots, widgets, layouts (i.e. rows and columns) may be passed to ``show`` in order to display them. When ``output_file`` has been called, the output will be to an HTML file, which is also opened in a new browser window or tab. When ``output_notebook`` has been called in a Jupyter notebook, the output will be inline in the associated notebook output cell. In a Jupyter notebook, a Bokeh application or callable may also be passed. A callable will be turned into an Application using a ``FunctionHandler``. The application will be run and displayed inline in the associated notebook output cell. browser (str, optional) : Specify the browser to use to open output files(default: None) For file output, the **browser** argument allows for specifying which browser to display in, e.g. "safari", "firefox", "opera", "windows-default". Not all platforms may support this option, see the documentation for the standard library webbrowser_ module for more information new (str, optional) : Specify the browser mode to use for output files (default: "tab") For file output, opens or raises the browser window showing the current output file. If **new** is 'tab', then opens a new tab. If **new** is 'window', then opens a new window. notebook_handle (bool, optional) : Whether to create a notebook interaction handle (default: False) For notebook output, toggles whether a handle which can be used with ``push_notebook`` is returned. Note that notebook handles only apply to standalone plots, layouts, etc. They do not apply when showing Applications in the notebook. notebook_url (URL, optional) : Location of the Jupyter notebook page (default: "localhost:8888") When showing Bokeh applications, the Bokeh server must be explicitly configured to allow connections originating from different URLs. This parameter defaults to the standard notebook host and port. If you are running on a different location, you will need to supply this value for the application to display properly. If no protocol is supplied in the URL, e.g. if it is of the form "localhost:8888", then "http" will be used. ``notebook_url`` can also be a function that takes one int for the bound server port. If the port is provided, the function needs to generate the full public URL to the bokeh server. If None is passed, the function is to generate the origin URL. Some parameters are only useful when certain output modes are active: * The ``browser`` and ``new`` parameters only apply when ``output_file`` is active. * The ``notebook_handle`` parameter only applies when ``output_notebook`` is active, and non-Application objects are being shown. It is only supported to Jupyter notebook, raise exception for other notebook types when it is True. * The ``notebook_url`` parameter only applies when showing Bokeh Applications in a Jupyter notebook. * Any additional keyword arguments are passed to :class:`~bokeh.server.Server` when showing a Bokeh app (added in version 1.1) Returns: When in a Jupyter notebook (with ``output_notebook`` enabled) and ``notebook_handle=True``, returns a handle that can be used by ``push_notebook``, None otherwise. .. _webbrowser: https://docs.python.org/2/library/webbrowser.html ''' state = curstate() is_application = getattr(obj, '_is_a_bokeh_application_class', False) if not (isinstance(obj, LayoutDOM) or is_application or callable(obj)): raise ValueError(_BAD_SHOW_MSG) # TODO (bev) check callable signature more thoroughly # This ugliness is to prevent importing bokeh.application (which would bring # in Tornado) just in order to show a non-server object if is_application or callable(obj): return run_notebook_hook(state.notebook_type, 'app', obj, state, notebook_url, **kw) return _show_with_state(obj, state, browser, new, notebook_handle=notebook_handle)
[ "def", "show", "(", "obj", ",", "browser", "=", "None", ",", "new", "=", "\"tab\"", ",", "notebook_handle", "=", "False", ",", "notebook_url", "=", "\"localhost:8888\"", ",", "*", "*", "kw", ")", ":", "state", "=", "curstate", "(", ")", "is_application",...
Immediately display a Bokeh object or application. :func:`show` may be called multiple times in a single Jupyter notebook cell to display multiple objects. The objects are displayed in order. Args: obj (LayoutDOM or Application or callable) : A Bokeh object to display. Bokeh plots, widgets, layouts (i.e. rows and columns) may be passed to ``show`` in order to display them. When ``output_file`` has been called, the output will be to an HTML file, which is also opened in a new browser window or tab. When ``output_notebook`` has been called in a Jupyter notebook, the output will be inline in the associated notebook output cell. In a Jupyter notebook, a Bokeh application or callable may also be passed. A callable will be turned into an Application using a ``FunctionHandler``. The application will be run and displayed inline in the associated notebook output cell. browser (str, optional) : Specify the browser to use to open output files(default: None) For file output, the **browser** argument allows for specifying which browser to display in, e.g. "safari", "firefox", "opera", "windows-default". Not all platforms may support this option, see the documentation for the standard library webbrowser_ module for more information new (str, optional) : Specify the browser mode to use for output files (default: "tab") For file output, opens or raises the browser window showing the current output file. If **new** is 'tab', then opens a new tab. If **new** is 'window', then opens a new window. notebook_handle (bool, optional) : Whether to create a notebook interaction handle (default: False) For notebook output, toggles whether a handle which can be used with ``push_notebook`` is returned. Note that notebook handles only apply to standalone plots, layouts, etc. They do not apply when showing Applications in the notebook. notebook_url (URL, optional) : Location of the Jupyter notebook page (default: "localhost:8888") When showing Bokeh applications, the Bokeh server must be explicitly configured to allow connections originating from different URLs. This parameter defaults to the standard notebook host and port. If you are running on a different location, you will need to supply this value for the application to display properly. If no protocol is supplied in the URL, e.g. if it is of the form "localhost:8888", then "http" will be used. ``notebook_url`` can also be a function that takes one int for the bound server port. If the port is provided, the function needs to generate the full public URL to the bokeh server. If None is passed, the function is to generate the origin URL. Some parameters are only useful when certain output modes are active: * The ``browser`` and ``new`` parameters only apply when ``output_file`` is active. * The ``notebook_handle`` parameter only applies when ``output_notebook`` is active, and non-Application objects are being shown. It is only supported to Jupyter notebook, raise exception for other notebook types when it is True. * The ``notebook_url`` parameter only applies when showing Bokeh Applications in a Jupyter notebook. * Any additional keyword arguments are passed to :class:`~bokeh.server.Server` when showing a Bokeh app (added in version 1.1) Returns: When in a Jupyter notebook (with ``output_notebook`` enabled) and ``notebook_handle=True``, returns a handle that can be used by ``push_notebook``, None otherwise. .. _webbrowser: https://docs.python.org/2/library/webbrowser.html
[ "Immediately", "display", "a", "Bokeh", "object", "or", "application", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/showing.py#L46-L145
30,519
bokeh/bokeh
bokeh/embed/elements.py
html_page_for_render_items
def html_page_for_render_items(bundle, docs_json, render_items, title, template=None, template_variables={}): ''' Render an HTML page from a template and Bokeh render items. Args: bundle (tuple): a tuple containing (bokehjs, bokehcss) docs_json (JSON-like): Serialized Bokeh Document render_items (RenderItems) Specific items to render from the document and where title (str or None) A title for the HTML page. If None, DEFAULT_TITLE is used template (str or Template or None, optional) : A Template to be used for the HTML page. If None, FILE is used. template_variables (dict, optional): Any Additional variables to pass to the template Returns: str ''' if title is None: title = DEFAULT_TITLE bokeh_js, bokeh_css = bundle json_id = make_id() json = escape(serialize_json(docs_json), quote=False) json = wrap_in_script_tag(json, "application/json", json_id) script = wrap_in_script_tag(script_for_render_items(json_id, render_items)) context = template_variables.copy() context.update(dict( title = title, bokeh_js = bokeh_js, bokeh_css = bokeh_css, plot_script = json + script, docs = render_items, base = FILE, macros = MACROS, )) if len(render_items) == 1: context["doc"] = context["docs"][0] context["roots"] = context["doc"].roots # XXX: backwards compatibility, remove for 1.0 context["plot_div"] = "\n".join(div_for_render_item(item) for item in render_items) if template is None: template = FILE elif isinstance(template, string_types): template = _env.from_string("{% extends base %}\n" + template) html = template.render(context) return encode_utf8(html)
python
def html_page_for_render_items(bundle, docs_json, render_items, title, template=None, template_variables={}): ''' Render an HTML page from a template and Bokeh render items. Args: bundle (tuple): a tuple containing (bokehjs, bokehcss) docs_json (JSON-like): Serialized Bokeh Document render_items (RenderItems) Specific items to render from the document and where title (str or None) A title for the HTML page. If None, DEFAULT_TITLE is used template (str or Template or None, optional) : A Template to be used for the HTML page. If None, FILE is used. template_variables (dict, optional): Any Additional variables to pass to the template Returns: str ''' if title is None: title = DEFAULT_TITLE bokeh_js, bokeh_css = bundle json_id = make_id() json = escape(serialize_json(docs_json), quote=False) json = wrap_in_script_tag(json, "application/json", json_id) script = wrap_in_script_tag(script_for_render_items(json_id, render_items)) context = template_variables.copy() context.update(dict( title = title, bokeh_js = bokeh_js, bokeh_css = bokeh_css, plot_script = json + script, docs = render_items, base = FILE, macros = MACROS, )) if len(render_items) == 1: context["doc"] = context["docs"][0] context["roots"] = context["doc"].roots # XXX: backwards compatibility, remove for 1.0 context["plot_div"] = "\n".join(div_for_render_item(item) for item in render_items) if template is None: template = FILE elif isinstance(template, string_types): template = _env.from_string("{% extends base %}\n" + template) html = template.render(context) return encode_utf8(html)
[ "def", "html_page_for_render_items", "(", "bundle", ",", "docs_json", ",", "render_items", ",", "title", ",", "template", "=", "None", ",", "template_variables", "=", "{", "}", ")", ":", "if", "title", "is", "None", ":", "title", "=", "DEFAULT_TITLE", "bokeh...
Render an HTML page from a template and Bokeh render items. Args: bundle (tuple): a tuple containing (bokehjs, bokehcss) docs_json (JSON-like): Serialized Bokeh Document render_items (RenderItems) Specific items to render from the document and where title (str or None) A title for the HTML page. If None, DEFAULT_TITLE is used template (str or Template or None, optional) : A Template to be used for the HTML page. If None, FILE is used. template_variables (dict, optional): Any Additional variables to pass to the template Returns: str
[ "Render", "an", "HTML", "page", "from", "a", "template", "and", "Bokeh", "render", "items", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/embed/elements.py#L68-L130
30,520
bokeh/bokeh
examples/app/stocks/download_sample_data.py
extract_hosted_zip
def extract_hosted_zip(data_url, save_dir, exclude_term=None): """Downloads, then extracts a zip file.""" zip_name = os.path.join(save_dir, 'temp.zip') # get the zip file try: print('Downloading %r to %r' % (data_url, zip_name)) zip_name, hdrs = urllib.request.urlretrieve(url=data_url, filename=zip_name) print('Download successfully completed') except IOError as e: print("Could not successfully retrieve %r" % data_url) raise e # extract, then remove temp file extract_zip(zip_name=zip_name, exclude_term=exclude_term) os.unlink(zip_name) print("Extraction Complete")
python
def extract_hosted_zip(data_url, save_dir, exclude_term=None): """Downloads, then extracts a zip file.""" zip_name = os.path.join(save_dir, 'temp.zip') # get the zip file try: print('Downloading %r to %r' % (data_url, zip_name)) zip_name, hdrs = urllib.request.urlretrieve(url=data_url, filename=zip_name) print('Download successfully completed') except IOError as e: print("Could not successfully retrieve %r" % data_url) raise e # extract, then remove temp file extract_zip(zip_name=zip_name, exclude_term=exclude_term) os.unlink(zip_name) print("Extraction Complete")
[ "def", "extract_hosted_zip", "(", "data_url", ",", "save_dir", ",", "exclude_term", "=", "None", ")", ":", "zip_name", "=", "os", ".", "path", ".", "join", "(", "save_dir", ",", "'temp.zip'", ")", "# get the zip file", "try", ":", "print", "(", "'Downloading...
Downloads, then extracts a zip file.
[ "Downloads", "then", "extracts", "a", "zip", "file", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/examples/app/stocks/download_sample_data.py#L7-L24
30,521
bokeh/bokeh
examples/app/stocks/download_sample_data.py
extract_zip
def extract_zip(zip_name, exclude_term=None): """Extracts a zip file to its containing directory.""" zip_dir = os.path.dirname(os.path.abspath(zip_name)) try: with zipfile.ZipFile(zip_name) as z: # write each zipped file out if it isn't a directory files = [zip_file for zip_file in z.namelist() if not zip_file.endswith('/')] print('Extracting %i files from %r.' % (len(files), zip_name)) for zip_file in files: # remove any provided extra directory term from zip file if exclude_term: dest_file = zip_file.replace(exclude_term, '') else: dest_file = zip_file dest_file = os.path.normpath(os.path.join(zip_dir, dest_file)) dest_dir = os.path.dirname(dest_file) # make directory if it does not exist if not os.path.isdir(dest_dir): os.makedirs(dest_dir) # read file from zip, then write to new directory data = z.read(zip_file) with open(dest_file, 'wb') as f: f.write(encode_utf8(data)) except zipfile.error as e: print("Bad zipfile (%r): %s" % (zip_name, e)) raise e
python
def extract_zip(zip_name, exclude_term=None): """Extracts a zip file to its containing directory.""" zip_dir = os.path.dirname(os.path.abspath(zip_name)) try: with zipfile.ZipFile(zip_name) as z: # write each zipped file out if it isn't a directory files = [zip_file for zip_file in z.namelist() if not zip_file.endswith('/')] print('Extracting %i files from %r.' % (len(files), zip_name)) for zip_file in files: # remove any provided extra directory term from zip file if exclude_term: dest_file = zip_file.replace(exclude_term, '') else: dest_file = zip_file dest_file = os.path.normpath(os.path.join(zip_dir, dest_file)) dest_dir = os.path.dirname(dest_file) # make directory if it does not exist if not os.path.isdir(dest_dir): os.makedirs(dest_dir) # read file from zip, then write to new directory data = z.read(zip_file) with open(dest_file, 'wb') as f: f.write(encode_utf8(data)) except zipfile.error as e: print("Bad zipfile (%r): %s" % (zip_name, e)) raise e
[ "def", "extract_zip", "(", "zip_name", ",", "exclude_term", "=", "None", ")", ":", "zip_dir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "zip_name", ")", ")", "try", ":", "with", "zipfile", ".", "ZipFile", "(...
Extracts a zip file to its containing directory.
[ "Extracts", "a", "zip", "file", "to", "its", "containing", "directory", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/examples/app/stocks/download_sample_data.py#L27-L61
30,522
bokeh/bokeh
bokeh/models/widgets/sliders.py
DateRangeSlider.value_as_datetime
def value_as_datetime(self): ''' Convenience property to retrieve the value tuple as a tuple of datetime objects. ''' if self.value is None: return None v1, v2 = self.value if isinstance(v1, numbers.Number): d1 = datetime.utcfromtimestamp(v1 / 1000) else: d1 = v1 if isinstance(v2, numbers.Number): d2 = datetime.utcfromtimestamp(v2 / 1000) else: d2 = v2 return d1, d2
python
def value_as_datetime(self): ''' Convenience property to retrieve the value tuple as a tuple of datetime objects. ''' if self.value is None: return None v1, v2 = self.value if isinstance(v1, numbers.Number): d1 = datetime.utcfromtimestamp(v1 / 1000) else: d1 = v1 if isinstance(v2, numbers.Number): d2 = datetime.utcfromtimestamp(v2 / 1000) else: d2 = v2 return d1, d2
[ "def", "value_as_datetime", "(", "self", ")", ":", "if", "self", ".", "value", "is", "None", ":", "return", "None", "v1", ",", "v2", "=", "self", ".", "value", "if", "isinstance", "(", "v1", ",", "numbers", ".", "Number", ")", ":", "d1", "=", "date...
Convenience property to retrieve the value tuple as a tuple of datetime objects.
[ "Convenience", "property", "to", "retrieve", "the", "value", "tuple", "as", "a", "tuple", "of", "datetime", "objects", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/widgets/sliders.py#L182-L198
30,523
bokeh/bokeh
bokeh/models/widgets/sliders.py
DateRangeSlider.value_as_date
def value_as_date(self): ''' Convenience property to retrieve the value tuple as a tuple of date objects. Added in version 1.1 ''' if self.value is None: return None v1, v2 = self.value if isinstance(v1, numbers.Number): dt = datetime.utcfromtimestamp(v1 / 1000) d1 = date(*dt.timetuple()[:3]) else: d1 = v1 if isinstance(v2, numbers.Number): dt = datetime.utcfromtimestamp(v2 / 1000) d2 = date(*dt.timetuple()[:3]) else: d2 = v2 return d1, d2
python
def value_as_date(self): ''' Convenience property to retrieve the value tuple as a tuple of date objects. Added in version 1.1 ''' if self.value is None: return None v1, v2 = self.value if isinstance(v1, numbers.Number): dt = datetime.utcfromtimestamp(v1 / 1000) d1 = date(*dt.timetuple()[:3]) else: d1 = v1 if isinstance(v2, numbers.Number): dt = datetime.utcfromtimestamp(v2 / 1000) d2 = date(*dt.timetuple()[:3]) else: d2 = v2 return d1, d2
[ "def", "value_as_date", "(", "self", ")", ":", "if", "self", ".", "value", "is", "None", ":", "return", "None", "v1", ",", "v2", "=", "self", ".", "value", "if", "isinstance", "(", "v1", ",", "numbers", ".", "Number", ")", ":", "dt", "=", "datetime...
Convenience property to retrieve the value tuple as a tuple of date objects. Added in version 1.1
[ "Convenience", "property", "to", "retrieve", "the", "value", "tuple", "as", "a", "tuple", "of", "date", "objects", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/models/widgets/sliders.py#L201-L220
30,524
bokeh/bokeh
bokeh/application/handlers/directory.py
DirectoryHandler.modify_document
def modify_document(self, doc): ''' Execute the configured ``main.py`` or ``main.ipynb`` to modify the document. This method will also search the app directory for any theme or template files, and automatically configure the document with them if they are found. ''' if self._lifecycle_handler.failed: return # Note: we do NOT copy self._theme, which assumes the Theme # class is immutable (has no setters) if self._theme is not None: doc.theme = self._theme if self._template is not None: doc.template = self._template # This internal handler should never add a template self._main_handler.modify_document(doc)
python
def modify_document(self, doc): ''' Execute the configured ``main.py`` or ``main.ipynb`` to modify the document. This method will also search the app directory for any theme or template files, and automatically configure the document with them if they are found. ''' if self._lifecycle_handler.failed: return # Note: we do NOT copy self._theme, which assumes the Theme # class is immutable (has no setters) if self._theme is not None: doc.theme = self._theme if self._template is not None: doc.template = self._template # This internal handler should never add a template self._main_handler.modify_document(doc)
[ "def", "modify_document", "(", "self", ",", "doc", ")", ":", "if", "self", ".", "_lifecycle_handler", ".", "failed", ":", "return", "# Note: we do NOT copy self._theme, which assumes the Theme", "# class is immutable (has no setters)", "if", "self", ".", "_theme", "is", ...
Execute the configured ``main.py`` or ``main.ipynb`` to modify the document. This method will also search the app directory for any theme or template files, and automatically configure the document with them if they are found.
[ "Execute", "the", "configured", "main", ".", "py", "or", "main", ".", "ipynb", "to", "modify", "the", "document", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/application/handlers/directory.py#L173-L193
30,525
bokeh/bokeh
bokeh/plotting/figure.py
Figure.scatter
def scatter(self, *args, **kwargs): ''' Creates a scatter plot of the given x and y items. Args: x (str or seq[float]) : values or field names of center x coordinates y (str or seq[float]) : values or field names of center y coordinates size (str or list[float]) : values or field names of sizes in screen units marker (str, or list[str]): values or field names of marker types color (color value, optional): shorthand to set both fill and line color source (:class:`~bokeh.models.sources.ColumnDataSource`) : a user-supplied data source. An attempt will be made to convert the object to :class:`~bokeh.models.sources.ColumnDataSource` if needed. If none is supplied, one is created for the user automatically. **kwargs: :ref:`userguide_styling_line_properties` and :ref:`userguide_styling_fill_properties` Examples: >>> p.scatter([1,2,3],[4,5,6], marker="square", fill_color="red") >>> p.scatter("data1", "data2", marker="mtype", source=data_source, ...) .. note:: When passing ``marker="circle"`` it is also possible to supply a ``radius`` value in data-space units. When configuring marker type from a data source column, *all* markers incuding circles may only be configured with ``size`` in screen units. ''' marker_type = kwargs.pop("marker", "circle") if isinstance(marker_type, string_types) and marker_type in _MARKER_SHORTCUTS: marker_type = _MARKER_SHORTCUTS[marker_type] # The original scatter implementation allowed circle scatters to set a # radius. We will leave this here for compatibility but note that it # only works when the marker type is "circle" (and not referencing a # data source column). Consider deprecating in the future. if marker_type == "circle" and "radius" in kwargs: return self.circle(*args, **kwargs) else: return self._scatter(*args, marker=marker_type, **kwargs)
python
def scatter(self, *args, **kwargs): ''' Creates a scatter plot of the given x and y items. Args: x (str or seq[float]) : values or field names of center x coordinates y (str or seq[float]) : values or field names of center y coordinates size (str or list[float]) : values or field names of sizes in screen units marker (str, or list[str]): values or field names of marker types color (color value, optional): shorthand to set both fill and line color source (:class:`~bokeh.models.sources.ColumnDataSource`) : a user-supplied data source. An attempt will be made to convert the object to :class:`~bokeh.models.sources.ColumnDataSource` if needed. If none is supplied, one is created for the user automatically. **kwargs: :ref:`userguide_styling_line_properties` and :ref:`userguide_styling_fill_properties` Examples: >>> p.scatter([1,2,3],[4,5,6], marker="square", fill_color="red") >>> p.scatter("data1", "data2", marker="mtype", source=data_source, ...) .. note:: When passing ``marker="circle"`` it is also possible to supply a ``radius`` value in data-space units. When configuring marker type from a data source column, *all* markers incuding circles may only be configured with ``size`` in screen units. ''' marker_type = kwargs.pop("marker", "circle") if isinstance(marker_type, string_types) and marker_type in _MARKER_SHORTCUTS: marker_type = _MARKER_SHORTCUTS[marker_type] # The original scatter implementation allowed circle scatters to set a # radius. We will leave this here for compatibility but note that it # only works when the marker type is "circle" (and not referencing a # data source column). Consider deprecating in the future. if marker_type == "circle" and "radius" in kwargs: return self.circle(*args, **kwargs) else: return self._scatter(*args, marker=marker_type, **kwargs)
[ "def", "scatter", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "marker_type", "=", "kwargs", ".", "pop", "(", "\"marker\"", ",", "\"circle\"", ")", "if", "isinstance", "(", "marker_type", ",", "string_types", ")", "and", "marker_type...
Creates a scatter plot of the given x and y items. Args: x (str or seq[float]) : values or field names of center x coordinates y (str or seq[float]) : values or field names of center y coordinates size (str or list[float]) : values or field names of sizes in screen units marker (str, or list[str]): values or field names of marker types color (color value, optional): shorthand to set both fill and line color source (:class:`~bokeh.models.sources.ColumnDataSource`) : a user-supplied data source. An attempt will be made to convert the object to :class:`~bokeh.models.sources.ColumnDataSource` if needed. If none is supplied, one is created for the user automatically. **kwargs: :ref:`userguide_styling_line_properties` and :ref:`userguide_styling_fill_properties` Examples: >>> p.scatter([1,2,3],[4,5,6], marker="square", fill_color="red") >>> p.scatter("data1", "data2", marker="mtype", source=data_source, ...) .. note:: When passing ``marker="circle"`` it is also possible to supply a ``radius`` value in data-space units. When configuring marker type from a data source column, *all* markers incuding circles may only be configured with ``size`` in screen units.
[ "Creates", "a", "scatter", "plot", "of", "the", "given", "x", "and", "y", "items", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/plotting/figure.py#L757-L801
30,526
bokeh/bokeh
bokeh/plotting/figure.py
Figure.hexbin
def hexbin(self, x, y, size, orientation="pointytop", palette="Viridis256", line_color=None, fill_color=None, aspect_scale=1, **kwargs): ''' Perform a simple equal-weight hexagonal binning. A :class:`~bokeh.models._glyphs.HexTile` glyph will be added to display the binning. The :class:`~bokeh.models.sources.ColumnDataSource` for the glyph will have columns ``q``, ``r``, and ``count``, where ``q`` and ``r`` are `axial coordinates`_ for a tile, and ``count`` is the associated bin count. It is often useful to set ``match_aspect=True`` on the associated plot, so that hexagonal tiles are all regular (i.e. not "stretched") in screen space. For more sophisticated use-cases, e.g. weighted binning or individually scaling hex tiles, use :func:`hex_tile` directly, or consider a higher level library such as HoloViews. Args: x (array[float]) : A NumPy array of x-coordinates to bin into hexagonal tiles. y (array[float]) : A NumPy array of y-coordinates to bin into hexagonal tiles size (float) : The size of the hexagonal tiling to use. The size is defined as distance from the center of a hexagon to a corner. In case the aspect scaling is not 1-1, then specifically `size` is the distance from the center to the "top" corner with the `"pointytop"` orientation, and the distance from the center to a "side" corner with the "flattop" orientation. orientation ("pointytop" or "flattop", optional) : Whether the hexagonal tiles should be oriented with a pointed corner on top, or a flat side on top. (default: "pointytop") palette (str or seq[color], optional) : A palette (or palette name) to use to colormap the bins according to count. (default: 'Viridis256') If ``fill_color`` is supplied, it overrides this value. line_color (color, optional) : The outline color for hex tiles, or None (default: None) fill_color (color, optional) : An optional fill color for hex tiles, or None. If None, then the ``palette`` will be used to color map the tiles by count. (default: None) aspect_scale (float) : Match a plot's aspect ratio scaling. When working with a plot with ``aspect_scale != 1``, this parameter can be set to match the plot, in order to draw regular hexagons (instead of "stretched" ones). This is roughly equivalent to binning in "screen space", and it may be better to use axis-aligned rectangular bins when plot aspect scales are not one. Any additional keyword arguments are passed to :func:`hex_tile`. Returns (Glyphrender, DataFrame) A tuple with the ``HexTile`` renderer generated to display the binning, and a Pandas ``DataFrame`` with columns ``q``, ``r``, and ``count``, where ``q`` and ``r`` are `axial coordinates`_ for a tile, and ``count`` is the associated bin count. Example: .. bokeh-plot:: :source-position: above import numpy as np from bokeh.models import HoverTool from bokeh.plotting import figure, show x = 2 + 2*np.random.standard_normal(500) y = 2 + 2*np.random.standard_normal(500) p = figure(match_aspect=True, tools="wheel_zoom,reset") p.background_fill_color = '#440154' p.grid.visible = False p.hexbin(x, y, size=0.5, hover_color="pink", hover_alpha=0.8) hover = HoverTool(tooltips=[("count", "@c"), ("(q,r)", "(@q, @r)")]) p.add_tools(hover) show(p) .. _axial coordinates: https://www.redblobgames.com/grids/hexagons/#coordinates-axial ''' from ..util.hex import hexbin bins = hexbin(x, y, size, orientation, aspect_scale=aspect_scale) if fill_color is None: fill_color = linear_cmap('c', palette, 0, max(bins.counts)) source = ColumnDataSource(data=dict(q=bins.q, r=bins.r, c=bins.counts)) r = self.hex_tile(q="q", r="r", size=size, orientation=orientation, aspect_scale=aspect_scale, source=source, line_color=line_color, fill_color=fill_color, **kwargs) return (r, bins)
python
def hexbin(self, x, y, size, orientation="pointytop", palette="Viridis256", line_color=None, fill_color=None, aspect_scale=1, **kwargs): ''' Perform a simple equal-weight hexagonal binning. A :class:`~bokeh.models._glyphs.HexTile` glyph will be added to display the binning. The :class:`~bokeh.models.sources.ColumnDataSource` for the glyph will have columns ``q``, ``r``, and ``count``, where ``q`` and ``r`` are `axial coordinates`_ for a tile, and ``count`` is the associated bin count. It is often useful to set ``match_aspect=True`` on the associated plot, so that hexagonal tiles are all regular (i.e. not "stretched") in screen space. For more sophisticated use-cases, e.g. weighted binning or individually scaling hex tiles, use :func:`hex_tile` directly, or consider a higher level library such as HoloViews. Args: x (array[float]) : A NumPy array of x-coordinates to bin into hexagonal tiles. y (array[float]) : A NumPy array of y-coordinates to bin into hexagonal tiles size (float) : The size of the hexagonal tiling to use. The size is defined as distance from the center of a hexagon to a corner. In case the aspect scaling is not 1-1, then specifically `size` is the distance from the center to the "top" corner with the `"pointytop"` orientation, and the distance from the center to a "side" corner with the "flattop" orientation. orientation ("pointytop" or "flattop", optional) : Whether the hexagonal tiles should be oriented with a pointed corner on top, or a flat side on top. (default: "pointytop") palette (str or seq[color], optional) : A palette (or palette name) to use to colormap the bins according to count. (default: 'Viridis256') If ``fill_color`` is supplied, it overrides this value. line_color (color, optional) : The outline color for hex tiles, or None (default: None) fill_color (color, optional) : An optional fill color for hex tiles, or None. If None, then the ``palette`` will be used to color map the tiles by count. (default: None) aspect_scale (float) : Match a plot's aspect ratio scaling. When working with a plot with ``aspect_scale != 1``, this parameter can be set to match the plot, in order to draw regular hexagons (instead of "stretched" ones). This is roughly equivalent to binning in "screen space", and it may be better to use axis-aligned rectangular bins when plot aspect scales are not one. Any additional keyword arguments are passed to :func:`hex_tile`. Returns (Glyphrender, DataFrame) A tuple with the ``HexTile`` renderer generated to display the binning, and a Pandas ``DataFrame`` with columns ``q``, ``r``, and ``count``, where ``q`` and ``r`` are `axial coordinates`_ for a tile, and ``count`` is the associated bin count. Example: .. bokeh-plot:: :source-position: above import numpy as np from bokeh.models import HoverTool from bokeh.plotting import figure, show x = 2 + 2*np.random.standard_normal(500) y = 2 + 2*np.random.standard_normal(500) p = figure(match_aspect=True, tools="wheel_zoom,reset") p.background_fill_color = '#440154' p.grid.visible = False p.hexbin(x, y, size=0.5, hover_color="pink", hover_alpha=0.8) hover = HoverTool(tooltips=[("count", "@c"), ("(q,r)", "(@q, @r)")]) p.add_tools(hover) show(p) .. _axial coordinates: https://www.redblobgames.com/grids/hexagons/#coordinates-axial ''' from ..util.hex import hexbin bins = hexbin(x, y, size, orientation, aspect_scale=aspect_scale) if fill_color is None: fill_color = linear_cmap('c', palette, 0, max(bins.counts)) source = ColumnDataSource(data=dict(q=bins.q, r=bins.r, c=bins.counts)) r = self.hex_tile(q="q", r="r", size=size, orientation=orientation, aspect_scale=aspect_scale, source=source, line_color=line_color, fill_color=fill_color, **kwargs) return (r, bins)
[ "def", "hexbin", "(", "self", ",", "x", ",", "y", ",", "size", ",", "orientation", "=", "\"pointytop\"", ",", "palette", "=", "\"Viridis256\"", ",", "line_color", "=", "None", ",", "fill_color", "=", "None", ",", "aspect_scale", "=", "1", ",", "*", "*"...
Perform a simple equal-weight hexagonal binning. A :class:`~bokeh.models._glyphs.HexTile` glyph will be added to display the binning. The :class:`~bokeh.models.sources.ColumnDataSource` for the glyph will have columns ``q``, ``r``, and ``count``, where ``q`` and ``r`` are `axial coordinates`_ for a tile, and ``count`` is the associated bin count. It is often useful to set ``match_aspect=True`` on the associated plot, so that hexagonal tiles are all regular (i.e. not "stretched") in screen space. For more sophisticated use-cases, e.g. weighted binning or individually scaling hex tiles, use :func:`hex_tile` directly, or consider a higher level library such as HoloViews. Args: x (array[float]) : A NumPy array of x-coordinates to bin into hexagonal tiles. y (array[float]) : A NumPy array of y-coordinates to bin into hexagonal tiles size (float) : The size of the hexagonal tiling to use. The size is defined as distance from the center of a hexagon to a corner. In case the aspect scaling is not 1-1, then specifically `size` is the distance from the center to the "top" corner with the `"pointytop"` orientation, and the distance from the center to a "side" corner with the "flattop" orientation. orientation ("pointytop" or "flattop", optional) : Whether the hexagonal tiles should be oriented with a pointed corner on top, or a flat side on top. (default: "pointytop") palette (str or seq[color], optional) : A palette (or palette name) to use to colormap the bins according to count. (default: 'Viridis256') If ``fill_color`` is supplied, it overrides this value. line_color (color, optional) : The outline color for hex tiles, or None (default: None) fill_color (color, optional) : An optional fill color for hex tiles, or None. If None, then the ``palette`` will be used to color map the tiles by count. (default: None) aspect_scale (float) : Match a plot's aspect ratio scaling. When working with a plot with ``aspect_scale != 1``, this parameter can be set to match the plot, in order to draw regular hexagons (instead of "stretched" ones). This is roughly equivalent to binning in "screen space", and it may be better to use axis-aligned rectangular bins when plot aspect scales are not one. Any additional keyword arguments are passed to :func:`hex_tile`. Returns (Glyphrender, DataFrame) A tuple with the ``HexTile`` renderer generated to display the binning, and a Pandas ``DataFrame`` with columns ``q``, ``r``, and ``count``, where ``q`` and ``r`` are `axial coordinates`_ for a tile, and ``count`` is the associated bin count. Example: .. bokeh-plot:: :source-position: above import numpy as np from bokeh.models import HoverTool from bokeh.plotting import figure, show x = 2 + 2*np.random.standard_normal(500) y = 2 + 2*np.random.standard_normal(500) p = figure(match_aspect=True, tools="wheel_zoom,reset") p.background_fill_color = '#440154' p.grid.visible = False p.hexbin(x, y, size=0.5, hover_color="pink", hover_alpha=0.8) hover = HoverTool(tooltips=[("count", "@c"), ("(q,r)", "(@q, @r)")]) p.add_tools(hover) show(p) .. _axial coordinates: https://www.redblobgames.com/grids/hexagons/#coordinates-axial
[ "Perform", "a", "simple", "equal", "-", "weight", "hexagonal", "binning", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/plotting/figure.py#L803-L912
30,527
bokeh/bokeh
bokeh/plotting/figure.py
Figure.harea_stack
def harea_stack(self, stackers, **kw): ''' Generate multiple ``HArea`` renderers for levels stacked left to right. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``x1`` and ``x2`` harea coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``harea``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2016* and *2017*, then the following call to ``harea_stack`` will will create two ``HArea`` renderers that stack: .. code-block:: python p.harea_stack(['2016', '2017'], y='y', color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.harea(x1=stack(), x2=stack('2016'), y='y', color='blue', source=source, name='2016') p.harea(x1=stack('2016'), x2=stack('2016', '2017'), y='y', color='red', source=source, name='2017') ''' result = [] for kw in _double_stack(stackers, "x1", "x2", **kw): result.append(self.harea(**kw)) return result
python
def harea_stack(self, stackers, **kw): ''' Generate multiple ``HArea`` renderers for levels stacked left to right. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``x1`` and ``x2`` harea coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``harea``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2016* and *2017*, then the following call to ``harea_stack`` will will create two ``HArea`` renderers that stack: .. code-block:: python p.harea_stack(['2016', '2017'], y='y', color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.harea(x1=stack(), x2=stack('2016'), y='y', color='blue', source=source, name='2016') p.harea(x1=stack('2016'), x2=stack('2016', '2017'), y='y', color='red', source=source, name='2017') ''' result = [] for kw in _double_stack(stackers, "x1", "x2", **kw): result.append(self.harea(**kw)) return result
[ "def", "harea_stack", "(", "self", ",", "stackers", ",", "*", "*", "kw", ")", ":", "result", "=", "[", "]", "for", "kw", "in", "_double_stack", "(", "stackers", ",", "\"x1\"", ",", "\"x2\"", ",", "*", "*", "kw", ")", ":", "result", ".", "append", ...
Generate multiple ``HArea`` renderers for levels stacked left to right. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``x1`` and ``x2`` harea coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``harea``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2016* and *2017*, then the following call to ``harea_stack`` will will create two ``HArea`` renderers that stack: .. code-block:: python p.harea_stack(['2016', '2017'], y='y', color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.harea(x1=stack(), x2=stack('2016'), y='y', color='blue', source=source, name='2016') p.harea(x1=stack('2016'), x2=stack('2016', '2017'), y='y', color='red', source=source, name='2017')
[ "Generate", "multiple", "HArea", "renderers", "for", "levels", "stacked", "left", "to", "right", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/plotting/figure.py#L914-L954
30,528
bokeh/bokeh
bokeh/plotting/figure.py
Figure.hbar_stack
def hbar_stack(self, stackers, **kw): ''' Generate multiple ``HBar`` renderers for levels stacked left to right. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``left`` and ``right`` bar coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``hbar``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2106* and *2017*, then the following call to ``hbar_stack`` will will create two ``HBar`` renderers that stack: .. code-block:: python p.hbar_stack(['2016', '2017'], x=10, width=0.9, color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.hbar(bottom=stack(), top=stack('2016'), x=10, width=0.9, color='blue', source=source, name='2016') p.hbar(bottom=stack('2016'), top=stack('2016', '2017'), x=10, width=0.9, color='red', source=source, name='2017') ''' result = [] for kw in _double_stack(stackers, "left", "right", **kw): result.append(self.hbar(**kw)) return result
python
def hbar_stack(self, stackers, **kw): ''' Generate multiple ``HBar`` renderers for levels stacked left to right. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``left`` and ``right`` bar coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``hbar``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2106* and *2017*, then the following call to ``hbar_stack`` will will create two ``HBar`` renderers that stack: .. code-block:: python p.hbar_stack(['2016', '2017'], x=10, width=0.9, color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.hbar(bottom=stack(), top=stack('2016'), x=10, width=0.9, color='blue', source=source, name='2016') p.hbar(bottom=stack('2016'), top=stack('2016', '2017'), x=10, width=0.9, color='red', source=source, name='2017') ''' result = [] for kw in _double_stack(stackers, "left", "right", **kw): result.append(self.hbar(**kw)) return result
[ "def", "hbar_stack", "(", "self", ",", "stackers", ",", "*", "*", "kw", ")", ":", "result", "=", "[", "]", "for", "kw", "in", "_double_stack", "(", "stackers", ",", "\"left\"", ",", "\"right\"", ",", "*", "*", "kw", ")", ":", "result", ".", "append...
Generate multiple ``HBar`` renderers for levels stacked left to right. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``left`` and ``right`` bar coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``hbar``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2106* and *2017*, then the following call to ``hbar_stack`` will will create two ``HBar`` renderers that stack: .. code-block:: python p.hbar_stack(['2016', '2017'], x=10, width=0.9, color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.hbar(bottom=stack(), top=stack('2016'), x=10, width=0.9, color='blue', source=source, name='2016') p.hbar(bottom=stack('2016'), top=stack('2016', '2017'), x=10, width=0.9, color='red', source=source, name='2017')
[ "Generate", "multiple", "HBar", "renderers", "for", "levels", "stacked", "left", "to", "right", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/plotting/figure.py#L956-L995
30,529
bokeh/bokeh
bokeh/plotting/figure.py
Figure.line_stack
def line_stack(self, x, y, **kw): ''' Generate multiple ``Line`` renderers for lines stacked vertically or horizontally. Args: x (seq[str]) : y (seq[str]) : Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``hbar``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2106* and *2017*, then the following call to ``line_stack`` with stackers for the y-coordinates will will create two ``Line`` renderers that stack: .. code-block:: python p.line_stack(['2016', '2017'], x='x', color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.line(y=stack('2016'), x='x', color='blue', source=source, name='2016') p.line(y=stack('2016', '2017'), x='x', color='red', source=source, name='2017') ''' if all(isinstance(val, (list, tuple)) for val in (x,y)): raise ValueError("Only one of x or y may be a list of stackers") result = [] if isinstance(y, (list, tuple)): kw['x'] = x for kw in _single_stack(y, "y", **kw): result.append(self.line(**kw)) return result if isinstance(x, (list, tuple)): kw['y'] = y for kw in _single_stack(x, "x", **kw): result.append(self.line(**kw)) return result return [self.line(x, y, **kw)]
python
def line_stack(self, x, y, **kw): ''' Generate multiple ``Line`` renderers for lines stacked vertically or horizontally. Args: x (seq[str]) : y (seq[str]) : Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``hbar``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2106* and *2017*, then the following call to ``line_stack`` with stackers for the y-coordinates will will create two ``Line`` renderers that stack: .. code-block:: python p.line_stack(['2016', '2017'], x='x', color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.line(y=stack('2016'), x='x', color='blue', source=source, name='2016') p.line(y=stack('2016', '2017'), x='x', color='red', source=source, name='2017') ''' if all(isinstance(val, (list, tuple)) for val in (x,y)): raise ValueError("Only one of x or y may be a list of stackers") result = [] if isinstance(y, (list, tuple)): kw['x'] = x for kw in _single_stack(y, "y", **kw): result.append(self.line(**kw)) return result if isinstance(x, (list, tuple)): kw['y'] = y for kw in _single_stack(x, "x", **kw): result.append(self.line(**kw)) return result return [self.line(x, y, **kw)]
[ "def", "line_stack", "(", "self", ",", "x", ",", "y", ",", "*", "*", "kw", ")", ":", "if", "all", "(", "isinstance", "(", "val", ",", "(", "list", ",", "tuple", ")", ")", "for", "val", "in", "(", "x", ",", "y", ")", ")", ":", "raise", "Valu...
Generate multiple ``Line`` renderers for lines stacked vertically or horizontally. Args: x (seq[str]) : y (seq[str]) : Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``hbar``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2106* and *2017*, then the following call to ``line_stack`` with stackers for the y-coordinates will will create two ``Line`` renderers that stack: .. code-block:: python p.line_stack(['2016', '2017'], x='x', color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.line(y=stack('2016'), x='x', color='blue', source=source, name='2016') p.line(y=stack('2016', '2017'), x='x', color='red', source=source, name='2017')
[ "Generate", "multiple", "Line", "renderers", "for", "lines", "stacked", "vertically", "or", "horizontally", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/plotting/figure.py#L997-L1053
30,530
bokeh/bokeh
bokeh/plotting/figure.py
Figure.varea_stack
def varea_stack(self, stackers, **kw): ''' Generate multiple ``VArea`` renderers for levels stacked bottom to top. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``y1`` and ``y1`` varea coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``varea``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2016* and *2017*, then the following call to ``varea_stack`` will will create two ``VArea`` renderers that stack: .. code-block:: python p.varea_stack(['2016', '2017'], x='x', color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.varea(y1=stack(), y2=stack('2016'), x='x', color='blue', source=source, name='2016') p.varea(y1=stack('2016'), y2=stack('2016', '2017'), x='x', color='red', source=source, name='2017') ''' result = [] for kw in _double_stack(stackers, "y1", "y2", **kw): result.append(self.varea(**kw)) return result
python
def varea_stack(self, stackers, **kw): ''' Generate multiple ``VArea`` renderers for levels stacked bottom to top. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``y1`` and ``y1`` varea coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``varea``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2016* and *2017*, then the following call to ``varea_stack`` will will create two ``VArea`` renderers that stack: .. code-block:: python p.varea_stack(['2016', '2017'], x='x', color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.varea(y1=stack(), y2=stack('2016'), x='x', color='blue', source=source, name='2016') p.varea(y1=stack('2016'), y2=stack('2016', '2017'), x='x', color='red', source=source, name='2017') ''' result = [] for kw in _double_stack(stackers, "y1", "y2", **kw): result.append(self.varea(**kw)) return result
[ "def", "varea_stack", "(", "self", ",", "stackers", ",", "*", "*", "kw", ")", ":", "result", "=", "[", "]", "for", "kw", "in", "_double_stack", "(", "stackers", ",", "\"y1\"", ",", "\"y2\"", ",", "*", "*", "kw", ")", ":", "result", ".", "append", ...
Generate multiple ``VArea`` renderers for levels stacked bottom to top. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``y1`` and ``y1`` varea coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``varea``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2016* and *2017*, then the following call to ``varea_stack`` will will create two ``VArea`` renderers that stack: .. code-block:: python p.varea_stack(['2016', '2017'], x='x', color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.varea(y1=stack(), y2=stack('2016'), x='x', color='blue', source=source, name='2016') p.varea(y1=stack('2016'), y2=stack('2016', '2017'), x='x', color='red', source=source, name='2017')
[ "Generate", "multiple", "VArea", "renderers", "for", "levels", "stacked", "bottom", "to", "top", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/plotting/figure.py#L1055-L1095
30,531
bokeh/bokeh
bokeh/plotting/figure.py
Figure.vbar_stack
def vbar_stack(self, stackers, **kw): ''' Generate multiple ``VBar`` renderers for levels stacked bottom to top. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``left`` and ``right`` bar coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``vbar``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2016* and *2017*, then the following call to ``vbar_stack`` will will create two ``VBar`` renderers that stack: .. code-block:: python p.vbar_stack(['2016', '2017'], x=10, width=0.9, color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.vbar(bottom=stack(), top=stack('2016'), x=10, width=0.9, color='blue', source=source, name='2016') p.vbar(bottom=stack('2016'), top=stack('2016', '2017'), x=10, width=0.9, color='red', source=source, name='2017') ''' result = [] for kw in _double_stack(stackers, "bottom", "top", **kw): result.append(self.vbar(**kw)) return result
python
def vbar_stack(self, stackers, **kw): ''' Generate multiple ``VBar`` renderers for levels stacked bottom to top. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``left`` and ``right`` bar coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``vbar``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2016* and *2017*, then the following call to ``vbar_stack`` will will create two ``VBar`` renderers that stack: .. code-block:: python p.vbar_stack(['2016', '2017'], x=10, width=0.9, color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.vbar(bottom=stack(), top=stack('2016'), x=10, width=0.9, color='blue', source=source, name='2016') p.vbar(bottom=stack('2016'), top=stack('2016', '2017'), x=10, width=0.9, color='red', source=source, name='2017') ''' result = [] for kw in _double_stack(stackers, "bottom", "top", **kw): result.append(self.vbar(**kw)) return result
[ "def", "vbar_stack", "(", "self", ",", "stackers", ",", "*", "*", "kw", ")", ":", "result", "=", "[", "]", "for", "kw", "in", "_double_stack", "(", "stackers", ",", "\"bottom\"", ",", "\"top\"", ",", "*", "*", "kw", ")", ":", "result", ".", "append...
Generate multiple ``VBar`` renderers for levels stacked bottom to top. Args: stackers (seq[str]) : a list of data source field names to stack successively for ``left`` and ``right`` bar coordinates. Additionally, the ``name`` of the renderer will be set to the value of each successive stacker (this is useful with the special hover variable ``$name``) Any additional keyword arguments are passed to each call to ``vbar``. If a keyword value is a list or tuple, then each call will get one value from the sequence. Returns: list[GlyphRenderer] Examples: Assuming a ``ColumnDataSource`` named ``source`` with columns *2016* and *2017*, then the following call to ``vbar_stack`` will will create two ``VBar`` renderers that stack: .. code-block:: python p.vbar_stack(['2016', '2017'], x=10, width=0.9, color=['blue', 'red'], source=source) This is equivalent to the following two separate calls: .. code-block:: python p.vbar(bottom=stack(), top=stack('2016'), x=10, width=0.9, color='blue', source=source, name='2016') p.vbar(bottom=stack('2016'), top=stack('2016', '2017'), x=10, width=0.9, color='red', source=source, name='2017')
[ "Generate", "multiple", "VBar", "renderers", "for", "levels", "stacked", "bottom", "to", "top", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/plotting/figure.py#L1097-L1137
30,532
bokeh/bokeh
bokeh/plotting/figure.py
Figure.graph
def graph(self, node_source, edge_source, layout_provider, **kwargs): ''' Creates a network graph using the given node, edge and layout provider. Args: node_source (:class:`~bokeh.models.sources.ColumnDataSource`) : a user-supplied data source for the graph nodes. An attempt will be made to convert the object to :class:`~bokeh.models.sources.ColumnDataSource` if needed. If none is supplied, one is created for the user automatically. edge_source (:class:`~bokeh.models.sources.ColumnDataSource`) : a user-supplied data source for the graph edges. An attempt will be made to convert the object to :class:`~bokeh.models.sources.ColumnDataSource` if needed. If none is supplied, one is created for the user automatically. layout_provider (:class:`~bokeh.models.graphs.LayoutProvider`) : a ``LayoutProvider`` instance to provide the graph coordinates in Cartesian space. **kwargs: :ref:`userguide_styling_line_properties` and :ref:`userguide_styling_fill_properties` ''' kw = _graph(node_source, edge_source, **kwargs) graph_renderer = GraphRenderer(layout_provider=layout_provider, **kw) self.renderers.append(graph_renderer) return graph_renderer
python
def graph(self, node_source, edge_source, layout_provider, **kwargs): ''' Creates a network graph using the given node, edge and layout provider. Args: node_source (:class:`~bokeh.models.sources.ColumnDataSource`) : a user-supplied data source for the graph nodes. An attempt will be made to convert the object to :class:`~bokeh.models.sources.ColumnDataSource` if needed. If none is supplied, one is created for the user automatically. edge_source (:class:`~bokeh.models.sources.ColumnDataSource`) : a user-supplied data source for the graph edges. An attempt will be made to convert the object to :class:`~bokeh.models.sources.ColumnDataSource` if needed. If none is supplied, one is created for the user automatically. layout_provider (:class:`~bokeh.models.graphs.LayoutProvider`) : a ``LayoutProvider`` instance to provide the graph coordinates in Cartesian space. **kwargs: :ref:`userguide_styling_line_properties` and :ref:`userguide_styling_fill_properties` ''' kw = _graph(node_source, edge_source, **kwargs) graph_renderer = GraphRenderer(layout_provider=layout_provider, **kw) self.renderers.append(graph_renderer) return graph_renderer
[ "def", "graph", "(", "self", ",", "node_source", ",", "edge_source", ",", "layout_provider", ",", "*", "*", "kwargs", ")", ":", "kw", "=", "_graph", "(", "node_source", ",", "edge_source", ",", "*", "*", "kwargs", ")", "graph_renderer", "=", "GraphRenderer...
Creates a network graph using the given node, edge and layout provider. Args: node_source (:class:`~bokeh.models.sources.ColumnDataSource`) : a user-supplied data source for the graph nodes. An attempt will be made to convert the object to :class:`~bokeh.models.sources.ColumnDataSource` if needed. If none is supplied, one is created for the user automatically. edge_source (:class:`~bokeh.models.sources.ColumnDataSource`) : a user-supplied data source for the graph edges. An attempt will be made to convert the object to :class:`~bokeh.models.sources.ColumnDataSource` if needed. If none is supplied, one is created for the user automatically. layout_provider (:class:`~bokeh.models.graphs.LayoutProvider`) : a ``LayoutProvider`` instance to provide the graph coordinates in Cartesian space. **kwargs: :ref:`userguide_styling_line_properties` and :ref:`userguide_styling_fill_properties`
[ "Creates", "a", "network", "graph", "using", "the", "given", "node", "edge", "and", "layout", "provider", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/plotting/figure.py#L1139-L1162
30,533
bokeh/bokeh
bokeh/core/property/validation.py
without_property_validation
def without_property_validation(input_function): ''' Turn off property validation during update callbacks Example: .. code-block:: python @without_property_validation def update(attr, old, new): # do things without validation See Also: :class:`~bokeh.core.properties.validate`: context mangager for more fine-grained control ''' @wraps(input_function) def func(*args, **kwargs): with validate(False): return input_function(*args, **kwargs) return func
python
def without_property_validation(input_function): ''' Turn off property validation during update callbacks Example: .. code-block:: python @without_property_validation def update(attr, old, new): # do things without validation See Also: :class:`~bokeh.core.properties.validate`: context mangager for more fine-grained control ''' @wraps(input_function) def func(*args, **kwargs): with validate(False): return input_function(*args, **kwargs) return func
[ "def", "without_property_validation", "(", "input_function", ")", ":", "@", "wraps", "(", "input_function", ")", "def", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "validate", "(", "False", ")", ":", "return", "input_function", "("...
Turn off property validation during update callbacks Example: .. code-block:: python @without_property_validation def update(attr, old, new): # do things without validation See Also: :class:`~bokeh.core.properties.validate`: context mangager for more fine-grained control
[ "Turn", "off", "property", "validation", "during", "update", "callbacks" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/property/validation.py#L80-L98
30,534
bokeh/bokeh
bokeh/core/templates.py
get_env
def get_env(): ''' Get the correct Jinja2 Environment, also for frozen scripts. ''' if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'): # PyInstaller uses _MEIPASS and only works with jinja2.FileSystemLoader templates_path = join(sys._MEIPASS, 'bokeh', 'core', '_templates') else: # Non-frozen Python and cx_Freeze can use __file__ directly templates_path = join(dirname(__file__), '_templates') return Environment(loader=FileSystemLoader(templates_path))
python
def get_env(): ''' Get the correct Jinja2 Environment, also for frozen scripts. ''' if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'): # PyInstaller uses _MEIPASS and only works with jinja2.FileSystemLoader templates_path = join(sys._MEIPASS, 'bokeh', 'core', '_templates') else: # Non-frozen Python and cx_Freeze can use __file__ directly templates_path = join(dirname(__file__), '_templates') return Environment(loader=FileSystemLoader(templates_path))
[ "def", "get_env", "(", ")", ":", "if", "getattr", "(", "sys", ",", "'frozen'", ",", "False", ")", "and", "hasattr", "(", "sys", ",", "'_MEIPASS'", ")", ":", "# PyInstaller uses _MEIPASS and only works with jinja2.FileSystemLoader", "templates_path", "=", "join", "...
Get the correct Jinja2 Environment, also for frozen scripts.
[ "Get", "the", "correct", "Jinja2", "Environment", "also", "for", "frozen", "scripts", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/core/templates.py#L72-L82
30,535
bokeh/bokeh
bokeh/server/protocol_handler.py
ProtocolHandler.handle
def handle(self, message, connection): ''' Delegate a received message to the appropriate handler. Args: message (Message) : The message that was receive that needs to be handled connection (ServerConnection) : The connection that received this message Raises: ProtocolError ''' handler = self._handlers.get((message.msgtype, message.revision)) if handler is None: handler = self._handlers.get(message.msgtype) if handler is None: raise ProtocolError("%s not expected on server" % message) try: work = yield handler(message, connection) except Exception as e: log.error("error handling message %r: %r", message, e) log.debug(" message header %r content %r", message.header, message.content, exc_info=1) work = connection.error(message, repr(e)) raise gen.Return(work)
python
def handle(self, message, connection): ''' Delegate a received message to the appropriate handler. Args: message (Message) : The message that was receive that needs to be handled connection (ServerConnection) : The connection that received this message Raises: ProtocolError ''' handler = self._handlers.get((message.msgtype, message.revision)) if handler is None: handler = self._handlers.get(message.msgtype) if handler is None: raise ProtocolError("%s not expected on server" % message) try: work = yield handler(message, connection) except Exception as e: log.error("error handling message %r: %r", message, e) log.debug(" message header %r content %r", message.header, message.content, exc_info=1) work = connection.error(message, repr(e)) raise gen.Return(work)
[ "def", "handle", "(", "self", ",", "message", ",", "connection", ")", ":", "handler", "=", "self", ".", "_handlers", ".", "get", "(", "(", "message", ".", "msgtype", ",", "message", ".", "revision", ")", ")", "if", "handler", "is", "None", ":", "hand...
Delegate a received message to the appropriate handler. Args: message (Message) : The message that was receive that needs to be handled connection (ServerConnection) : The connection that received this message Raises: ProtocolError
[ "Delegate", "a", "received", "message", "to", "the", "appropriate", "handler", "." ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/protocol_handler.py#L76-L105
30,536
bokeh/bokeh
bokeh/server/session.py
_needs_document_lock
def _needs_document_lock(func): '''Decorator that adds the necessary locking and post-processing to manipulate the session's document. Expects to decorate a method on ServerSession and transforms it into a coroutine if it wasn't already. ''' @gen.coroutine def _needs_document_lock_wrapper(self, *args, **kwargs): # while we wait for and hold the lock, prevent the session # from being discarded. This avoids potential weirdness # with the session vanishing in the middle of some async # task. if self.destroyed: log.debug("Ignoring locked callback on already-destroyed session.") raise gen.Return(None) self.block_expiration() try: with (yield self._lock.acquire()): if self._pending_writes is not None: raise RuntimeError("internal class invariant violated: _pending_writes " + \ "should be None if lock is not held") self._pending_writes = [] try: result = yield yield_for_all_futures(func(self, *args, **kwargs)) finally: # we want to be very sure we reset this or we'll # keep hitting the RuntimeError above as soon as # any callback goes wrong pending_writes = self._pending_writes self._pending_writes = None for p in pending_writes: yield p raise gen.Return(result) finally: self.unblock_expiration() return _needs_document_lock_wrapper
python
def _needs_document_lock(func): '''Decorator that adds the necessary locking and post-processing to manipulate the session's document. Expects to decorate a method on ServerSession and transforms it into a coroutine if it wasn't already. ''' @gen.coroutine def _needs_document_lock_wrapper(self, *args, **kwargs): # while we wait for and hold the lock, prevent the session # from being discarded. This avoids potential weirdness # with the session vanishing in the middle of some async # task. if self.destroyed: log.debug("Ignoring locked callback on already-destroyed session.") raise gen.Return(None) self.block_expiration() try: with (yield self._lock.acquire()): if self._pending_writes is not None: raise RuntimeError("internal class invariant violated: _pending_writes " + \ "should be None if lock is not held") self._pending_writes = [] try: result = yield yield_for_all_futures(func(self, *args, **kwargs)) finally: # we want to be very sure we reset this or we'll # keep hitting the RuntimeError above as soon as # any callback goes wrong pending_writes = self._pending_writes self._pending_writes = None for p in pending_writes: yield p raise gen.Return(result) finally: self.unblock_expiration() return _needs_document_lock_wrapper
[ "def", "_needs_document_lock", "(", "func", ")", ":", "@", "gen", ".", "coroutine", "def", "_needs_document_lock_wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# while we wait for and hold the lock, prevent the session", "# from being dis...
Decorator that adds the necessary locking and post-processing to manipulate the session's document. Expects to decorate a method on ServerSession and transforms it into a coroutine if it wasn't already.
[ "Decorator", "that", "adds", "the", "necessary", "locking", "and", "post", "-", "processing", "to", "manipulate", "the", "session", "s", "document", ".", "Expects", "to", "decorate", "a", "method", "on", "ServerSession", "and", "transforms", "it", "into", "a",...
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/session.py#L47-L82
30,537
bokeh/bokeh
bokeh/server/session.py
ServerSession.unsubscribe
def unsubscribe(self, connection): """This should only be called by ``ServerConnection.unsubscribe_session`` or our book-keeping will be broken""" self._subscribed_connections.discard(connection) self._last_unsubscribe_time = current_time()
python
def unsubscribe(self, connection): """This should only be called by ``ServerConnection.unsubscribe_session`` or our book-keeping will be broken""" self._subscribed_connections.discard(connection) self._last_unsubscribe_time = current_time()
[ "def", "unsubscribe", "(", "self", ",", "connection", ")", ":", "self", ".", "_subscribed_connections", ".", "discard", "(", "connection", ")", "self", ".", "_last_unsubscribe_time", "=", "current_time", "(", ")" ]
This should only be called by ``ServerConnection.unsubscribe_session`` or our book-keeping will be broken
[ "This", "should", "only", "be", "called", "by", "ServerConnection", ".", "unsubscribe_session", "or", "our", "book", "-", "keeping", "will", "be", "broken" ]
dc8cf49e4e4302fd38537ad089ece81fbcca4737
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/server/session.py#L175-L178
30,538
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget.set_cwd
def set_cwd(self, dirname): """Set shell current working directory.""" # Replace single for double backslashes on Windows if os.name == 'nt': dirname = dirname.replace(u"\\", u"\\\\") if not self.external_kernel: code = u"get_ipython().kernel.set_cwd(u'''{}''')".format(dirname) if self._reading: self.kernel_client.input(u'!' + code) else: self.silent_execute(code) self._cwd = dirname
python
def set_cwd(self, dirname): """Set shell current working directory.""" # Replace single for double backslashes on Windows if os.name == 'nt': dirname = dirname.replace(u"\\", u"\\\\") if not self.external_kernel: code = u"get_ipython().kernel.set_cwd(u'''{}''')".format(dirname) if self._reading: self.kernel_client.input(u'!' + code) else: self.silent_execute(code) self._cwd = dirname
[ "def", "set_cwd", "(", "self", ",", "dirname", ")", ":", "# Replace single for double backslashes on Windows", "if", "os", ".", "name", "==", "'nt'", ":", "dirname", "=", "dirname", ".", "replace", "(", "u\"\\\\\"", ",", "u\"\\\\\\\\\"", ")", "if", "not", "sel...
Set shell current working directory.
[ "Set", "shell", "current", "working", "directory", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L110-L122
30,539
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget.set_bracket_matcher_color_scheme
def set_bracket_matcher_color_scheme(self, color_scheme): """Set color scheme for matched parentheses.""" bsh = sh.BaseSH(parent=self, color_scheme=color_scheme) mpcolor = bsh.get_matched_p_color() self._bracket_matcher.format.setBackground(mpcolor)
python
def set_bracket_matcher_color_scheme(self, color_scheme): """Set color scheme for matched parentheses.""" bsh = sh.BaseSH(parent=self, color_scheme=color_scheme) mpcolor = bsh.get_matched_p_color() self._bracket_matcher.format.setBackground(mpcolor)
[ "def", "set_bracket_matcher_color_scheme", "(", "self", ",", "color_scheme", ")", ":", "bsh", "=", "sh", ".", "BaseSH", "(", "parent", "=", "self", ",", "color_scheme", "=", "color_scheme", ")", "mpcolor", "=", "bsh", ".", "get_matched_p_color", "(", ")", "s...
Set color scheme for matched parentheses.
[ "Set", "color", "scheme", "for", "matched", "parentheses", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L136-L140
30,540
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget.set_color_scheme
def set_color_scheme(self, color_scheme, reset=True): """Set color scheme of the shell.""" self.set_bracket_matcher_color_scheme(color_scheme) self.style_sheet, dark_color = create_qss_style(color_scheme) self.syntax_style = color_scheme self._style_sheet_changed() self._syntax_style_changed() if reset: self.reset(clear=True) if not dark_color: self.silent_execute("%colors linux") else: self.silent_execute("%colors lightbg")
python
def set_color_scheme(self, color_scheme, reset=True): """Set color scheme of the shell.""" self.set_bracket_matcher_color_scheme(color_scheme) self.style_sheet, dark_color = create_qss_style(color_scheme) self.syntax_style = color_scheme self._style_sheet_changed() self._syntax_style_changed() if reset: self.reset(clear=True) if not dark_color: self.silent_execute("%colors linux") else: self.silent_execute("%colors lightbg")
[ "def", "set_color_scheme", "(", "self", ",", "color_scheme", ",", "reset", "=", "True", ")", ":", "self", ".", "set_bracket_matcher_color_scheme", "(", "color_scheme", ")", "self", ".", "style_sheet", ",", "dark_color", "=", "create_qss_style", "(", "color_scheme"...
Set color scheme of the shell.
[ "Set", "color", "scheme", "of", "the", "shell", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L142-L154
30,541
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget.long_banner
def long_banner(self): """Banner for IPython widgets with pylab message""" # Default banner try: from IPython.core.usage import quick_guide except Exception: quick_guide = '' banner_parts = [ 'Python %s\n' % self.interpreter_versions['python_version'], 'Type "copyright", "credits" or "license" for more information.\n\n', 'IPython %s -- An enhanced Interactive Python.\n' % \ self.interpreter_versions['ipython_version'], quick_guide ] banner = ''.join(banner_parts) # Pylab additions pylab_o = self.additional_options['pylab'] autoload_pylab_o = self.additional_options['autoload_pylab'] mpl_installed = programs.is_module_installed('matplotlib') if mpl_installed and (pylab_o and autoload_pylab_o): pylab_message = ("\nPopulating the interactive namespace from " "numpy and matplotlib\n") banner = banner + pylab_message # Sympy additions sympy_o = self.additional_options['sympy'] if sympy_o: lines = """ These commands were executed: >>> from __future__ import division >>> from sympy import * >>> x, y, z, t = symbols('x y z t') >>> k, m, n = symbols('k m n', integer=True) >>> f, g, h = symbols('f g h', cls=Function) """ banner = banner + lines if (pylab_o and sympy_o): lines = """ Warning: pylab (numpy and matplotlib) and symbolic math (sympy) are both enabled at the same time. Some pylab functions are going to be overrided by the sympy module (e.g. plot) """ banner = banner + lines return banner
python
def long_banner(self): """Banner for IPython widgets with pylab message""" # Default banner try: from IPython.core.usage import quick_guide except Exception: quick_guide = '' banner_parts = [ 'Python %s\n' % self.interpreter_versions['python_version'], 'Type "copyright", "credits" or "license" for more information.\n\n', 'IPython %s -- An enhanced Interactive Python.\n' % \ self.interpreter_versions['ipython_version'], quick_guide ] banner = ''.join(banner_parts) # Pylab additions pylab_o = self.additional_options['pylab'] autoload_pylab_o = self.additional_options['autoload_pylab'] mpl_installed = programs.is_module_installed('matplotlib') if mpl_installed and (pylab_o and autoload_pylab_o): pylab_message = ("\nPopulating the interactive namespace from " "numpy and matplotlib\n") banner = banner + pylab_message # Sympy additions sympy_o = self.additional_options['sympy'] if sympy_o: lines = """ These commands were executed: >>> from __future__ import division >>> from sympy import * >>> x, y, z, t = symbols('x y z t') >>> k, m, n = symbols('k m n', integer=True) >>> f, g, h = symbols('f g h', cls=Function) """ banner = banner + lines if (pylab_o and sympy_o): lines = """ Warning: pylab (numpy and matplotlib) and symbolic math (sympy) are both enabled at the same time. Some pylab functions are going to be overrided by the sympy module (e.g. plot) """ banner = banner + lines return banner
[ "def", "long_banner", "(", "self", ")", ":", "# Default banner", "try", ":", "from", "IPython", ".", "core", ".", "usage", "import", "quick_guide", "except", "Exception", ":", "quick_guide", "=", "''", "banner_parts", "=", "[", "'Python %s\\n'", "%", "self", ...
Banner for IPython widgets with pylab message
[ "Banner", "for", "IPython", "widgets", "with", "pylab", "message" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L173-L217
30,542
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget.reset_namespace
def reset_namespace(self, warning=False, message=False): """Reset the namespace by removing all names defined by the user.""" reset_str = _("Remove all variables") warn_str = _("All user-defined variables will be removed. " "Are you sure you want to proceed?") kernel_env = self.kernel_manager._kernel_spec.env if warning: box = MessageCheckBox(icon=QMessageBox.Warning, parent=self) box.setWindowTitle(reset_str) box.set_checkbox_text(_("Don't show again.")) box.setStandardButtons(QMessageBox.Yes | QMessageBox.No) box.setDefaultButton(QMessageBox.Yes) box.set_checked(False) box.set_check_visible(True) box.setText(warn_str) answer = box.exec_() # Update checkbox based on user interaction CONF.set('ipython_console', 'show_reset_namespace_warning', not box.is_checked()) self.ipyclient.reset_warning = not box.is_checked() if answer != QMessageBox.Yes: return try: if self._reading: self.dbg_exec_magic('reset', '-f') else: if message: self.reset() self._append_html(_("<br><br>Removing all variables..." "\n<hr>"), before_prompt=False) self.silent_execute("%reset -f") if kernel_env.get('SPY_AUTOLOAD_PYLAB_O') == 'True': self.silent_execute("from pylab import *") if kernel_env.get('SPY_SYMPY_O') == 'True': sympy_init = """ from __future__ import division from sympy import * x, y, z, t = symbols('x y z t') k, m, n = symbols('k m n', integer=True) f, g, h = symbols('f g h', cls=Function) init_printing()""" self.silent_execute(dedent(sympy_init)) if kernel_env.get('SPY_RUN_CYTHON') == 'True': self.silent_execute("%reload_ext Cython") self.refresh_namespacebrowser() if not self.external_kernel: self.silent_execute( 'get_ipython().kernel.close_all_mpl_figures()') except AttributeError: pass
python
def reset_namespace(self, warning=False, message=False): """Reset the namespace by removing all names defined by the user.""" reset_str = _("Remove all variables") warn_str = _("All user-defined variables will be removed. " "Are you sure you want to proceed?") kernel_env = self.kernel_manager._kernel_spec.env if warning: box = MessageCheckBox(icon=QMessageBox.Warning, parent=self) box.setWindowTitle(reset_str) box.set_checkbox_text(_("Don't show again.")) box.setStandardButtons(QMessageBox.Yes | QMessageBox.No) box.setDefaultButton(QMessageBox.Yes) box.set_checked(False) box.set_check_visible(True) box.setText(warn_str) answer = box.exec_() # Update checkbox based on user interaction CONF.set('ipython_console', 'show_reset_namespace_warning', not box.is_checked()) self.ipyclient.reset_warning = not box.is_checked() if answer != QMessageBox.Yes: return try: if self._reading: self.dbg_exec_magic('reset', '-f') else: if message: self.reset() self._append_html(_("<br><br>Removing all variables..." "\n<hr>"), before_prompt=False) self.silent_execute("%reset -f") if kernel_env.get('SPY_AUTOLOAD_PYLAB_O') == 'True': self.silent_execute("from pylab import *") if kernel_env.get('SPY_SYMPY_O') == 'True': sympy_init = """ from __future__ import division from sympy import * x, y, z, t = symbols('x y z t') k, m, n = symbols('k m n', integer=True) f, g, h = symbols('f g h', cls=Function) init_printing()""" self.silent_execute(dedent(sympy_init)) if kernel_env.get('SPY_RUN_CYTHON') == 'True': self.silent_execute("%reload_ext Cython") self.refresh_namespacebrowser() if not self.external_kernel: self.silent_execute( 'get_ipython().kernel.close_all_mpl_figures()') except AttributeError: pass
[ "def", "reset_namespace", "(", "self", ",", "warning", "=", "False", ",", "message", "=", "False", ")", ":", "reset_str", "=", "_", "(", "\"Remove all variables\"", ")", "warn_str", "=", "_", "(", "\"All user-defined variables will be removed. \"", "\"Are you sure y...
Reset the namespace by removing all names defined by the user.
[ "Reset", "the", "namespace", "by", "removing", "all", "names", "defined", "by", "the", "user", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L237-L294
30,543
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget.create_shortcuts
def create_shortcuts(self): """Create shortcuts for ipyconsole.""" inspect = config_shortcut(self._control.inspect_current_object, context='Console', name='Inspect current object', parent=self) clear_console = config_shortcut(self.clear_console, context='Console', name='Clear shell', parent=self) restart_kernel = config_shortcut(self.ipyclient.restart_kernel, context='ipython_console', name='Restart kernel', parent=self) new_tab = config_shortcut(lambda: self.new_client.emit(), context='ipython_console', name='new tab', parent=self) reset_namespace = config_shortcut(lambda: self._reset_namespace(), context='ipython_console', name='reset namespace', parent=self) array_inline = config_shortcut(self._control.enter_array_inline, context='array_builder', name='enter array inline', parent=self) array_table = config_shortcut(self._control.enter_array_table, context='array_builder', name='enter array table', parent=self) clear_line = config_shortcut(self.ipyclient.clear_line, context='console', name='clear line', parent=self) return [inspect, clear_console, restart_kernel, new_tab, reset_namespace, array_inline, array_table, clear_line]
python
def create_shortcuts(self): """Create shortcuts for ipyconsole.""" inspect = config_shortcut(self._control.inspect_current_object, context='Console', name='Inspect current object', parent=self) clear_console = config_shortcut(self.clear_console, context='Console', name='Clear shell', parent=self) restart_kernel = config_shortcut(self.ipyclient.restart_kernel, context='ipython_console', name='Restart kernel', parent=self) new_tab = config_shortcut(lambda: self.new_client.emit(), context='ipython_console', name='new tab', parent=self) reset_namespace = config_shortcut(lambda: self._reset_namespace(), context='ipython_console', name='reset namespace', parent=self) array_inline = config_shortcut(self._control.enter_array_inline, context='array_builder', name='enter array inline', parent=self) array_table = config_shortcut(self._control.enter_array_table, context='array_builder', name='enter array table', parent=self) clear_line = config_shortcut(self.ipyclient.clear_line, context='console', name='clear line', parent=self) return [inspect, clear_console, restart_kernel, new_tab, reset_namespace, array_inline, array_table, clear_line]
[ "def", "create_shortcuts", "(", "self", ")", ":", "inspect", "=", "config_shortcut", "(", "self", ".", "_control", ".", "inspect_current_object", ",", "context", "=", "'Console'", ",", "name", "=", "'Inspect current object'", ",", "parent", "=", "self", ")", "...
Create shortcuts for ipyconsole.
[ "Create", "shortcuts", "for", "ipyconsole", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L296-L323
30,544
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget.silent_execute
def silent_execute(self, code): """Execute code in the kernel without increasing the prompt""" try: self.kernel_client.execute(to_text_string(code), silent=True) except AttributeError: pass
python
def silent_execute(self, code): """Execute code in the kernel without increasing the prompt""" try: self.kernel_client.execute(to_text_string(code), silent=True) except AttributeError: pass
[ "def", "silent_execute", "(", "self", ",", "code", ")", ":", "try", ":", "self", ".", "kernel_client", ".", "execute", "(", "to_text_string", "(", "code", ")", ",", "silent", "=", "True", ")", "except", "AttributeError", ":", "pass" ]
Execute code in the kernel without increasing the prompt
[ "Execute", "code", "in", "the", "kernel", "without", "increasing", "the", "prompt" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L326-L331
30,545
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget.silent_exec_method
def silent_exec_method(self, code): """Silently execute a kernel method and save its reply The methods passed here **don't** involve getting the value of a variable but instead replies that can be handled by ast.literal_eval. To get a value see `get_value` Parameters ---------- code : string Code that contains the kernel method as part of its string See Also -------- handle_exec_method : Method that deals with the reply Note ---- This is based on the _silent_exec_callback method of RichJupyterWidget. Therefore this is licensed BSD """ # Generate uuid, which would be used as an indication of whether or # not the unique request originated from here local_uuid = to_text_string(uuid.uuid1()) code = to_text_string(code) if self.kernel_client is None: return msg_id = self.kernel_client.execute('', silent=True, user_expressions={ local_uuid:code }) self._kernel_methods[local_uuid] = code self._request_info['execute'][msg_id] = self._ExecutionRequest(msg_id, 'silent_exec_method')
python
def silent_exec_method(self, code): """Silently execute a kernel method and save its reply The methods passed here **don't** involve getting the value of a variable but instead replies that can be handled by ast.literal_eval. To get a value see `get_value` Parameters ---------- code : string Code that contains the kernel method as part of its string See Also -------- handle_exec_method : Method that deals with the reply Note ---- This is based on the _silent_exec_callback method of RichJupyterWidget. Therefore this is licensed BSD """ # Generate uuid, which would be used as an indication of whether or # not the unique request originated from here local_uuid = to_text_string(uuid.uuid1()) code = to_text_string(code) if self.kernel_client is None: return msg_id = self.kernel_client.execute('', silent=True, user_expressions={ local_uuid:code }) self._kernel_methods[local_uuid] = code self._request_info['execute'][msg_id] = self._ExecutionRequest(msg_id, 'silent_exec_method')
[ "def", "silent_exec_method", "(", "self", ",", "code", ")", ":", "# Generate uuid, which would be used as an indication of whether or", "# not the unique request originated from here", "local_uuid", "=", "to_text_string", "(", "uuid", ".", "uuid1", "(", ")", ")", "code", "=...
Silently execute a kernel method and save its reply The methods passed here **don't** involve getting the value of a variable but instead replies that can be handled by ast.literal_eval. To get a value see `get_value` Parameters ---------- code : string Code that contains the kernel method as part of its string See Also -------- handle_exec_method : Method that deals with the reply Note ---- This is based on the _silent_exec_callback method of RichJupyterWidget. Therefore this is licensed BSD
[ "Silently", "execute", "a", "kernel", "method", "and", "save", "its", "reply" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L333-L368
30,546
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget.handle_exec_method
def handle_exec_method(self, msg): """ Handle data returned by silent executions of kernel methods This is based on the _handle_exec_callback of RichJupyterWidget. Therefore this is licensed BSD. """ user_exp = msg['content'].get('user_expressions') if not user_exp: return for expression in user_exp: if expression in self._kernel_methods: # Process kernel reply method = self._kernel_methods[expression] reply = user_exp[expression] data = reply.get('data') if 'get_namespace_view' in method: if data is not None and 'text/plain' in data: literal = ast.literal_eval(data['text/plain']) view = ast.literal_eval(literal) else: view = None self.sig_namespace_view.emit(view) elif 'get_var_properties' in method: if data is not None and 'text/plain' in data: literal = ast.literal_eval(data['text/plain']) properties = ast.literal_eval(literal) else: properties = None self.sig_var_properties.emit(properties) elif 'get_cwd' in method: if data is not None and 'text/plain' in data: self._cwd = ast.literal_eval(data['text/plain']) if PY2: self._cwd = encoding.to_unicode_from_fs(self._cwd) else: self._cwd = '' self.sig_change_cwd.emit(self._cwd) elif 'get_syspath' in method: if data is not None and 'text/plain' in data: syspath = ast.literal_eval(data['text/plain']) else: syspath = None self.sig_show_syspath.emit(syspath) elif 'get_env' in method: if data is not None and 'text/plain' in data: env = ast.literal_eval(data['text/plain']) else: env = None self.sig_show_env.emit(env) elif 'getattr' in method: if data is not None and 'text/plain' in data: is_spyder_kernel = data['text/plain'] if 'SpyderKernel' in is_spyder_kernel: self.sig_is_spykernel.emit(self) else: if data is not None and 'text/plain' in data: self._kernel_reply = ast.literal_eval(data['text/plain']) else: self._kernel_reply = None self.sig_got_reply.emit() # Remove method after being processed self._kernel_methods.pop(expression)
python
def handle_exec_method(self, msg): """ Handle data returned by silent executions of kernel methods This is based on the _handle_exec_callback of RichJupyterWidget. Therefore this is licensed BSD. """ user_exp = msg['content'].get('user_expressions') if not user_exp: return for expression in user_exp: if expression in self._kernel_methods: # Process kernel reply method = self._kernel_methods[expression] reply = user_exp[expression] data = reply.get('data') if 'get_namespace_view' in method: if data is not None and 'text/plain' in data: literal = ast.literal_eval(data['text/plain']) view = ast.literal_eval(literal) else: view = None self.sig_namespace_view.emit(view) elif 'get_var_properties' in method: if data is not None and 'text/plain' in data: literal = ast.literal_eval(data['text/plain']) properties = ast.literal_eval(literal) else: properties = None self.sig_var_properties.emit(properties) elif 'get_cwd' in method: if data is not None and 'text/plain' in data: self._cwd = ast.literal_eval(data['text/plain']) if PY2: self._cwd = encoding.to_unicode_from_fs(self._cwd) else: self._cwd = '' self.sig_change_cwd.emit(self._cwd) elif 'get_syspath' in method: if data is not None and 'text/plain' in data: syspath = ast.literal_eval(data['text/plain']) else: syspath = None self.sig_show_syspath.emit(syspath) elif 'get_env' in method: if data is not None and 'text/plain' in data: env = ast.literal_eval(data['text/plain']) else: env = None self.sig_show_env.emit(env) elif 'getattr' in method: if data is not None and 'text/plain' in data: is_spyder_kernel = data['text/plain'] if 'SpyderKernel' in is_spyder_kernel: self.sig_is_spykernel.emit(self) else: if data is not None and 'text/plain' in data: self._kernel_reply = ast.literal_eval(data['text/plain']) else: self._kernel_reply = None self.sig_got_reply.emit() # Remove method after being processed self._kernel_methods.pop(expression)
[ "def", "handle_exec_method", "(", "self", ",", "msg", ")", ":", "user_exp", "=", "msg", "[", "'content'", "]", ".", "get", "(", "'user_expressions'", ")", "if", "not", "user_exp", ":", "return", "for", "expression", "in", "user_exp", ":", "if", "expression...
Handle data returned by silent executions of kernel methods This is based on the _handle_exec_callback of RichJupyterWidget. Therefore this is licensed BSD.
[ "Handle", "data", "returned", "by", "silent", "executions", "of", "kernel", "methods" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L370-L433
30,547
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget.set_backend_for_mayavi
def set_backend_for_mayavi(self, command): """ Mayavi plots require the Qt backend, so we try to detect if one is generated to change backends """ calling_mayavi = False lines = command.splitlines() for l in lines: if not l.startswith('#'): if 'import mayavi' in l or 'from mayavi' in l: calling_mayavi = True break if calling_mayavi: message = _("Changing backend to Qt for Mayavi") self._append_plain_text(message + '\n') self.silent_execute("%gui inline\n%gui qt")
python
def set_backend_for_mayavi(self, command): """ Mayavi plots require the Qt backend, so we try to detect if one is generated to change backends """ calling_mayavi = False lines = command.splitlines() for l in lines: if not l.startswith('#'): if 'import mayavi' in l or 'from mayavi' in l: calling_mayavi = True break if calling_mayavi: message = _("Changing backend to Qt for Mayavi") self._append_plain_text(message + '\n') self.silent_execute("%gui inline\n%gui qt")
[ "def", "set_backend_for_mayavi", "(", "self", ",", "command", ")", ":", "calling_mayavi", "=", "False", "lines", "=", "command", ".", "splitlines", "(", ")", "for", "l", "in", "lines", ":", "if", "not", "l", ".", "startswith", "(", "'#'", ")", ":", "if...
Mayavi plots require the Qt backend, so we try to detect if one is generated to change backends
[ "Mayavi", "plots", "require", "the", "Qt", "backend", "so", "we", "try", "to", "detect", "if", "one", "is", "generated", "to", "change", "backends" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L435-L450
30,548
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget.change_mpl_backend
def change_mpl_backend(self, command): """ If the user is trying to change Matplotlib backends with %matplotlib, send the same command again to the kernel to correctly change it. Fixes issue 4002 """ if command.startswith('%matplotlib') and \ len(command.splitlines()) == 1: if not 'inline' in command: self.silent_execute(command)
python
def change_mpl_backend(self, command): """ If the user is trying to change Matplotlib backends with %matplotlib, send the same command again to the kernel to correctly change it. Fixes issue 4002 """ if command.startswith('%matplotlib') and \ len(command.splitlines()) == 1: if not 'inline' in command: self.silent_execute(command)
[ "def", "change_mpl_backend", "(", "self", ",", "command", ")", ":", "if", "command", ".", "startswith", "(", "'%matplotlib'", ")", "and", "len", "(", "command", ".", "splitlines", "(", ")", ")", "==", "1", ":", "if", "not", "'inline'", "in", "command", ...
If the user is trying to change Matplotlib backends with %matplotlib, send the same command again to the kernel to correctly change it. Fixes issue 4002
[ "If", "the", "user", "is", "trying", "to", "change", "Matplotlib", "backends", "with", "%matplotlib", "send", "the", "same", "command", "again", "to", "the", "kernel", "to", "correctly", "change", "it", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L452-L463
30,549
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget._context_menu_make
def _context_menu_make(self, pos): """Reimplement the IPython context menu""" menu = super(ShellWidget, self)._context_menu_make(pos) return self.ipyclient.add_actions_to_context_menu(menu)
python
def _context_menu_make(self, pos): """Reimplement the IPython context menu""" menu = super(ShellWidget, self)._context_menu_make(pos) return self.ipyclient.add_actions_to_context_menu(menu)
[ "def", "_context_menu_make", "(", "self", ",", "pos", ")", ":", "menu", "=", "super", "(", "ShellWidget", ",", "self", ")", ".", "_context_menu_make", "(", "pos", ")", "return", "self", ".", "ipyclient", ".", "add_actions_to_context_menu", "(", "menu", ")" ]
Reimplement the IPython context menu
[ "Reimplement", "the", "IPython", "context", "menu" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L473-L476
30,550
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget._banner_default
def _banner_default(self): """ Reimplement banner creation to let the user decide if he wants a banner or not """ # Don't change banner for external kernels if self.external_kernel: return '' show_banner_o = self.additional_options['show_banner'] if show_banner_o: return self.long_banner() else: return self.short_banner()
python
def _banner_default(self): """ Reimplement banner creation to let the user decide if he wants a banner or not """ # Don't change banner for external kernels if self.external_kernel: return '' show_banner_o = self.additional_options['show_banner'] if show_banner_o: return self.long_banner() else: return self.short_banner()
[ "def", "_banner_default", "(", "self", ")", ":", "# Don't change banner for external kernels", "if", "self", ".", "external_kernel", ":", "return", "''", "show_banner_o", "=", "self", ".", "additional_options", "[", "'show_banner'", "]", "if", "show_banner_o", ":", ...
Reimplement banner creation to let the user decide if he wants a banner or not
[ "Reimplement", "banner", "creation", "to", "let", "the", "user", "decide", "if", "he", "wants", "a", "banner", "or", "not" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L478-L490
30,551
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget._syntax_style_changed
def _syntax_style_changed(self): """Refresh the highlighting with the current syntax style by class.""" if self._highlighter is None: # ignore premature calls return if self.syntax_style: self._highlighter._style = create_style_class(self.syntax_style) self._highlighter._clear_caches() else: self._highlighter.set_style_sheet(self.style_sheet)
python
def _syntax_style_changed(self): """Refresh the highlighting with the current syntax style by class.""" if self._highlighter is None: # ignore premature calls return if self.syntax_style: self._highlighter._style = create_style_class(self.syntax_style) self._highlighter._clear_caches() else: self._highlighter.set_style_sheet(self.style_sheet)
[ "def", "_syntax_style_changed", "(", "self", ")", ":", "if", "self", ".", "_highlighter", "is", "None", ":", "# ignore premature calls", "return", "if", "self", ".", "syntax_style", ":", "self", ".", "_highlighter", ".", "_style", "=", "create_style_class", "(",...
Refresh the highlighting with the current syntax style by class.
[ "Refresh", "the", "highlighting", "with", "the", "current", "syntax", "style", "by", "class", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L496-L505
30,552
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/shell.py
ShellWidget._prompt_started_hook
def _prompt_started_hook(self): """Emit a signal when the prompt is ready.""" if not self._reading: self._highlighter.highlighting_on = True self.sig_prompt_ready.emit()
python
def _prompt_started_hook(self): """Emit a signal when the prompt is ready.""" if not self._reading: self._highlighter.highlighting_on = True self.sig_prompt_ready.emit()
[ "def", "_prompt_started_hook", "(", "self", ")", ":", "if", "not", "self", ".", "_reading", ":", "self", ".", "_highlighter", ".", "highlighting_on", "=", "True", "self", ".", "sig_prompt_ready", ".", "emit", "(", ")" ]
Emit a signal when the prompt is ready.
[ "Emit", "a", "signal", "when", "the", "prompt", "is", "ready", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/shell.py#L507-L511
30,553
spyder-ide/spyder
spyder/plugins/editor/panels/manager.py
PanelsManager.clear
def clear(self): """Removes all panel from the CodeEditor.""" for i in range(4): while len(self._panels[i]): key = sorted(list(self._panels[i].keys()))[0] panel = self.remove(key) panel.setParent(None) panel.deleteLater()
python
def clear(self): """Removes all panel from the CodeEditor.""" for i in range(4): while len(self._panels[i]): key = sorted(list(self._panels[i].keys()))[0] panel = self.remove(key) panel.setParent(None) panel.deleteLater()
[ "def", "clear", "(", "self", ")", ":", "for", "i", "in", "range", "(", "4", ")", ":", "while", "len", "(", "self", ".", "_panels", "[", "i", "]", ")", ":", "key", "=", "sorted", "(", "list", "(", "self", ".", "_panels", "[", "i", "]", ".", ...
Removes all panel from the CodeEditor.
[ "Removes", "all", "panel", "from", "the", "CodeEditor", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/manager.py#L97-L104
30,554
spyder-ide/spyder
spyder/plugins/editor/panels/manager.py
PanelsManager.resize
def resize(self): """Resizes panels.""" crect = self.editor.contentsRect() view_crect = self.editor.viewport().contentsRect() s_bottom, s_left, s_right, s_top = self._compute_zones_sizes() tw = s_left + s_right th = s_bottom + s_top w_offset = crect.width() - (view_crect.width() + tw) h_offset = crect.height() - (view_crect.height() + th) left = 0 panels = self.panels_for_zone(Panel.Position.LEFT) panels.sort(key=lambda panel: panel.order_in_zone, reverse=True) for panel in panels: if not panel.isVisible(): continue panel.adjustSize() size_hint = panel.sizeHint() panel.setGeometry(crect.left() + left, crect.top() + s_top, size_hint.width(), crect.height() - s_bottom - s_top - h_offset) left += size_hint.width() right = 0 panels = self.panels_for_zone(Panel.Position.RIGHT) panels.sort(key=lambda panel: panel.order_in_zone, reverse=True) for panel in panels: if not panel.isVisible(): continue size_hint = panel.sizeHint() panel.setGeometry( crect.right() - right - size_hint.width() - w_offset, crect.top() + s_top, size_hint.width(), crect.height() - s_bottom - s_top - h_offset) right += size_hint.width() top = 0 panels = self.panels_for_zone(Panel.Position.TOP) panels.sort(key=lambda panel: panel.order_in_zone) for panel in panels: if not panel.isVisible(): continue size_hint = panel.sizeHint() panel.setGeometry(crect.left(), crect.top() + top, crect.width() - w_offset, size_hint.height()) top += size_hint.height() bottom = 0 panels = self.panels_for_zone(Panel.Position.BOTTOM) panels.sort(key=lambda panel: panel.order_in_zone) for panel in panels: if not panel.isVisible(): continue size_hint = panel.sizeHint() panel.setGeometry( crect.left(), crect.bottom() - bottom - size_hint.height() - h_offset, crect.width() - w_offset, size_hint.height()) bottom += size_hint.height()
python
def resize(self): """Resizes panels.""" crect = self.editor.contentsRect() view_crect = self.editor.viewport().contentsRect() s_bottom, s_left, s_right, s_top = self._compute_zones_sizes() tw = s_left + s_right th = s_bottom + s_top w_offset = crect.width() - (view_crect.width() + tw) h_offset = crect.height() - (view_crect.height() + th) left = 0 panels = self.panels_for_zone(Panel.Position.LEFT) panels.sort(key=lambda panel: panel.order_in_zone, reverse=True) for panel in panels: if not panel.isVisible(): continue panel.adjustSize() size_hint = panel.sizeHint() panel.setGeometry(crect.left() + left, crect.top() + s_top, size_hint.width(), crect.height() - s_bottom - s_top - h_offset) left += size_hint.width() right = 0 panels = self.panels_for_zone(Panel.Position.RIGHT) panels.sort(key=lambda panel: panel.order_in_zone, reverse=True) for panel in panels: if not panel.isVisible(): continue size_hint = panel.sizeHint() panel.setGeometry( crect.right() - right - size_hint.width() - w_offset, crect.top() + s_top, size_hint.width(), crect.height() - s_bottom - s_top - h_offset) right += size_hint.width() top = 0 panels = self.panels_for_zone(Panel.Position.TOP) panels.sort(key=lambda panel: panel.order_in_zone) for panel in panels: if not panel.isVisible(): continue size_hint = panel.sizeHint() panel.setGeometry(crect.left(), crect.top() + top, crect.width() - w_offset, size_hint.height()) top += size_hint.height() bottom = 0 panels = self.panels_for_zone(Panel.Position.BOTTOM) panels.sort(key=lambda panel: panel.order_in_zone) for panel in panels: if not panel.isVisible(): continue size_hint = panel.sizeHint() panel.setGeometry( crect.left(), crect.bottom() - bottom - size_hint.height() - h_offset, crect.width() - w_offset, size_hint.height()) bottom += size_hint.height()
[ "def", "resize", "(", "self", ")", ":", "crect", "=", "self", ".", "editor", ".", "contentsRect", "(", ")", "view_crect", "=", "self", ".", "editor", ".", "viewport", "(", ")", ".", "contentsRect", "(", ")", "s_bottom", ",", "s_left", ",", "s_right", ...
Resizes panels.
[ "Resizes", "panels", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/manager.py#L163-L222
30,555
spyder-ide/spyder
spyder/plugins/editor/panels/manager.py
PanelsManager.update_floating_panels
def update_floating_panels(self): """Update foating panels.""" crect = self.editor.contentsRect() panels = self.panels_for_zone(Panel.Position.FLOATING) for panel in panels: if not panel.isVisible(): continue panel.set_geometry(crect)
python
def update_floating_panels(self): """Update foating panels.""" crect = self.editor.contentsRect() panels = self.panels_for_zone(Panel.Position.FLOATING) for panel in panels: if not panel.isVisible(): continue panel.set_geometry(crect)
[ "def", "update_floating_panels", "(", "self", ")", ":", "crect", "=", "self", ".", "editor", ".", "contentsRect", "(", ")", "panels", "=", "self", ".", "panels_for_zone", "(", "Panel", ".", "Position", ".", "FLOATING", ")", "for", "panel", "in", "panels", ...
Update foating panels.
[ "Update", "foating", "panels", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/manager.py#L224-L231
30,556
spyder-ide/spyder
spyder/plugins/editor/panels/manager.py
PanelsManager._update_viewport_margins
def _update_viewport_margins(self): """Update viewport margins.""" top = 0 left = 0 right = 0 bottom = 0 for panel in self.panels_for_zone(Panel.Position.LEFT): if panel.isVisible(): width = panel.sizeHint().width() left += width for panel in self.panels_for_zone(Panel.Position.RIGHT): if panel.isVisible(): width = panel.sizeHint().width() right += width for panel in self.panels_for_zone(Panel.Position.TOP): if panel.isVisible(): height = panel.sizeHint().height() top += height for panel in self.panels_for_zone(Panel.Position.BOTTOM): if panel.isVisible(): height = panel.sizeHint().height() bottom += height self._margin_sizes = (top, left, right, bottom) self.editor.setViewportMargins(left, top, right, bottom)
python
def _update_viewport_margins(self): """Update viewport margins.""" top = 0 left = 0 right = 0 bottom = 0 for panel in self.panels_for_zone(Panel.Position.LEFT): if panel.isVisible(): width = panel.sizeHint().width() left += width for panel in self.panels_for_zone(Panel.Position.RIGHT): if panel.isVisible(): width = panel.sizeHint().width() right += width for panel in self.panels_for_zone(Panel.Position.TOP): if panel.isVisible(): height = panel.sizeHint().height() top += height for panel in self.panels_for_zone(Panel.Position.BOTTOM): if panel.isVisible(): height = panel.sizeHint().height() bottom += height self._margin_sizes = (top, left, right, bottom) self.editor.setViewportMargins(left, top, right, bottom)
[ "def", "_update_viewport_margins", "(", "self", ")", ":", "top", "=", "0", "left", "=", "0", "right", "=", "0", "bottom", "=", "0", "for", "panel", "in", "self", ".", "panels_for_zone", "(", "Panel", ".", "Position", ".", "LEFT", ")", ":", "if", "pan...
Update viewport margins.
[ "Update", "viewport", "margins", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/manager.py#L255-L278
30,557
spyder-ide/spyder
spyder/plugins/editor/panels/manager.py
PanelsManager._compute_zones_sizes
def _compute_zones_sizes(self): """Compute panel zone sizes.""" # Left panels left = 0 for panel in self.panels_for_zone(Panel.Position.LEFT): if not panel.isVisible(): continue size_hint = panel.sizeHint() left += size_hint.width() # Right panels right = 0 for panel in self.panels_for_zone(Panel.Position.RIGHT): if not panel.isVisible(): continue size_hint = panel.sizeHint() right += size_hint.width() # Top panels top = 0 for panel in self.panels_for_zone(Panel.Position.TOP): if not panel.isVisible(): continue size_hint = panel.sizeHint() top += size_hint.height() # Bottom panels bottom = 0 for panel in self.panels_for_zone(Panel.Position.BOTTOM): if not panel.isVisible(): continue size_hint = panel.sizeHint() bottom += size_hint.height() self._top, self._left, self._right, self._bottom = ( top, left, right, bottom) return bottom, left, right, top
python
def _compute_zones_sizes(self): """Compute panel zone sizes.""" # Left panels left = 0 for panel in self.panels_for_zone(Panel.Position.LEFT): if not panel.isVisible(): continue size_hint = panel.sizeHint() left += size_hint.width() # Right panels right = 0 for panel in self.panels_for_zone(Panel.Position.RIGHT): if not panel.isVisible(): continue size_hint = panel.sizeHint() right += size_hint.width() # Top panels top = 0 for panel in self.panels_for_zone(Panel.Position.TOP): if not panel.isVisible(): continue size_hint = panel.sizeHint() top += size_hint.height() # Bottom panels bottom = 0 for panel in self.panels_for_zone(Panel.Position.BOTTOM): if not panel.isVisible(): continue size_hint = panel.sizeHint() bottom += size_hint.height() self._top, self._left, self._right, self._bottom = ( top, left, right, bottom) return bottom, left, right, top
[ "def", "_compute_zones_sizes", "(", "self", ")", ":", "# Left panels", "left", "=", "0", "for", "panel", "in", "self", ".", "panels_for_zone", "(", "Panel", ".", "Position", ".", "LEFT", ")", ":", "if", "not", "panel", ".", "isVisible", "(", ")", ":", ...
Compute panel zone sizes.
[ "Compute", "panel", "zone", "sizes", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/manager.py#L291-L323
30,558
spyder-ide/spyder
spyder/utils/introspection/fallback_plugin.py
get_definition_with_regex
def get_definition_with_regex(source, token, start_line=-1): """ Find the definition of an object within a source closest to a given line """ if not token: return None if DEBUG_EDITOR: t0 = time.time() patterns = [ # python / cython keyword definitions r'^c?import.*\W{0}{1}', r'from.*\W{0}\W.*c?import ', r'from .* c?import.*\W{0}{1}', r'class\s*{0}{1}', r'c?p?def[^=]*\W{0}{1}', r'cdef.*\[.*\].*\W{0}{1}', # enaml keyword definitions r'enamldef.*\W{0}{1}', r'attr.*\W{0}{1}', r'event.*\W{0}{1}', r'id\s*:.*\W{0}{1}'] matches = get_matches(patterns, source, token, start_line) if not matches: patterns = [r'.*\Wself.{0}{1}[^=!<>]*=[^=]', r'.*\W{0}{1}[^=!<>]*=[^=]', r'self.{0}{1}[^=!<>]*=[^=]', r'{0}{1}[^=!<>]*=[^=]'] matches = get_matches(patterns, source, token, start_line) # find the one closest to the start line (prefer before the start line) if matches: min_dist = len(source.splitlines()) best_ind = 0 for match in matches: dist = abs(start_line - match) if match <= start_line or not best_ind: if dist < min_dist: min_dist = dist best_ind = match if matches: if DEBUG_EDITOR: log_dt(LOG_FILENAME, 'regex definition match', t0) return best_ind else: if DEBUG_EDITOR: log_dt(LOG_FILENAME, 'regex definition failed match', t0) return None
python
def get_definition_with_regex(source, token, start_line=-1): """ Find the definition of an object within a source closest to a given line """ if not token: return None if DEBUG_EDITOR: t0 = time.time() patterns = [ # python / cython keyword definitions r'^c?import.*\W{0}{1}', r'from.*\W{0}\W.*c?import ', r'from .* c?import.*\W{0}{1}', r'class\s*{0}{1}', r'c?p?def[^=]*\W{0}{1}', r'cdef.*\[.*\].*\W{0}{1}', # enaml keyword definitions r'enamldef.*\W{0}{1}', r'attr.*\W{0}{1}', r'event.*\W{0}{1}', r'id\s*:.*\W{0}{1}'] matches = get_matches(patterns, source, token, start_line) if not matches: patterns = [r'.*\Wself.{0}{1}[^=!<>]*=[^=]', r'.*\W{0}{1}[^=!<>]*=[^=]', r'self.{0}{1}[^=!<>]*=[^=]', r'{0}{1}[^=!<>]*=[^=]'] matches = get_matches(patterns, source, token, start_line) # find the one closest to the start line (prefer before the start line) if matches: min_dist = len(source.splitlines()) best_ind = 0 for match in matches: dist = abs(start_line - match) if match <= start_line or not best_ind: if dist < min_dist: min_dist = dist best_ind = match if matches: if DEBUG_EDITOR: log_dt(LOG_FILENAME, 'regex definition match', t0) return best_ind else: if DEBUG_EDITOR: log_dt(LOG_FILENAME, 'regex definition failed match', t0) return None
[ "def", "get_definition_with_regex", "(", "source", ",", "token", ",", "start_line", "=", "-", "1", ")", ":", "if", "not", "token", ":", "return", "None", "if", "DEBUG_EDITOR", ":", "t0", "=", "time", ".", "time", "(", ")", "patterns", "=", "[", "# pyth...
Find the definition of an object within a source closest to a given line
[ "Find", "the", "definition", "of", "an", "object", "within", "a", "source", "closest", "to", "a", "given", "line" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/introspection/fallback_plugin.py#L201-L247
30,559
spyder-ide/spyder
spyder/utils/introspection/fallback_plugin.py
python_like_exts
def python_like_exts(): """Return a list of all python-like extensions""" exts = [] for lang in languages.PYTHON_LIKE_LANGUAGES: exts.extend(list(languages.ALL_LANGUAGES[lang])) return ['.' + ext for ext in exts]
python
def python_like_exts(): """Return a list of all python-like extensions""" exts = [] for lang in languages.PYTHON_LIKE_LANGUAGES: exts.extend(list(languages.ALL_LANGUAGES[lang])) return ['.' + ext for ext in exts]
[ "def", "python_like_exts", "(", ")", ":", "exts", "=", "[", "]", "for", "lang", "in", "languages", ".", "PYTHON_LIKE_LANGUAGES", ":", "exts", ".", "extend", "(", "list", "(", "languages", ".", "ALL_LANGUAGES", "[", "lang", "]", ")", ")", "return", "[", ...
Return a list of all python-like extensions
[ "Return", "a", "list", "of", "all", "python", "-", "like", "extensions" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/introspection/fallback_plugin.py#L265-L270
30,560
spyder-ide/spyder
spyder/utils/introspection/fallback_plugin.py
all_editable_exts
def all_editable_exts(): """Return a list of all editable extensions""" exts = [] for (language, extensions) in languages.ALL_LANGUAGES.items(): exts.extend(list(extensions)) return ['.' + ext for ext in exts]
python
def all_editable_exts(): """Return a list of all editable extensions""" exts = [] for (language, extensions) in languages.ALL_LANGUAGES.items(): exts.extend(list(extensions)) return ['.' + ext for ext in exts]
[ "def", "all_editable_exts", "(", ")", ":", "exts", "=", "[", "]", "for", "(", "language", ",", "extensions", ")", "in", "languages", ".", "ALL_LANGUAGES", ".", "items", "(", ")", ":", "exts", ".", "extend", "(", "list", "(", "extensions", ")", ")", "...
Return a list of all editable extensions
[ "Return", "a", "list", "of", "all", "editable", "extensions" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/introspection/fallback_plugin.py#L273-L278
30,561
spyder-ide/spyder
spyder/utils/introspection/fallback_plugin.py
FallbackPlugin.get_info
def get_info(self, info): """Get a formatted calltip and docstring from Fallback""" if info['docstring']: if info['filename']: filename = os.path.basename(info['filename']) filename = os.path.splitext(filename)[0] else: filename = '<module>' resp = dict(docstring=info['docstring'], name=filename, note='', argspec='', calltip=None) return resp else: return default_info_response()
python
def get_info(self, info): """Get a formatted calltip and docstring from Fallback""" if info['docstring']: if info['filename']: filename = os.path.basename(info['filename']) filename = os.path.splitext(filename)[0] else: filename = '<module>' resp = dict(docstring=info['docstring'], name=filename, note='', argspec='', calltip=None) return resp else: return default_info_response()
[ "def", "get_info", "(", "self", ",", "info", ")", ":", "if", "info", "[", "'docstring'", "]", ":", "if", "info", "[", "'filename'", "]", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "info", "[", "'filename'", "]", ")", "filename", ...
Get a formatted calltip and docstring from Fallback
[ "Get", "a", "formatted", "calltip", "and", "docstring", "from", "Fallback" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/introspection/fallback_plugin.py#L129-L144
30,562
spyder-ide/spyder
spyder/plugins/outlineexplorer/widgets.py
get_item_children
def get_item_children(item): """Return a sorted list of all the children items of 'item'.""" children = [item.child(index) for index in range(item.childCount())] for child in children[:]: others = get_item_children(child) if others is not None: children += others return sorted(children, key=lambda child: child.line)
python
def get_item_children(item): """Return a sorted list of all the children items of 'item'.""" children = [item.child(index) for index in range(item.childCount())] for child in children[:]: others = get_item_children(child) if others is not None: children += others return sorted(children, key=lambda child: child.line)
[ "def", "get_item_children", "(", "item", ")", ":", "children", "=", "[", "item", ".", "child", "(", "index", ")", "for", "index", "in", "range", "(", "item", ".", "childCount", "(", ")", ")", "]", "for", "child", "in", "children", "[", ":", "]", ":...
Return a sorted list of all the children items of 'item'.
[ "Return", "a", "sorted", "list", "of", "all", "the", "children", "items", "of", "item", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L121-L128
30,563
spyder-ide/spyder
spyder/plugins/outlineexplorer/widgets.py
item_at_line
def item_at_line(root_item, line): """ Find and return the item of the outline explorer under which is located the specified 'line' of the editor. """ previous_item = root_item item = root_item for item in get_item_children(root_item): if item.line > line: return previous_item previous_item = item else: return item
python
def item_at_line(root_item, line): """ Find and return the item of the outline explorer under which is located the specified 'line' of the editor. """ previous_item = root_item item = root_item for item in get_item_children(root_item): if item.line > line: return previous_item previous_item = item else: return item
[ "def", "item_at_line", "(", "root_item", ",", "line", ")", ":", "previous_item", "=", "root_item", "item", "=", "root_item", "for", "item", "in", "get_item_children", "(", "root_item", ")", ":", "if", "item", ".", "line", ">", "line", ":", "return", "previ...
Find and return the item of the outline explorer under which is located the specified 'line' of the editor.
[ "Find", "and", "return", "the", "item", "of", "the", "outline", "explorer", "under", "which", "is", "located", "the", "specified", "line", "of", "the", "editor", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L131-L143
30,564
spyder-ide/spyder
spyder/plugins/outlineexplorer/widgets.py
OutlineExplorerTreeWidget.set_current_editor
def set_current_editor(self, editor, update): """Bind editor instance""" editor_id = editor.get_id() if editor_id in list(self.editor_ids.values()): item = self.editor_items[editor_id] if not self.freeze: self.scrollToItem(item) self.root_item_selected(item) self.__hide_or_show_root_items(item) if update: self.save_expanded_state() tree_cache = self.editor_tree_cache[editor_id] self.populate_branch(editor, item, tree_cache) self.restore_expanded_state() else: root_item = FileRootItem(editor.fname, self, editor.is_python()) root_item.set_text(fullpath=self.show_fullpath) tree_cache = self.populate_branch(editor, root_item) self.__hide_or_show_root_items(root_item) self.root_item_selected(root_item) self.editor_items[editor_id] = root_item self.editor_tree_cache[editor_id] = tree_cache self.resizeColumnToContents(0) if editor not in self.editor_ids: self.editor_ids[editor] = editor_id self.ordered_editor_ids.append(editor_id) self.__sort_toplevel_items() self.current_editor = editor
python
def set_current_editor(self, editor, update): """Bind editor instance""" editor_id = editor.get_id() if editor_id in list(self.editor_ids.values()): item = self.editor_items[editor_id] if not self.freeze: self.scrollToItem(item) self.root_item_selected(item) self.__hide_or_show_root_items(item) if update: self.save_expanded_state() tree_cache = self.editor_tree_cache[editor_id] self.populate_branch(editor, item, tree_cache) self.restore_expanded_state() else: root_item = FileRootItem(editor.fname, self, editor.is_python()) root_item.set_text(fullpath=self.show_fullpath) tree_cache = self.populate_branch(editor, root_item) self.__hide_or_show_root_items(root_item) self.root_item_selected(root_item) self.editor_items[editor_id] = root_item self.editor_tree_cache[editor_id] = tree_cache self.resizeColumnToContents(0) if editor not in self.editor_ids: self.editor_ids[editor] = editor_id self.ordered_editor_ids.append(editor_id) self.__sort_toplevel_items() self.current_editor = editor
[ "def", "set_current_editor", "(", "self", ",", "editor", ",", "update", ")", ":", "editor_id", "=", "editor", ".", "get_id", "(", ")", "if", "editor_id", "in", "list", "(", "self", ".", "editor_ids", ".", "values", "(", ")", ")", ":", "item", "=", "s...
Bind editor instance
[ "Bind", "editor", "instance" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L267-L294
30,565
spyder-ide/spyder
spyder/plugins/outlineexplorer/widgets.py
OutlineExplorerTreeWidget.file_renamed
def file_renamed(self, editor, new_filename): """File was renamed, updating outline explorer tree""" if editor is None: # This is needed when we can't find an editor to attach # the outline explorer to. # Fix issue 8813 return editor_id = editor.get_id() if editor_id in list(self.editor_ids.values()): root_item = self.editor_items[editor_id] root_item.set_path(new_filename, fullpath=self.show_fullpath) self.__sort_toplevel_items()
python
def file_renamed(self, editor, new_filename): """File was renamed, updating outline explorer tree""" if editor is None: # This is needed when we can't find an editor to attach # the outline explorer to. # Fix issue 8813 return editor_id = editor.get_id() if editor_id in list(self.editor_ids.values()): root_item = self.editor_items[editor_id] root_item.set_path(new_filename, fullpath=self.show_fullpath) self.__sort_toplevel_items()
[ "def", "file_renamed", "(", "self", ",", "editor", ",", "new_filename", ")", ":", "if", "editor", "is", "None", ":", "# This is needed when we can't find an editor to attach\r", "# the outline explorer to.\r", "# Fix issue 8813\r", "return", "editor_id", "=", "editor", "....
File was renamed, updating outline explorer tree
[ "File", "was", "renamed", "updating", "outline", "explorer", "tree" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L296-L307
30,566
spyder-ide/spyder
spyder/plugins/outlineexplorer/widgets.py
OutlineExplorerTreeWidget.set_editor_ids_order
def set_editor_ids_order(self, ordered_editor_ids): """ Order the root file items in the Outline Explorer following the provided list of editor ids. """ if self.ordered_editor_ids != ordered_editor_ids: self.ordered_editor_ids = ordered_editor_ids if self.sort_files_alphabetically is False: self.__sort_toplevel_items()
python
def set_editor_ids_order(self, ordered_editor_ids): """ Order the root file items in the Outline Explorer following the provided list of editor ids. """ if self.ordered_editor_ids != ordered_editor_ids: self.ordered_editor_ids = ordered_editor_ids if self.sort_files_alphabetically is False: self.__sort_toplevel_items()
[ "def", "set_editor_ids_order", "(", "self", ",", "ordered_editor_ids", ")", ":", "if", "self", ".", "ordered_editor_ids", "!=", "ordered_editor_ids", ":", "self", ".", "ordered_editor_ids", "=", "ordered_editor_ids", "if", "self", ".", "sort_files_alphabetically", "is...
Order the root file items in the Outline Explorer following the provided list of editor ids.
[ "Order", "the", "root", "file", "items", "in", "the", "Outline", "Explorer", "following", "the", "provided", "list", "of", "editor", "ids", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L333-L341
30,567
spyder-ide/spyder
spyder/plugins/outlineexplorer/widgets.py
OutlineExplorerTreeWidget.__sort_toplevel_items
def __sort_toplevel_items(self): """ Sort the root file items in alphabetical order if 'sort_files_alphabetically' is True, else order the items as specified in the 'self.ordered_editor_ids' list. """ if self.show_all_files is False: return current_ordered_items = [self.topLevelItem(index) for index in range(self.topLevelItemCount())] if self.sort_files_alphabetically: new_ordered_items = sorted( current_ordered_items, key=lambda item: osp.basename(item.path.lower())) else: new_ordered_items = [ self.editor_items.get(e_id) for e_id in self.ordered_editor_ids if self.editor_items.get(e_id) is not None] if current_ordered_items != new_ordered_items: selected_items = self.selectedItems() self.save_expanded_state() for index in range(self.topLevelItemCount()): self.takeTopLevelItem(0) for index, item in enumerate(new_ordered_items): self.insertTopLevelItem(index, item) self.restore_expanded_state() self.clearSelection() if selected_items: selected_items[-1].setSelected(True)
python
def __sort_toplevel_items(self): """ Sort the root file items in alphabetical order if 'sort_files_alphabetically' is True, else order the items as specified in the 'self.ordered_editor_ids' list. """ if self.show_all_files is False: return current_ordered_items = [self.topLevelItem(index) for index in range(self.topLevelItemCount())] if self.sort_files_alphabetically: new_ordered_items = sorted( current_ordered_items, key=lambda item: osp.basename(item.path.lower())) else: new_ordered_items = [ self.editor_items.get(e_id) for e_id in self.ordered_editor_ids if self.editor_items.get(e_id) is not None] if current_ordered_items != new_ordered_items: selected_items = self.selectedItems() self.save_expanded_state() for index in range(self.topLevelItemCount()): self.takeTopLevelItem(0) for index, item in enumerate(new_ordered_items): self.insertTopLevelItem(index, item) self.restore_expanded_state() self.clearSelection() if selected_items: selected_items[-1].setSelected(True)
[ "def", "__sort_toplevel_items", "(", "self", ")", ":", "if", "self", ".", "show_all_files", "is", "False", ":", "return", "current_ordered_items", "=", "[", "self", ".", "topLevelItem", "(", "index", ")", "for", "index", "in", "range", "(", "self", ".", "t...
Sort the root file items in alphabetical order if 'sort_files_alphabetically' is True, else order the items as specified in the 'self.ordered_editor_ids' list.
[ "Sort", "the", "root", "file", "items", "in", "alphabetical", "order", "if", "sort_files_alphabetically", "is", "True", "else", "order", "the", "items", "as", "specified", "in", "the", "self", ".", "ordered_editor_ids", "list", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L343-L374
30,568
spyder-ide/spyder
spyder/plugins/outlineexplorer/widgets.py
OutlineExplorerTreeWidget.get_root_item
def get_root_item(self, item): """Return the root item of the specified item.""" root_item = item while isinstance(root_item.parent(), QTreeWidgetItem): root_item = root_item.parent() return root_item
python
def get_root_item(self, item): """Return the root item of the specified item.""" root_item = item while isinstance(root_item.parent(), QTreeWidgetItem): root_item = root_item.parent() return root_item
[ "def", "get_root_item", "(", "self", ",", "item", ")", ":", "root_item", "=", "item", "while", "isinstance", "(", "root_item", ".", "parent", "(", ")", ",", "QTreeWidgetItem", ")", ":", "root_item", "=", "root_item", ".", "parent", "(", ")", "return", "r...
Return the root item of the specified item.
[ "Return", "the", "root", "item", "of", "the", "specified", "item", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L547-L552
30,569
spyder-ide/spyder
spyder/plugins/outlineexplorer/widgets.py
OutlineExplorerTreeWidget.get_visible_items
def get_visible_items(self): """Return a list of all visible items in the treewidget.""" items = [] iterator = QTreeWidgetItemIterator(self) while iterator.value(): item = iterator.value() if not item.isHidden(): if item.parent(): if item.parent().isExpanded(): items.append(item) else: items.append(item) iterator += 1 return items
python
def get_visible_items(self): """Return a list of all visible items in the treewidget.""" items = [] iterator = QTreeWidgetItemIterator(self) while iterator.value(): item = iterator.value() if not item.isHidden(): if item.parent(): if item.parent().isExpanded(): items.append(item) else: items.append(item) iterator += 1 return items
[ "def", "get_visible_items", "(", "self", ")", ":", "items", "=", "[", "]", "iterator", "=", "QTreeWidgetItemIterator", "(", "self", ")", "while", "iterator", ".", "value", "(", ")", ":", "item", "=", "iterator", ".", "value", "(", ")", "if", "not", "it...
Return a list of all visible items in the treewidget.
[ "Return", "a", "list", "of", "all", "visible", "items", "in", "the", "treewidget", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L554-L567
30,570
spyder-ide/spyder
spyder/plugins/outlineexplorer/widgets.py
OutlineExplorerWidget.setup_buttons
def setup_buttons(self): """Setup the buttons of the outline explorer widget toolbar.""" self.fromcursor_btn = create_toolbutton( self, icon=ima.icon('fromcursor'), tip=_('Go to cursor position'), triggered=self.treewidget.go_to_cursor_position) buttons = [self.fromcursor_btn] for action in [self.treewidget.collapse_all_action, self.treewidget.expand_all_action, self.treewidget.restore_action, self.treewidget.collapse_selection_action, self.treewidget.expand_selection_action]: buttons.append(create_toolbutton(self)) buttons[-1].setDefaultAction(action) return buttons
python
def setup_buttons(self): """Setup the buttons of the outline explorer widget toolbar.""" self.fromcursor_btn = create_toolbutton( self, icon=ima.icon('fromcursor'), tip=_('Go to cursor position'), triggered=self.treewidget.go_to_cursor_position) buttons = [self.fromcursor_btn] for action in [self.treewidget.collapse_all_action, self.treewidget.expand_all_action, self.treewidget.restore_action, self.treewidget.collapse_selection_action, self.treewidget.expand_selection_action]: buttons.append(create_toolbutton(self)) buttons[-1].setDefaultAction(action) return buttons
[ "def", "setup_buttons", "(", "self", ")", ":", "self", ".", "fromcursor_btn", "=", "create_toolbutton", "(", "self", ",", "icon", "=", "ima", ".", "icon", "(", "'fromcursor'", ")", ",", "tip", "=", "_", "(", "'Go to cursor position'", ")", ",", "triggered"...
Setup the buttons of the outline explorer widget toolbar.
[ "Setup", "the", "buttons", "of", "the", "outline", "explorer", "widget", "toolbar", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L650-L664
30,571
spyder-ide/spyder
spyder/plugins/outlineexplorer/widgets.py
OutlineExplorerWidget.get_options
def get_options(self): """ Return outline explorer options """ return dict( show_fullpath=self.treewidget.show_fullpath, show_all_files=self.treewidget.show_all_files, group_cells=self.treewidget.group_cells, show_comments=self.treewidget.show_comments, sort_files_alphabetically=( self.treewidget.sort_files_alphabetically), expanded_state=self.treewidget.get_expanded_state(), scrollbar_position=self.treewidget.get_scrollbar_position(), visibility=self.isVisible() )
python
def get_options(self): """ Return outline explorer options """ return dict( show_fullpath=self.treewidget.show_fullpath, show_all_files=self.treewidget.show_all_files, group_cells=self.treewidget.group_cells, show_comments=self.treewidget.show_comments, sort_files_alphabetically=( self.treewidget.sort_files_alphabetically), expanded_state=self.treewidget.get_expanded_state(), scrollbar_position=self.treewidget.get_scrollbar_position(), visibility=self.isVisible() )
[ "def", "get_options", "(", "self", ")", ":", "return", "dict", "(", "show_fullpath", "=", "self", ".", "treewidget", ".", "show_fullpath", ",", "show_all_files", "=", "self", ".", "treewidget", ".", "show_all_files", ",", "group_cells", "=", "self", ".", "tr...
Return outline explorer options
[ "Return", "outline", "explorer", "options" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/outlineexplorer/widgets.py#L675-L689
30,572
spyder-ide/spyder
spyder/api/editorextension.py
EditorExtension.on_uninstall
def on_uninstall(self): """Uninstalls the editor extension from the editor.""" self._on_close = True self.enabled = False self._editor = None
python
def on_uninstall(self): """Uninstalls the editor extension from the editor.""" self._on_close = True self.enabled = False self._editor = None
[ "def", "on_uninstall", "(", "self", ")", ":", "self", ".", "_on_close", "=", "True", "self", ".", "enabled", "=", "False", "self", ".", "_editor", "=", "None" ]
Uninstalls the editor extension from the editor.
[ "Uninstalls", "the", "editor", "extension", "from", "the", "editor", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/api/editorextension.py#L112-L116
30,573
spyder-ide/spyder
spyder/__init__.py
get_versions
def get_versions(reporev=True): """Get version information for components used by Spyder""" import sys import platform import qtpy import qtpy.QtCore revision = None if reporev: from spyder.utils import vcs revision, branch = vcs.get_git_revision(os.path.dirname(__dir__)) if not sys.platform == 'darwin': # To avoid a crash with our Mac app system = platform.system() else: system = 'Darwin' return { 'spyder': __version__, 'python': platform.python_version(), # "2.7.3" 'bitness': 64 if sys.maxsize > 2**32 else 32, 'qt': qtpy.QtCore.__version__, 'qt_api': qtpy.API_NAME, # PyQt5 'qt_api_ver': qtpy.PYQT_VERSION, 'system': system, # Linux, Windows, ... 'release': platform.release(), # XP, 10.6, 2.2.0, etc. 'revision': revision, # '9fdf926eccce' }
python
def get_versions(reporev=True): """Get version information for components used by Spyder""" import sys import platform import qtpy import qtpy.QtCore revision = None if reporev: from spyder.utils import vcs revision, branch = vcs.get_git_revision(os.path.dirname(__dir__)) if not sys.platform == 'darwin': # To avoid a crash with our Mac app system = platform.system() else: system = 'Darwin' return { 'spyder': __version__, 'python': platform.python_version(), # "2.7.3" 'bitness': 64 if sys.maxsize > 2**32 else 32, 'qt': qtpy.QtCore.__version__, 'qt_api': qtpy.API_NAME, # PyQt5 'qt_api_ver': qtpy.PYQT_VERSION, 'system': system, # Linux, Windows, ... 'release': platform.release(), # XP, 10.6, 2.2.0, etc. 'revision': revision, # '9fdf926eccce' }
[ "def", "get_versions", "(", "reporev", "=", "True", ")", ":", "import", "sys", "import", "platform", "import", "qtpy", "import", "qtpy", ".", "QtCore", "revision", "=", "None", "if", "reporev", ":", "from", "spyder", ".", "utils", "import", "vcs", "revisio...
Get version information for components used by Spyder
[ "Get", "version", "information", "for", "components", "used", "by", "Spyder" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/__init__.py#L67-L95
30,574
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/arrayeditor.py
is_number
def is_number(dtype): """Return True is datatype dtype is a number kind""" return is_float(dtype) or ('int' in dtype.name) or ('long' in dtype.name) \ or ('short' in dtype.name)
python
def is_number(dtype): """Return True is datatype dtype is a number kind""" return is_float(dtype) or ('int' in dtype.name) or ('long' in dtype.name) \ or ('short' in dtype.name)
[ "def", "is_number", "(", "dtype", ")", ":", "return", "is_float", "(", "dtype", ")", "or", "(", "'int'", "in", "dtype", ".", "name", ")", "or", "(", "'long'", "in", "dtype", ".", "name", ")", "or", "(", "'short'", "in", "dtype", ".", "name", ")" ]
Return True is datatype dtype is a number kind
[ "Return", "True", "is", "datatype", "dtype", "is", "a", "number", "kind" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L101-L104
30,575
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/arrayeditor.py
get_idx_rect
def get_idx_rect(index_list): """Extract the boundaries from a list of indexes""" rows, cols = list(zip(*[(i.row(), i.column()) for i in index_list])) return ( min(rows), max(rows), min(cols), max(cols) )
python
def get_idx_rect(index_list): """Extract the boundaries from a list of indexes""" rows, cols = list(zip(*[(i.row(), i.column()) for i in index_list])) return ( min(rows), max(rows), min(cols), max(cols) )
[ "def", "get_idx_rect", "(", "index_list", ")", ":", "rows", ",", "cols", "=", "list", "(", "zip", "(", "*", "[", "(", "i", ".", "row", "(", ")", ",", "i", ".", "column", "(", ")", ")", "for", "i", "in", "index_list", "]", ")", ")", "return", ...
Extract the boundaries from a list of indexes
[ "Extract", "the", "boundaries", "from", "a", "list", "of", "indexes" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L107-L110
30,576
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/arrayeditor.py
ArrayModel.columnCount
def columnCount(self, qindex=QModelIndex()): """Array column number""" if self.total_cols <= self.cols_loaded: return self.total_cols else: return self.cols_loaded
python
def columnCount(self, qindex=QModelIndex()): """Array column number""" if self.total_cols <= self.cols_loaded: return self.total_cols else: return self.cols_loaded
[ "def", "columnCount", "(", "self", ",", "qindex", "=", "QModelIndex", "(", ")", ")", ":", "if", "self", ".", "total_cols", "<=", "self", ".", "cols_loaded", ":", "return", "self", ".", "total_cols", "else", ":", "return", "self", ".", "cols_loaded" ]
Array column number
[ "Array", "column", "number" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L197-L202
30,577
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/arrayeditor.py
ArrayDelegate.createEditor
def createEditor(self, parent, option, index): """Create editor widget""" model = index.model() value = model.get_value(index) if model._data.dtype.name == "bool": value = not value model.setData(index, to_qvariant(value)) return elif value is not np.ma.masked: editor = QLineEdit(parent) editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) editor.setAlignment(Qt.AlignCenter) if is_number(self.dtype): validator = QDoubleValidator(editor) validator.setLocale(QLocale('C')) editor.setValidator(validator) editor.returnPressed.connect(self.commitAndCloseEditor) return editor
python
def createEditor(self, parent, option, index): """Create editor widget""" model = index.model() value = model.get_value(index) if model._data.dtype.name == "bool": value = not value model.setData(index, to_qvariant(value)) return elif value is not np.ma.masked: editor = QLineEdit(parent) editor.setFont(get_font(font_size_delta=DEFAULT_SMALL_DELTA)) editor.setAlignment(Qt.AlignCenter) if is_number(self.dtype): validator = QDoubleValidator(editor) validator.setLocale(QLocale('C')) editor.setValidator(validator) editor.returnPressed.connect(self.commitAndCloseEditor) return editor
[ "def", "createEditor", "(", "self", ",", "parent", ",", "option", ",", "index", ")", ":", "model", "=", "index", ".", "model", "(", ")", "value", "=", "model", ".", "get_value", "(", "index", ")", "if", "model", ".", "_data", ".", "dtype", ".", "na...
Create editor widget
[ "Create", "editor", "widget" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L363-L380
30,578
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/arrayeditor.py
ArrayDelegate.commitAndCloseEditor
def commitAndCloseEditor(self): """Commit and close editor""" editor = self.sender() # Avoid a segfault with PyQt5. Variable value won't be changed # but at least Spyder won't crash. It seems generated by a bug in sip. try: self.commitData.emit(editor) except AttributeError: pass self.closeEditor.emit(editor, QAbstractItemDelegate.NoHint)
python
def commitAndCloseEditor(self): """Commit and close editor""" editor = self.sender() # Avoid a segfault with PyQt5. Variable value won't be changed # but at least Spyder won't crash. It seems generated by a bug in sip. try: self.commitData.emit(editor) except AttributeError: pass self.closeEditor.emit(editor, QAbstractItemDelegate.NoHint)
[ "def", "commitAndCloseEditor", "(", "self", ")", ":", "editor", "=", "self", ".", "sender", "(", ")", "# Avoid a segfault with PyQt5. Variable value won't be changed\r", "# but at least Spyder won't crash. It seems generated by a bug in sip.\r", "try", ":", "self", ".", "commit...
Commit and close editor
[ "Commit", "and", "close", "editor" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L382-L391
30,579
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/arrayeditor.py
ArrayDelegate.setEditorData
def setEditorData(self, editor, index): """Set editor widget's data""" text = from_qvariant(index.model().data(index, Qt.DisplayRole), str) editor.setText(text)
python
def setEditorData(self, editor, index): """Set editor widget's data""" text = from_qvariant(index.model().data(index, Qt.DisplayRole), str) editor.setText(text)
[ "def", "setEditorData", "(", "self", ",", "editor", ",", "index", ")", ":", "text", "=", "from_qvariant", "(", "index", ".", "model", "(", ")", ".", "data", "(", "index", ",", "Qt", ".", "DisplayRole", ")", ",", "str", ")", "editor", ".", "setText", ...
Set editor widget's data
[ "Set", "editor", "widget", "s", "data" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L393-L396
30,580
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/arrayeditor.py
ArrayView.resize_to_contents
def resize_to_contents(self): """Resize cells to contents""" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.resizeColumnsToContents() self.model().fetch_more(columns=True) self.resizeColumnsToContents() QApplication.restoreOverrideCursor()
python
def resize_to_contents(self): """Resize cells to contents""" QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.resizeColumnsToContents() self.model().fetch_more(columns=True) self.resizeColumnsToContents() QApplication.restoreOverrideCursor()
[ "def", "resize_to_contents", "(", "self", ")", ":", "QApplication", ".", "setOverrideCursor", "(", "QCursor", "(", "Qt", ".", "WaitCursor", ")", ")", "self", ".", "resizeColumnsToContents", "(", ")", "self", ".", "model", "(", ")", ".", "fetch_more", "(", ...
Resize cells to contents
[ "Resize", "cells", "to", "contents" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L464-L470
30,581
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/arrayeditor.py
ArrayView._sel_to_text
def _sel_to_text(self, cell_range): """Copy an array portion to a unicode string""" if not cell_range: return row_min, row_max, col_min, col_max = get_idx_rect(cell_range) if col_min == 0 and col_max == (self.model().cols_loaded-1): # we've selected a whole column. It isn't possible to # select only the first part of a column without loading more, # so we can treat it as intentional and copy the whole thing col_max = self.model().total_cols-1 if row_min == 0 and row_max == (self.model().rows_loaded-1): row_max = self.model().total_rows-1 _data = self.model().get_data() if PY3: output = io.BytesIO() else: output = io.StringIO() try: np.savetxt(output, _data[row_min:row_max+1, col_min:col_max+1], delimiter='\t', fmt=self.model().get_format()) except: QMessageBox.warning(self, _("Warning"), _("It was not possible to copy values for " "this array")) return contents = output.getvalue().decode('utf-8') output.close() return contents
python
def _sel_to_text(self, cell_range): """Copy an array portion to a unicode string""" if not cell_range: return row_min, row_max, col_min, col_max = get_idx_rect(cell_range) if col_min == 0 and col_max == (self.model().cols_loaded-1): # we've selected a whole column. It isn't possible to # select only the first part of a column without loading more, # so we can treat it as intentional and copy the whole thing col_max = self.model().total_cols-1 if row_min == 0 and row_max == (self.model().rows_loaded-1): row_max = self.model().total_rows-1 _data = self.model().get_data() if PY3: output = io.BytesIO() else: output = io.StringIO() try: np.savetxt(output, _data[row_min:row_max+1, col_min:col_max+1], delimiter='\t', fmt=self.model().get_format()) except: QMessageBox.warning(self, _("Warning"), _("It was not possible to copy values for " "this array")) return contents = output.getvalue().decode('utf-8') output.close() return contents
[ "def", "_sel_to_text", "(", "self", ",", "cell_range", ")", ":", "if", "not", "cell_range", ":", "return", "row_min", ",", "row_max", ",", "col_min", ",", "col_max", "=", "get_idx_rect", "(", "cell_range", ")", "if", "col_min", "==", "0", "and", "col_max",...
Copy an array portion to a unicode string
[ "Copy", "an", "array", "portion", "to", "a", "unicode", "string" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L495-L523
30,582
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/arrayeditor.py
ArrayEditorWidget.change_format
def change_format(self): """Change display format""" format, valid = QInputDialog.getText(self, _( 'Format'), _( "Float formatting"), QLineEdit.Normal, self.model.get_format()) if valid: format = str(format) try: format % 1.1 except: QMessageBox.critical(self, _("Error"), _("Format (%s) is incorrect") % format) return self.model.set_format(format)
python
def change_format(self): """Change display format""" format, valid = QInputDialog.getText(self, _( 'Format'), _( "Float formatting"), QLineEdit.Normal, self.model.get_format()) if valid: format = str(format) try: format % 1.1 except: QMessageBox.critical(self, _("Error"), _("Format (%s) is incorrect") % format) return self.model.set_format(format)
[ "def", "change_format", "(", "self", ")", ":", "format", ",", "valid", "=", "QInputDialog", ".", "getText", "(", "self", ",", "_", "(", "'Format'", ")", ",", "_", "(", "\"Float formatting\"", ")", ",", "QLineEdit", ".", "Normal", ",", "self", ".", "mod...
Change display format
[ "Change", "display", "format" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L585-L598
30,583
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/arrayeditor.py
ArrayEditor.change_active_widget
def change_active_widget(self, index): """ This is implemented for handling negative values in index for 3d arrays, to give the same behavior as slicing """ string_index = [':']*3 string_index[self.last_dim] = '<font color=red>%i</font>' self.slicing_label.setText((r"Slicing: [" + ", ".join(string_index) + "]") % index) if index < 0: data_index = self.data.shape[self.last_dim] + index else: data_index = index slice_index = [slice(None)]*3 slice_index[self.last_dim] = data_index stack_index = self.dim_indexes[self.last_dim].get(data_index) if stack_index is None: stack_index = self.stack.count() try: self.stack.addWidget(ArrayEditorWidget( self, self.data[tuple(slice_index)])) except IndexError: # Handle arrays of size 0 in one axis self.stack.addWidget(ArrayEditorWidget(self, self.data)) self.dim_indexes[self.last_dim][data_index] = stack_index self.stack.update() self.stack.setCurrentIndex(stack_index)
python
def change_active_widget(self, index): """ This is implemented for handling negative values in index for 3d arrays, to give the same behavior as slicing """ string_index = [':']*3 string_index[self.last_dim] = '<font color=red>%i</font>' self.slicing_label.setText((r"Slicing: [" + ", ".join(string_index) + "]") % index) if index < 0: data_index = self.data.shape[self.last_dim] + index else: data_index = index slice_index = [slice(None)]*3 slice_index[self.last_dim] = data_index stack_index = self.dim_indexes[self.last_dim].get(data_index) if stack_index is None: stack_index = self.stack.count() try: self.stack.addWidget(ArrayEditorWidget( self, self.data[tuple(slice_index)])) except IndexError: # Handle arrays of size 0 in one axis self.stack.addWidget(ArrayEditorWidget(self, self.data)) self.dim_indexes[self.last_dim][data_index] = stack_index self.stack.update() self.stack.setCurrentIndex(stack_index)
[ "def", "change_active_widget", "(", "self", ",", "index", ")", ":", "string_index", "=", "[", "':'", "]", "*", "3", "string_index", "[", "self", ".", "last_dim", "]", "=", "'<font color=red>%i</font>'", "self", ".", "slicing_label", ".", "setText", "(", "(",...
This is implemented for handling negative values in index for 3d arrays, to give the same behavior as slicing
[ "This", "is", "implemented", "for", "handling", "negative", "values", "in", "index", "for", "3d", "arrays", "to", "give", "the", "same", "behavior", "as", "slicing" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L775-L801
30,584
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/arrayeditor.py
ArrayEditor.current_dim_changed
def current_dim_changed(self, index): """ This change the active axis the array editor is plotting over in 3D """ self.last_dim = index string_size = ['%i']*3 string_size[index] = '<font color=red>%i</font>' self.shape_label.setText(('Shape: (' + ', '.join(string_size) + ') ') % self.data.shape) if self.index_spin.value() != 0: self.index_spin.setValue(0) else: # this is done since if the value is currently 0 it does not emit # currentIndexChanged(int) self.change_active_widget(0) self.index_spin.setRange(-self.data.shape[index], self.data.shape[index]-1)
python
def current_dim_changed(self, index): """ This change the active axis the array editor is plotting over in 3D """ self.last_dim = index string_size = ['%i']*3 string_size[index] = '<font color=red>%i</font>' self.shape_label.setText(('Shape: (' + ', '.join(string_size) + ') ') % self.data.shape) if self.index_spin.value() != 0: self.index_spin.setValue(0) else: # this is done since if the value is currently 0 it does not emit # currentIndexChanged(int) self.change_active_widget(0) self.index_spin.setRange(-self.data.shape[index], self.data.shape[index]-1)
[ "def", "current_dim_changed", "(", "self", ",", "index", ")", ":", "self", ".", "last_dim", "=", "index", "string_size", "=", "[", "'%i'", "]", "*", "3", "string_size", "[", "index", "]", "=", "'<font color=red>%i</font>'", "self", ".", "shape_label", ".", ...
This change the active axis the array editor is plotting over in 3D
[ "This", "change", "the", "active", "axis", "the", "array", "editor", "is", "plotting", "over", "in", "3D" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L803-L820
30,585
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/arrayeditor.py
ArrayEditor.error
def error(self, message): """An error occured, closing the dialog box""" QMessageBox.critical(self, _("Array editor"), message) self.setAttribute(Qt.WA_DeleteOnClose) self.reject()
python
def error(self, message): """An error occured, closing the dialog box""" QMessageBox.critical(self, _("Array editor"), message) self.setAttribute(Qt.WA_DeleteOnClose) self.reject()
[ "def", "error", "(", "self", ",", "message", ")", ":", "QMessageBox", ".", "critical", "(", "self", ",", "_", "(", "\"Array editor\"", ")", ",", "message", ")", "self", ".", "setAttribute", "(", "Qt", ".", "WA_DeleteOnClose", ")", "self", ".", "reject", ...
An error occured, closing the dialog box
[ "An", "error", "occured", "closing", "the", "dialog", "box" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L835-L839
30,586
spyder-ide/spyder
spyder/utils/introspection/utils.py
find_lexer_for_filename
def find_lexer_for_filename(filename): """Get a Pygments Lexer given a filename. """ filename = filename or '' root, ext = os.path.splitext(filename) if ext in custom_extension_lexer_mapping: lexer = get_lexer_by_name(custom_extension_lexer_mapping[ext]) else: try: lexer = get_lexer_for_filename(filename) except Exception: return TextLexer() return lexer
python
def find_lexer_for_filename(filename): """Get a Pygments Lexer given a filename. """ filename = filename or '' root, ext = os.path.splitext(filename) if ext in custom_extension_lexer_mapping: lexer = get_lexer_by_name(custom_extension_lexer_mapping[ext]) else: try: lexer = get_lexer_for_filename(filename) except Exception: return TextLexer() return lexer
[ "def", "find_lexer_for_filename", "(", "filename", ")", ":", "filename", "=", "filename", "or", "''", "root", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", "ext", "in", "custom_extension_lexer_mapping", ":", "lexer", "=", ...
Get a Pygments Lexer given a filename.
[ "Get", "a", "Pygments", "Lexer", "given", "a", "filename", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/introspection/utils.py#L169-L181
30,587
spyder-ide/spyder
spyder/utils/introspection/utils.py
get_keywords
def get_keywords(lexer): """Get the keywords for a given lexer. """ if not hasattr(lexer, 'tokens'): return [] if 'keywords' in lexer.tokens: try: return lexer.tokens['keywords'][0][0].words except: pass keywords = [] for vals in lexer.tokens.values(): for val in vals: try: if isinstance(val[0], words): keywords.extend(val[0].words) else: ini_val = val[0] if ')\\b' in val[0] or ')(\\s+)' in val[0]: val = re.sub(r'\\.', '', val[0]) val = re.sub(r'[^0-9a-zA-Z|]+', '', val) if '|' in ini_val: keywords.extend(val.split('|')) else: keywords.append(val) except Exception: continue return keywords
python
def get_keywords(lexer): """Get the keywords for a given lexer. """ if not hasattr(lexer, 'tokens'): return [] if 'keywords' in lexer.tokens: try: return lexer.tokens['keywords'][0][0].words except: pass keywords = [] for vals in lexer.tokens.values(): for val in vals: try: if isinstance(val[0], words): keywords.extend(val[0].words) else: ini_val = val[0] if ')\\b' in val[0] or ')(\\s+)' in val[0]: val = re.sub(r'\\.', '', val[0]) val = re.sub(r'[^0-9a-zA-Z|]+', '', val) if '|' in ini_val: keywords.extend(val.split('|')) else: keywords.append(val) except Exception: continue return keywords
[ "def", "get_keywords", "(", "lexer", ")", ":", "if", "not", "hasattr", "(", "lexer", ",", "'tokens'", ")", ":", "return", "[", "]", "if", "'keywords'", "in", "lexer", ".", "tokens", ":", "try", ":", "return", "lexer", ".", "tokens", "[", "'keywords'", ...
Get the keywords for a given lexer.
[ "Get", "the", "keywords", "for", "a", "given", "lexer", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/introspection/utils.py#L184-L211
30,588
spyder-ide/spyder
spyder/utils/introspection/utils.py
get_words
def get_words(file_path=None, content=None, extension=None): """ Extract all words from a source code file to be used in code completion. Extract the list of words that contains the file in the editor, to carry out the inline completion similar to VSCode. """ if (file_path is None and (content is None or extension is None) or file_path and content and extension): error_msg = ('Must provide `file_path` or `content` and `extension`') raise Exception(error_msg) if file_path and content is None and extension is None: extension = os.path.splitext(file_path)[1] with open(file_path) as infile: content = infile.read() if extension in ['.css']: regex = re.compile(r'([^a-zA-Z-])') elif extension in ['.R', '.c', '.md', '.cpp', '.java', '.py']: regex = re.compile(r'([^a-zA-Z_])') else: regex = re.compile(r'([^a-zA-Z])') words = sorted(set(regex.sub(r' ', content).split())) return words
python
def get_words(file_path=None, content=None, extension=None): """ Extract all words from a source code file to be used in code completion. Extract the list of words that contains the file in the editor, to carry out the inline completion similar to VSCode. """ if (file_path is None and (content is None or extension is None) or file_path and content and extension): error_msg = ('Must provide `file_path` or `content` and `extension`') raise Exception(error_msg) if file_path and content is None and extension is None: extension = os.path.splitext(file_path)[1] with open(file_path) as infile: content = infile.read() if extension in ['.css']: regex = re.compile(r'([^a-zA-Z-])') elif extension in ['.R', '.c', '.md', '.cpp', '.java', '.py']: regex = re.compile(r'([^a-zA-Z_])') else: regex = re.compile(r'([^a-zA-Z])') words = sorted(set(regex.sub(r' ', content).split())) return words
[ "def", "get_words", "(", "file_path", "=", "None", ",", "content", "=", "None", ",", "extension", "=", "None", ")", ":", "if", "(", "file_path", "is", "None", "and", "(", "content", "is", "None", "or", "extension", "is", "None", ")", "or", "file_path",...
Extract all words from a source code file to be used in code completion. Extract the list of words that contains the file in the editor, to carry out the inline completion similar to VSCode.
[ "Extract", "all", "words", "from", "a", "source", "code", "file", "to", "be", "used", "in", "code", "completion", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/introspection/utils.py#L213-L238
30,589
spyder-ide/spyder
spyder/utils/introspection/utils.py
get_parent_until
def get_parent_until(path): """ Given a file path, determine the full module path. e.g. '/usr/lib/python2.7/dist-packages/numpy/core/__init__.pyc' yields 'numpy.core' """ dirname = osp.dirname(path) try: mod = osp.basename(path) mod = osp.splitext(mod)[0] imp.find_module(mod, [dirname]) except ImportError: return items = [mod] while 1: items.append(osp.basename(dirname)) try: dirname = osp.dirname(dirname) imp.find_module('__init__', [dirname + os.sep]) except ImportError: break return '.'.join(reversed(items))
python
def get_parent_until(path): """ Given a file path, determine the full module path. e.g. '/usr/lib/python2.7/dist-packages/numpy/core/__init__.pyc' yields 'numpy.core' """ dirname = osp.dirname(path) try: mod = osp.basename(path) mod = osp.splitext(mod)[0] imp.find_module(mod, [dirname]) except ImportError: return items = [mod] while 1: items.append(osp.basename(dirname)) try: dirname = osp.dirname(dirname) imp.find_module('__init__', [dirname + os.sep]) except ImportError: break return '.'.join(reversed(items))
[ "def", "get_parent_until", "(", "path", ")", ":", "dirname", "=", "osp", ".", "dirname", "(", "path", ")", "try", ":", "mod", "=", "osp", ".", "basename", "(", "path", ")", "mod", "=", "osp", ".", "splitext", "(", "mod", ")", "[", "0", "]", "imp"...
Given a file path, determine the full module path. e.g. '/usr/lib/python2.7/dist-packages/numpy/core/__init__.pyc' yields 'numpy.core'
[ "Given", "a", "file", "path", "determine", "the", "full", "module", "path", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/introspection/utils.py#L241-L263
30,590
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/kernelconnect.py
KernelConnectionDialog.load_connection_settings
def load_connection_settings(self): """Load the user's previously-saved kernel connection settings.""" existing_kernel = CONF.get("existing-kernel", "settings", {}) connection_file_path = existing_kernel.get("json_file_path", "") is_remote = existing_kernel.get("is_remote", False) username = existing_kernel.get("username", "") hostname = existing_kernel.get("hostname", "") port = str(existing_kernel.get("port", 22)) is_ssh_kf = existing_kernel.get("is_ssh_keyfile", False) ssh_kf = existing_kernel.get("ssh_key_file_path", "") if connection_file_path != "": self.cf.setText(connection_file_path) if username != "": self.un.setText(username) if hostname != "": self.hn.setText(hostname) if ssh_kf != "": self.kf.setText(ssh_kf) self.rm_group.setChecked(is_remote) self.pn.setText(port) self.kf_radio.setChecked(is_ssh_kf) self.pw_radio.setChecked(not is_ssh_kf) try: import keyring ssh_passphrase = keyring.get_password("spyder_remote_kernel", "ssh_key_passphrase") ssh_password = keyring.get_password("spyder_remote_kernel", "ssh_password") if ssh_passphrase: self.kfp.setText(ssh_passphrase) if ssh_password: self.pw.setText(ssh_password) except Exception: pass
python
def load_connection_settings(self): """Load the user's previously-saved kernel connection settings.""" existing_kernel = CONF.get("existing-kernel", "settings", {}) connection_file_path = existing_kernel.get("json_file_path", "") is_remote = existing_kernel.get("is_remote", False) username = existing_kernel.get("username", "") hostname = existing_kernel.get("hostname", "") port = str(existing_kernel.get("port", 22)) is_ssh_kf = existing_kernel.get("is_ssh_keyfile", False) ssh_kf = existing_kernel.get("ssh_key_file_path", "") if connection_file_path != "": self.cf.setText(connection_file_path) if username != "": self.un.setText(username) if hostname != "": self.hn.setText(hostname) if ssh_kf != "": self.kf.setText(ssh_kf) self.rm_group.setChecked(is_remote) self.pn.setText(port) self.kf_radio.setChecked(is_ssh_kf) self.pw_radio.setChecked(not is_ssh_kf) try: import keyring ssh_passphrase = keyring.get_password("spyder_remote_kernel", "ssh_key_passphrase") ssh_password = keyring.get_password("spyder_remote_kernel", "ssh_password") if ssh_passphrase: self.kfp.setText(ssh_passphrase) if ssh_password: self.pw.setText(ssh_password) except Exception: pass
[ "def", "load_connection_settings", "(", "self", ")", ":", "existing_kernel", "=", "CONF", ".", "get", "(", "\"existing-kernel\"", ",", "\"settings\"", ",", "{", "}", ")", "connection_file_path", "=", "existing_kernel", ".", "get", "(", "\"json_file_path\"", ",", ...
Load the user's previously-saved kernel connection settings.
[ "Load", "the", "user", "s", "previously", "-", "saved", "kernel", "connection", "settings", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/kernelconnect.py#L164-L200
30,591
spyder-ide/spyder
spyder/plugins/ipythonconsole/widgets/kernelconnect.py
KernelConnectionDialog.save_connection_settings
def save_connection_settings(self): """Save user's kernel connection settings.""" if not self.save_layout.isChecked(): return is_ssh_key = bool(self.kf_radio.isChecked()) connection_settings = { "json_file_path": self.cf.text(), "is_remote": self.rm_group.isChecked(), "username": self.un.text(), "hostname": self.hn.text(), "port": self.pn.text(), "is_ssh_keyfile": is_ssh_key, "ssh_key_file_path": self.kf.text() } CONF.set("existing-kernel", "settings", connection_settings) try: import keyring if is_ssh_key: keyring.set_password("spyder_remote_kernel", "ssh_key_passphrase", self.kfp.text()) else: keyring.set_password("spyder_remote_kernel", "ssh_password", self.pw.text()) except Exception: pass
python
def save_connection_settings(self): """Save user's kernel connection settings.""" if not self.save_layout.isChecked(): return is_ssh_key = bool(self.kf_radio.isChecked()) connection_settings = { "json_file_path": self.cf.text(), "is_remote": self.rm_group.isChecked(), "username": self.un.text(), "hostname": self.hn.text(), "port": self.pn.text(), "is_ssh_keyfile": is_ssh_key, "ssh_key_file_path": self.kf.text() } CONF.set("existing-kernel", "settings", connection_settings) try: import keyring if is_ssh_key: keyring.set_password("spyder_remote_kernel", "ssh_key_passphrase", self.kfp.text()) else: keyring.set_password("spyder_remote_kernel", "ssh_password", self.pw.text()) except Exception: pass
[ "def", "save_connection_settings", "(", "self", ")", ":", "if", "not", "self", ".", "save_layout", ".", "isChecked", "(", ")", ":", "return", "is_ssh_key", "=", "bool", "(", "self", ".", "kf_radio", ".", "isChecked", "(", ")", ")", "connection_settings", "...
Save user's kernel connection settings.
[ "Save", "user", "s", "kernel", "connection", "settings", "." ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/widgets/kernelconnect.py#L202-L231
30,592
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/importwizard.py
get_color
def get_color(value, alpha): """Return color depending on value type""" color = QColor() for typ in COLORS: if isinstance(value, typ): color = QColor(COLORS[typ]) color.setAlphaF(alpha) return color
python
def get_color(value, alpha): """Return color depending on value type""" color = QColor() for typ in COLORS: if isinstance(value, typ): color = QColor(COLORS[typ]) color.setAlphaF(alpha) return color
[ "def", "get_color", "(", "value", ",", "alpha", ")", ":", "color", "=", "QColor", "(", ")", "for", "typ", "in", "COLORS", ":", "if", "isinstance", "(", "value", ",", "typ", ")", ":", "color", "=", "QColor", "(", "COLORS", "[", "typ", "]", ")", "c...
Return color depending on value type
[ "Return", "color", "depending", "on", "value", "type" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L96-L103
30,593
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/importwizard.py
ContentsWidget.get_col_sep
def get_col_sep(self): """Return the column separator""" if self.tab_btn.isChecked(): return u"\t" elif self.ws_btn.isChecked(): return None return to_text_string(self.line_edt.text())
python
def get_col_sep(self): """Return the column separator""" if self.tab_btn.isChecked(): return u"\t" elif self.ws_btn.isChecked(): return None return to_text_string(self.line_edt.text())
[ "def", "get_col_sep", "(", "self", ")", ":", "if", "self", ".", "tab_btn", ".", "isChecked", "(", ")", ":", "return", "u\"\\t\"", "elif", "self", ".", "ws_btn", ".", "isChecked", "(", ")", ":", "return", "None", "return", "to_text_string", "(", "self", ...
Return the column separator
[ "Return", "the", "column", "separator" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L236-L242
30,594
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/importwizard.py
ContentsWidget.get_row_sep
def get_row_sep(self): """Return the row separator""" if self.eol_btn.isChecked(): return u"\n" return to_text_string(self.line_edt_row.text())
python
def get_row_sep(self): """Return the row separator""" if self.eol_btn.isChecked(): return u"\n" return to_text_string(self.line_edt_row.text())
[ "def", "get_row_sep", "(", "self", ")", ":", "if", "self", ".", "eol_btn", ".", "isChecked", "(", ")", ":", "return", "u\"\\n\"", "return", "to_text_string", "(", "self", ".", "line_edt_row", ".", "text", "(", ")", ")" ]
Return the row separator
[ "Return", "the", "row", "separator" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L244-L248
30,595
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/importwizard.py
ContentsWidget.set_as_data
def set_as_data(self, as_data): """Set if data type conversion""" self._as_data = as_data self.asDataChanged.emit(as_data)
python
def set_as_data(self, as_data): """Set if data type conversion""" self._as_data = as_data self.asDataChanged.emit(as_data)
[ "def", "set_as_data", "(", "self", ",", "as_data", ")", ":", "self", ".", "_as_data", "=", "as_data", "self", ".", "asDataChanged", ".", "emit", "(", "as_data", ")" ]
Set if data type conversion
[ "Set", "if", "data", "type", "conversion" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L259-L262
30,596
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/importwizard.py
PreviewTableModel._display_data
def _display_data(self, index): """Return a data element""" return to_qvariant(self._data[index.row()][index.column()])
python
def _display_data(self, index): """Return a data element""" return to_qvariant(self._data[index.row()][index.column()])
[ "def", "_display_data", "(", "self", ",", "index", ")", ":", "return", "to_qvariant", "(", "self", ".", "_data", "[", "index", ".", "row", "(", ")", "]", "[", "index", ".", "column", "(", ")", "]", ")" ]
Return a data element
[ "Return", "a", "data", "element" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L284-L286
30,597
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/importwizard.py
PreviewTableModel.data
def data(self, index, role=Qt.DisplayRole): """Return a model data element""" if not index.isValid(): return to_qvariant() if role == Qt.DisplayRole: return self._display_data(index) elif role == Qt.BackgroundColorRole: return to_qvariant(get_color(self._data[index.row()][index.column()], .2)) elif role == Qt.TextAlignmentRole: return to_qvariant(int(Qt.AlignRight|Qt.AlignVCenter)) return to_qvariant()
python
def data(self, index, role=Qt.DisplayRole): """Return a model data element""" if not index.isValid(): return to_qvariant() if role == Qt.DisplayRole: return self._display_data(index) elif role == Qt.BackgroundColorRole: return to_qvariant(get_color(self._data[index.row()][index.column()], .2)) elif role == Qt.TextAlignmentRole: return to_qvariant(int(Qt.AlignRight|Qt.AlignVCenter)) return to_qvariant()
[ "def", "data", "(", "self", ",", "index", ",", "role", "=", "Qt", ".", "DisplayRole", ")", ":", "if", "not", "index", ".", "isValid", "(", ")", ":", "return", "to_qvariant", "(", ")", "if", "role", "==", "Qt", ".", "DisplayRole", ":", "return", "se...
Return a model data element
[ "Return", "a", "model", "data", "element" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L288-L298
30,598
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/importwizard.py
PreviewTableModel.parse_data_type
def parse_data_type(self, index, **kwargs): """Parse a type to an other type""" if not index.isValid(): return False try: if kwargs['atype'] == "date": self._data[index.row()][index.column()] = \ datestr_to_datetime(self._data[index.row()][index.column()], kwargs['dayfirst']).date() elif kwargs['atype'] == "perc": _tmp = self._data[index.row()][index.column()].replace("%", "") self._data[index.row()][index.column()] = eval(_tmp)/100. elif kwargs['atype'] == "account": _tmp = self._data[index.row()][index.column()].replace(",", "") self._data[index.row()][index.column()] = eval(_tmp) elif kwargs['atype'] == "unicode": self._data[index.row()][index.column()] = to_text_string( self._data[index.row()][index.column()]) elif kwargs['atype'] == "int": self._data[index.row()][index.column()] = int( self._data[index.row()][index.column()]) elif kwargs['atype'] == "float": self._data[index.row()][index.column()] = float( self._data[index.row()][index.column()]) self.dataChanged.emit(index, index) except Exception as instance: print(instance)
python
def parse_data_type(self, index, **kwargs): """Parse a type to an other type""" if not index.isValid(): return False try: if kwargs['atype'] == "date": self._data[index.row()][index.column()] = \ datestr_to_datetime(self._data[index.row()][index.column()], kwargs['dayfirst']).date() elif kwargs['atype'] == "perc": _tmp = self._data[index.row()][index.column()].replace("%", "") self._data[index.row()][index.column()] = eval(_tmp)/100. elif kwargs['atype'] == "account": _tmp = self._data[index.row()][index.column()].replace(",", "") self._data[index.row()][index.column()] = eval(_tmp) elif kwargs['atype'] == "unicode": self._data[index.row()][index.column()] = to_text_string( self._data[index.row()][index.column()]) elif kwargs['atype'] == "int": self._data[index.row()][index.column()] = int( self._data[index.row()][index.column()]) elif kwargs['atype'] == "float": self._data[index.row()][index.column()] = float( self._data[index.row()][index.column()]) self.dataChanged.emit(index, index) except Exception as instance: print(instance)
[ "def", "parse_data_type", "(", "self", ",", "index", ",", "*", "*", "kwargs", ")", ":", "if", "not", "index", ".", "isValid", "(", ")", ":", "return", "False", "try", ":", "if", "kwargs", "[", "'atype'", "]", "==", "\"date\"", ":", "self", ".", "_d...
Parse a type to an other type
[ "Parse", "a", "type", "to", "an", "other", "type" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L308-L334
30,599
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/importwizard.py
PreviewTable._shape_text
def _shape_text(self, text, colsep=u"\t", rowsep=u"\n", transpose=False, skiprows=0, comments='#'): """Decode the shape of the given text""" assert colsep != rowsep out = [] text_rows = text.split(rowsep)[skiprows:] for row in text_rows: stripped = to_text_string(row).strip() if len(stripped) == 0 or stripped.startswith(comments): continue line = to_text_string(row).split(colsep) line = [try_to_parse(to_text_string(x)) for x in line] out.append(line) # Replace missing elements with np.nan's or None's if programs.is_module_installed('numpy'): from numpy import nan out = list(zip_longest(*out, fillvalue=nan)) else: out = list(zip_longest(*out, fillvalue=None)) # Tranpose the last result to get the expected one out = [[r[col] for r in out] for col in range(len(out[0]))] if transpose: return [[r[col] for r in out] for col in range(len(out[0]))] return out
python
def _shape_text(self, text, colsep=u"\t", rowsep=u"\n", transpose=False, skiprows=0, comments='#'): """Decode the shape of the given text""" assert colsep != rowsep out = [] text_rows = text.split(rowsep)[skiprows:] for row in text_rows: stripped = to_text_string(row).strip() if len(stripped) == 0 or stripped.startswith(comments): continue line = to_text_string(row).split(colsep) line = [try_to_parse(to_text_string(x)) for x in line] out.append(line) # Replace missing elements with np.nan's or None's if programs.is_module_installed('numpy'): from numpy import nan out = list(zip_longest(*out, fillvalue=nan)) else: out = list(zip_longest(*out, fillvalue=None)) # Tranpose the last result to get the expected one out = [[r[col] for r in out] for col in range(len(out[0]))] if transpose: return [[r[col] for r in out] for col in range(len(out[0]))] return out
[ "def", "_shape_text", "(", "self", ",", "text", ",", "colsep", "=", "u\"\\t\"", ",", "rowsep", "=", "u\"\\n\"", ",", "transpose", "=", "False", ",", "skiprows", "=", "0", ",", "comments", "=", "'#'", ")", ":", "assert", "colsep", "!=", "rowsep", "out",...
Decode the shape of the given text
[ "Decode", "the", "shape", "of", "the", "given", "text" ]
f76836ce1b924bcc4efd3f74f2960d26a4e528e0
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/importwizard.py#L376-L399