コード例 #1
0
ファイル: test_themes.py プロジェクト: brianpanneton/bokeh
 def test_construct_empty_theme_from_file(self):
     with (tempfile.NamedTemporaryFile()) as file:
         # create and apply empty theme with no exception thrown
         file.file.write("".encode('utf-8'))
         file.file.flush()
         theme = Theme(filename=file.name)
         theme.apply_to_model(ThemedModel())
コード例 #2
0
ファイル: test_themes.py プロジェクト: Apple3124/bokeh
 def test_construct_empty_theme_from_file(self):
     # windows will throw permissions error with auto-delete
     with (tempfile.NamedTemporaryFile(delete=False)) as file:
         # create and apply empty theme with no exception thrown
         file.file.write("".encode('utf-8'))
         file.file.flush()
         theme = Theme(filename=file.name)
         theme.apply_to_model(ThemedModel())
     file.close()
     os.remove(file.name)
コード例 #3
0
ファイル: test_themes.py プロジェクト: Apple3124/bokeh
 def test_construct_nonempty_theme_from_file(self):
     # windows will throw permissions error with auto-delete
     with (tempfile.NamedTemporaryFile(delete=False)) as file:
         # create and apply empty theme with no exception thrown
         file.file.write(FILE_CONTENTS)
         file.file.flush()
         theme = Theme(filename=file.name)
         self.assertDictEqual(dict(number=57), theme._for_class(ThemedModel))
         self.assertDictEqual(dict(number=57, another_string="boo"), theme._for_class(SubOfThemedModel))
     file.close()
     os.remove(file.name)
コード例 #4
0
ファイル: test_themes.py プロジェクト: brianpanneton/bokeh
    def test_construct_nonempty_theme_from_file(self):
        with (tempfile.NamedTemporaryFile()) as file:
            # create and apply empty theme with no exception thrown
            file.file.write("""
attrs:
    ThemedModel:
        number: 57
    SubOfThemedModel:
        another_string: "boo"
            """.encode('utf-8'))
            file.file.flush()
            theme = Theme(filename=file.name)
            self.assertDictEqual(dict(number=57), theme._for_class(ThemedModel))
            self.assertDictEqual(dict(number=57, another_string="boo"), theme._for_class(SubOfThemedModel))
コード例 #5
0
ファイル: test_themes.py プロジェクト: digitalsatori/Bokeh
 def test_theming_a_model(self):
     theme = Theme(json={
         'attrs' : {
             'ThemedModel' : {
                 'string' : 'w00t'
             }
         }
     })
     obj = ThemedModel()
     changes = dict(calls=[])
     assert 'hello' == obj.string
     def record_trigger(attr, old, new_):
         changes['calls'].append((attr, old, new_))
     obj.on_change('string', record_trigger)
     theme.apply_to_model(obj)
     assert 'w00t' == obj.string
     assert [('string', 'hello', 'w00t')] == changes['calls']
コード例 #6
0
ファイル: test_themes.py プロジェクト: Apple3124/bokeh
 def test_theming_a_model_via_base(self):
     theme = Theme(json={
         'attrs' : {
             'ThemedModel' : {
                 'string' : 'w00t'
             }
         }
     })
     obj = SubOfThemedModel()
     changes = dict(calls=[])
     def record_trigger(attr, old, new_):
         changes['calls'].append((attr, old, new_))
     obj.on_change('string', record_trigger)
     self.assertEqual('hello', obj.string)
     theme.apply_to_model(obj)
     self.assertEqual('w00t', obj.string)
     self.assertEqual([('string', 'hello', 'w00t')], changes['calls'])
コード例 #7
0
ファイル: test_themes.py プロジェクト: Apple3124/bokeh
 def test_subclass_theme_used_rather_than_base(self):
     theme = Theme(json={
         'attrs' : {
             'ThemedModel' : {
                 'string' : 'w00t'
             },
             'SubOfThemedModel' : {
                 'string' : 'bar'
             }
         }
     })
     obj = SubOfThemedModel()
     self.assertEqual('hello', obj.string)
     changes = dict(calls=[])
     def record_trigger(attr, old, new_):
         changes['calls'].append((attr, old, new_))
     obj.on_change('string', record_trigger)
     theme.apply_to_model(obj)
     self.assertEqual('bar', obj.string)
     self.assertEqual([('string', 'hello', 'bar')], changes['calls'])
コード例 #8
0
 def test_list_of_models_different_docs(self):
     # should use new temp doc for eveything inside with-block
     d = Document()
     orig_theme = d.theme
     p1 = Model()
     p2 = Model()
     d.add_root(p2)
     assert p1.document is None
     assert p2.document is not None
     with beu.OutputDocumentFor([p1, p2], apply_theme=Theme(json={})):
         assert p1.document is not None
         assert p2.document is not None
         assert p1.document is not d
         assert p2.document is not d
         assert p1.document == p2.document
         assert p1.document.theme is not orig_theme
     assert p1.document is None
     assert p2.document is not None
     assert p2.document.theme is orig_theme
コード例 #9
0
ファイル: test_themes.py プロジェクト: oviquezr/bokeh
    def test_setting_document_theme_to_none(self) -> None:
        theme = Theme(json={'attrs': {'ThemedModel': {'string': 'w00t'}}})
        obj = ThemedModel()
        doc = Document()
        doc.add_root(obj)
        changes = dict(calls=[])

        def record_trigger(attr, old, new_):
            changes['calls'].append((attr, old, new_))

        obj.on_change('string', record_trigger)
        doc.theme = theme
        assert 'w00t' == obj.string
        # setting to None reverts to default theme
        doc.theme = None
        assert doc.theme is not None
        assert 'hello' == obj.string
        assert [('string', 'hello', 'w00t'),
                ('string', 'w00t', 'hello')] == changes['calls']
コード例 #10
0
ファイル: test_themes.py プロジェクト: oviquezr/bokeh
    def test_theming_a_document_before_adding_root(self) -> None:
        theme = Theme(json={'attrs': {'ThemedModel': {'string': 'w00t'}}})
        obj = ThemedModel()
        doc = Document()
        assert 'hello' == obj.string
        doc.theme = theme
        assert doc.theme is theme
        changes = dict(calls=[])

        def record_trigger(attr, old, new_):
            changes['calls'].append((attr, old, new_))

        obj.on_change('string', record_trigger)
        doc.add_root(obj)
        assert 'w00t' == obj.string
        doc.remove_root(obj)
        assert 'hello' == obj.string
        assert [('string', 'hello', 'w00t'),
                ('string', 'w00t', 'hello')] == changes['calls']
コード例 #11
0
    def test_setting_document_theme_to_none(self):
        theme = Theme(json={'attrs': {'ThemedModel': {'string': 'w00t'}}})
        obj = ThemedModel()
        doc = Document()
        doc.add_root(obj)
        changes = dict(calls=[])

        def record_trigger(attr, old, new_):
            changes['calls'].append((attr, old, new_))

        obj.on_change('string', record_trigger)
        doc.theme = theme
        self.assertEqual('w00t', obj.string)
        # setting to None reverts to default theme
        doc.theme = None
        self.assertIsNot(doc.theme, None)
        self.assertEqual('hello', obj.string)
        self.assertEqual([('string', 'hello', 'w00t'),
                          ('string', 'w00t', 'hello')], changes['calls'])
コード例 #12
0
    def test_theming_a_document_before_adding_root(self):
        theme = Theme(json={'attrs': {'ThemedModel': {'string': 'w00t'}}})
        obj = ThemedModel()
        doc = Document()
        self.assertEqual('hello', obj.string)
        doc.theme = theme
        self.assertIs(doc.theme, theme)
        changes = dict(calls=[])

        def record_trigger(attr, old, new_):
            changes['calls'].append((attr, old, new_))

        obj.on_change('string', record_trigger)
        doc.add_root(obj)
        self.assertEqual('w00t', obj.string)
        doc.remove_root(obj)
        self.assertEqual('hello', obj.string)
        self.assertEqual([('string', 'hello', 'w00t'),
                          ('string', 'w00t', 'hello')], changes['calls'])
コード例 #13
0
    def simple_plot(self, countries=['Germany', 'Austria', 'Italy']):
        if type(countries) != list:
            raise TypeError('countries argument accepts type list, '
                            f'got {type(countries)} instead')

        confirmed = self.confirmed_df.loc[:, (countries, slice(None),
                                              slice(None), slice(None))]

        confirmed.columns = (
            confirmed.columns.droplevel(3).droplevel(2).droplevel(1))

        pandas_bokeh.output_file(os.path.join('figures', 'simple_plot.html'))
        curdoc().theme = Theme(json=jt)
        confirmed.plot_bokeh.line(figsize=(1500, 750),
                                  title="simple plot",
                                  plot_data_points=True,
                                  plot_data_points_size=5,
                                  marker="circle",
                                  sizing_mode='scale_both')
コード例 #14
0
def modify_doc(doc):
    data_url = "http://www.neracoos.org/erddap/tabledap/B01_sbe37_all.csvp?time,temperature&depth=1&temperature_qc=0&time>=2016-02-15&time<=2017-03-22"
    df = pd.read_csv(data_url, parse_dates=True, index_col=0)
    df = df.rename(columns={'temperature (celsius)': 'temperature'})
    df.index.name = 'time'

    source = ColumnDataSource(data=df)

    plot = figure(x_axis_type='datetime',
                  y_range=(0, 25),
                  y_axis_label='Temperature (Celsius)',
                  title="Sea Surface Temperature at 43.18, -70.43")
    plot.line('time', 'temperature', source=source)

    def callback(attr, old, new):
        if new == 0:
            data = df
        else:
            data = df.rolling('{0}D'.format(new)).mean()
        source.data = ColumnDataSource(data=data).data

    slider = Slider(start=0,
                    end=30,
                    value=0,
                    step=1,
                    title="Smoothing by N Days")
    slider.on_change('value', callback)

    doc.add_root(column(slider, plot))

    doc.theme = Theme(json=yaml.load("""
        attrs:
            Figure:
                background_fill_color: "#DDDDDD"
                outline_line_color: white
                toolbar_location: above
                height: 500
                width: 800
            Grid:
                grid_line_dash: [6, 4]
                grid_line_color: white
    """))
コード例 #15
0
    def setup_doc(doc):
        # 1: In order to retrieve the directory of the html file, the templates directory must first be loaded into the
        #    Environment.
        # 2: Load the dataspot HTML into template
        # 3: Attach the template to the working doc
        # 4: Load the styling file of the Bokeh visualization, also located in templates
        # 5: Attach the styling to the working doc
        root = os.path.abspath(os.sep)
        templates_path = os.path.join(root, 'app/templates')
        theme_path = os.path.join(root, 'app/templates/theme.yml')

        env = Environment(loader=FileSystemLoader(templates_path))
        template = env.get_template('dataspot.html')
        doc.template = template
        doc.title = 'Dataspot'

        theme_template = Theme(theme_path)
        doc.theme = theme_template

        return doc
コード例 #16
0
def bkapp(curdoc):
    import time
    time.sleep(5)

    df = sea_surface_temperature.copy()
    source = ColumnDataSource(data=df)

    plot = figure(x_axis_type='datetime', y_range=(0, 25), y_axis_label='Temperature (Celsius)',
                  title="Sea Surface Temperature at 43.18, -70.43")
    plot.line('time', 'temperature', source=source)

    def callback(attr, old, new):
        if new == 0:
            data = df
        else:
            data = df.rolling('{0}D'.format(new)).mean()
        source.data = data
    plot.sizing_mode = "stretch_both"

    slider = Slider(start=0, end=30, value=0, step=1, title="Smoothing by N Days")
    slider.on_change('value', callback)

    paragraph = Paragraph(text="IOloop's id: %s" % str(id(bokeh_server.io_loop.asyncio_loop)))

    row = pn.Row(slider, plot, name="chart_1")
    row.sizing_mode = "stretch_both"
    row.server_doc(curdoc)

    other_figure = figure(title="Jajaja")
    other_figure.scatter(x=[1,2,3], y=[4,5,6])
    other_figure.sizing_mode = "stretch_both"
    pn.Pane(other_figure, name="chart_2").server_doc(curdoc)

    curdoc.theme = Theme(filename="theme.yaml")

    # Options for Jinja template rendered by the Bokeh Server
    # (as opposed of by Starlette):
    curdoc.template = (Environment(loader=FileSystemLoader(searchpath="templates"))
                       .get_template("index.html")
                       )
    curdoc.template_variables["rendered_by_bokeh_server"] = True
コード例 #17
0
def get_plot(doc):
    """Get the plots and set up the layout.
    :param doc: document we will output.
    :type doc: Document
    """
    id_run, data_type = parse_arguments()

    data = pd.read_csv(f'../output/{id_run}/VISUALISATION/{data_type}.csv',
                       index_col=0)
    res = pd.read_csv(f'../output/{id_run}/VISUALISATION/res.csv', index_col=0)

    try:
        smear_plot = SmearPlot(res)
        tab1 = smear_plot.get_tabs()
    except:
        tab1 = ErrorPlot().get_tabs()

    try:
        pca_plot = PCAPlot(data)
        tab2 = pca_plot.get_tabs()
    except:
        tab2 = ErrorPlot().get_tabs()

    try:
        volcano_plot = VolcanoPlot(res)
        tab3 = volcano_plot.get_tabs()
    except:
        tab3 = ErrorPlot().get_tabs()

    try:
        heatmap_plot = HeatmapPlot(
            count_matrix=data,
            deseq_results=res,
        )
        tab4 = heatmap_plot.get_tabs()
    except:
        tab4 = ErrorPlot().get_tabs()

    doc.theme = Theme('../src/visualisations/theme.yaml')
    doc.add_root(Tabs(tabs=[tab1, tab2, tab3, tab4]))
    doc.title = "DRAW report"
コード例 #18
0
def bkapp(doc):
    df = sea_surface_temperature.copy()
    source = ColumnDataSource(data=df)

    plot = figure(x_axis_type='datetime', y_range=(0, 25), y_axis_label='Temperature (Celsius)',
                  title="Sea Surface Temperature at 43.18, -70.43")
    plot.line('time', 'temperature', source=source)

    def callback(attr, old, new):
        if new == 0:
            data = df
        else:
            data = df.rolling('{0}D'.format(new)).mean()
        source.data = ColumnDataSource.from_df(data)

    slider = Slider(start=0, end=30, value=0, step=1, title="Smoothing by N Days")
    slider.on_change('value', callback)

    doc.add_root(column(slider, plot))

    doc.theme = Theme(filename="theme.yaml")
コード例 #19
0
def modify_doc(doc):
    df = sea_surface_temperature.copy()
    source = ColumnDataSource(data=df)

    plot = figure(x_axis_type='datetime', y_range=(0, 25), y_axis_label='Temperature (Celsius)',
                  title="Sea Surface Temperature at 43.18, -70.43")
    plot.line('time', 'temperature', source=source)

    #def callback(attr, old, new):
    #    if new == 0:
    #        data = df
    #    else:
    #        data = df.rolling('{0}D'.format(new)).mean()
    #    source.data = ColumnDataSource(data=data).data

    #slider = Slider(start=0, end=30, value=0, step=1, title="Smoothing by N Days")
    #slider.on_change('value', callback)

    doc.add_root(column(plot))

    doc.theme = Theme(filename='D:/InstrPlatform/DataStation/src/TestScripts/theme.yaml')
コード例 #20
0
ファイル: directory.py プロジェクト: zlxs23/bokeh
    def __init__(self, *args, **kwargs):
        super(DirectoryHandler, self).__init__(*args, **kwargs)

        if 'filename' not in kwargs:
            raise ValueError('Must pass a filename to DirectoryHandler')
        src_path = kwargs['filename']
        argv = kwargs.get('argv', [])

        main_py = join(src_path, 'main.py')
        main_ipy = join(src_path, 'main.ipynb')
        if exists(main_py) and exists(main_ipy):
            log.warn(
                "Found both 'main.py' and 'main.ipynb' in %s, using 'main.py'"
                % (src_path))
            main = main_py
        elif exists(main_py):
            main = main_py
        elif exists(main_ipy):
            main = main_ipy
        else:
            raise ValueError("No 'main.py' or 'main.ipynb' in %s" % (src_path))
        self._path = src_path
        self._main = main
        self._main_handler = ScriptHandler(filename=self._main, argv=argv)

        lifecycle = join(src_path, 'server_lifecycle.py')
        if exists(lifecycle):
            self._lifecycle = lifecycle
            self._lifecycle_handler = ServerLifecycleHandler(
                filename=self._lifecycle, argv=argv)
        else:
            self._lifecycle = None
            self._lifecycle_handler = Handler()  # no-op handler

        self._theme = None
        themeyaml = join(src_path, 'theme.yaml')
        if exists(themeyaml):
            from bokeh.themes import Theme
            self._theme = Theme(filename=themeyaml)
コード例 #21
0
def modify_doc(doc):
    """Renders the initial webpage"""
    # Create Input controls
    topic_options = [
        "topic_{0}".format(x) for x in data.list_known_jsonschemas()
    ]
    proto_options = [
        "protobuf_{0}".format(x) for x in data.list_known_protobufs()
    ]
    modelselec = Select(title="Model Selection",
                        value=DEFAULT_UNSELECTED,
                        options=topic_options + proto_options +
                        [DEFAULT_UNSELECTED],
                        name=MODEL_SELECTION)

    # Add a handler for input changes
    modelselec.on_change('value', lambda attr, old, new: modelselec_change())

    # construct what the user will see
    selec = widgetbox([modelselec])
    doc.add_root(selec)
    doc.theme = Theme(filename="theme.yaml")
コード例 #22
0
def modify_doc(doc):
    with open('batch_size.pickle', 'rb') as handle:
        project_dict = pickle.load(handle)

    data = project_dict['rollbar-gem'][0.1]
    source = ColumnDataSource(data)

    plot = figure(x_axis_type='linear',
                  y_range=(-200, 200),
                  y_axis_label='Improvement (%)',
                  x_axis_label='Batch Size')
    plot.line('x', 'y', source=source)

    def callback(attr, old, new):
        global project_name

        if attr == 'active':
            data = project_dict[project_name_dict[new]][0.1]
            project_name = project_name_dict[new]

        else:
            data = project_dict[project_name][new]

        source.data = ColumnDataSource(data=data).data

    slider = Slider(start=0.1,
                    end=1,
                    value=0.1,
                    step=0.01,
                    title="Risk Threshold")
    slider.on_change('value', callback)

    radio_button_group = RadioButtonGroup(labels=project_list, active=0)

    radio_button_group.on_change('active', callback)

    doc.add_root(column(radio_button_group, slider, plot))

    doc.theme = Theme(filename="../theme.yaml")
コード例 #23
0
def modify_doc(doc):
    df = sea_surface_temperature.copy()
    source = ColumnDataSource(data=df)

    plot = figure(x_axis_type='datetime',
                  y_range=(0, 25),
                  y_axis_label='Temperature (Celsius)',
                  title="Sea Surface Temperature at 43.18, -70.43")
    plot.line('time', 'temperature', source=source)

    def callback(attr, old, new):
        if new == 0:
            data = df
        else:
            data = df.rolling('{0}D'.format(new)).mean()
        source.data = ColumnDataSource(data=data).data

    slider = Slider(start=0,
                    end=30,
                    value=0,
                    step=1,
                    title="Smoothing by N Days")
    slider.on_change('value', callback)

    doc.add_root(column(slider, plot))

    doc.theme = Theme(json=yaml.load("""
        attrs:
            Figure:
                background_fill_color: "#DDDDDD"
                outline_line_color: white
                toolbar_location: above
                height: 500
                width: 800
            Grid:
                grid_line_dash: [6, 4]
                grid_line_color: white
    """))
コード例 #24
0
def modify_doc(doc):

    #    doc = curdoc()

    source = ColumnDataSource(data=dict(time=[0], temperature=[0]))

    plot = figure(x_axis_type='datetime',
                  y_range=(0, 25),
                  y_axis_label='Temperature (Celsius)',
                  title="Sea Surface Temperature at 43.18, -70.43")
    plot.line('time', 'temperature', source=source)

    doc.add_root(column(plot, ))

    doc.theme = Theme(filename="theme.yaml")

    print "updating:"

    def updateit():
        data = recieve_broadcast()
        source.data = ColumnDataSource(data=data).data

    doc.add_periodic_callback(updateit, 1000)
コード例 #25
0
def bkapp_table(doc):
    """Create a Table App

    Arguments:
        doc {Document} -- bokeh document

    Returns:
        Document -- updated bokeh document
    """
    data = sea_surface_temperature.copy()
    data.reset_index(inplace=True)
    source = ColumnDataSource(data=data)

    columns = [
        TableColumn(field='time', title='Time', formatter=DateFormatter(format='yy-mm-dd')),
        TableColumn(field='temperature', title='Temperature')
    ]

    data_table = DataTable(source=source, columns=columns, width=400,
                           selectable='checkbox', index_position=None)

    doc.theme = Theme(filename=os.path.join(cwd(), 'theme.yaml'))
    return doc.add_root(data_table)
コード例 #26
0
    def rate_plot(self, countries=None):
        total_df = self.calc_totals(countries)

        plot_df = pd.DataFrame()

        plot_df['confirmed'] = total_df.confirmed.diff()
        plot_df['confirmed_mean'] = plot_df['confirmed'].rolling(
            7, center=True, min_periods=3).mean()
        plot_df['deaths'] = total_df.deaths.diff().clip(lower=0)
        plot_df['deaths_mean'] = plot_df['deaths'].rolling(
            7, center=True, min_periods=3).mean()
        plot_df['recovered'] = total_df.recovered.diff().clip(lower=0)
        plot_df['recovered_mean'] = plot_df['recovered'].rolling(
            7, center=True, min_periods=3).mean()

        c_string = self.countries_to_string(countries)

        pandas_bokeh.output_file(os.path.join('figures', 'rate.html'))
        curdoc().theme = Theme(json=jt)
        plot_df.plot_bokeh.line(
            figsize=(1500, 750),
            title=f'{c_string} daily COVID-19 cases' + self.data_disclaimer,
            ylabel='Number of newly affected individuals per day',
            sizing_mode='scale_both')
コード例 #27
0
 def test_construct_bad_attrs(self):
     with pytest.raises(ValueError) as exc:
         Theme(json=dict(attrs=42))
     assert "should be a dictionary of class names" in repr(exc.value)
コード例 #28
0
 def test_construct_json_and_filename(self):
     with pytest.raises(ValueError) as exc:
         # we check "" and {} as falsey values, to try to trick
         # our code into thinking they weren't provided.
         Theme(filename="", json={})
     assert "not both" in repr(exc.value)
コード例 #29
0
 def test_construct_no_json_or_filename(self):
     with pytest.raises(ValueError) as exc:
         Theme()
     assert "requires json or a filename" in repr(exc.value)
コード例 #30
0
 def test_construct_empty_theme_from_json(self):
     # create and apply empty theme with no exception thrown
     theme = Theme(json=dict())
     theme.apply_to_model(ThemedModel())
コード例 #31
0
ファイル: worker.py プロジェクト: prasunanand/distributed
from distributed.metrics import time
from distributed.utils import log_errors, key_split, format_time

logger = logging.getLogger(__name__)

with open(
        os.path.join(os.path.dirname(__file__), "..", "templates",
                     "base.html")) as f:
    template_source = f.read()

from jinja2 import Environment, FileSystemLoader

env = Environment(loader=FileSystemLoader(
    os.path.join(os.path.dirname(__file__), "..", "templates")))

BOKEH_THEME = Theme(os.path.join(os.path.dirname(__file__), "..",
                                 "theme.yaml"))

template_variables = {"pages": ["status", "system", "profile", "crossfilter"]}


class StateTable(DashboardComponent):
    """ Currently running tasks """
    def __init__(self, worker):
        self.worker = worker

        names = [
            "Stored", "Executing", "Ready", "Waiting", "Connections", "Serving"
        ]
        self.source = ColumnDataSource({name: [] for name in names})

        columns = {name: TableColumn(field=name, title=name) for name in names}
コード例 #32
0
ファイル: directory.py プロジェクト: zebulon2/bokeh
    def __init__(self, *, filename: PathLike, argv: List[str] = []) -> None:
        '''
        Keywords:
            filename (str) : a path to an application directory with either "main.py" or "main.ipynb"

            argv (list[str], optional) : a list of string arguments to make available as sys.argv to main.py
        '''
        super().__init__()

        src_path = filename

        init_py = join(src_path, '__init__.py')
        if exists(init_py):
            self._package_runner = CodeRunner(
                open(init_py).read(), init_py, argv)
            self._package = self._package_runner.new_module()
            assert self._package is not None
            sys.modules[self._package.__name__] = self._package
        else:
            self._package_runner = None
            self._package = None

        main_py = join(src_path, 'main.py')
        main_ipy = join(src_path, 'main.ipynb')
        if exists(main_py) and exists(main_ipy):
            log.warning(
                f"Found both 'main.py' and 'main.ipynb' in {src_path}, using 'main.py'"
            )
            main = main_py
        elif exists(main_py):
            main = main_py
        elif exists(main_ipy):
            main = main_ipy
        else:
            raise ValueError(f"No 'main.py' or 'main.ipynb' in {src_path}")
        self._path = src_path
        self._main = main

        handler = NotebookHandler if main.endswith('.ipynb') else ScriptHandler
        self._main_handler = handler(filename=self._main,
                                     argv=argv,
                                     package=self._package)

        hooks = None
        app_hooks = join(src_path, 'app_hooks.py')
        lifecycle = join(src_path, 'server_lifecycle.py')
        if exists(app_hooks) and exists(lifecycle):
            raise ValueError(
                "Directory style apps can provide either server_lifecycle.py or app_hooks.py, not both."
            )
        elif exists(lifecycle):
            hooks = lifecycle
        elif exists(app_hooks):
            hooks = app_hooks

        if hooks is not None:
            self._lifecycle_handler = ServerLifecycleHandler(
                filename=hooks, argv=argv, package=self._package)
        else:
            self._lifecycle_handler = Handler()  # no-op handler

        if exists(app_hooks):
            assert hooks is not None
            self._request_handler = ServerRequestHandler(filename=hooks,
                                                         argv=argv,
                                                         package=self._package)
        else:
            self._request_handler = Handler()  # no-op handler

        self._theme = None
        themeyaml = join(src_path, 'theme.yaml')
        if exists(themeyaml):
            from bokeh.themes import Theme
            self._theme = Theme(filename=themeyaml)

        appstatic = join(src_path, 'static')
        if exists(appstatic):
            self._static = appstatic

        self._template = None
        appindex = join(src_path, 'templates', 'index.html')
        if exists(appindex):
            env = Environment(loader=FileSystemLoader(dirname(appindex)))
            self._template = env.get_template('index.html')
コード例 #33
0
ファイル: theme.py プロジェクト: jetilton/eda
theme = Theme(
    json={
        'attrs': {
            'Figure': {
                'background_fill_color': '#f0f0f0',
                'border_fill_color': 'white',
                'outline_line_color': 'white',
                'outline_line_width': 0,
                'outline_line_alpha': 0.0,
                'width': 1800
            },
            'Axis': {
                'axis_line_color': "white",
                'axis_label_text_color': "black",
                'axis_label_standoff': 30,
                'axis_label_text_font_size': '15pt',
                'axis_label_text_font_style': 'bold',
                'major_label_text_color': "black",
                'major_label_text_font_size': '10pt',
                'major_label_text_font_style': 'bold',
                'major_tick_line_color': "white",
                'minor_tick_line_color': "white",
                'minor_tick_line_color': "white",
            },
            'Grid': {
                'grid_line_width': 2,
                'grid_line_dash': 'solid',
                'grid_line_alpha': 1,
                'grid_line_color': 'white'
            },
            'Circle': {
                'size': 10,
            },
            'Line': {
                #'line_width': 5,
                'line_join': 'miter',
                'line_cap': 'round'
            },
            'Segment': {
                'line_width': 3
            },
            'Vbar': {
                'line_width': 10
            },
            'Title': {
                'text_color': "black",
                'text_font_size': '25pt'
            },
            'Fill': {
                'fill_color': 'orange'
            }
        }
    })
コード例 #34
0
from django.conf import settings
from django.http import HttpRequest, HttpResponse
from django.shortcuts import render

from bokeh.document import Document
from bokeh.embed import server_document
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, Slider
from bokeh.plotting import figure
from bokeh.sampledata.sea_surface_temperature import sea_surface_temperature
from bokeh.themes import Theme

from .models import SeaSurfaceTemperature

theme = Theme(filename=join(settings.THEMES_DIR, "theme.yaml"))


def sea_surface_handler(doc: Document) -> None:
    df = sea_surface_temperature.copy()
    source = ColumnDataSource(data=df)

    plot = figure(x_axis_type="datetime",
                  y_range=(0, 25),
                  y_axis_label="Temperature (Celsius)",
                  title="Sea Surface Temperature at 43.18, -70.43")
    plot.line("time", "temperature", source=source)

    def callback(attr: str, old: Any, new: Any) -> None:
        if new == 0:
            data = df
コード例 #35
0
 def test_construct_bad_class_props(self):
     with pytest.raises(ValueError) as exc:
         Theme(json=dict(attrs=dict(SomeClass=42)))
     assert "should be a dictionary of properties" in repr(exc.value)
コード例 #36
0
                       y='y',
                       width=1,
                       height=10,
                       color='crcolor',
                       source=crsource)

# set up hover tool to show color hex code and sample swatch
p2.select_one(HoverTool).tooltips = [('color',
                                      '$color[hex, rgb, swatch]:crcolor'),
                                     ('RGB levels', '@RGBs')]

# theme everything for a cleaner look
curdoc().theme = Theme(json=yaml.load("""
attrs:
    Plot:
        toolbar_location: null
    Grid:
        grid_line_color: null
    Axis:
        axis_line_color: null
        major_label_text_color: null
        major_tick_line_color: null
        minor_tick_line_color: null
"""))

layout = hplot(vform(red_slider, green_slider, blue_slider), vform(p1, p2))

output_file("color_sliders.html")

show(layout)
コード例 #37
0
 def setup_method(self):
     self.orig_theme = curdoc().theme
     curdoc().theme = Theme(json={})
コード例 #38
0
ファイル: test_themes.py プロジェクト: Apple3124/bokeh
 def test_construct_empty_theme_from_json(self):
     # create and apply empty theme with no exception thrown
     theme = Theme(json=dict())
     theme.apply_to_model(ThemedModel())