Exemplo n.º 1
0
 def test_basic(self):
     t = Theme(json={})
     d = Document()
     d._old_theme = t
     beu._unset_temp_theme(d)
     assert d.theme is t
     assert not hasattr(d, "_old_theme")
Exemplo n.º 2
0
 def test_output(self):
     p1 = Model()
     p2 = Model()
     d = Document()
     d.add_root(p1)
     d.add_root(p2)
     out = beu.standalone_docs_json([p1, p2])
     expected = beu.standalone_docs_json_and_render_items([p1, p2])[0]
     assert list(out.values()) ==list(expected.values())
Exemplo n.º 3
0
 def test_single_model_with_document(self):
     # should use existing doc in with-block
     p = Model()
     d = Document()
     orig_theme = d.theme
     d.add_root(p)
     with beu.OutputDocumentFor([p], apply_theme=beu.FromCurdoc):
         assert p.document is d
         assert d.theme is curdoc().theme
     assert p.document is d
     assert d.theme is orig_theme
Exemplo n.º 4
0
 def test_with_doc_in_child_raises_error(self):
     doc = Document()
     p1 = Model()
     p2 = SomeModelInTestObjects(child=Model())
     doc.add_root(p2.child)
     assert p1.document is None
     assert p2.document is None
     assert p2.child.document is doc
     with pytest.raises(RuntimeError) as e:
         with beu.OutputDocumentFor([p1, p2]):
             pass
         assert "already in a doc" in str(e)
Exemplo n.º 5
0
 def test_passing_doc(self):
     p1 = Model()
     d = Document()
     d.add_root(p1)
     docs_json, render_items = beu.standalone_docs_json_and_render_items([d])
     doc = list(docs_json.values())[0]
     assert doc['title'] == "Bokeh Application"
     assert doc['version'] == __version__
     assert len(doc['roots']['root_ids']) == 1
     assert len(doc['roots']['references']) == 1
     assert doc['roots']['references'] == [{'attributes': {}, 'id': str(p1._id), 'type': 'Model'}]
     assert len(render_items) == 1
Exemplo n.º 6
0
def test_without_document_lock():
    d = Document()
    assert curdoc() is not d
    curdoc_from_cb = []
    @locking.without_document_lock
    def cb():
        curdoc_from_cb.append(curdoc())
    callback_obj = d.add_next_tick_callback(cb)
    callback_obj.callback()
    assert callback_obj.callback.nolock == True
    assert len(curdoc_from_cb) == 1
    assert curdoc_from_cb[0]._doc is d
    assert isinstance(curdoc_from_cb[0], locking.UnlockedDocumentProxy)
Exemplo n.º 7
0
    def test_log_warning_if_python_event_callback(self, caplog):
        d = Document()
        m1 = EmbedTestUtilModel()
        c1 = _GoodEventCallback()
        d.add_root(m1)

        m1.on_event(Tap, c1)
        assert len(m1._event_callbacks) != 0

        with caplog.at_level(logging.WARN):
            beu.standalone_docs_json_and_render_items(m1)
            assert len(caplog.records) == 1
            assert caplog.text != ''
Exemplo n.º 8
0
 def test_delgation(self, mock_sdjari):
     p1 = Model()
     p2 = Model()
     d = Document()
     d.add_root(p1)
     d.add_root(p2)
     # ignore error unpacking None mock result, just checking to see that
     # standalone_docs_json_and_render_items is called as expected
     try:
         beu.standalone_docs_json([p1, p2])
     except ValueError:
         pass
     mock_sdjari.assert_called_once_with([p1, p2])
Exemplo n.º 9
0
    def test_top_level_same_doc(self):
        d = Document()
        p1 = Model()
        p2 = Model()
        d.add_root(p1)
        d.add_root(p2)
        beu._create_temp_doc([p1, p2])
        assert isinstance(p1.document, Document)
        assert p1.document is not d
        assert isinstance(p2.document, Document)
        assert p2.document is not d

        assert p2.document == p1.document
Exemplo n.º 10
0
 def test_list_of_model_same_as_roots(self):
     # should use existing doc in with-block
     p1 = Model()
     p2 = Model()
     d = Document()
     orig_theme = d.theme
     d.add_root(p1)
     d.add_root(p2)
     with beu.OutputDocumentFor([p1, p2], apply_theme=beu.FromCurdoc):
         assert p1.document is d
         assert p2.document is d
         assert d.theme is curdoc().theme
     assert p1.document is d
     assert p2.document is d
     assert d.theme is orig_theme
Exemplo n.º 11
0
    def test_with_events(self, mock_comms):
        mock_comm = MagicMock()
        mock_send = MagicMock(return_value="junk")
        mock_comm.send = mock_send
        mock_comms.return_value = mock_comm

        d = Document()

        handle = binb.CommsHandle("comms", d)
        d.title = "foo"
        binb.push_notebook(d, None, handle)
        assert mock_comms.call_count > 0
        assert mock_send.call_count == 3 # sends header, metadata, then content
        assert json.loads(mock_send.call_args[0][0]) == {u"events": [{u"kind": u"TitleChanged", u"title": u"foo"}], u"references": []}
        assert mock_send.call_args[1] == {}
Exemplo n.º 12
0
def test_other_attrs_raise() -> None:
    d = locking.UnlockedDocumentProxy(Document())
    assert curdoc() is not d
    for attr in (set(dir(d._doc)) - set(dir(d))) | {'foo'}:
        with pytest.raises(AttributeError) as e:
            getattr(d, attr)
        assert e.value.args[0] == locking.UNSAFE_DOC_ATTR_USAGE_MSG
Exemplo n.º 13
0
 def test_basic(self) -> None:
     t = Theme(json={})
     d = Document()
     beu._themes[d] = t
     beu._unset_temp_theme(d)
     assert d.theme is t
     assert d not in beu._themes
Exemplo n.º 14
0
 def test_list_of_model_same_as_roots_with_always_new(self):
     # should use new temp doc for everything inside with-block
     p1 = Model()
     p2 = Model()
     d = Document()
     orig_theme = d.theme
     d.add_root(p1)
     d.add_root(p2)
     with beu.OutputDocumentFor([p1, p2], always_new=True):
         assert p1.document is not d
         assert p2.document is not d
         assert p1.document is p2.document
         assert p2.document.theme is orig_theme
     assert p1.document is d
     assert p2.document is d
     assert d.theme is orig_theme
Exemplo n.º 15
0
 def test_list_of_model_subset_roots(self):
     # should use new temp doc for subset inside with-block
     p1 = Model()
     p2 = Model()
     d = Document()
     orig_theme = d.theme
     d.add_root(p1)
     d.add_root(p2)
     with beu.OutputDocumentFor([p1], apply_theme=beu.FromCurdoc):
         assert p1.document is not d
         assert p2.document is d
         assert p1.document.theme is curdoc().theme
         assert p2.document.theme is orig_theme
     assert p1.document is d
     assert p2.document is d
     assert d.theme is orig_theme
Exemplo n.º 16
0
    def test_child_docs(self):
        d = Document()
        p1 = Model()
        p2 = SomeModelInTestObjects(child=Model())
        d.add_root(p2.child)
        beu._create_temp_doc([p1, p2])

        assert isinstance(p1.document, Document)
        assert p1.document is not d
        assert isinstance(p2.document, Document)
        assert p2.document is not d
        assert isinstance(p2.child.document, Document)
        assert p2.child.document is not d

        assert p2.document == p1.document
        assert p2.document == p2.child.document
Exemplo n.º 17
0
    def test_child_docs(self):
        d = Document()
        p1 = Model()
        p2 = SomeModelInTestObjects(child=Model())
        d.add_root(p2.child)
        beu._create_temp_doc([p1, p2])

        assert isinstance(p1.document, Document)
        assert p1.document is not d
        assert isinstance(p2.document, Document)
        assert p2.document is not d
        assert isinstance(p2.child.document, Document)
        assert p2.child.document is not d

        assert p2.document == p1.document
        assert p2.document == p2.child.document
Exemplo n.º 18
0
 def test_apply_theme(self) -> None:
     t = Theme(json={})
     d = Document()
     orig = d.theme
     beu._set_temp_theme(d, t)
     assert d._old_theme is orig
     assert d.theme is t
Exemplo n.º 19
0
 def test_list_of_model_subset_roots(self) -> None:
     # should use new temp doc for subset inside with-block
     p1 = SomeModel()
     p2 = SomeModel()
     d = Document()
     orig_theme = d.theme
     d.add_root(p1)
     d.add_root(p2)
     with beu.OutputDocumentFor([p1], apply_theme=Theme(json={})):
         assert p1.document is not d
         assert p2.document is d
         assert p1.document.theme is not orig_theme
         assert p2.document.theme is orig_theme
     assert p1.document is d
     assert p2.document is d
     assert d.theme is orig_theme
Exemplo n.º 20
0
 def test_list_of_model_same_as_roots_with_always_new(self):
     # should use new temp doc for everything inside with-block
     p1 = Model()
     p2 = Model()
     d = Document()
     orig_theme = d.theme
     d.add_root(p1)
     d.add_root(p2)
     with beu.OutputDocumentFor([p1, p2], always_new=True, apply_theme=beu.FromCurdoc):
         assert p1.document is not d
         assert p2.document is not d
         assert p1.document is p2.document
         assert p2.document.theme is curdoc().theme
     assert p1.document is d
     assert p2.document is d
     assert d.theme is orig_theme
Exemplo n.º 21
0
 def test_list_of_model_subset_roots(self):
     # should use new temp doc for subset inside with-block
     p1 = Model()
     p2 = Model()
     d = Document()
     orig_theme = d.theme
     d.add_root(p1)
     d.add_root(p2)
     with beu.OutputDocumentFor([p1], apply_theme=beu.FromCurdoc):
         assert p1.document is not d
         assert p2.document is d
         assert p1.document.theme is curdoc().theme
         assert p2.document.theme is orig_theme
     assert p1.document is d
     assert p2.document is d
     assert d.theme is orig_theme
Exemplo n.º 22
0
    def test_child_docs(self) -> None:
        d = Document()
        p1 = SomeModel()
        p2 = OtherModel(child=SomeModel())
        d.add_root(p2.child)
        beu._create_temp_doc([p1, p2])

        assert isinstance(p1.document, Document)
        assert p1.document is not d
        assert isinstance(p2.document, Document)
        assert p2.document is not d
        assert isinstance(p2.child.document, Document)
        assert p2.child.document is not d

        assert p2.document == p1.document
        assert p2.document == p2.child.document
Exemplo n.º 23
0
def test_show_doc_no_server(mock_notebook_content, mock__publish_display_data,
                            mock_get_comms):
    mock_get_comms.return_value = "comms"
    s = State()
    d = Document()
    mock_notebook_content.return_value = ["notebook_script", "notebook_div", d]

    class Obj(object):
        id = None

        def references(self):
            return []

    assert mock__publish_display_data.call_count == 0
    binb.show_doc(Obj(), s, True)

    expected_args = ({
        'application/javascript': 'notebook_script',
        'application/vnd.bokehjs_exec.v0+json': ''
    }, )
    expected_kwargs = {
        'metadata': {
            'application/vnd.bokehjs_exec.v0+json': {
                'id': None
            }
        }
    }

    assert d._hold is not None
    assert mock__publish_display_data.call_count == 2  # two mime types
    assert mock__publish_display_data.call_args[0] == expected_args
    assert mock__publish_display_data.call_args[1] == expected_kwargs
Exemplo n.º 24
0
def updateText(doc: Document, sourceBuySell, sourceVolume, psOrders, psDataSource, psPressure, suuData):
    dt = doc.get_model_by_name("divText")

    text = f"Số lượng Hose data point đã scraped được: <br/> {len(sourceBuySell.data['buyPressure'])}<br/>"
    text += f"Số order phái sinh đã match trong ngày: <br/>{len(psOrders['index'])} <br/>"

    text += f"Dư mua: {sourceBuySell.data['buyPressure'][-1]:.2f}  &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp"
    text += f"Dư bán: {sourceBuySell.data['sellPressure'][-1]:.2f} <br/>"
    # TODO: add Aggregate nnBuy & nnSell
    # text += f"NN mua(total): {sourceBuySell.iloc[-1]['nnBuy']:.2f} &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp"
    # text += f"NN bán(total): {idf.iloc[-1]['nnSell']:.2f} <br/>"

    ############################################ HOSE Indicators ############################################
    currentSource: ColumnDataSource = doc.get_model_by_name("glyphBuyPressure").data_source  # upBuySell
    n_recent_buysell = len(sourceBuySell.data['buyPressure'])
    n_old_buysell = len(currentSource.data['buyPressure'])
    numHoseUpdates = n_recent_buysell - n_old_buysell

    hoseUpdate = {key: sourceBuySell.data[key][n_old_buysell: n_recent_buysell] for key in sourceBuySell.data.keys()}
    currentSource.stream(hoseUpdate)
    text += f"<br/><br/>Số data-points mới cho HOSE chưa được cập nhật: <br/>{numHoseUpdates}<br/>"

    ############################################### Ps Candles ##############################################
    psSource: ColumnDataSource = doc.get_model_by_name("glyphOHLCSegment").data_source
    nPSCandles = len(psSource.data['open'])
    nPSOrders = len(psSource.data['open']) # TODO: fixed this num thing      nPSOrders = psSource.data['num'][0]
    nUnupdatedPSOrders = len(psOrders) - nPSOrders

    text += f"Số data-point mới cho Phái Sinh chưa được cập nhật: <br/> {len(psDataSource.data['index']) - nPSCandles}<br/>"  # update
    if nUnupdatedPSOrders > 0:
        pass

    ############################################### Ps Pressure ##############################################
    if (datetime.now().hour * 60 + datetime.now().minute) > 14 * 60 + 30:
        dt.text = text
        return

    text += f"psBuyPressure: &nbsp&nbsp{ psPressure['psBuyPressure']:.2f} <br/>psSellPressure:&nbsp&nbsp {psPressure['psSellPressure']:.2f} <br/>"
    text += f"buyVolumes: {psPressure['volBuys']} &nbsp&nbsp (total {psPressure['totalVolBuys']}) <br/> "
    text += f"sellVolumes: {psPressure['volSells']} &nbsp&nbsp (total {psPressure['totalVolSells']}) <br/> "

    ############################################### Suu ##############################################
    text += f"""<br/>foreignerBuyVolume: {suuData["foreignerBuyVolume"]}, &nbsp&nbsp  foreignerSellVolume {suuData["foreignerSellVolume"]}<br/> """
    text += f"""totalBidVolume: {suuData["totalBidVolume"]}, &nbsp&nbsp  totalOfferVolume {suuData["totalOfferVolume"]}<br/><br/>"""
    text += f"""Net BU-SD: {suuData['python']['Net BU-SD']} ({timeAgo(suuData)} s ago)"""

    dt.text = text
Exemplo n.º 25
0
 def test_passing_doc(self):
     p1 = Model()
     d = Document()
     d.add_root(p1)
     docs_json, render_items = beu.standalone_docs_json_and_render_items(
         [d])
     doc = list(docs_json.values())[0]
     assert doc['title'] == "Bokeh Application"
     assert doc['version'] == __version__
     assert len(doc['roots']['root_ids']) == 1
     assert len(doc['roots']['references']) == 1
     assert doc['roots']['references'] == [{
         'attributes': {},
         'id': str(p1.id),
         'type': 'Model'
     }]
     assert len(render_items) == 1
    def test_no_events(self, mock_comms):
        mock_comms.return_value = MagicMock()

        d = Document()

        handle = binb.CommsHandle("comms", d)
        binb.push_notebook(d, None, handle)
        assert mock_comms.call_count == 0
Exemplo n.º 27
0
    def test_suppress_warnings(self, caplog):
        d = Document()
        m1 = EmbedTestUtilModel()
        c1 = _GoodPropertyCallback()
        c2 = _GoodEventCallback()
        d.add_root(m1)

        m1.on_change('name', c1)
        assert len(m1._callbacks) != 0

        m1.on_event(Tap, c2)
        assert len(m1._event_callbacks) != 0

        with caplog.at_level(logging.WARN):
            beu.standalone_docs_json_and_render_items(m1, suppress_callback_warning=True)
            assert len(caplog.records) == 0
            assert caplog.text == ''
Exemplo n.º 28
0
 def test_apply_from_curdoc(self):
     t = Theme(json={})
     curdoc().theme = t
     d = Document()
     orig = d.theme
     beu._set_temp_theme(d, beu.FromCurdoc)
     assert d._old_theme is orig
     assert d.theme is t
Exemplo n.º 29
0
    def test_suppress_warnings(self, caplog):
        d = Document()
        m1 = EmbedTestUtilModel()
        c1 = _GoodPropertyCallback()
        c2 = _GoodEventCallback()
        d.add_root(m1)

        m1.on_change('name', c1)
        assert len(m1._callbacks) != 0

        m1.on_event(Tap, c2)
        assert len(m1._event_callbacks) != 0

        with caplog.at_level(logging.WARN):
            beu.standalone_docs_json_and_render_items(m1, suppress_callback_warning=True)
            assert len(caplog.records) == 0
            assert caplog.text == ''
Exemplo n.º 30
0
def test_without_document_lock_accepts_async_function() -> None:
    i = 0
    d = Document()

    @locking.without_document_lock
    async def cb():
        nonlocal i
        await asyncio.sleep(0.1)
        i += 1

    callback_obj = d.add_next_tick_callback(cb)

    loop = asyncio.get_event_loop()
    loop.run_until_complete(callback_obj.callback())

    assert callback_obj.callback.nolock == True
    assert i == 1
Exemplo n.º 31
0
 def test_error_on_mixed_list(self):
     p = SomeModel()
     d = Document()
     orig_theme = d.theme
     with pytest.raises(ValueError) as e:
         with beu.OutputDocumentFor([p, d]):
             pass
     assert str(e.value).endswith(_ODFERR)
     assert d.theme is orig_theme
Exemplo n.º 32
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 = SomeModel()
     p2 = SomeModel()
     d.add_root(p2)
     assert p1.document is None
     assert p2.document is not None
     with beu.OutputDocumentFor([p1, p2], apply_theme=beu.FromCurdoc):
         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 curdoc().theme
     assert p1.document is None
     assert p2.document is not None
     assert p2.document.theme is orig_theme
Exemplo n.º 33
0
 def test_with_docs(self):
     d1 = Document()
     d2 = Document()
     p1 = SomeModel()
     d1.add_root(p1)
     p2 = OtherModel(child=SomeModel())
     d2.add_root(p2.child)
     beu._create_temp_doc([p1, p2])
     beu._dispose_temp_doc([p1, p2])
     assert p1.document is d1
     assert p2.document is None
     assert p2.child.document is d2
Exemplo n.º 34
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=beu.FromCurdoc):
         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 curdoc().theme
     assert p1.document is None
     assert p2.document is not None
     assert p2.document.theme is orig_theme
Exemplo n.º 35
0
    def test_with_events(self, mock_comms: PropertyMock) -> None:
        mock_comm = MagicMock()
        mock_send = MagicMock(return_value="junk")
        mock_comm.send = mock_send
        mock_comms.return_value = mock_comm

        d = Document()

        handle = binb.CommsHandle("comms", d)
        d.title = "foo"
        binb.push_notebook(document=d, handle=handle)
        assert mock_comms.call_count > 0
        assert mock_send.call_count == 3  # sends header, metadata, then content
        assert json.loads(mock_send.call_args[0][0]) == {
            "events": [{
                "kind": "TitleChanged",
                "title": "foo"
            }],
        }
        assert mock_send.call_args[1] == {}
Exemplo n.º 36
0
    def test_with_events(self, mock_comms):
        mock_comm = MagicMock()
        mock_send = MagicMock(return_value="junk")
        mock_comm.send = mock_send
        mock_comms.return_value = mock_comm

        d = Document()

        handle = binb.CommsHandle("comms", d)
        d.title = "foo"
        binb.push_notebook(d, None, handle)
        assert mock_comms.call_count > 0
        assert mock_send.call_count == 3  # sends header, metadata, then content
        assert json.loads(mock_send.call_args[0][0]) == {
            u"events": [{
                u"kind": u"TitleChanged",
                u"title": u"foo"
            }],
            u"references": []
        }
        assert mock_send.call_args[1] == {}
Exemplo n.º 37
0
    def test_top_level_different_doc(self):
        d1 = Document()
        d2 = Document()
        p1 = SomeModel()
        p2 = SomeModel()
        d1.add_root(p1)
        d2.add_root(p2)
        beu._create_temp_doc([p1, p2])
        assert isinstance(p1.document, Document)
        assert p1.document is not d1
        assert isinstance(p2.document, Document)
        assert p2.document is not d2

        assert p2.document == p1.document
Exemplo n.º 38
0
def test_next_tick_callback_works():
    d = locking.UnlockedDocumentProxy(Document())
    assert curdoc() is not d
    curdoc_from_cb = []
    def cb():
        curdoc_from_cb.append(curdoc())
    callback_obj = d.add_next_tick_callback(cb)
    callback_obj.callback()
    assert len(curdoc_from_cb) == 1
    assert curdoc_from_cb[0] is d._doc
    def cb2(): pass
    callback_obj = d.add_next_tick_callback(cb2)
    d.remove_next_tick_callback(callback_obj)
Exemplo n.º 39
0
def main(doc: Document) -> None:
    from bokeh.layouts import layout
    from bokeh.models import Button
    from .bokeh_visualiser import main as plot
    repo_path = TextInput(title='Repository path:', value='../bokeh')
    include_files = TextInput(title='Include files:', value='.py .js')
    exclude_files = TextInput(title='Exclude files:', value='.csv')
    limit = TextInput(title='Top contributors (0-9):', value='9')
    use_cache = Toggle(label='Use cache (ignores include/exclude)',
                       active=True)
    visualise = Button(label='Go', button_type='primary')
    visualise.on_click(lambda: plot(
        doc,
        get_path_input(repo_path),
        get_tokens_input(include_files),
        get_tokens_input(exclude_files),
        get_count_input(limit),
        logged_get_toggle_input(use_cache),
    ))
    doc.add_root(
        layout([[repo_path, include_files, exclude_files, limit],
                [use_cache, visualise]]))
Exemplo n.º 40
0
def test_other_attrs_raise():
    d = locking.UnlockedDocumentProxy(Document())
    assert curdoc() is not d
    with pytest.raises(RuntimeError) as e:
        d.foo
        assert str(
            e
        ) == "Only add_next_tick_callback may be used safely without taking the document lock; "
        "to make other changes to the document, add a next tick callback and make your changes "
        "from that callback."
    for attr in dir(d._doc):
        if attr in ["add_next_tick_callback", "remove_next_tick_callback"]:
            continue
        with pytest.raises(RuntimeError) as e:
            getattr(d, "foo")
Exemplo n.º 41
0
def updateDoc(doc: Document):
    #if DEBUG: print(f"updated {doc}")
    sourceBuySell, sourceVolume = requestHoseData()

    ###################### Hose Buy, Sell #######################
    sourceBS = doc.get_model_by_name("glyphSellPressure").data_source
    lsource = len(sourceBS.data['index'])
    lnew = len(sourceBuySell.data['index'])
    if lnew > lsource:
        hoseUpdate = {key: sourceBuySell.data[key][lsource: lnew] for key in sourceBuySell.data.keys()}
        sourceBS.stream(hoseUpdate)

    ################# Liquidity *  nnBuy, nnSell #################
    sourceVol = doc.get_model_by_name("glyphTotalValue").data_source
    updateSource(sourceVol , sourceVolume) #update

    ######################### ohlcCandles #########################
    psOrders, psDataSource, psPressure = requestPSData()
    sourcePs = doc.get_model_by_name("glyphOHLCSegment").data_source
    updateSource(sourcePs, psDataSource)

    ######################### Text Display #########################
    suuData = None
    updateText(doc, sourceBuySell, sourceVolume, psOrders, psDataSource, psPressure, suuData = fetchSuuData())
Exemplo n.º 42
0
 def test_with_docs(self):
     d1 = Document()
     d2 = Document()
     p1 = Model()
     d1.add_root(p1)
     p2 = SomeModelInTestObjects(child=Model())
     d2.add_root(p2.child)
     beu._create_temp_doc([p1, p2])
     beu._dispose_temp_doc([p1, p2])
     assert p1.document is d1
     assert p2.document is None
     assert p2.child.document is d2
Exemplo n.º 43
0
    def test_top_level_different_doc(self):
        d1 = Document()
        d2 = Document()
        p1 = Model()
        p2 = Model()
        d1.add_root(p1)
        d2.add_root(p2)
        beu._create_temp_doc([p1, p2])
        assert isinstance(p1.document, Document)
        assert p1.document is not d1
        assert isinstance(p2.document, Document)
        assert p2.document is not d2

        assert p2.document == p1.document
Exemplo n.º 44
0
 def test_no_old_theme(self):
     d = Document()
     orig = d.theme
     beu._unset_temp_theme(d)
     assert d.theme is orig
     assert not hasattr(d, "_old_theme")
Exemplo n.º 45
0
 def test_apply_None(self):
     d = Document()
     orig = d.theme
     beu._set_temp_theme(d, None)
     assert d._old_theme is orig
     assert d.theme is orig
Exemplo n.º 46
0
 def update(self, new_data, doc: Document) -> None:
     new = {"acc": [new_data[0]], "step": [new_data[1]]}
     # add_next_tick_callback() can be used safely without taking the document lock
     doc.add_next_tick_callback(lambda: self.source.stream(new))
def attachDocToServer(doc: Document):
    global page, sourceVolume, sourceBuySell
    page, activate, sourceBuySell, sourceVolume = makeMasterPlot()
    doc.add_root(column(page))
    docs.append(doc)
    activate()
Exemplo n.º 48
0
def save(panel,
         filename,
         title=None,
         resources=None,
         template=None,
         template_variables=None,
         embed=False,
         max_states=1000,
         max_opts=3,
         embed_json=False,
         json_prefix='',
         save_path='./',
         load_path=None,
         progress=True):
    """
    Saves Panel objects to file.

    Arguments
    ---------
    panel: Viewable
      The Panel Viewable to save to file
    filename: string or file-like object
      Filename to save the plot to
    title: string
      Optional title for the plot
    resources: bokeh resources
      One of the valid bokeh.resources (e.g. CDN or INLINE)
    template:
      template file, as used by bokeh.file_html. If None will use bokeh defaults
    template_variables:
      template_variables file dict, as used by bokeh.file_html
    embed: bool
      Whether the state space should be embedded in the saved file.
    max_states: int
      The maximum number of states to embed
    max_opts: int
      The maximum number of states for a single widget
    embed_json: boolean (default=True)
      Whether to export the data to json files
    json_prefix: str (default='')
      Prefix for the randomly json directory
    save_path: str (default='./')
      The path to save json files to
    load_path: str (default=None)
      The path or URL the json files will be loaded from.
    progress: boolean (default=True)
      Whether to report progress
    """
    from ..pane import PaneBase

    if isinstance(panel, PaneBase) and len(panel.layout) > 1:
        panel = panel.layout

    as_png = isinstance(filename, string_types) and filename.endswith('png')

    doc = Document()
    comm = Comm()
    with config.set(embed=embed):
        with swap_html_model(as_png):
            model = panel.get_root(doc, comm)
        if embed:
            embed_state(panel, model, doc, max_states, max_opts, embed_json,
                        json_prefix, save_path, load_path, progress)
        else:
            add_to_doc(model, doc, True)

    if as_png:
        save_png(model, filename=filename)
        return
    elif isinstance(filename, string_types) and not filename.endswith('.html'):
        filename = filename + '.html'

    kwargs = {}
    if title is None:
        title = 'Panel'
    if resources is None:
        resources = CDN
    if template:
        kwargs['template'] = template
    if template_variables:
        kwargs['template_variables'] = template_variables

    html = file_html(doc, resources, title, **kwargs)
    if hasattr(filename, 'write'):
        html = decode_utf8(html)
        if isinstance(filename, io.BytesIO):
            html = html.encode('utf-8')
        filename.write(html)
        return
    with io.open(filename, mode="w", encoding="utf-8") as f:
        f.write(decode_utf8(html))