예제 #1
0
def create_callbacks():
    def delete(i):
        def callback(*data):
            return """# Delete
            {}""".format(datetime.now().time().isoformat())

        return callback

    def toggle(i):
        def callback(*data):
            return "Toggle {}".format(datetime.now().time().isoformat())

        return callback

    for model_id in IDS:
        try:
            app.callback(Output('model-{}-markdown'.format(model_id),
                                'children'),
                         events=[
                             Event('model-{}-delete-button'.format(model_id),
                                   'click')
                         ])(delete(model_id))

            app.callback(Output('model-{}-p'.format(model_id), 'children'),
                         events=[
                             Event('model-{}-toggle-button'.format(model_id),
                                   'click')
                         ])(toggle(model_id))
        except CantHaveMultipleOutputs:
            continue
예제 #2
0
    def test_exception_event_not_in_component(self):
        app = dash.Dash('')
        app.layout = Div([
            Div(id='button'),
            Div(id='output'),
            Div(id='graph-output'),
            dcc.Graph(id='graph')
        ], id='body')

        for id in ['output', 'body']:
            self.assertRaises(
                exceptions.NonExistantEventException,
                app.callback,
                Output(id, 'children'),
                events=[Event(id, 'style')]
            )
            app.callback(
                Output(id, 'children'),
                events=[Event(id, 'click')]
            )

        self.assertRaises(
            exceptions.NonExistantEventException,
            app.callback,
            Output('output', 'children'),
            events=[Event('graph', 'zoom')]
        )
        app.callback(
            Output('graph-output', 'children'),
            events=[Event('graph', 'click')]
        )
예제 #3
0
    def update_lists(self):
        @self.app.callback(Output(self.chart_selector.id, 'options'),
                           events=[Event('dt', 'interval')])
        def update_graphs_list():
            return [{'label': ch, 'value': ch} for ch in cnf.GUI.CHARTS_GENERAL] + \
                   [{'label': ch['name'], 'value': ch['name']} for ch in self.presenter.charts.values()]

        @self.app.callback(Output(self.features_selector.id, 'options'),
                           events=[Event('dt', 'interval')])
        def update_features_list():
            return [{'label': name, 'value': name} for name in self.presenter.data_raw['features_names']] + \
                   [{'label': 'LABELS', 'value': 'LABELS'}, {'label': 'ALL', 'value': 'ALL'}]
예제 #4
0
    def start(self):
        self._main_thread = spawn(self._server)
        self.logger.debug('server started on localhost:{}'.format(self.port()))

        self.data = self.data_dict_to_data_list(self.data_dict)
        figure = {'data': self.data, 'layout': {'title': self.title()}}
        app_layout = [
            dcc.Graph(id=self.title(), figure=figure),
            dcc.Interval(id='interval-component', interval=self.update_interval() * 1000)
        ]

        self.app.layout = html.Div(app_layout)

        @self.app.callback(Output(self.title(), 'figure'),
                           events=[Event('interval-component', 'interval')])
        def update_graph_live():
            return {'data': self.data, 'layout': {'title': self.title()}}

        @self.app.server.route('/shutdown', methods=['GET'])
        def shutdown():
            shutdown_server()
            return 'OK'

        def shutdown_server():
            func = request.environ.get('werkzeug.server.shutdown')
            if func is None:
                self.logger.warning('Not running with the Werkzeug Server')
            func()
        super().start()
예제 #5
0
    def test_callback_registry(self):
        app = dash.Dash('')
        input = dcc.Input(id='input')
        input._events = ['blur', 'change']

        app.layout = Div([
            input,
            Div(id='output-1'),
            Div(id='output-2'),
            Div(id='output-3')
        ],
                         id='body')

        app.callback(Output('body', 'children'), [Input('input', 'value')])
        app.callback(Output('output-1', 'children'), [Input('input', 'value')])
        app.callback(
            Output('output-2', 'children'),
            [Input('input', 'value')],
            state=[State('input', 'value')],
        )
        app.callback(
            Output('output-3', 'children'),
            [Input('input', 'value')],
            state=[State('input', 'value')],
            events=[Event('input', 'blur')],
        )
예제 #6
0
def main():
    """
    Main program: responsible for setting up html divs and app
    :return:
    """
    app = dash.Dash()

    app.layout = html.Div([
        html.Div(id='target'),  # div that shows output
        dcc.Input(id='input', type='text', value=''),
        html.Button(id='submit', type='submit', children='ok'),
        dcc.Graph(id='network-graph',
                  style={
                      'height': '100vh',
                      'width': '100vw'
                  })
    ])

    #decorator for the search bar
    @app.callback(
        Output(component_id='network-graph', component_property='figure'
               ),  # output text, connects to target in html.Div
        [],
        [State('input', 'value')
         ],  # connected to id='input' getting the 'value' property from it
        # State('connecting element', value collected)
        [Event('submit', 'click')]
    )  #connected to the html.Button, callback triggered on action
    # Event('connecting_id', action)
    def make_map(
        hyperlink
    ):  # state variable is the 'value' property from the State in the decorator
        return build_network(hyperlink)

    app.run_server(debug=False)
예제 #7
0
def main():
    """
    Main program: responsible for setting up html divs and app
    :return:
    """
    app = dash.Dash()

    app.layout = html.Div([
        html.Div(id='target', children=''),  # div that shows output
        dcc.Input(id='input', type='text', value='Enter an IMDB hyperlink'),
        html.Button(id='submit', type='submit', children='ok'),
    ])

    #decorator for the search bar
    @app.callback(
        Output(component_id='target', component_property='children'
               ),  # output text, connects to target in html.Div
        [],
        [State('input', 'value')
         ],  # connected to id='input' getting the 'value' property from it
        # State('connecting element', value collected)
        [Event('submit', 'click')]
    )  #connected to the html.Button, callback triggered on action
    # Event('connecting_id', action)
    def make_map(
        state
    ):  #state variable is the 'value' property from the State in the decorator
        return "callback received value: {}".format(state)

    app.run_server(debug=False)
예제 #8
0
	def __init__(self, pi_data):
		self.app = dash.Dash(__name__)
		self.app.layout = dhtml.Div([
				dcc.Graph(id='live-pi-graph', animate=True),
				dcc.Interval(id='update-graph', interval=900),
				dhtml.Output(id='pi-output'),
				dhtml.Div([dhtml.Output(id='digit-count')])])
		self.ix = 0
		self.pi_string = '3.'
		self.digit_counter = 'Digits printed: {}'.format(len(self.pi_string)-2)
		self.pi_data = pi_data[2:] #Skip '3.'
		self.data_length = len(self.pi_data)
		self.y_axis = deque(maxlen=150)
		self.x_axis = deque(maxlen=150)
		self.count = 0

		@self.app.callback(Output('live-pi-graph', 'figure'), 
							events=[Event('update-graph', 'interval')])
		def updateGraph():
			if self.ix < self.data_length:
				self.x_axis.append(self.ix)
				self.y_axis.append(self.pi_data[self.ix])
				self.ix +=1
				data = pgo.Scatter(x=list(self.x_axis), y=list(self.y_axis), name="Digits of Pi",
				mode = 'lines+markers', marker=dict(size=10, color='rgba(255, 0, 0, .9)', line=dict(width=2)))
				return {'data': [data], 'layout': pgo.Layout(title='Pi Day 2018 by @swoldemi', xaxis=dict(range=[min(self.x_axis), max(self.x_axis)]), yaxis=dict(range=[0, 12]), autosize=True)}
			else:
				sys.exit(0)

		@self.app.callback(Output(component_id='pi-output', component_property='children'), 
		events=[Event('update-graph', 'interval')])
		def printPi():
			if self.ix-1 < self.data_length:
				self.pi_string = self.pi_string + self.pi_data[self.ix-1]
				self.count +=1
				if self.count > 2:
					self.pi_string = self.pi_string + '\n'
					self.count = 0
				return self.pi_string

		@self.app.callback(Output(component_id='digit-count', component_property='children'), 
		events=[Event('update-graph', 'interval')])
		def displayDigitCount():
			self.digit_counter = 'Digits printed: {}'.format(len(self.pi_string)-2)
			return self.digit_counter
예제 #9
0
    def test_events_state_and_inputs(self):
        app = Dash(__name__)
        app.layout = html.Div([
            html.Button('Click Me', id='button'),
            dcc.Input(value='Initial Input', id='input'),
            dcc.Input(value='Initial State', id='state'),
            html.Div(id='output')
        ])

        call_count = Value('i', 0)

        @app.callback(Output('output', 'children'),
                      inputs=[Input('input', 'value')],
                      state=[State('state', 'value')],
                      events=[Event('button', 'click')])
        def update_output(input, state):
            call_count.value += 1
            return 'input="{}", state="{}"'.format(input, state)

        self.startServer(app)
        btn = lambda: self.driver.find_element_by_id('button')
        output = lambda: self.driver.find_element_by_id('output')
        input = lambda: self.driver.find_element_by_id('input')
        state = lambda: self.driver.find_element_by_id('state')

        # callback gets called with initial input
        self.assertEqual(call_count.value, 1)
        self.assertEqual(output().text,
                         'input="Initial Input", state="Initial State"')

        btn().click()
        wait_for(lambda: call_count.value == 2)
        self.assertEqual(output().text,
                         'input="Initial Input", state="Initial State"')

        input().send_keys('x')
        wait_for(lambda: call_count.value == 3)
        self.assertEqual(output().text,
                         'input="Initial Inputx", state="Initial State"')

        state().send_keys('x')
        time.sleep(0.75)
        self.assertEqual(call_count.value, 3)
        self.assertEqual(output().text,
                         'input="Initial Inputx", state="Initial State"')

        btn().click()
        wait_for(lambda: call_count.value == 4)
        self.assertEqual(output().text,
                         'input="Initial Inputx", state="Initial Statex"')
예제 #10
0
    def test_event_creating_inputs(self):
        app = Dash(__name__)

        ids = {
            k: k
            for k in ['button', 'button-output', 'input', 'input-output']
        }
        app.layout = html.Div(
            [html.Button(id=ids['button']),
             html.Div(id=ids['button-output'])])
        for script in dcc._js_dist:
            script['namespace'] = 'dash_core_components'
            app.scripts.append_script(script)

        app.config.supress_callback_exceptions = True
        call_counts = {
            ids['input-output']: Value('i', 0),
            ids['button-output']: Value('i', 0)
        }

        @app.callback(Output(ids['button-output'], 'children'),
                      events=[Event(ids['button'], 'click')])
        def display():
            call_counts['button-output'].value += 1
            return html.Div([
                dcc.Input(id=ids['input'], value='initial state'),
                html.Div(id=ids['input-output'])
            ])

        @app.callback(Output(ids['input-output'], 'children'),
                      [Input(ids['input'], 'value')])
        def update_input(value):
            call_counts['input-output'].value += 1
            return 'Input is equal to "{}"'.format(value)

        self.startServer(app)
        time.sleep(1)
        self.assertEqual(call_counts[ids['button-output']].value, 0)
        self.assertEqual(call_counts[ids['input-output']].value, 0)

        btn = lambda: self.driver.find_element_by_id(ids['button'])
        output = lambda: self.driver.find_element_by_id(ids['input-output'])
        with self.assertRaises(Exception):
            output()

        btn().click()
        wait_for(lambda: call_counts[ids['input-output']].value == 1)
        self.assertEqual(call_counts[ids['button-output']].value, 1)
        self.assertEqual(output().text, 'Input is equal to "initial state"')
예제 #11
0
    def test_exception_component_is_not_right_type(self):
        app = dash.Dash('')
        app.layout = Div([dcc.Input(id='input'), Div(id='output')], id='body')

        test_args = [
            ['asdf', ['asdf'], [], []],
            [Output('output', 'children'),
             Input('input', 'value'), [], []],
            [Output('output', 'children'), [],
             State('input', 'value'), []],
            [Output('output', 'children'), [], [],
             Event('input', 'click')],
        ]
        for args in test_args:
            self.assertRaises(exceptions.IncorrectTypeException, app.callback,
                              *args)
예제 #12
0
def link_factor(app: dash.Dash, i: int, factor: Factor):
    def apply_reverse(tt):
        a, r = tt
        return 4 - a if r else a

    @app.callback(
        Output(f"f-{i}", 'value'),
        inputs=[Input(f"q-{x}", 'value') for x in factor.question_ids],
        events=[Event('submit', 'click')],
    )
    def f(*args):
        sol = seq(args).map(_ - 1).zip(factor.rev).map(apply_reverse).sum() / (
            len(args) * 4)
        logging.getLogger('calc_factor').info(
            f"{pp.pformat({'args': args, 'factor': factor._asdict(), 'sol': sol})}"
        )
        return sol
예제 #13
0
    def return_layout(self):
        self.layout = html.Div([
            html.Link(rel='stylesheet', href='/static/bootstrap.min.css'),

            # The graph.
            dcc.Graph(id='live-update-spectrogram',
                      animate=False,
                      config={'displayModeBar': False}),
            dcc.Interval(id='interval-component',
                         interval=PLOT_REFRESH_INTERVAL),
        ])

        @self.app.callback(Output('live-update-spectrogram', 'figure'),
                           events=[Event('interval-component', 'interval')])
        def update_graph_scatter():
            self.mode = self.controller.serial_getmode()
            if 'b' in self.mode:
                # update the data queue.
                self.process_data()

            if len(self.data_dict.keys()) > 0:
                trace1 = go.Scatter(x=list(self.data_dict.keys()),
                                    y=list(self.data_dict.values()),
                                    mode='lines',
                                    name='PSD',
                                    line={'shape': 'spline'},
                                    fill='tozeroy')

                data = [trace1]

                layout = go.Layout(
                    # title='Bioimpedance Spectroscopy',
                    xaxis=dict(title='Frequency (Hz)',
                               type='linear',
                               autorange=True),
                    yaxis=dict(title='Amplitude', autorange=True))

                return {'data': data, 'layout': layout}

        return self.layout
예제 #14
0
    def start(self):
        self._main_thread = spawn(self._server)
        self.logger.debug('server started on localhost:8050')
        super().start()

        self.data_dict = {
            s.name(): {'x': [], 'y': [], 'name': s.name()}
            for s in self.graph_series()
        }
        self.data = self.data_dict_to_data_list(self.data_dict)
        figure = {'data': self.data, 'layout': {'title': self.title()}}
        app_layout = [
            dcc.Graph(id=self.title(), figure=figure),
            dcc.Interval(id='interval-component', interval=1 * 1000)
        ]

        self.app.layout = html.Div(app_layout)

        @self.app.callback(Output(self.title(), 'figure'),
                           events=[Event('interval-component', 'interval')])
        def update_graph_live():
            return {'data': self.data, 'layout': {'title': self.title()}}
예제 #15
0
    def test_events_and_state(self):
        app = Dash(__name__)
        app.layout = html.Div([
            html.Button('Click Me', id='button'),
            dcc.Input(value='Initial State', id='state'),
            html.Div(id='output')
        ])

        call_count = Value('i', 0)

        @app.callback(Output('output', 'children'),
                      state=[State('state', 'value')],
                      events=[Event('button', 'click')])
        def update_output(value):
            call_count.value += 1
            return value

        self.startServer(app)
        btn = self.driver.find_element_by_id('button')
        output = lambda: self.driver.find_element_by_id('output')

        self.assertEqual(call_count.value, 0)
        self.assertEqual(output().text, '')

        btn.click()
        wait_for(lambda: output().text == 'Initial State')
        self.assertEqual(call_count.value, 1)

        # Changing state shouldn't fire the callback
        state = self.driver.find_element_by_id('state')
        state.send_keys('x')
        time.sleep(0.75)
        self.assertEqual(output().text, 'Initial State')
        self.assertEqual(call_count.value, 1)

        btn.click()
        wait_for(lambda: output().text == 'Initial Statex')
        self.assertEqual(call_count.value, 2)
예제 #16
0
    def test_events(self):
        app = Dash(__name__)
        app.layout = html.Div(
            [html.Button('Click Me', id='button'),
             html.Div(id='output')])

        call_count = Value('i', 0)

        @app.callback(Output('output', 'children'),
                      events=[Event('button', 'click')])
        def update_output():
            call_count.value += 1
            return 'Click'

        self.startServer(app)
        btn = self.driver.find_element_by_id('button')
        output = lambda: self.driver.find_element_by_id('output')
        self.assertEqual(call_count.value, 0)
        self.assertEqual(output().text, '')

        btn.click()
        wait_for(lambda: output().text == 'Click')
        self.assertEqual(call_count.value, 1)
                 className='row'),
        html.Div([
            html.Button('Revoke Access',
                        id='revoke-button',
                        type='submit',
                        className='button button-primary',
                        n_clicks_timestamp='0'),
            html.Div(id='revoke-response', style={'color': 'red'}),
        ],
                 className='row')
    ])
])


@app.callback(Output('policy-key-response', 'children'),
              events=[Event('create-policy-button', 'click')])
def create_policy():
    label = 'vehicle-data'
    label = label.encode()

    policy_pubkey = alicia.get_policy_pubkey_from_label(label)

    return "The policy public key for " \
           "label '{}' is {}".format(label.decode('utf-8'), policy_pubkey.to_bytes().hex())


@app.callback(
    Output('grant-response', 'children'),
    [Input('revoke-button', 'n_clicks_timestamp')], [
        State('grant-button', 'n_clicks_timestamp'),
        State('days', 'value'),
예제 #18
0
                     'value': 'AAPL'
                 }],
                 value='COKE'),
    dcc.Dropdown(id='column-selector-events-example',
                 options=[{
                     'label': i,
                     'value': i
                 } for i in ['Open', 'High', 'Low', 'Close', 'High - Low']],
                 value='Open'),
    html.Button('Update Graph', id='my-button-events-example'),
    dcc.Graph(id='graph-events-example')
])


@app.callback(Output('graph-events-example', 'figure'),
              events=[Event('my-button-events-example', 'click')],
              state=[
                  State('stock-ticker-dropdown-events-example', 'value'),
                  State('column-selector-events-example', 'value')
              ])
def update_graph(stock_ticker, column):
    df = web.DataReader(stock_ticker, 'google', dt(2017, 1, 1), dt.now())

    if column != 'High - Low':
        y = df[column]
    else:
        y = df.High - df.Low

    return go.Figure(data=[go.Scatter(x=df.index, y=y)],
                     layout=go.Layout(yaxis=go.YAxis(title=column)))
예제 #19
0
#--------------------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------------------

# CALLBACKS


@app.callback(Output('nmf-button1', 'n_clicks'), [
    Input('mindf-input', 'value'),
    Input('maxdf-input', 'value'),
    Input('preprocessing-dropdown', 'value'),
    Input('ngram-range-dropdown', 'value')
], [State('nmf-button1', 'n_clicks')], [Event('nmf-button1', 'click')])
def step_one_callback(min_df_value, max_df_value, preprocessing_type,
                      ngram_range_value, button_clicks):

    if button_clicks == 1:

        # Translate ngram range dropdown's value into a usable tuple
        ngram_selection = ngram_values_dict[ngram_range_value]

        print(button_clicks)

        # Generate mode string
        if preprocessing_type == 'stemming':

            print('stemming mode activated')
            mode_selection = 'stem_tfidf_matrix'
예제 #20
0
def run_server():
    # Setup the app
    server = flask.Flask(__name__)
    app = dash.Dash(__name__, server=server, csrf_protect=False)
    app.scripts.config.serve_locally = False
    dcc._js_dist[0]['external_url'] = 'https://cdn.plot.ly/plotly-finance-1.28.0.min.js'
    # Add caching
    cache = Cache(app.server, config={'CACHE_TYPE': 'simple'})
    timeout = 60 * 60  # 1 hour
    # Controls
    app.update_graph = update_graph
    # Layout
    app.GraphicList = []
    app.newGraphic = lambda name: app.GraphicList.append(newGraphic(name))
    app.layout = html.Div(
        [
            html.Div(
                [
                    html.H2(
                        'japonicus Evolution Statistics',
                        style={'padding-top': '20', 'text-align': 'center'},
                    ),
                    html.Div(
                        [
                            dcc.Interval(id='my-interval'),
                            dcc.RadioItems(
                                id='set-time',
                                value=5000,
                                options=[
                                    {'label': 'Every 60 seconds', 'value': 60000},
                                    {'label': 'Every 15 seconds', 'value': 15000},
                                    {
                                        'label': 'Every hour', 'value': 60 * 60 * 1000
                                    },  # or just every hour
                                ],
                            ),
                        ]
                    ),
                    html.Div(id='display-time'),
                ]
            ),
            html.Div(id='Graphs'),
        ],
        style={'width': '1100', 'margin-left': 'auto', 'margin-right': 'auto', 'font-family': 'overpass', 'background-color': '#F3F3F3'},
        # Traces>Color
    )
    app.config['suppress_callback_exceptions'] = True

    @app.callback(
        Output('display-time', 'children'), events=[Event('my-interval', 'interval')]
    )
    def display_time():
        return str(datetime.datetime.now())

    @app.callback(Output('my-interval', 'interval'), [Input('set-time', 'value')])
    def update_interval(value):
        return value

    @cache.memoize(timeout=timeout)
    @app.callback(
        Output('Graphs', 'children'), events=[Event('my-interval', 'interval')]
    )
    def updateGraphs():
        '''
        for F in range(len(app.GraphicList)):
            if app.GraphicList[F].Active:
                app.GraphicList[F].__setattr__('figure', update_graph(app.GraphicList[F].id))
        '''
        return app.GraphicList

    # External css
    external_css = [
        "https://fonts.googleapis.com/css?family=Overpass:400,400i,700,700i",
        "https://cdn.rawgit.com/plotly/dash-app-stylesheets/c6a126a684eaaa94a708d41d6ceb32b28ac78583/dash-technical-charting.css",
    ]
    for css in external_css:
        app.css.append_css({"external_url": css})
    # Run the Dash app
    if __name__ == '__main__':
        app.server.run(debug=True, host='0.0.0.0')
    else:  # this way it integrates with main interface without child procs across pipes,
        return app
예제 #21
0
        dict(title="OHLC")
    }


@app.callback(Output('v', 'figure'), [Input('symbol-dropdown', 'value')])
def plot_v(value):
    global data
    dates, _, _, _, _, volume = data.get_ohlcv(value)
    return {
        'data': [go.Bar(x=dates, y=volume)],
        'layout': dict(title="Volume")
    }


@app.callback(Output('market-prices-graph', 'figure'),
              events=[Event('graph-speed-update', 'interval')])
def update_market_prices():
    global selected_dropdown_value
    global data
    prices = data.get_prices(selected_dropdown_value)
    prices = [list(p) for p in zip(*prices)]
    if len(prices) > 0:
        traces = []
        x = list(prices[3])
        for i, key in enumerate(['bid', 'ask']):
            trace = go.Scatter(x=x, y=prices[i], name=key, opacity=0.8)
            traces.append(trace)
        return {'data': traces, 'layout': dict(title="Market Prices")}


@app.callback(Output('market-prices-hist', 'figure'),
예제 #22
0
def pos_neg_neutral(col):
    if col >= POS_NEG_NEUT:
        # positive
        return 1
    elif col <= -POS_NEG_NEUT:
        # negative:
        return -1

    else:
        return 0


@app.callback(
    Output('recent-tweets-table', 'children'),
    [Input(component_id='sentiment_term', component_property='value')],
    events=[Event('recent-table-update', 'interval')])
def update_recent_tweets(sentiment_term):
    if sentiment_term:
        df = pd.read_sql(
            "SELECT sentiment.* FROM sentiment_fts fts LEFT JOIN sentiment ON fts.rowid = sentiment.id WHERE fts.sentiment_fts MATCH ? ORDER BY fts.rowid DESC LIMIT 10",
            conn,
            params=(sentiment_term + '*', ))
    else:
        df = pd.read_sql(
            "SELECT * FROM sentiment ORDER BY id DESC, unix DESC LIMIT 10",
            conn)

    df['date'] = pd.to_datetime(df['unix'], unit='ms')

    df = df.drop(['unix', 'id'], axis=1)
    df = df[['date', 'tweet', 'sentiment']]
예제 #23
0
                                          'value': 'Ford'
                                      },
                                      {
                                          'label': 'Samsung',
                                          'value': 'Samsung'
                                      },
                                  ]))
             ]),
    html.Div(id='live-update-graph', style={'backgroundColor': 'transparent'}),
    dcc.Interval(id='interval-update', interval=10000)
])


@app.callback(Output('live-update-graph', 'children'),
              [Input('my_dropdown', 'value')],
              events=[Event('interval-update', 'interval')])

# def api(value):

#     data = response.json()
#     pretty = pd.DataFrame()

# def api(value):
# response = requests.get("http://104.154.230.56/api/get_tweets_with_lat_long/{}".format(value))
# data = response.json()
# pretty = pd.DataFrame()

# df_sent = pd.DataFrame.from_dict(json_normalize(data['Sentiment_Value']), orient='columns')
# df_lat = pd.DataFrame.from_dict(json_normalize(data['Latitude']), orient='columns')
# df_long = pd.DataFrame.from_dict(json_normalize(data['Longitude']), orient='columns')
# df_tweet = pd.DataFrame.from_dict(json_normalize(data['Tweet_Text']), orient='columns')
예제 #24
0
                             type='line',
                             line=Line(dash='dash', color='#2E5266', width=5)),
                        dict(xref='x',
                             yref='y',
                             y1=int(max(bin_val_max, y_val_max)) + 0.5,
                             y0=0,
                             x0=median_val,
                             x1=median_val,
                             type='line',
                             line=Line(dash='dot', color='#BD9391', width=5))
                    ])
    return Figure(data=[trace, trace1, trace2, trace3], layout=layout)


@app.callback(Output('bin-auto', 'values'), [Input('bin-slider', 'value')],
              [State('wind-speed', 'figure')], [Event('bin-slider', 'change')])
def deselect_auto(sliderValue, wind_speed_figure):
    if (wind_speed_figure is not None
            and len(wind_speed_figure['data'][0]['y']) > 5):
        return ['']
    else:
        return ['Auto']


@app.callback(Output('bin-size', 'children'), [Input('bin-auto', 'values')],
              [State('bin-slider', 'value')], [])
def deselect_auto(autoValue, sliderValue):
    if 'Auto' in autoValue:
        return '# of Bins: Auto'
    else:
        return '# of Bins: ' + str(int(sliderValue))
예제 #25
0
from collections import deque
import sqlite3
import pandas as pd

#popular topics: google, olympics, trump, gun, usa

app = dash.Dash(__name__)
app.layout = html.Div([
    html.H2('Live Twitter Sentiment'),
    dcc.Graph(id='live-graph', animate=True),
    dcc.Interval(id='graph-update', interval=1 * 1000),
])


@app.callback(Output('live-graph', 'figure'),
              events=[Event('graph-update', 'interval')])
def update_graph_scatter():
    try:
        conn = sqlite3.connect('twitter.db')
        c = conn.cursor()
        df = pd.read_sql(
            "SELECT * FROM sentiment WHERE tweet LIKE '%is%' ORDER BY unix DESC LIMIT 1000",
            conn)
        df.sort_values('unix', inplace=True)
        df['sentiment_smoothed'] = df['sentiment'].rolling(int(len(df) /
                                                               5)).mean()
        df.dropna(inplace=True)

        X = df.unix.values[-100:]
        Y = df.sentiment_smoothed.values[-100:]
예제 #26
0
    dcc.Interval(id='graph-update', interval=1 * 1000),
])

app_colors = {
    'background': '#0C0F0A',
    'text': '#FFFFFF',
    'sentiment-plot': '#41EAD4',
    'volume-bar': '#FBFC74',
    'someothercolor': '#FF206E',
}


@app.callback(
    Output('live-graph', 'figure'),
    [Input(component_id='sentiment_term', component_property='value')],
    events=[Event('graph-update', 'interval')])
def update_graph_scatter(sentiment_term):
    try:
        conn = sqlite3.connect('twitter.db')
        c = conn.cursor()
        df = pd.read_sql(
            "SELECT * FROM sentiment WHERE tweet LIKE ? ORDER BY unix DESC LIMIT 1000",
            conn,
            params=('%' + sentiment_term + '%', ))
        df.sort_values('unix', inplace=True)
        df['date'] = pd.to_datetime(df['unix'], unit='ms')
        df.set_index('date', inplace=True)
        df['sentiment_smoothed'] = df['sentiment'].rolling(int(len(df) /
                                                               5)).mean()
        df.dropna(inplace=True)
        #df = df.resample('1s').mean() #averaging per second
예제 #27
0
    def registerCallbacks(self, app):
        terminalId = self.terminalId
        intervalId = self.intervalId
        buttonId = self.buttonId

        # Add support for staying scrolled to bottom of 'terminal' div
        # app.scripts.append_script({'external_url': 'https://codepen.io/plevin/pen/MvpeNV.js'})

        # Since events aren't handled as well as inputs, we convert the
        # timer event into an input by setting the value in a hidden <div>.
        @app.callback(Output('timer-div', 'children'),
                      events=[Event(intervalId, 'interval')])
        def timerToInput():
            return str(time.time())  # because it changes each call

        @app.callback(Output(terminalId, 'children'),
                      [Input('timer-div', 'children')])
        def updateTerminal(timer):
            # print("updateTerminal(%s)" % timer)
            if not self.proc:
                return self.text

            newText = ''

            # Loop while there is data to read
            q = self.queue
            while q.qsize() > 0:
                buf = q.get_nowait()
                if buf == '':
                    break

                newText += buf.decode('utf-8')

            self.text += newText

            self.status = self.proc.poll()
            self.running = self.status is None
            if not self.running:
                self.text += "\n[Process exited]\n"
                self.proc = self.fd = None

            return self.text

        @app.callback(
            Output('button-div', 'children'),  # writing to this is a no-op
            [Input(buttonId, 'n_clicks')])
        def processClick(clicks):
            if clicks is None:
                return ''

            if self.running:
                self.stopCommand()
            else:
                command = self.page.getCommand()
                self.runCommand(command)

            return str(time.time())

        # Set button text to match running state, on click or timer.
        @app.callback(
            Output(buttonId, 'children'),
            [Input('button-div', 'children'),
             Input('timer-div', 'children')])
        def clicks(buttonInfo, timerInfo):
            # print("clicks: button:%s, timer:%s" % (buttonInfo, timerInfo))
            return 'Stop' if self.running else 'Run'

        # Set a short interval timer when a proc is running, otherwise
        # set it to an hour (effectively disabling it.)
        @app.callback(
            Output(intervalId, 'interval'),
            [Input('button-div', 'children'),
             Input('timer-div', 'children')])
        def setTimer(buttonInfo, timerInfo):
            # print("setTimer: button:%s, timer:%s" % (buttonInfo, timerInfo))
            oneHour = 60 * 60 * 1000
            ms = self.ms if self.running else oneHour
            return ms
예제 #28
0
            ],
                     className='row'),
            html.Div(id='heartbeats', className='row'),
            dcc.Interval(id='heartbeat-update', interval=1000, n_intervals=0),
        ],
                 className='row'),
        # Hidden div inside the app that stores previously decrypted heartbeats
        html.Div(id='latest-decrypted-heartbeats', style={'display': 'none'})
    ])

    return layout


@app.callback(Output('pub-key',
                     'children'), [], [State('bob-unique-id', 'children')],
              [Event('gen-key-button', 'click')])
def gen_doctor_pubkey(bob_id):
    bob_pubkeys = demo_keys.get_recipient_pubkeys(bob_id)
    return bob_pubkeys['enc'].to_bytes().hex()


@app.callback(Output('latest-decrypted-heartbeats', 'children'), [], [
    State('read-button', 'n_clicks_timestamp'),
    State('latest-decrypted-heartbeats', 'children'),
    State('bob-unique-id', 'children')
], [Event('heartbeat-update', 'interval'),
    Event('read-button', 'click')])
def update_cached_decrypted_heartbeats_list(read_time, json_latest_values,
                                            bob_id):
    if int(read_time) == 0:
        # button never clicked but triggered by interval
예제 #29
0
    def get_chart(cls):

        data = Status.fetch()

        top_div = html.Div([html.H1('FOMO DRIVEN DEVELOPMENT')])
        top_div2 = html.Div([html.H2('GUNBOT SUPER FILTER')])
        banner = html.Div([top_div, top_div2], className='banner')

        bottom_div = html.Div([
            dcc.Graph(id='live-graph', animate=True),
            dcc.Interval(
                id='graph-update',
                interval=15 * 1000,
            )
        ])

        app = dash.Dash(__name__)
        app.layout = html.Div([banner, bottom_div], className='container')

        app.css.append_css({
            'external_url':
            'https://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,600,700'
        })

        app.css.append_css(
            {'external_url': 'https://codepen.io/dgnsrekt/pen/wXXNWM.css'})

        app.css.append_css(
            {'external_url': 'https://codepen.io/dgnsrekt/pen/dKKKLP.css'})

        @app.callback(Output('live-graph', 'figure'),
                      events=[Event('graph-update', 'interval')])
        def update_graph():
            data = Status.fetch()

            index = data.index
            balance = data.balance
            positions = data.positions

            b_trace = go.Scatter(name='balance-btc',
                                 x=list(index),
                                 y=list(balance),
                                 mode='lines',
                                 marker=dict(size=14, color=COLORS['balance']),
                                 connectgaps=True)

            p_trace = go.Scatter(name='positions',
                                 x=list(index),
                                 y=list(positions),
                                 yaxis='y2',
                                 mode='markers',
                                 marker=dict(color=COLORS['positions']))
            layout = go.Layout(legend=dict(font=dict(color=COLORS['legend'])),
                               plot_bgcolor='#000000',
                               paper_bgcolor='#000000',
                               font=dict(family='Source Sans Pro'),
                               xaxis=dict(autorange=True,
                                          color=COLORS['legend'],
                                          title='TIME'),
                               yaxis=dict(autorange=True,
                                          color=COLORS['balance'],
                                          title='BTC BALANCE'),
                               yaxis2=dict(autorange=True,
                                           title='OPEN POSITIONS',
                                           color=COLORS['positions'],
                                           overlaying='y',
                                           side='right',
                                           range=[0,
                                                  int(max(positions) + 5)]))
            return {'data': [b_trace, p_trace], 'layout': layout}

        return app
예제 #30
0
파일: interface.py 프로젝트: tmjnow/tRECS
            html.Tr(
                [html.Td(df.iloc[i][col][:150] + ' ...') for col in columns])
            for i in range(1)
        ])
    ## If data has more than 3 entries, display first 3 entries as a sample
    else:
        return html.Table([html.Tr([html.Th(col) for col in columns])] + [
            html.Tr(
                [html.Td(df.iloc[i][col][:150] + ' ...') for col in columns])
            for i in range(3)
        ])


## ------- WHEN USER PRESSES NEXT STEP, CHANGE CONTENT AND INCREMENT SLIDER --------
@app.callback(Output(component_id='slider', component_property='value'),
              events=[Event('next-button', 'click')])
def next():
    # '''
    # 	Description: Used for switching of page content. When next step button pressed, increments or resets global variable step.
    # 	Params: None
    # 	Returns: Incremented or reset global step variable.
    # '''

    global step
    if step == 5:
        step = 0
        return step
    else:
        step += 1
        return step