Esempio n. 1
0
def start_dashboard(dashboard: Dashboard, args: argparse.Namespace) -> None:
    app = Application()
    app.add(dashboard)
    if args.dashboard_allow_websocket_origin:
        allow_websocket_origin = args.dashboard_allow_websocket_origin
    else:
        allow_websocket_origin = [
            'localhost:{}'.format(args.dashboard_port),
            '{}:{}'.format(args.external_hostname, args.dashboard_port)
        ]
    server = Server(app,
                    port=args.dashboard_port,
                    allow_websocket_origin=allow_websocket_origin)
    server.start()
def view_metamodel(meta_model_comp, resolution, port_number, browser):
    """
    Visualize a metamodel.

    Parameters
    ----------
    meta_model_comp : MetaModelStructuredComp or MetaModelUnStructuredComp
        The metamodel component.
    resolution : int
        Number of points to control contour plot resolution.
    port_number : int
        Bokeh plot port number.
    browser : bool
        Boolean to show the browser
    """
    from bokeh.application.application import Application
    from bokeh.application.handlers import FunctionHandler

    def make_doc(doc):
        MetaModelVisualization(meta_model_comp, resolution, doc=doc)

    server = Server({'/': Application(FunctionHandler(make_doc))}, port=int(port_number))
    if browser:
        server.io_loop.add_callback(server.show, "/")
    else:
        print('Server started, to view go to http://localhost:{}/'.format(port_number))

    server.io_loop.start()
Esempio n. 3
0
def main():
    """The photodiag command line interface.

    This is a wrapper around bokeh server that provides an interface to launch
    applications bundled with the photodiag package.
    """
    # Discover photodiag apps
    apps_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                             'apps')
    available_apps = []
    for module_info in pkgutil.iter_modules([apps_path]):
        if module_info.ispkg:
            available_apps.append(module_info.name)

    parser = argparse.ArgumentParser(
        prog='photodiag',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument(
        'app',
        type=str,
        choices=available_apps,
        help="photodiag application",
    )

    parser.add_argument('--port',
                        type=int,
                        default=5006,
                        help="the port to listen on for HTTP requests")

    parser.add_argument(
        '--allow-websocket-origin',
        metavar='HOST[:PORT]',
        type=str,
        action='append',
        default=None,
        help="hostname that can connect to the server websocket",
    )

    parser.add_argument(
        '--args',
        nargs=argparse.REMAINDER,
        default=[],
        help="command line arguments for the photodiag application",
    )

    args = parser.parse_args()

    app_path = os.path.join(apps_path, args.app)
    logger.info(app_path)

    handler = DirectoryHandler(filename=app_path, argv=args.args)
    server = Server(
        {'/': Application(handler)},
        port=args.port,
        allow_websocket_origin=args.allow_websocket_origin,
    )

    server.start()
    server.io_loop.start()
Esempio n. 4
0
 def test_show_with_app(self, mock__run_notebook_hook):
     app = Application()
     io.show(app, notebook_url="baz")
     io._state.notebook_type == "foo"
     self.assertTrue(mock__run_notebook_hook.called)
     self.assertEqual(mock__run_notebook_hook.call_args[0][0], io._state.notebook_type)
     self.assertEqual(mock__run_notebook_hook.call_args[0][1:], ("app", app, io._state, "baz"))
     self.assertEqual(mock__run_notebook_hook.call_args[1], {})
Esempio n. 5
0
class BokehPlotter(object):
    def __init__(self, handlers, port=5006):
        self.app = Application()
        for handler in handlers:
            self.app.add(handler)
        self.server = Server({'/': self.app}, port=port)
        self.thread = Thread(target=self.server.io_loop.start)

    def start(self):
        self.server.start()
        self.server.io_loop.add_callback(self.server.show, '/')
        self.thread.start()

    def stop(self):
        self.server.io_loop.stop()
        self.server.stop()
        self.thread.join()
Esempio n. 6
0
def test_show_with_app(mock_run_notebook_hook):
    curstate().reset()
    app = Application()
    output_notebook()
    bis.show(app, notebook_url="baz")
    assert curstate().notebook_type == "jupyter"
    assert mock_run_notebook_hook.call_count == 1
    assert mock_run_notebook_hook.call_args[0][0] == curstate().notebook_type
    assert mock_run_notebook_hook.call_args[0][1:] == ("app", app, curstate(), "baz")
    assert mock_run_notebook_hook.call_args[1] == {}
Esempio n. 7
0
    def ready(self):

        print("DjangoBokehConfig.ready()")
        os.environ['BOKEH_NODEJS_PATH'] = settings.BOKEH_NODEJS_PATH

        bokeh_app_base_path = os.path.join(settings.BASE_DIR, "djangobokeh",
                                           "bokeh_apps")
        path_list = glob.glob(os.path.join(bokeh_app_base_path, "*.py"))
        print(path_list)

        applications = {}
        for path in path_list:
            application = build_single_handler_application(path)

            route = application.handlers[0].url_path()

            if not route:
                if '/' in applications:
                    raise RuntimeError(
                        "Don't know the URL path to use for %s" % (path))
                route = '/'
            applications[route] = application

        if callable(applications):
            applications = Application(FunctionHandler(applications))

        if isinstance(applications, Application):
            applications = {'/': applications}

        for k, v in list(applications.items()):
            if callable(v):
                applications[k] = Application(FunctionHandler(v))
            if all(not isinstance(handler, DocumentLifecycleHandler)
                   for handler in applications[k]._handlers):
                applications[k].add(DocumentLifecycleHandler())

        self._applications = dict()

        for k, v in applications.items():
            self._applications[k] = ApplicationContext(v, url=k)

        self.routing_config = RoutingConfiguration(self._applications)
Esempio n. 8
0
def main():
    """The pyzebra command line interface.

    This is a wrapper around a bokeh server that provides an interface to launch the application,
    bundled with the pyzebra package.
    """
    app_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "app",
                            "app.py")

    parser = argparse.ArgumentParser(
        prog="pyzebra", formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument("--port",
                        type=int,
                        default=5006,
                        help="port to listen on for HTTP requests")

    parser.add_argument(
        "--allow-websocket-origin",
        metavar="HOST[:PORT]",
        type=str,
        action="append",
        default=None,
        help="hostname that can connect to the server websocket",
    )

    parser.add_argument(
        "--args",
        nargs=argparse.REMAINDER,
        default=[],
        help="command line arguments for the pyzebra application",
    )

    args = parser.parse_args()

    logger.info(app_path)

    handler = ScriptHandler(filename=app_path, argv=args.args)
    server = Server(
        {"/": Application(handler)},
        port=args.port,
        allow_websocket_origin=args.allow_websocket_origin,
    )

    server.start()
    server.io_loop.start()
Esempio n. 9
0
def view_metamodel(meta_model_comp, port_number):
    """
    Visualize a metamodel.

    Parameters
    ----------
    meta_model_comp : MetaModelStructuredComp or MetaModelUnStructuredComp
        The metamodel component.
    port_number : int
        Bokeh plot port number.
    """
    from bokeh.application.application import Application
    from bokeh.application.handlers import FunctionHandler

    def make_doc(doc):
        MetaModelVisualization(meta_model_comp, doc=doc)

    # print('Opening Bokeh application on http://localhost:5006/')
    server = Server({'/': Application(FunctionHandler(make_doc))},
                    port=int(port_number))
    server.io_loop.add_callback(server.show, "/")
    server.io_loop.start()
Esempio n. 10
0
    def __init__(self,
                 run=True,
                 view=True,
                 handler=None,
                 l=None,
                 name='Base_server0'):
        self.top = None
        self.app = None
        self.doc = None
        self.fig = None
        self.layout = None

        # ----------------------------------
        def modify_doc(doc):
            p = figure()
            p.circle([0, 5, 10], [0, 5, 10], size=15)
            self.top = column(p, Div(text='App has been created successfuly'))
            doc.add_root(self.top)
            pass

        #----------------------------------
        if handler is None: handler = modify_doc
        if l != None:
            self.l = l
            handler = self.l.f
            l.attach_serv(self)
        self.port = initialize_port()
        self.app_handler = Application(FunctionHandler(handler))
        self.server = Server({'/': self.app_handler},
                             num_proc=4,
                             port=self.port,
                             allow_websocket_origin=[f"*"])
        self.server.start()
        self.name = name
        self.announce()
        Base_server.ALL_SERVERS.append(self)
        if run: self.start_ioloop()
        if view: self.server.io_loop.add_callback(lambda: self.go_to())
if "docs" not in globals():
    docs = []
    page = column()
    sourceBuySell: ColumnDataSource = ColumnDataSource({ # ['buyPressure', 'index', 'sellPressure', 'time']
        'buyPressure':[],
        'sellPressure':[],
        'index': [], })
    sourceVolume:ColumnDataSource = ColumnDataSource({ #  ['index', 'nnBuy', 'nnSell', 'time', 'totalValue']
        'index': [],
        'nnBuy': [],
        'nnSell': [],
        'totalValue': [],})


def attachDocToServer(doc: Document):
    global page, sourceVolume, sourceBuySell
    page, activate, sourceBuySell, sourceVolume = makeMasterPlot()
    doc.add_root(column(page))
    docs.append(doc)
    activate()


if __name__ == "__main__":
    s = Server({'/': Application(FunctionHandler(attachDocToServer))},
               num_proc=16,
               port=BOKEH_PORT,
               allow_websocket_origin=["*"])
    s.start()
    threading_func_wrapper(s.io_loop.start, delay=0.01)
    threading_func_wrapper(lambda: view(f"http://localhost:{BOKEH_PORT}"), 0.5)
Esempio n. 12
0
def main():
    """The streamvis command line interface.

    This is a wrapper around bokeh server that provides an interface to launch
    applications bundled with the streamvis package.
    """
    base_path = os.path.dirname(os.path.abspath(__file__))

    # Discover streamvis apps
    apps_path = os.path.join(base_path, "apps")
    available_apps = []
    for module_info in pkgutil.iter_modules([apps_path]):
        available_apps.append(module_info.name)

    # Prepare argument parser
    parser = argparse.ArgumentParser(
        prog="streamvis", formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )

    parser.add_argument("-v", "--version", action="version", version=f"%(prog)s {__version__}")

    parser.add_argument("app", type=str, choices=available_apps, help="streamvis application")

    parser.add_argument(
        "--port", type=int, default=5006, help="a port to listen on for HTTP requests"
    )

    parser.add_argument(
        "--allow-websocket-origin",
        metavar="HOST[:PORT]",
        type=str,
        action="append",
        default=None,
        help="a hostname that can connect to the server websocket",
    )

    parser.add_argument(
        "--page-title", type=str, default="StreamVis", help="browser tab title for the application"
    )

    parser.add_argument(
        "--address",
        metavar="PROTOCOL://HOST:PORT",
        type=str,
        default="tcp://127.0.0.1:9001",
        help="an address string for zmq socket",
    )

    parser.add_argument(
        "--connection-mode",
        type=str,
        choices=["connect", "bind"],
        default="connect",
        help="whether to bind a socket to an address or connect to a remote socket with an address",
    )

    parser.add_argument(
        "--io-threads",
        type=int,
        default=1,
        help="the size of the zmq thread pool to handle I/O operations",
    )

    parser.add_argument(
        "--buffer-size",
        type=int,
        default=1,
        help="a number of last received zmq messages to keep in memory",
    )

    parser.add_argument(
        "--hit-threshold",
        type=int,
        default=15,
        help="a number of spots above which a shot is registered in statistics as 'hit'",
    )

    parser.add_argument(
        "--max-client-connections",
        type=int,
        default=2,
        help="a maximum number of concurrent client connections",
    )

    parser.add_argument(
        "--client-fps", type=float, default=1, help="client update rate in frames per second",
    )

    parser.add_argument(
        "--allow-client-subnet",
        type=str,
        action="append",
        default=None,
        help="a subnet from which client connections are allowed",
    )

    parser.add_argument(
        "--args",
        nargs=argparse.REMAINDER,
        default=[],
        help="command line arguments for the streamvis application",
    )

    args = parser.parse_args()

    app_path = os.path.join(apps_path, args.app + ".py")
    logger.info(app_path)

    # StatisticsHandler is used by Receiver to parse metadata information to be displayed in
    # 'statistics' application, all messages are being processed.
    stats = StatisticsHandler(hit_threshold=args.hit_threshold, buffer_size=args.buffer_size)

    # Receiver gets messages via zmq stream and parses statistics with StatisticsHandler
    receiver = Receiver(on_receive=stats.parse, buffer_size=args.buffer_size)

    # Start receiver in a separate thread
    start_receiver = partial(receiver.start, args.io_threads, args.connection_mode, args.address)
    t = Thread(target=start_receiver, daemon=True)
    t.start()

    # Reconstructs requested images
    jf_adapter = StreamAdapter()

    # StreamvisHandler is a custom bokeh application Handler, which sets some of the core
    # properties for new bokeh documents created by all applications.
    sv_handler = StreamvisHandler(receiver, stats, jf_adapter, args)
    sv_check_handler = StreamvisCheckHandler(
        max_sessions=args.max_client_connections, allow_client_subnet=args.allow_client_subnet
    )

    applications = dict()  # List of bokeh applications

    # Main application
    bokeh_handler = ScriptHandler(filename=app_path, argv=args.args)
    applications["/"] = Application(sv_handler, bokeh_handler, sv_check_handler)

    # Add all common applications
    common_apps_path = os.path.join(base_path, "common_apps")
    for module_info in pkgutil.iter_modules([common_apps_path]):
        app_name = module_info.name
        bokeh_handler = ScriptHandler(filename=os.path.join(common_apps_path, app_name + ".py"))
        sv_check_handler = StreamvisCheckHandler(allow_client_subnet=args.allow_client_subnet)
        applications[f"/{app_name}"] = Application(sv_handler, bokeh_handler, sv_check_handler)

    server = Server(
        applications,
        port=args.port,
        allow_websocket_origin=args.allow_websocket_origin,
        unused_session_lifetime_milliseconds=1,
        check_unused_sessions_milliseconds=3000,
    )

    server.start()
    server.io_loop.start()
Esempio n. 13
0
                 radome_observer.relative_humidity, radome_observer.pressure)


if __name__ == '__main__':
    logconfig.basicConfig(
        format=
        "%(asctime)-15s %(levelname)-8s [%(name)s] [%(module)s:%(funcName)s] %(message)s",
        level=logging.DEBUG,
    )
    os.makedirs(RUNS_DIR, exist_ok=True)
    lw = LogWatcher()
    logging.getLogger().addHandler(lw)
    wx = Weather(callback=wx_received)
    wx.start()
    server = Server(
        {'/': Application(SessionHandler(lw=lw, runs_dir=RUNS_DIR))},
        allow_websocket_origin=[socket.getfqdn().lower() + ":5006"],
        extra_patterns=[
            (r'/runs/()', DirectoryHandler, {
                'path': RUNS_DIR
            }),
            (r'/runs/(.*)/', DirectoryHandler, {
                'path': RUNS_DIR
            }),
            (r'/runs/(.*)', tornado.web.StaticFileHandler, {
                'path': RUNS_DIR
            }),
        ],
    )
    server.start()
    server.io_loop.start()
Esempio n. 14
0
class PeriodicUpdateHandler(Handler):
    def __init__(self):
        super(PeriodicUpdateHandler, self).__init__()
        self.df = pd.DataFrame(columns=('x', 'y'))
        self.n = 50
        self.period_ms = 500

    def modify_document(self, doc):
        source = ColumnDataSource(self.df)
        p = figure()
        p.scatter('x', 'y', source=source, alpha=0.5)

        def callback():
            sample = np.random.multivariate_normal([0, 0], [[1, 0], [0, 1]],
                                                   self.n)
            df_new = pd.DataFrame(sample, columns=('x', 'y'))
            source.stream(df_new, 10 * self.n)

        doc.add_root(p)
        doc.add_periodic_callback(callback, self.period_ms)


bkapp = Application(PeriodicUpdateHandler())
server = Server({'/': bkapp})
server.start()

if __name__ == '__main__':
    print('Opening Bokeh application on http://localhost:5006/')

    server.io_loop.add_callback(server.show, "/")
    server.io_loop.start()
Esempio n. 15
0
 def __init__(self, handlers, port=5006):
     self.app = Application()
     for handler in handlers:
         self.app.add(handler)
     self.server = Server({'/': self.app}, port=port)
     self.thread = Thread(target=self.server.io_loop.start)
Esempio n. 16
0
        plot.line('time', 'temperature', source=self.source)

        def callback(attr, old, new):
            if new == 0:
                data = self.df
            else:
                data = self.df.rolling('{0}D'.format(new)).mean()
            self.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))


# Setting num_procs here means we can't touch the IOLoop before now, we must
# let Server handle that. If you need to explicitly handle IOLoops then you
# will need to use the lower level BaseServer class.
handler = MyHandler()
server = Server({'/': Application(handler)}, num_procs=1)
server.start()

if __name__ == '__main__':
    print('Opening Bokeh application on http://localhost:5006/')

    server.io_loop.add_callback(server.show, "/")
    server.io_loop.start()