def swap_html_model(swap): """ Temporary fix to swap HTML model for Div model during png export to avoid issues with DOMParser compatibility in PhantomJS. Can be removed when switching to chromedriver. """ from ..viewable import Viewable state._html_escape = False swapped = [] for viewable in param.concrete_descendents(Viewable).values(): model = getattr(viewable, '_bokeh_model', None) try: swap_model = issubclass(model, HTML) and swap assert swap_model except Exception: continue else: viewable._bokeh_model = Div swapped.append(viewable) try: yield finally: state._html_escape = True for viewable in swapped: viewable._bokeh_model = HTML
def _apply_signatures(self): from inspect import Parameter, Signature from .viewable import Viewable descendants = param.concrete_descendents(Viewable) for cls in reversed(list(descendants.values())): if cls.__doc__.startswith('params'): prefix = cls.__doc__.split('\n')[0] cls.__doc__ = cls.__doc__.replace(prefix, '') sig = inspect.signature(cls.__init__) sig_params = list(sig.parameters.values()) if not sig_params or sig_params[-1] != Parameter( 'params', Parameter.VAR_KEYWORD): continue parameters = sig_params[:-1] processed_kws, keyword_groups = set(), [] for cls in reversed(cls.mro()): keyword_group = [] for (k, v) in sorted(cls.__dict__.items()): if (isinstance(v, param.Parameter) and k not in processed_kws and not v.readonly): keyword_group.append(k) processed_kws.add(k) keyword_groups.append(keyword_group) parameters += [ Parameter(name, Parameter.KEYWORD_ONLY) for kws in reversed(keyword_groups) for name in kws if name not in sig.parameters ] kwarg_name = '_kwargs' if 'kwargs' in processed_kws else 'kwargs' parameters.append(Parameter(kwarg_name, Parameter.VAR_KEYWORD)) cls.__init__.__signature__ = Signature( parameters, return_annotation=sig.return_annotation)
def css_files(self): from ..config import config from ..reactive import ReactiveHTML files = super(Resources, self).css_files for model in param.concrete_descendents(ReactiveHTML).values(): if hasattr(model, '__css__'): for css_file in model.__css__: if css_file not in files: files.append(css_file) for cssf in config.css_files: if os.path.isfile(cssf) or cssf in files: continue files.append(cssf) if self.mode == 'server': if state.rel_path: dist_dir = f'{state.rel_path}/{LOCAL_DIST}' else: dist_dir = LOCAL_DIST else: dist_dir = CDN_DIST for cssf in glob.glob(str(DIST_DIR / 'css' / '*.css')): if self.mode == 'inline': break files.append(dist_dir + f'css/{os.path.basename(cssf)}') return files
def get_pane_type(cls, obj): """ Returns the applicable Pane type given an object by resolving the precedence of all types whose applies method declares that the object is supported. Arguments --------- obj (object): The object type to return a Pane for Returns ------- The applicable Pane type with the highest precedence. """ if isinstance(obj, Viewable): return type(obj) descendents = [] for p in param.concrete_descendents(PaneBase).values(): priority = p.applies(obj) if p.priority is None else p.priority if isinstance(priority, bool) and priority: raise ValueError('If a Pane declares no priority ' 'the applies method should return a ' 'priority value specific to the ' 'object type or False, but the %s pane ' 'declares no priority.' % p.__name__) elif priority is None or priority is False: continue descendents.append((priority, p)) pane_types = reversed(sorted(descendents, key=lambda x: x[0])) for _, pane_type in pane_types: applies = pane_type.applies(obj) if isinstance(applies, bool) and not applies: continue return pane_type raise TypeError('%s type could not be rendered.' % type(obj).__name__)
def __init__(self, **params): super(StepFilter, self).__init__(**params) self.filter_type = self.previousFilterType = None self.param['filterTypeSelector'].objects = [view for view in param.concrete_descendents(Filter).values() if view in filterTypeSupported] self.param['filterTypeSelector'].default = self.param['filterTypeSelector'].objects[0] self.dashboard = Dashboard(specification=r'specYamlFile/default/nouveau_dashboard_default_config.yml') self.filterTypeParametersDynamicWidgetsSelector = None
def bundle_resources(): from .config import panel_extension from .template.base import BasicTemplate for imp in panel_extension._imports.values(): if imp.startswith('panel.'): __import__(imp) bundle_dir = pathlib.Path(__file__).parent.joinpath('dist', 'bundled') js_files = {} css_files = {} for name, model in Model.model_class_reverse_map.items(): if not name.startswith('panel.'): continue prev_jsfiles = getattr(model, '__javascript_raw__', None) prev_jsbundle = getattr(model, '__tarball__', None) prev_cls = model for cls in model.__mro__[1:]: jsfiles = getattr(cls, '__javascript_raw__', None) if ((jsfiles is None and prev_jsfiles is not None) or (jsfiles is not None and jsfiles != prev_jsfiles)): if prev_jsbundle: js_files[prev_cls.__name__] = prev_jsbundle else: js_files[prev_cls.__name__] = prev_jsfiles break prev_cls = cls prev_cssfiles = getattr(model, '__css_raw__', None) prev_cls = model for cls in model.__mro__[1:]: cssfiles = getattr(cls, '__css_raw__', None) if ((cssfiles is None and prev_cssfiles is not None) or (cssfiles is not None and cssfiles != prev_cssfiles)): css_files[prev_cls.__name__] = prev_cssfiles break prev_cls = cls for name, jsfiles in js_files.items(): if isinstance(jsfiles, dict): write_bundled_tarball(name, jsfiles, bundle_dir) else: write_bundled_files(name, jsfiles, bundle_dir) for name, cssfiles in css_files.items(): write_bundled_files(name, cssfiles, bundle_dir) # Bundle external template dependencies for name, template in param.concrete_descendents(BasicTemplate).items(): write_bundled_files(name, list(template._resources['css'].values()), bundle_dir) write_bundled_files(name, list(template._resources['js'].values()), bundle_dir) template_dir = pathlib.Path(inspect.getfile(template)).parent dest_dir = bundle_dir / name.lower() dest_dir.mkdir(parents=True, exist_ok=True) for css in glob.glob(str(template_dir / '*.css')): shutil.copyfile(css, dest_dir / os.path.basename(css))
def _coerce(self, dataset): if self.interface_applies(dataset, coerce=False): return dataset pandas_interfaces = param.concrete_descendents(PandasInterface) datatypes = [ intfc.datatype for intfc in pandas_interfaces.values() if dataset.interface.multi == intfc.multi ] return dataset.clone(datatype=datatypes)
def _get_type(cls, filter_type): try: __import__(f'lumen.filters.{filter_type}') except Exception: pass for filt in param.concrete_descendents(cls).values(): if filt.filter_type == filter_type: return filt raise ValueError(f"No Filter for filter_type '{filter_type}' could be found.")
def require_components(): """ Returns JS snippet to load the required dependencies in the classic notebook using REQUIRE JS. """ from .config import config from .reactive import ReactiveHTML configs, requirements, exports = [], [], {} js_requires = [] from bokeh.model import Model for qual_name, model in Model.model_class_reverse_map.items(): # We need to enable Models from Panel as well as Panel extensions # like awesome_panel_extensions. # The Bokeh models do not have "." in the qual_name if "." in qual_name: js_requires.append(model) js_requires += list(param.concrete_descendents(ReactiveHTML).values()) for export, js in config.js_files.items(): name = js.split('/')[-1].replace('.min', '').split('.')[-2] conf = {'paths': {name: js[:-3]}, 'exports': {name: export}} js_requires.append(conf) skip_import = {} for model in js_requires: if hasattr(model, '__js_skip__'): skip_import.update(model.__js_skip__) if not (hasattr(model, '__js_require__') or isinstance(model, dict)): continue if isinstance(model, dict): model_require = model else: model_require = dict(model.__js_require__) model_exports = model_require.pop('exports', {}) if not any(model_require == config for config in configs): configs.append(model_require) for req in list(model_require.get('paths', [])): if isinstance(req, tuple): model_require['paths'] = dict(model_require['paths']) model_require['paths'][req[0]] = model_require['paths'].pop(req) reqs = req[1] if isinstance(req, tuple) else (req,) for r in reqs: if r not in requirements: requirements.append(r) if r in model_exports: exports[r] = model_exports[r] return configs, requirements, exports, skip_import
def get_pane_type(cls, obj): if isinstance(obj, Viewable): return type(obj) descendents = [(p.precedence, p) for p in param.concrete_descendents(PaneBase).values()] pane_types = reversed(sorted(descendents, key=lambda x: x[0])) for _, pane_type in pane_types: if not pane_type.applies(obj): continue return pane_type raise TypeError('%s type could not be rendered.' % type(obj).__name__)
def _get_type(cls, source_type): try: __import__(f'lumen.sources.{source_type}') except Exception: pass for source in param.concrete_descendents(cls).values(): if source.source_type == source_type: return source raise ValueError( f"No Source for source_type '{source_type}' could be found.")
def test_empty_element_constructor(self): failed_elements = [] for name, el in param.concrete_descendents(Element).items(): if issubclass(el, (Annotation, BaseShape, Div, Tiles)): continue try: el([]) except: failed_elements.append(name) self.assertEqual(failed_elements, [])
def test_empty_element_constructor(self): failed_elements = [] for name, el in param.concrete_descendents(Element).items(): if issubclass(el, (Annotation, BaseShape, Div, Tiles, Trisurface)): continue try: el([]) except: failed_elements.append(name) self.assertEqual(failed_elements, [])
def js_modules(self): from ..config import config from ..reactive import ReactiveHTML modules = list(config.js_modules.values()) for model in param.concrete_descendents(ReactiveHTML).values(): if hasattr(model, '__javascript_modules__'): for jsmodule in model.__javascript_modules__: if jsmodule not in modules: modules.append(jsmodule) return modules
def test_all_linked_stream_parameters_owners(): "Test to ensure operations can accept parameters in streams dictionary" stream_classes = param.concrete_descendents(LinkedStream) for stream_class in stream_classes.values(): for name, p in stream_class.param.params().items(): if name != 'name' and (p.owner != stream_class): msg = ("Linked stream %r has parameter %r which is " "inherited from %s. Parameter needs to be redeclared " "in the class definition of this linked stream.") raise Exception(msg % (stream_class, name, p.owner))
def __init__(self, **kwargs): from ..config import config from ..reactive import ReactiveHTML js_modules = list(config.js_modules.values()) for model in param.concrete_descendents(ReactiveHTML).values(): if hasattr(model, '__javascript_modules__'): for js_module in model.__javascript_modules__: if js_module not in js_modules: js_modules.append(js_module) self.js_modules = kwargs.pop("js_modules", js_modules) super().__init__(**kwargs)
def find_autolinkable(): try: import holoviews as hv import param except ImportError: print('no holoviews and/or param: skipping autolinks') return {} # Class names for auto-linking excluded_names = { 'UniformNdMapping', 'NdMapping', 'MultiDimensionalMapping', 'Empty', 'CompositeOverlay', 'Collator', 'AdjointLayout'} dimensioned = set(param.concrete_descendents(hv.core.Dimensioned).keys()) all_elements = set(param.concrete_descendents(hv.Element).keys()) all_streams = set(param.concrete_descendents(hv.streams.Stream).keys()) all_containers = set((dimensioned - all_elements) - excluded_names) return {'elements': filter_available(all_elements, 'elements'), 'streams': filter_available(all_streams, 'streams'), 'containers': filter_available(all_containers, 'containers')}
def setUp(self): self.previous_backend = Store.current_backend self.comm_manager = bokeh_renderer.comm_manager bokeh_renderer.comm_manager = comms.CommManager if not bokeh_renderer: raise SkipTest("Bokeh required to test plot instantiation") Store.current_backend = 'bokeh' self._padding = {} for plot in concrete_descendents(ElementPlot).values(): self._padding[plot] = plot.padding plot.padding = 0
def setUp(self): self.previous_backend = Store.current_backend self.comm_manager = mpl_renderer.comm_manager mpl_renderer.comm_manager = comms.CommManager if not mpl_renderer: raise SkipTest("Matplotlib required to test plot instantiation") Store.set_current_backend('matplotlib') self._padding = {} for plot in concrete_descendents(ElementPlot).values(): self._padding[plot] = plot.padding plot.padding = 0
def _get_type(cls, transform_type): if '.' in transform_type: return resolve_module_reference(transform_type, Transform) try: __import__(f'lumen.transforms.{transform_type}') except Exception: pass for transform in param.concrete_descendents(cls).values(): if transform.transform_type == transform_type: return transform raise ValueError(f"No Transform for transform_type '{transform_type}' could be found.")
def _load_local_modules(self): for imp in ('filters', 'sources', 'transforms', 'template', 'views'): path = os.path.join(self._root, imp + '.py') if not os.path.isfile(path): continue spec = importlib.util.spec_from_file_location( f"local_lumen.{imp}", path) self._modules[imp] = module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) templates = param.concrete_descendents(BasicTemplate) _TEMPLATES.update({k[:-8].lower(): v for k, v in templates.items()})
def __new__(mcs, name, bases, dict_): def add_test(p): def test(self): # instantiate parameter with no default (but supply # any required args) p(*positional_args.get(p,tuple())) return test for p_name, p_type in concrete_descendents(Parameter).items(): dict_["test_default_of_%s"%p_name] = add_test(p_type) return type.__new__(mcs, name, bases, dict_)
def __init__(self, **params): super(StepTransform, self).__init__(**params) self.transformTypeParametersDynamicWidgetsSelector = self.transform_type = self.previousTransformType = None self.param['transformTypeSelector'].objects = [ transform for transform in param.concrete_descendents(Transform).values() if transform in transformTypeSupported ] self.param['transformTypeSelector'].default = self.param[ 'transformTypeSelector'].objects[0] self.dashboard = Dashboard( specification= r'specYamlFile/default/nouveau_dashboard_default_config.yml')
def extra_resources(self, resources, resource_type): """ Adds resources for ReactiveHTML components. """ from ..reactive import ReactiveHTML for model in param.concrete_descendents(ReactiveHTML).values(): if not (getattr(model, resource_type, None) and model._loaded()): continue for resource in getattr(model, resource_type, []): if not isurl(resource) and not resource.startswith( 'static/extensions'): resource = component_resource_path(model, resource_type, resource) if resource not in resources: resources.append(resource)
def _get_type(cls, view_type): """ Returns the matching View type. """ if '.' in view_type: return resolve_module_reference(view_type, View) try: __import__(f'lumen.views.{view_type}') except Exception: pass for view in param.concrete_descendents(cls).values(): if view.view_type == view_type: return view if view_type is not None: raise ValueError(f"View type '{view_type}' could not be found.") return View
def __new__(mcs, name, bases, dict_): def test_skip(*args,**kw): from nose.exc import SkipTest raise SkipTest def add_test(p): def test(self): # instantiate parameter with no default (but supply # any required args) p(*positional_args.get(p,tuple())) return test for p_name, p_type in concrete_descendents(Parameter).items(): dict_["test_default_of_%s"%p_name] = add_test(p_type) if p_name not in skip else test_skip return type.__new__(mcs, name, bases, dict_)
def js_files(self): from ..config import config from ..reactive import ReactiveHTML files = super(Resources, self).js_files for model in param.concrete_descendents(ReactiveHTML).values(): if hasattr(model, '__javascript__'): for jsfile in model.__javascript__: if jsfile not in files: files.append(jsfile) js_files = [] for js_file in files: if (js_file.startswith(state.base_url) or js_file.startswith('static/')): if js_file.startswith(state.base_url): js_file = js_file[len(state.base_url):] if state.rel_path: js_file = f'{state.rel_path}/{js_file}' js_files.append(js_file) js_files += list(config.js_files.values()) # Load requirejs last to avoid interfering with other libraries require_index = [ i for i, jsf in enumerate(js_files) if 'require' in jsf ] if self.mode == 'server': if state.rel_path: dist_dir = f'{state.rel_path}/{LOCAL_DIST}' else: dist_dir = LOCAL_DIST else: dist_dir = CDN_DIST if require_index: requirejs = js_files.pop(require_index[0]) if any('ace' in jsf for jsf in js_files): js_files.append(dist_dir + 'pre_require.js') js_files.append(requirejs) if any('ace' in jsf for jsf in js_files): js_files.append(dist_dir + 'post_require.js') return js_files
def get_pane_type(cls, obj): if isinstance(obj, Viewable): return type(obj) descendents = [] for p in param.concrete_descendents(PaneBase).values(): precedence = p.applies( obj) if p.precedence is None else p.precedence if isinstance(precedence, bool) and precedence: raise ValueError('If a Pane declares no precedence ' 'the applies method should return a ' 'precedence value specific to the ' 'object type or False, but the %s pane ' 'declares no precedence.' % p.__name__) elif precedence is None or precedence is False: continue descendents.append((precedence, p)) pane_types = reversed(sorted(descendents, key=lambda x: x[0])) for _, pane_type in pane_types: applies = pane_type.applies(obj) if isinstance(applies, bool) and not applies: continue return pane_type raise TypeError('%s type could not be rendered.' % type(obj).__name__)
def bundle_resources(): from .config import panel_extension from .template.base import BasicTemplate from .template.theme import Theme for imp in panel_extension._imports.values(): if imp.startswith('panel.'): __import__(imp) bundle_dir = pathlib.Path(__file__).parent.joinpath('dist', 'bundled') js_files = {} css_files = {} for name, model in Model.model_class_reverse_map.items(): if not name.startswith('panel.'): continue prev_jsfiles = getattr(model, '__javascript_raw__', None) prev_jsbundle = getattr(model, '__tarball__', None) prev_cls = model for cls in model.__mro__[1:]: jsfiles = getattr(cls, '__javascript_raw__', None) if ((jsfiles is None and prev_jsfiles is not None) or (jsfiles is not None and jsfiles != prev_jsfiles)): if prev_jsbundle: js_files[prev_cls.__name__] = prev_jsbundle else: js_files[prev_cls.__name__] = prev_jsfiles break prev_cls = cls prev_cssfiles = getattr(model, '__css_raw__', None) prev_cls = model for cls in model.__mro__[1:]: cssfiles = getattr(cls, '__css_raw__', None) if ((cssfiles is None and prev_cssfiles is not None) or (cssfiles is not None and cssfiles != prev_cssfiles)): css_files[prev_cls.__name__] = prev_cssfiles break prev_cls = cls for name, jsfiles in js_files.items(): if isinstance(jsfiles, dict): write_bundled_tarball(name, jsfiles, bundle_dir) else: write_bundled_files(name, jsfiles, bundle_dir) for name, cssfiles in css_files.items(): write_bundled_files(name, cssfiles, bundle_dir) # Bundle external template dependencies for name, template in param.concrete_descendents(BasicTemplate).items(): if template._resources.get('bundle', True): write_bundled_files( name, list(template._resources.get('css', {}).values()), bundle_dir, 'css') write_bundled_files( name, list(template._resources.get('js', {}).values()), bundle_dir, 'js') js_modules = [] for tar_name, js_module in template._resources.get( 'js_modules', {}).items(): if tar_name not in template._resources.get('tarball', {}): js_modules.append(js_module) write_bundled_files(name, js_modules, bundle_dir, 'js', ext='mjs') for tarball in template._resources.get('tarball', {}).values(): write_bundled_tarball('js', tarball, bundle_dir, module=True) template_dir = pathlib.Path(inspect.getfile(template)).parent dest_dir = bundle_dir / name.lower() dest_dir.mkdir(parents=True, exist_ok=True) for css in glob.glob(str(template_dir / '*.css')): shutil.copyfile(css, dest_dir / os.path.basename(css)) template_css = template._css if not isinstance(template_css, list): template_css = [template_css] if template_css else [] for css in template_css: tmpl_name = name for cls in template.__mro__[2:-5]: tmpl_css = cls._css if isinstance(cls._css, list) else [cls._css] if css in tmpl_css: tmpl_name = cls.__name__.lower() tmpl_dest_dir = bundle_dir / tmpl_name tmpl_dest_dir.mkdir(parents=True, exist_ok=True) shutil.copyfile(css, tmpl_dest_dir / os.path.basename(css)) if template._js: shutil.copyfile(template._js, dest_dir / os.path.basename(template._js)) # Bundle base themes dest_dir = bundle_dir / 'theme' theme_dir = pathlib.Path(inspect.getfile(Theme)).parent dest_dir.mkdir(parents=True, exist_ok=True) for css in glob.glob(str(theme_dir / '*.css')): shutil.copyfile(css, dest_dir / os.path.basename(css)) # Bundle Theme classes for name, theme in param.concrete_descendents(Theme).items(): if theme.base_css: theme_bundle_dir = bundle_dir / theme.param.base_css.owner.__name__.lower( ) theme_bundle_dir.mkdir(parents=True, exist_ok=True) shutil.copyfile( theme.base_css, theme_bundle_dir / os.path.basename(theme.base_css)) if theme.css: tmplt_bundle_dir = bundle_dir / theme._template.__name__.lower() tmplt_bundle_dir.mkdir(parents=True, exist_ok=True) shutil.copyfile(theme.css, tmplt_bundle_dir / os.path.basename(theme.css))
assert len(widget._models) == 2 assert len(row._models) == 2 assert len(row[0]._models) == 2 assert len(row[1]._models) == 2 for cb in document.session_destroyed_callbacks: cb(session_context) assert len(widget._models) == 0 assert len(row._models) == 0 assert len(row[0]._models) == 0 assert len(row[1]._models) == 0 list_templates = [ t for t in param.concrete_descendents(BasicTemplate).values() if not issubclass(t, ReactTemplate) ] @latest_param @pytest.mark.parametrize('template', list_templates) def test_basic_template(template, document, comm): tmplt = template(title='BasicTemplate', header_background='blue', header_color='red') tmplt._update_vars() tvars = tmplt._render_variables assert tvars['app_title'] == 'BasicTemplate' assert tvars['header_background'] == 'blue' assert tvars['header_color'] == 'red' assert tvars['nav'] == False
import param import numpy as np from bokeh.layouts import Column from bokeh.models import Div as BkDiv, Slider as BkSlider from panel.io import block_comm from panel.models.widgets import Player as BkPlayer, FileInput as BkFileInput from panel.widgets import (TextInput, StaticText, FloatSlider, IntSlider, RangeSlider, LiteralInput, Checkbox, Select, MultiSelect, Button, Toggle, DatePicker, DateRangeSlider, DiscreteSlider, DatetimeInput, CrossSelector, DiscretePlayer, ToggleGroup, FileInput, Widget, CompositeWidget) all_widgets = [ w for w in param.concrete_descendents(Widget).values() if not w.__name__.startswith('_') and not issubclass(w, CompositeWidget) ] @pytest.mark.parametrize('widget', all_widgets) def test_widget_disabled_properties(widget, document, comm): w = widget(disabled=True) model = w._get_root(document, comm) assert model.disabled == True model.disabled = False assert model.disabled == False
def __setitem__(self, key, val): raise NotImplementedError("Models must define properties via the property_setup method") def keys(self): "The list of available property keys." return self.properties.keys() def items(self): "The property items." return self.properties.items() # Register the sheets and projections available in Topographica def register_submodel_decorators(classes,superclass=None): """ Register a Model decorator for each of the non-abstract classes provided. Only registers those that are subclasses of the given superclass, if specified. """ with param.logging_level('CRITICAL'): for c in classes: if (isinstance(c, type) and (superclass==None or issubclass(c, superclass)) and (not hasattr(c, "_%s__abstract" % c.name))): Model.register_decorator(c) register_submodel_decorators(param.concrete_descendents(topo.sheet.Sheet).values()) register_submodel_decorators(param.concrete_descendents(topo.projection.Projection).values())