Пример #1
0
                html.Thead(
                    html.Tr(
                        [
                            html.Th('第一列'),
                            html.Th('第二列'),
                        ]
                    )
                ),
                html.Tbody(
                    [
                        html.Tr(
                            [
                                html.Td('一行一列'),
                                html.Td('一行二列'),
                            ]
                        ),
                        html.Tr(
                            [
                                html.Td('二行一列'),
                                html.Td('二行二列'),
                            ]
                        )
                    ]
                )
            ]
        ),
        style={
            'margin-top': '50px'  # 设置顶部留白区域高度
        }
    )
)
        部分超高频词与无意义助词已经被剔除,无法查询或出现在结果中,例如`但、国家、会`。
        分析基于2011年来的外交部长讲话。
    '''),
    html.Br(),
    html.Div([
        dcc.Input(
            id="init_words",
            placeholder='在这里进行输入',
            style={'width': '80%'},
        )
    ]),
    html.Br(),
    html.Div([
        html.Table([
            html.Tbody([html.Tr(
                id='r1'), html.Tr(id='r2'),
                        html.Tr(id='r3')])
        ])
    ])
])


@app.callback(
    [
        Output(component_id="r1", component_property="children"),
        Output(component_id="r2", component_property="children"),
        Output(component_id="r3", component_property="children")
    ],
    [Input(component_id='init_words', component_property='value')],
)
def getSimilarWords(words):
Пример #3
0
            dcc.Input(
                placeholder="Enter a year",
                id="input",
                style={"width":"60%"},type='number'
                ),
            html.Button(id='submit-button', n_clicks=0, children='Submit'),
            html.Div(id='dummy'),
            
        ]
        , style={"text-align":"center", "width":"100%", "columnCount":2}),

    html.Table(
        [
            html.Tbody([
                html.Tr([
                    html.Td(pop.iloc[i][col]) for col in pop.columns
                ]) for i in range(min(len(pop), 5))
            ], id="table1")
        ], style={"width": "100%"}
    ),


    dcc.Graph(
        id='graph-1',
        figure={
            'data': [
                {'x':pop['Year'],'y':pop['Total Population']}],
            'layout': dict(
                xaxis={'title': 'Year'},
                yaxis={'title': 'Total Population'})
Пример #4
0
        html.Td(
            dbc.Input(id='z-' + elem.replace(' ', '-'),
                      value=0,
                      type='number',
                      min=0,
                      max=10,
                      step=0.0000001,
                      placeholder='z')),
        html.Td(
            dbc.Input(id='v-' + elem.replace(' ', '-'),
                      type='number',
                      placeholder='Velocity (km/s)',
                      value=0))
    ])
    elem_input_array.append(row)
table_body_one = [html.Tbody(elem_input_array)]

elem_input_array = []
for elem in list(elements.keys())[9:]:
    row = html.Tr([
        html.Td(
            dbc.Checkbox(id='standalone-checkbox-' + elem.replace(' ', '-'))),
        html.Td(elem),
        html.Td(dbc.Badge(
            '__',  #elem,
            color=elements[elem]['color'])),
        html.Td(
            dbc.Input(id='z-' + elem.replace(' ', '-'),
                      value=0,
                      type='number',
                      min=0,
Пример #5
0
dropdown_game_type = dbc.DropdownMenu(
    [
        dbc.DropdownMenuItem(str("Game Type").upper(), header=True),
        dbc.DropdownMenuItem(str("All").upper(), id="gt_all", n_clicks=0),
        dbc.DropdownMenuItem(str("Standard").upper(), id="gt_std", n_clicks=0),
        dbc.DropdownMenuItem(str("Tournament").upper(), id="gt_tourney", n_clicks=0),
    ],
    label="Game Type",
    id="dropdown_game_type",
)

dropdown_states = dbc.Row(
    justify="center",
    children=[
        html.Tbody("xsxsxs", id="g_status", style={"margin": "10px"}),
        html.Tbody("xsxsxs", id="g_winner", style={"margin": "10px"}),
        html.Tbody("xsxsxs", id="g_time_control", style={"margin": "10px"}),
        html.Tbody(children="111", id="g_game_type", style={"margin": "10px"}),
    ],
)

popover_status = dbc.Popover(
    [
        dbc.PopoverHeader("Status of the Game"),
        dbc.PopoverBody(
            "Games can be over in a myriad of ways, either by checkmate, draw, player resignation, or when a player runs out of time. Filter the games by these conditions here."
        ),
    ],
    trigger="hover",
    target="dropdown_status",
Пример #6
0
                           id="button_spend")

table_header = [
    html.Thead(
        html.Tr([
            html.Th("Job"),
            html.Th("Compagnie"),
            html.Th("Location"),
            html.Th("Salary"),
            html.Th("Summary"),
            html.Th("Lien"),
            html.Th("Site")
        ]))
]

table_body = [html.Tbody(id='formulaire')]

body = dbc.Container(
    [
        dbc.Row([dbc.Form([what_input, where_input, submit_button])]),
        html.Br(),
        html.Br(),
        dbc.Row([
            dbc.Table(table_header + table_body,
                      bordered=True,
                      dark=True,
                      hover=True,
                      responsive=True,
                      striped=True)
        ])
    ],
Пример #7
0
    def test_multi_output(self):
        app = dash.Dash(__name__)
        app.scripts.config.serve_locally = True

        app.layout = html.Div([
            html.Button('OUTPUT', id='output-btn'),
            html.Table([
                html.Thead(
                    [html.Tr([html.Th('Output 1'),
                              html.Th('Output 2')])]),
                html.Tbody([
                    html.Tr([html.Td(id='output1'),
                             html.Td(id='output2')]),
                ])
            ]),
            html.Div(id='output3'),
            html.Div(id='output4'),
            html.Div(id='output5')
        ])

        @app.callback(
            [Output('output1', 'children'),
             Output('output2', 'children')], [Input('output-btn', 'n_clicks')],
            [State('output-btn', 'n_clicks_timestamp')])
        def on_click(n_clicks, n_clicks_timestamp):
            if n_clicks is None:
                raise PreventUpdate

            return n_clicks, n_clicks_timestamp

        # Dummy callback for DuplicateCallbackOutput test.
        @app.callback(Output('output3', 'children'),
                      [Input('output-btn', 'n_clicks')])
        def dummy_callback(n_clicks):
            if n_clicks is None:
                raise PreventUpdate

            return 'Output 3: {}'.format(n_clicks)

        # Test that a multi output can't be included in a single output
        with self.assertRaises(DuplicateCallbackOutput) as context:

            @app.callback(Output('output1', 'children'),
                          [Input('output-btn', 'n_clicks')])
            def on_click_duplicate(n_clicks):
                if n_clicks is None:
                    raise PreventUpdate

                return 'something else'

        self.assertTrue('output1' in context.exception.args[0])

        # Test a multi output cannot contain a used single output
        with self.assertRaises(DuplicateCallbackOutput) as context:

            @app.callback(
                [Output('output3', 'children'),
                 Output('output4', 'children')],
                [Input('output-btn', 'n_clicks')])
            def on_click_duplicate_multi(n_clicks):
                if n_clicks is None:
                    raise PreventUpdate

                return 'something else'

        self.assertTrue('output3' in context.exception.args[0])

        with self.assertRaises(DuplicateCallbackOutput) as context:

            @app.callback(
                [Output('output5', 'children'),
                 Output('output5', 'children')],
                [Input('output-btn', 'n_clicks')])
            def on_click_same_output(n_clicks):
                return n_clicks

        self.assertTrue('output5' in context.exception.args[0])

        with self.assertRaises(DuplicateCallbackOutput) as context:

            @app.callback(
                [Output('output1', 'children'),
                 Output('output5', 'children')],
                [Input('output-btn', 'n_clicks')])
            def overlapping_multi_output(n_clicks):
                return n_clicks

        self.assertTrue(
            '{\'output1.children\'}' in context.exception.args[0]
            or "set(['output1.children'])" in context.exception.args[0])

        self.startServer(app)

        t = time.time()

        btn = self.wait_for_element_by_id('output-btn')
        btn.click()
        time.sleep(1)

        self.wait_for_text_to_equal('#output1', '1')
        output2 = self.wait_for_element_by_css_selector('#output2')

        self.assertGreater(int(output2.text), t)
Пример #8
0
    rows_for_table.append(
        html.Tr([
            html.Td(row["datetime"]),
            html.Td(row["season"]),
            html.Td(row["holiday"]),
            html.Td(row["workingday"]),
            html.Td(row["weather"]),
            html.Td(row["temp"]),
            html.Td(row["atemp"]),
            html.Td(row["humidity"]),
            html.Td(row["windspeed"]),
            html.Td(row["count"])
        ]))

## add organized columns into table ##
table_body = [html.Tbody(rows_for_table)]

### Parse Data for Vis1 ################################################################################################
vis_count_by_date = dp.vis_count_by_date()
gofig = go.Figure()
date_count = gofig.add_trace(
    go.Scatter(x=vis_count_by_date["date"], y=vis_count_by_date["count"]))

### Parse Data for Vis2 ################################################################################################
visd2 = dp.vis_rel_count_temp()

### Parse Data for Vis3 ################################################################################################
heatfig = dp.vis_heatmap()


@server.route("/", methods=['GET'])
Пример #9
0
def fit_model(xvars, yvars, algo_choice, dataset_choice, problem_type):
    """
    Take user choices and, if all are present, fit the appropriate model. \
    The results of fitting are given to hidden divs. When the user uses \
    the tab menu then the appropriate menu is rendered.

    Args:
        xvars (list(str)): predictor variables.
        yvars (str): target variable.
        algo_choice (str): The choice of algorithm type.
        dataset_choice (str): Name of the dataset.
        problem_type (str): The type of learning problem.

    Returns:
        list, dict: Dash element(s) with the results of model fitting,
                    and parameters for plotting a graph.
    """

    df = dill.loads(redis_conn.get(dataset_choice))

    # Make sure all variables have a value before fitting
    if any(x is None for x in [xvars, yvars, df, dataset_choice,
                               algo_choice]):
        raise PreventUpdate()

    # The inverse mapping of ml_options, use it to get the sklearn model
    model = node_options[algo_choice]["model_class"]()

    # TODO: This probably needs a better/cleaner implementation and/or
    #       might need to be used in other parts as well.
    y = pd.factorize(df[yvars])
    model.fit(df[xvars], y[0])

    predictions = model.predict(df[xvars])
    score = model.score(df[xvars], y[0])

    metrics = []
    if problem_type == "regression":
        metrics.append(html.H4(f"Mean Squared Error: {score:.3f}"))

    elif problem_type == "classification":
        metrics.append(html.H4(f"Accuracy: {100*score:.3f} %"))
        metrics.append(html.H4("Confusion matrix:"))

        classes = df[yvars].unique()

        confusion = confusion_matrix(y[0], predictions)
        metrics.append(html.Table([
            html.Thead([html.Th(cls) for cls in classes]),

            html.Tbody([
               html.Tr([html.Td(item) for item in row])
               for row in confusion
            ])
        ]))

    else:
        metrics.append("Not implemented")

    labels = model.predict(df[xvars])
    # TODO: Visualize the (in)correctly grouped points.
    # If we have >=2 variables, visualize the classification
    if len(xvars) >= 3:

        trace1 = go.Scatter3d(x=df[xvars[0]],
                              y=df[xvars[1]],
                              z=df[xvars[2]],
                              showlegend=False,
                              mode='markers',
                              marker={
                                  'color': labels.astype(np.float),
                                  'line': dict(color='black', width=1)
                              })

        figure = {
            'data': [trace1],
            'layout': layouts.default_2d(xvars[0], yvars[0])
        }

    elif len(xvars) == 2:
        traces = scatterplot(df[xvars[0]], df[xvars[1]],
                             marker={'color': labels.astype(np.float)})

        figure = {
            'data': [traces],
            'layout': go.Layout(
                xaxis={'title': xvars[0]},
                yaxis={'title': yvars[0]},
                legend={'x': 0, 'y': 1},
                hovermode='closest'
            )
        }

    else:
        figure = {}

    return metrics, figure
Пример #10
0
def get_html_medal_table(rows):
    return html.Table([
        html.Tbody(rows)
    ])
        # Body
            html.Tbody(
                [html.Tr([
                    html.Td('Affiliate',style={'padding-bottom':'10px','padding-right': '30px','textAlign': 'left','color':'#597E16','fontSize': 18,'fontWeight':'bold'}),
                    html.Td(children=html.Div(dcc.Dropdown(id='Affiliate',
                                                           options=[{'label': k, 'value': k} for k in ['CH','NL','AT','IE','RO','CZ']],
                                                           style={'color':'#000000','width':'100px',})),style={'padding-bottom':'10px','padding-left': '10px','padding-right': '40px'})
                    ]),
                html.Tr([
                    html.Td('From Date',style={'padding-bottom':'10px','padding-right': '30px','textAlign': 'left','color':'#597E16','fontSize': 18,'fontWeight':'bold'}),
                    html.Td(children=html.Div(dcc.DatePickerSingle(
                                                           id='start_date',
                                                           min_date_allowed=dt(2018, 1, 1),
                                                           max_date_allowed=today_date,
                                                           initial_visible_month=today_date,
                                                           date=str(today_date),

                                                       )),style={'padding-bottom':'10px','padding-left': '10px','padding-right': '40px'})
                    ]),
                html.Tr([
                    html.Td('To Date',style={'padding-bottom':'10px','padding-right': '30px','textAlign': 'left','color':'#597E16','fontSize': 18,'fontWeight':'bold'}),
                    html.Td(children=html.Div(dcc.DatePickerSingle(
                                                           id='end_date',
                                                           min_date_allowed=dt(2018, 1, 1),
                                                           max_date_allowed=today_date,
                                                           initial_visible_month=today_date,
                                                           date=str(today_date),
                                                       )),style={'padding-bottom':'10px','padding-left': '10px','padding-right': '40px'})
                    ])
                ])
    ],style={
Пример #12
0
def update_quick_look_section_2(selected_country):
    # filtered data
    df_filtered = df[df["Country"] == selected_country]
    # filtered by selected country and indicator
    df_filtered = df_filtered[df_filtered["Name"] == "NEET.Female"]
    # drop rows with missing indicator values
    df_filtered = df_filtered.dropna(axis="index", subset=["value"])

    df_filtered.sort_values('Year', inplace=True)
    women = str(df_filtered['value'].tail(1).tolist()[0]) + "%" if len(
        df_filtered) != 0 else 'NA'

    # filtered data
    df_filtered = df[df["Country"] == selected_country]
    # filtered by selected country and indicator
    df_filtered = df_filtered[df_filtered["Name"] == "NEET.Male"]
    # drop rows with missing indicator values
    df_filtered = df_filtered.dropna(axis="index", subset=["value"])

    df_filtered.sort_values('Year', inplace=True)
    men = str(df_filtered['value'].tail(1).tolist()[0]) + '%' if len(
        df_filtered) != 0 else 'NA'

    return html.Table(
        # Header
        html.Tbody([
            html.Tr(
                [
                    html.Th(
                        'Youth NEET', colSpan='2', style={'textAlign': 'left'})
                ],
                style={
                    'borderTop': '1px solid light-grey',
                    'fontSize': '16px',
                    'colspan': '2',
                    'color': 'white',
                    'width': '100%'
                })
        ] + [
            html.Tr(
                [
                    html.Th('Women:', style={'textAlign': 'left'}),
                    html.Th(women,
                            style={
                                'marginLeft': 'auto',
                                'textAlign': 'right'
                            })
                ],
                style={
                    'borderTop': '1px solid light-grey',
                    'fontSize': '15px',
                    'color': 'white',
                    'width': '100%'
                })
        ] + [
            html.Tr(
                [
                    html.Th('Men:', style={'textAlign': 'left'}),
                    html.Th(men,
                            style={
                                'marginLeft': 'auto',
                                'textAlign': 'right'
                            })
                ],
                style={
                    'borderTop': '1px solid light-grey',
                    'fontSize': '15px',
                    'color': 'white',
                    'width': '100%'
                })
        ], ),
        style={'width': '100%'})
Пример #13
0
PH_kaggle_filter = (df['country'] == 'Philippines') & (df['date']
                                                       == df.iloc[-1]['date'])
PH_kaggle_df = df[PH_kaggle_filter]

topline_header1 = [
    html.Thead(
        html.Tr(
            [html.Th("Confirmed"),
             html.Th("Deaths"),
             html.Th("Recovered")]))
]
topline_body1 = [
    html.Tbody(children=[
        html.Tr(children=[
            html.Td(html.H2(PH_kaggle_df['confirmed'])),  # From Kaggle
            html.Td(html.H2(PH_kaggle_df['deaths'])),  # From Kaggle
            html.Td(html.H2(PH_kaggle_df['recovered']))  # From Kaggle
        ])
    ])
]

topline_header2 = [
    html.Thead(
        html.Tr([
            html.Th("Active"),
            html.Th("Fatality Rate"),
            html.Th("Recovery Rate")
        ]))
]
topline_body2 = [
    html.Tbody(children=[
Пример #14
0
             ]
         )
     ),
     html.Tbody(
         [
             html.Tr(
                 [
                     html.Th("1", scope="row"),
                     html.Td("Tom"),
                     html.Td("Cruise"),
                 ]
             ),
             html.Tr(
                 [
                     html.Th("2", scope="row"),
                     html.Td("Jodie"),
                     html.Td("Foster"),
                 ]
             ),
             html.Tr(
                 [
                     html.Th("3", scope="row"),
                     html.Td("Chadwick"),
                     html.Td("Boseman"),
                 ]
             ),
         ]
     ),
 ],
 responsive=True,
 striped=True,
Пример #15
0
 html.Tbody([
     html.Tr([
         html.Td(
             [
                 html.P(dd_list_stats[0]),
                 dcc.Graph(figure=small_multiple_choropleths[0])
             ],
             style={
                 'width': '33.3%',
                 'display': 'inline-block',
                 'margin': '0',
                 'padding': '0',
                 'border': 'none'
             }),
         html.Td(
             [
                 html.P(dd_list_stats[3]),
                 dcc.Graph(figure=small_multiple_choropleths[3])
             ],
             style={
                 'width': '33.3%',
                 'display': 'inline-block',
                 'margin': '0',
                 'padding': '0',
                 'border': 'none'
             }),
         html.Td(
             [
                 html.P(dd_list_stats[4]),
                 dcc.Graph(figure=small_multiple_choropleths[4])
             ],
             style={
                 'width': '33.3%',
                 'display': 'inline-block',
                 'margin': '0',
                 'padding': '0',
                 'border': 'none'
             }),
     ],
             style={
                 'width': '100%',
                 'display': 'inline-block'
             }),
     html.Tr([
         html.Td(
             [
                 html.P(dd_list_stats[5]),
                 dcc.Graph(figure=small_multiple_choropleths[5])
             ],
             style={
                 'width': '33.3%',
                 'display': 'inline-block',
                 'margin': '0',
                 'padding': '0',
                 'border': 'none'
             }),
         html.Td(
             [
                 html.P(dd_list_stats[7]),
                 dcc.Graph(figure=small_multiple_choropleths[7])
             ],
             style={
                 'width': '33.3%',
                 'display': 'inline-block',
                 'margin': '0',
                 'padding': '0',
                 'border': 'none'
             }),
         html.Td(
             [
                 html.P(dd_list_stats[9]),
                 dcc.Graph(figure=small_multiple_choropleths[9])
             ],
             style={
                 'width': '33.3%',
                 'display': 'inline-block',
                 'margin': '0',
                 'padding': '0',
                 'border': 'none'
             }),
     ],
             style={
                 'width': '100%',
                 'display': 'inline-block'
             }),
     html.Tr([
         html.Td(
             [
                 html.P(dd_list_stats[10]),
                 dcc.Graph(figure=small_multiple_choropleths[10])
             ],
             style={
                 'width': '33.3%',
                 'display': 'inline-block',
                 'margin': '0',
                 'padding': '0',
                 'border': 'none'
             }),
         html.Td(
             [
                 html.P(dd_list_stats[11]),
                 dcc.Graph(figure=small_multiple_choropleths[11])
             ],
             style={
                 'width': '33.3%',
                 'display': 'inline-block',
                 'margin': '0',
                 'padding': '0',
                 'border': 'none'
             }),
         html.Td(
             [
                 html.P(dd_list_stats[12]),
                 dcc.Graph(figure=small_multiple_choropleths[12])
             ],
             style={
                 'width': '33.3%',
                 'display': 'inline-block',
                 'margin': '0',
                 'padding': '0',
                 'border': 'none'
             }),
     ],
             style={
                 'width': '100%',
                 'display': 'inline-block'
             }),
     html.Tr([
         html.Td(
             [
                 html.P(dd_list_stats[13]),
                 dcc.Graph(figure=small_multiple_choropleths[13])
             ],
             style={
                 'width': '33.3%',
                 'display': 'inline-block',
                 'margin': '0',
                 'padding': '0',
                 'border': 'none'
             }),
         html.Td(
             [
                 html.P(dd_list_stats[14]),
                 dcc.Graph(figure=small_multiple_choropleths[14])
             ],
             style={
                 'width': '33.3%',
                 'display': 'inline-block',
                 'margin': '0',
                 'padding': '0',
                 'border': 'none'
             }),
         html.Td(
             [
                 html.P(dd_list_stats[15]),
                 dcc.Graph(figure=small_multiple_choropleths[15])
             ],
             style={
                 'width': '33.3%',
                 'display': 'inline-block',
                 'margin': '0',
                 'padding': '0',
                 'border': 'none'
             }),
     ],
             style={
                 'width': '100%',
                 'display': 'inline-block'
             }),
     html.Tr([
         html.Td(
             [
                 html.P(dd_list_stats[23]),
                 dcc.Graph(figure=small_multiple_choropleths[23])
             ],
             style={
                 'width': '33.3%',
                 'display': 'inline-block',
                 'margin': '0',
                 'padding': '0',
                 'border': 'none'
             }),
         html.Td(
             [
                 html.P(dd_list_stats[24]),
                 dcc.Graph(figure=small_multiple_choropleths[24])
             ],
             style={
                 'width': '33.3%',
                 'display': 'inline-block',
                 'margin': '0',
                 'padding': '0',
                 'border': 'none'
             }),
         html.Td(
             [
                 html.P(dd_list_stats[25]),
                 dcc.Graph(figure=small_multiple_choropleths[25])
             ],
             style={
                 'width': '33.3%',
                 'display': 'inline-block',
                 'margin': '0',
                 'padding': '0',
                 'border': 'none'
             }),
     ],
             style={
                 'width': '100%',
                 'display': 'inline-block'
             }),
 ],
            style={
                'width': '100%',
                'display': 'inline-block'
            }),
                     'margin-right': 10,
                     'max-width': 50000
                 }),

        ### Table initialization
        html.Div(
            id="recent-tweets-table",
            children=[
                html.Thead(
                    html.Tr(children=[], style={'color': app_colors['text']})),
                html.Tbody([
                    html.Tr(
                        children=[],
                        style={
                            'color':
                            app_colors['text'],
                            'background-color':
                            app_colors['backgroundTableRows'],
                            'border': '0.2px',
                            'font - size': '0.7rem'
                        })
                ])
            ],
            className='col s12 m6 l6',
            style={
                'width': '98%',
                'margin-top': 30,
                'margin-left': 15,
                'margin-right': 15,
                'max-width': 50
            }),
        html.Footer(
Пример #17
0
def update_sidebar_on_row_click(selected_cells, publication_type,
                                searched_domains, data, current_children,
                                suggestions):
    if selected_cells is None or len(selected_cells) == 0:
        return current_children

    selected_row = data[selected_cells[0]['row']]

    table_tooltips = [
        'Data opublikowania rozporządzenia',
        'Wartość punktowa podana w rozporządzeniu',
    ]
    table_header = [
        html.Thead(
            html.Tr([
                html.Th('Data', title=table_tooltips[0]),
                html.Th('Punkty', title=table_tooltips[1]),
            ]))
    ]

    past_points = [
        html.Tr([
            html.Td(date, title=table_tooltips[0]),
            html.Td(points,
                    title=table_tooltips[1] +
                    '\nPunktacja według starego systemu (max 50 pkt)',
                    style={'text-decoration': 'underline'}),
        ]) if publication_type == 'czasopisma' and int(date[:4]) < 2018 else
        html.Tr([
            html.Td(date, title=table_tooltips[0]),
            html.Td(points, title=table_tooltips[1]),
        ]) for _, date, points in selected_row['PointsHistory']
    ]

    table_body = [html.Tbody(past_points)]
    title = selected_row['Title']

    domains = []
    with Cursor(engine) as cursor:
        if publication_type == 'czasopisma':
            domains = cursor.get_journal_domains(selected_row['Title'])
        elif publication_type == 'konferencje':
            domains = cursor.get_conference_domains(selected_row['Title'])

    result = [
        html.H5(title),
        dbc.Table(table_header + table_body, bordered=True),
    ]
    if domains:
        result.extend([
            html.P('Przypisane dziedziny:'),
            html.Ul(
                id='domain-list',
                children=[
                    html.Li(html.Strong(i))
                    if i in searched_domains else html.Li(i) for i in domains
                ],
            ),
        ])

    original_name, additional_list = suggestions[selected_cells[0]['row']]
    suggestion_list = [
        dcc.Markdown(
            format_suggestions_based_on_search_sidebar(original_name,
                                                       additional_list))
    ]
    result.extend(suggestion_list)
    return result
Пример #18
0
for i in range(0, 5):
    new = data.iloc[i]
    tbody.append(
        html.Tr([
            html.Td(new[0]),
            html.Td(new[1]),
            html.Td(round(new[2], 4)),
            html.Td(round(new[3], 4)),
            html.Td(new[4])
        ]))

# table_header = [
#     html.Thead(html.Tr([html.Th("First Name"), html.Th("Last Name")]))
# ]

table_body = [html.Tbody(tbody)]
# Plotly mapbox public token
mapbox_access_token = "pk.eyJ1IjoiemVlcmFrd3luZSIsImEiOiJjazdyenBsbzAwaW9wM2ZudjFnbmZlNDBhIn0.yVq3jzmrcnc5QeUPCkKnLQ"

app.layout = html.Div(children=[
    # TOP ROW
    html.Div(
        [
            html.Div(
                className="one-third column",
                children=[
                    html.Img(
                        src=app.get_asset_url("dash-logo-new.png"),
                        id="plotly-image",
                        style={
                            "height": "50px",
Пример #19
0
    html.Tbody(
        style={
            'display': 'block',
            'backgroundColor': colors['background'],
            'textAlign': 'center',
            'color': 'white'
        },
        children=[
            html.Div(
                style={'backgroundColor': colors['background']},
                children=[
                    html.Article(children=[
                        html.Br(),
                        html.H3('Selection du jeu de données'),
                        html.Br(),
                        dcc.Dropdown(
                            id='DataSet_dropdown',
                            options=[
                                {
                                    'label': '1er jeu de données : Kaggle',
                                    'value': 'Emotion_final.csv'
                                },
                                {
                                    'label': '2em jeu de données: Data.word',
                                    'value': 'text_emotion.csv'
                                },
                            ],
                            optionHeight=60,
                            value='Emotion_final.csv',
                            clearable=False,
                        ),
                        html.Br(),
                        html.H3('Selection des émotions'),
                        html.Br(),
                        dcc.RadioItems(id='Emotion_radio'),
                        html.Br(),
                        html.H3('Histogramme des Emotions'),

                        ## Fig 1 : Hist des Emotions
                        dcc.Graph(id='Hist_emotions'),
                    ]),
                ]),
            html.Div(
                id='Block_right',
                children=[
                    html.Section(
                        id='Block_1',
                        children=[
                            html.Article(
                                id='Block_1_Article_1',
                                children=[

                                    ## Fig 2 : Hist des mots
                                    html.
                                    H3("Classement des mots du mot le plus frequent au moins présent"
                                       ),
                                    dcc.Graph(id='Hist_mots', ),
                                    dcc.RangeSlider(id='word_rank_slider',
                                                    min=0,
                                                    max=100,
                                                    step=1,
                                                    value=[2, 50],
                                                    marks={
                                                        0: {
                                                            'label':
                                                            'Top(min)',
                                                            'style': {
                                                                'color':
                                                                '#90A4AE'
                                                            }
                                                        },
                                                        50: {
                                                            'label': 'Top(50)'
                                                        },
                                                        100: {
                                                            'label':
                                                            'Top(Max)',
                                                            'style': {
                                                                'color':
                                                                '#90A4AE'
                                                            }
                                                        }
                                                    },
                                                    allowCross=False),
                                ]),
                            html.Article(
                                id='Block_1_Article_2',
                                children=[
                                    html.H3('Repartition des Emotions '),
                                    dcc.Graph(
                                        # Fig 3 : Pie Chart
                                        id='Pie_chart'),
                                ]),
                        ]),
                    html.Section(
                        id='Block_2',
                        children=[
                            html.Article(
                                id='Block_2_Article_1',
                                children=[
                                    html.H3('Base de données'),
                                    # Tableau des données
                                    html.Div(id='div_table_data',
                                             children=[
                                                 html.Div(id='page1_table'),
                                             ]),
                                ]),
                        ]),
                ]),
        ]),
Пример #20
0
    def content_table(self, cache_sim1=None, cache_sim2=None, cache_bm=None):
        
        if cache_sim1 is not None:
            
            name1 = cache_sim1['sector'].upper() + ' (' + cache_sim1['weighting'] +', ' + cache_sim1['reb_freq'] + ')'
            name2 = cache_sim2['sector'].upper() + ' (' + cache_sim2['weighting'] +', ' + cache_sim2['reb_freq'] + ')'
            name3 = 'S&P 500'

            table_header = [
                html.Thead(
                    html.Tr(
                        [
                            html.Th(""), 
                            html.Th(name1, style={'color':con.SIM1_RED}),
                            html.Th(name2, style={'color':con.SIM2_BLUE}),
                            html.Th(name3, style={'color':'grey'}),
                        ]
                    )
                )
            ]

            row1 = html.Tr(
                [
                    html.Td('Return (p.a)'), 
                    html.Td(self.__format(in_int=cache_sim1['anu_ret'], to_percent=True, add_sign=True)), 
                    html.Td(self.__format(in_int=cache_sim2['anu_ret'], to_percent=True, add_sign=True)), 
                    html.Td(self.__format(in_int=cache_bm['anu_ret'], to_percent=True, add_sign=True)), 
                ]
            )
            
            row2 = html.Tr(
                [
                    html.Td('Vol (p.a)'), 
                    html.Td(self.__format(in_int=cache_sim1['anu_vol'], to_percent=True)), 
                    html.Td(self.__format(in_int=cache_sim2['anu_vol'], to_percent=True)), 
                    html.Td(self.__format(in_int=cache_bm['anu_vol'], to_percent=True)), 
                ]
            )

            row3 = html.Tr(
                [
                    html.Td('IR'), 
                    html.Td(self.__format(in_int=cache_sim1['ir'], to_percent=False)), 
                    html.Td(self.__format(in_int=cache_sim2['ir'], to_percent=False)), 
                    html.Td(self.__format(in_int=cache_bm['ir'], to_percent=False)), 
                ]
            )

            row4 = html.Tr(
                [
                    html.Td('Max DD'),
                    html.Td(self.__format(in_int=cache_sim1['dd'], to_percent=True)), 
                    html.Td(self.__format(in_int=cache_sim2['dd'], to_percent=True)), 
                    html.Td(self.__format(in_int=cache_bm['dd'], to_percent=True)), 
                ]
            )

            row5 = html.Tr(
                [
                    html.Td('No of Assets'),
                    html.Td(self.__format(in_int=cache_sim1['no_of_assets'], to_percent=False)), 
                    html.Td(self.__format(in_int=cache_sim2['no_of_assets'], to_percent=False)), 
                    html.Td(self.__format(in_int=500, to_percent=False)), 
                ]
            )

            table_body = [html.Tbody([row1, row2, row3, row4, row5])]

            table = dbc.Table(table_header + table_body, bordered=True, striped=True, hover=True, dark=False)	

            return table
Пример #21
0
import dash_bootstrap_components as dbc
import dash_html_components as html
import pandas as pd

df = pd.DataFrame({
    "First Name": ["Arthur", "Ford", "Zaphod", "Trillian"],
    "Last Name": ["Dent", "Prefect", "Beeblebrox", "Astra"],
})

table_header = [
    html.Thead(html.Tr(children=[html.Th(col) for col in df.columns]))
]

table_body = [
    html.Tbody([
        html.Tr([html.Td(df.loc[i, col]) for col in df.columns])
        for i in df.index
    ])
]

table = dbc.Table(table_header + table_body, bordered=True)
Пример #22
0
    html.Td("To maintain your weight you need:"),
    html.Td(id="maintain-output"),
    html.Td("Kcal/day")
])
row3 = html.Tr([
    html.Td("To lose .45 kg (1 lb) per week you need:"),
    html.Td(id="lose-output"),
    html.Td("Kcal/day")
])
row4 = html.Tr([
    html.Td("To gain .45 kg (1 lb) per week you need:"),
    html.Td(id="gain-output"),
    html.Td("Kcal/day")
])

table_body = [html.Tbody([row1, row2, row3, row4])]

results = dbc.Table(
    table_body,
    bordered=True,
    striped=True,
)

#######################################################################################################################

# Build activity level
activity_level = dbc.FormGroup(
    [
        dbc.Label("Activity Level", html_for="activity-dropdown", width=2),
        dbc.Col(
            [
Пример #23
0
def change_redshift(z, *args, **kwargs):
    elem_input_array = []
    for elem in list(elements.keys())[:9]:
        row = html.Tr([
            html.Td(
                dbc.Checkbox(id='standalone-checkbox-' +
                             elem.replace(' ', '-'))),
            html.Td(elem),
            html.Td(dbc.Badge(
                '__',  #elem,
                color=elements[elem]['color'])),
            html.Td(
                dbc.Input(id='z-' + elem.replace(' ', '-'),
                          value=z,
                          type='number',
                          min=0,
                          max=10,
                          step=0.0000001,
                          placeholder='z')),
            html.Td(
                dbc.Input(id='v-' + elem.replace(' ', '-'),
                          type='number',
                          placeholder='Velocity (km/s)',
                          value=0))
        ])
        elem_input_array.append(row)
    table_body_one = [html.Tbody(elem_input_array)]

    elem_input_array = []
    for elem in list(elements.keys())[9:]:
        row = html.Tr([
            html.Td(
                dbc.Checkbox(id='standalone-checkbox-' +
                             elem.replace(' ', '-'))),
            html.Td(elem),
            html.Td(dbc.Badge(
                '__',  #elem,
                color=elements[elem]['color'])),
            html.Td(
                dbc.Input(id='z-' + elem.replace(' ', '-'),
                          value=z,
                          type='number',
                          min=0,
                          max=10,
                          step=0.0000001,
                          placeholder='z')),
            html.Td(
                dbc.Input(id='v-' + elem.replace(' ', '-'),
                          type='number',
                          placeholder='Velocity (km/s)',
                          value=0))
        ])
        elem_input_array.append(row)
    table_body_two = [html.Tbody(elem_input_array)]
    return [
        dbc.Row([
            dbc.Table(
                html.Tbody([
                    html.Tr([
                        html.Td(dbc.Table(table_body_one, bordered=True), ),
                        html.Td(dbc.Table(table_body_two, bordered=True), )
                    ]),
                ]))
        ])
    ]
Пример #24
0
        html.Button('Click to store in localStorage', id='local-button'),
        html.Button('Click to store in sessionStorage', id='session-button')
    ]),
    html.Div([
        html.Table([
            html.Thead([
                html.Tr([
                    html.Th('Memory clicks'),
                    html.Th('Local clicks'),
                    html.Th('Session clicks')
                ])
            ]),
            html.Tbody([
                html.Tr([
                    html.Td(0, id='memory-clicks'),
                    html.Td(0, id='local-clicks'),
                    html.Td(0, id='session-clicks')
                ])
            ])
        ])
    ])
])

# Create two callback for every store.
for store in ('memory', 'local', 'session'):

    # add a click to the appropriate store.
    @app.callback(Output(store, 'data'),
                  [Input('{}-button'.format(store), 'n_clicks')],
                  [State(store, 'data')])
    def on_click(n_clicks, data):
Пример #25
0
def update_graph(term,n):
    global old_term
    if term == '' : 
        term = old_term
    old_term = term
    conn = sqlite3.connect('twitter.db')
    # manage_data(conn)
    df = pd.read_sql("select * from sentiment where tweet like '%"+term+"%' order by unix desc limit 1000",conn)
        
    df['unix'] = pd.to_datetime(df['unix'],unit='ms')
    df.sort_values('unix',inplace=True)
    df.set_index('unix',inplace=True)
    df = df.iloc[-100:,:]
    tableData = df.iloc[-10:,:]
    
    positive = 0
    negative = 0
    neutral = 0
    for senti in df['sentiment']:
        if senti > 0:
            positive += 1
        if senti < 0:
            negative += 1
        else:
            neutral += 1
    
    df['smoothe_sentiment'] = df['sentiment'].rolling(int(len(df)/5)).mean()
    
    df = df.resample('2s').mean()
    df.dropna(inplace=True)
            
    X = df.index
    Y = df.smoothe_sentiment.values
    
    data = go.Scatter(
        x=list(X),
        y=list(Y),
        name = 'Scatter',
        mode = 'lines+markers'
    )
    
    layout = go.Layout(xaxis = dict(range=[min(X),max(X)]),
                       yaxis = dict(range=[min(Y),max(Y)]),
                       margin=dict(l=40,r=20,b=20,t=60,pad=0),
                       template = 'plotly_dark',
                       hovermode='x')
    
    
    pie = go.Pie(values=[positive,negative,neutral],
                 labels= ['Positive','Negative','Neutral'],
                 text=['Positive','Negative','Neutral'],
                 marker={'colors' :['green','red','blue']},
                 hole = 0.4)
    
    print(tableData.columns)
    return [{'data':[data],'layout':layout},
            {'data':[pie],'layout':layout},
            html.Table(className="responsive-table",
                       children=[
                          html.Thead(
                              html.Tr(
                                  children=[
                                      html.Th(col.title()) for col in tableData.columns.values],
                                  style={'color':app_colors['text']}
                                  )
                              ),
                          html.Tbody(
                              [
                              html.Tr(
                                  children=[
                                      html.Td(data) for data in d
                                      ], style={'color':app_colors['text'],
                                                'background-color':quick_color(d[1])}
                                  )
                               for d in tableData.values.tolist()])
                          ]
    )]
Пример #26
0
                                sep='\t')
    cardData[txt] = pd.read_csv(os.path.join(
        data_dir, 'sub-all_task-' + task + '_desc-physioCard.tsv'),
                                sep='\t')

# QC summary data
max_rows = 200
qctable = html.Table(
    [
        html.Thead(
            html.Tr(
                [html.Th(col)
                 for col in df_qcsummary.columns.values.tolist()])),
        html.Tbody([
            html.Tr([
                html.Td(df_qcsummary.iloc[i][col], style=writeStyle(col))
                for col in df_qcsummary.columns
            ], ) for i in range(min(len(df_qcsummary), max_rows))
        ]),
    ],
    className='qcsummary',
)

# ------------ #
# ------------ #
# FIGURES      #
# ------------ #
# ------------ #

# HEAD MOVEMENT TAB
# Fig 1
colors = n_colors('rgb(5, 200, 200)', 'rgb(200, 10, 10)', 28, colortype='rgb')
Пример #27
0
def update_output(
    rows,
    add_rows,
    theor_drop_val,
    sure_context_bool,
    # pw params
    pw_drop_val,
    TKW_d,
    GEW_b,
    GEW_a,
    PW_b,
    PW_a,
    POW_r,
    pw_n_clicks,
    pw_user_func,
    # um params
    um_drop_val,
    um_TKU_a,
    um_TKU_l,
    um_TKU_r,
    um_RU_exp,
    um_RU_lm,
    um_BU_a,
    um_EXU_a,
    um_n_clicks,
    um_user_func,
    # gl params
    gl_drop_val,
    gl_TKU_a,
    gl_TKU_l,
    gl_TKU_r,
    gl_RU_exp,
    gl_RU_lm,
    gl_BU_a,
    gl_EXU_a,
    gl_n_clicks,
    gl_user_func,
    # rg params
    rg_drop_val,
    LS_weight,
    rg_n_clicks,
    rg_user_func,
    # sl params
    sl_drop_val,
    OG_theta,
    sl_n_clicks,
    sl_user_func,
    sl_delta,
    # sdt params
    sdt_drop_val,
    AH_eta,
    sdt_k,
    sdt_n_clicks,
    sdt_user_func,
):
    # if theor_drop_val in ["RT", "ST"]:
    if sure_context_bool:
        pays_RT_ST = [
            [float(i["std_payoffs_tbl"]) for i in rows],
            [float(i["std_payoffs_tbl"]) for i in add_rows],
        ]
        probs_RT_ST = [float(i["std_probabilities_tbl"]) for i in rows]
    else:
        pays_RT_ST = [
            [float(i["std_payoffs_tbl"]) for i in rows],
            [float(i["comp_payoffs_tbl"]) for i in rows],
        ]
        probs_RT_ST = [float(i["std_probabilities_tbl"]) for i in rows]
    # elif theor_drop_val == "SDT":
    probs_SDT = [
        [float(i["std_probabilities_tbl"]) for i in rows],
        [float(i["comp_probabilities_tbl"]) for i in rows],
    ]
    pays_SDT = [float(i["std_payoffs_tbl"]) for i in rows]
    # elif theor_drop_val == "RDRA":
    probs_RDRA = [
        [float(i["std_probabilities_tbl"]) for i in rows],
        [float(i["std_probabilities_tbl"]) for i in add_rows],
    ]
    pays_RDRA = [
        [float(i["std_payoffs_tbl"]) for i in rows],
        [float(i["std_payoffs_tbl"]) for i in add_rows],
    ]
    # else:
    probs_EU_CPT = [float(i["std_probabilities_tbl"]) for i in rows]
    pays_EU_CPT = [float(i["std_payoffs_tbl"]) for i in rows]

    # calc mean for risk premium
    mean_val = sm.mean(
        [float(i["std_payoffs_tbl"]) for i in rows],
        [float(i["std_probabilities_tbl"]) for i in rows],
    )

    # pw params
    if pw_drop_val == "TKW":
        pw_kwargs = {"d": TKW_d}
    elif pw_drop_val == "GEW":
        pw_kwargs = {"b": GEW_b, "a": GEW_a}
    elif pw_drop_val == "PW":
        pw_kwargs = {"b": PW_b, "a": PW_a}
    elif pw_drop_val == "LW":
        pw_kwargs = {}
    elif pw_drop_val == "POW":
        pw_kwargs = {"r": POW_r}
    elif pw_drop_val == "YW":
        pw_kwargs = {"text": pw_user_func}
    # um params
    if um_drop_val == "TKU":
        um_kwargs = {"a": um_TKU_a, "l": um_TKU_l, "r": um_TKU_r}
    elif um_drop_val == "RU":
        um_kwargs = {"exp": um_RU_exp, "mult": um_RU_lm}
    elif um_drop_val == "LU":
        um_kwargs = {}
    elif um_drop_val == "BU":
        um_kwargs = {"a": um_BU_a}
    elif um_drop_val == "EXU":
        um_kwargs = {"a": um_EXU_a}
    elif um_drop_val == "YU":
        um_kwargs = {"text": um_user_func}
    # gl params
    if gl_drop_val == "TKU":
        gl_kwargs = {"a": gl_TKU_a, "l": gl_TKU_l, "r": gl_TKU_r}
    elif gl_drop_val == "RU":
        gl_kwargs = {"exp": gl_RU_exp, "mult": gl_RU_lm}
    elif gl_drop_val == "LU":
        gl_kwargs = {}
    elif gl_drop_val == "BU":
        gl_kwargs = {"a": gl_BU_a}
    elif gl_drop_val == "EXU":
        gl_kwargs = {"a": gl_EXU_a}
    elif gl_drop_val == "YU":
        gl_kwargs = {"text": gl_user_func}
    # rg params
    if rg_drop_val == "LS":
        rg_kwargs = {"weight": LS_weight}
    elif rg_drop_val == "YR":
        rg_kwargs = {
            "text": rg_user_func,
        }
    # sl params
    if sl_drop_val == "OG":
        sl_kwargs = {"theta": OG_theta}
    elif sl_drop_val == "YS":
        sl_kwargs = {
            "text": sl_user_func,
        }
    # sdt params
    if sdt_drop_val == "AH":
        sdt_kwargs = {"eta": AH_eta}
    elif sdt_drop_val == "YB":
        sdt_kwargs = {
            "text": sdt_user_func,
        }

    # calculate generic theory results
    res_eu = mf.expected_utility(pays_EU_CPT, probs_EU_CPT)
    res_cpt = mf.cumulative_prospect_theory(pays_EU_CPT, probs_EU_CPT)
    res_sdt = mf.sav_dis_theory(pays_SDT, probs_SDT)
    res_rdra = mf.RDRA_theory(pays_RDRA, probs_RDRA)
    res_rt = mf.regret_theory(pays_RT_ST, probs_RT_ST)
    res_st = mf.salience_theory(
        pays_RT_ST,
        probs_RT_ST,
    )

    # create RT_ST pretty lottery display
    if sure_context_bool == False:
        RT_ST_lottery = lot_to_str(pays_RT_ST, [probs_RT_ST])
    elif sure_context_bool == True:
        RT_ST_lottery = lot_to_str(pays_RT_ST, [probs_RT_ST, [1]])

    # calculate conditional result
    if theor_drop_val == "EU":
        res = fd.mf_func_dict[theor_drop_val][0](
            pays_EU_CPT,
            probs_EU_CPT,
            um_function=fd.um_func_dict[um_drop_val][0],
            um_kwargs=um_kwargs,
            ce_function=fd.um_func_dict[um_drop_val][3],
        )
        focus_lottery = lot_to_str([pays_EU_CPT], [probs_EU_CPT])
    elif theor_drop_val == "RDRA":
        res = fd.mf_func_dict[theor_drop_val][0](
            pays_RDRA,
            probs_RDRA,
            um_function=fd.um_func_dict[um_drop_val][0],
            um_kwargs=um_kwargs,
            ce_function=fd.um_func_dict[um_drop_val][3],
            gl_function=fd.um_func_dict[gl_drop_val][0],
            gl_kwargs=gl_kwargs,
        )
        focus_lottery = lot_to_str(pays_RDRA, probs_RDRA)
    elif theor_drop_val == "RT":
        res = fd.mf_func_dict[theor_drop_val][0](
            pays_RT_ST,
            probs_RT_ST,
            um_function=fd.um_func_dict[um_drop_val][0],
            um_kwargs=um_kwargs,
            ce_function=fd.um_func_dict[um_drop_val][3],
            rg_function=fd.rg_func_dict[rg_drop_val][0],
            rg_kwargs=rg_kwargs,
        )
        focus_lottery = RT_ST_lottery
    elif theor_drop_val == "ST":
        res = fd.mf_func_dict[theor_drop_val][0](
            pays_RT_ST,
            probs_RT_ST,
            um_function=fd.um_func_dict[um_drop_val][0],
            um_kwargs=um_kwargs,
            ce_function=fd.um_func_dict[um_drop_val][3],
            sl_function=fd.sl_func_dict[sl_drop_val][0],
            sl_kwargs=sl_kwargs,
            delta=sl_delta,
        )
        focus_lottery = RT_ST_lottery
    elif theor_drop_val == "SDT":
        res = fd.mf_func_dict[theor_drop_val][0](
            pays_SDT,
            probs_SDT,
            bivu_function=fd.sdt_func_dict[sdt_drop_val][0],
            bivu_kwargs=sdt_kwargs,
            um_function=fd.um_func_dict[um_drop_val][0],
            um_kwargs=um_kwargs,
            ce_function=fd.um_func_dict[um_drop_val][3],
            k=sdt_k,
        )
        focus_lottery = lot_to_str([pays_SDT], probs_SDT)
    elif theor_drop_val == "CPT":
        res = fd.mf_func_dict[theor_drop_val][0](
            pays_EU_CPT,
            probs_EU_CPT,
            um_function=fd.um_func_dict[um_drop_val][0],
            pw_function=fd.pw_func_dict[pw_drop_val][0],
            um_kwargs=um_kwargs,
            ce_function=fd.um_func_dict[um_drop_val][3],
            pw_kwargs=pw_kwargs,
        )
        res = list(res)
        if pw_drop_val == "YW":
            res[1] = nan
        focus_lottery = lot_to_str([pays_EU_CPT], [probs_EU_CPT])

    if isnan(res[1]) and theor_drop_val == "RDRA":
        toast_bool, toast_text = (
            True,
            "Currently, the calculation of the certainty equivalent is not implemented for this theory.",
        )
    elif isnan(res[1]):
        toast_bool, toast_text = (
            True,
            "You entered a custom function. For security reasons, I can't calculate the certainty equivalent and the Risk Premium.",
        )
    else:
        toast_bool, toast_text = False, ""

    if theor_drop_val == "EU":
        intermed_output = None
    elif theor_drop_val == "CPT":
        intermed_output = html.Div([
            f"Probability weighting function: {fd.pw_func_dict[pw_drop_val][1]}, Parameters: {dict_print(pw_kwargs)}"
        ])
    elif theor_drop_val == "RT":
        intermed_output = html.Div([
            f"Regret function: {fd.rg_func_dict[rg_drop_val][1]}, Parameters: {dict_print(rg_kwargs)}",
        ])
    elif theor_drop_val == "ST":
        intermed_output = html.Div([
            f"Salience function: {fd.sl_func_dict[sl_drop_val][1]}, Parameters: {dict_print(sl_kwargs)}",
        ])
    elif theor_drop_val == "SDT":
        intermed_output = html.Div([
            f"Bivariate Utility function: {fd.sdt_func_dict[sdt_drop_val][1]}, Parameters: {dict_print(sdt_kwargs)}",
        ])
    elif theor_drop_val == "RDRA":
        intermed_output = html.Div([
            f"Gain Loss Utility function: {fd.um_func_dict[gl_drop_val][1]}, Parameters: {dict_print(gl_kwargs)}",
        ])

    tkw_kwargs = {"d": 0.65}
    bu_kwargs = {"a": 0}
    ru_kwargs = {"exp": 2, "mult": "3"}
    lu_kwargs = {}
    tku_kwargs = {"a": 0.88, "l": 2.25}
    og_kwargs = {"theta": 0.1}
    ah_kwargs = {"eta": 0.1}
    ls_kwargs = {"weight": 1}

    if theor_drop_val == "ST":
        focus_name_params = f"{fd.mf_func_dict['ST'][1]}, Parameters: local thinking - $\\delta$: {sl_delta}"
    elif theor_drop_val == "SDT":
        focus_name_params = f"{fd.mf_func_dict['SDT'][1]}, Parameters: savoring coefficient - k: {sdt_k}"
    else:
        focus_name_params = fd.mf_func_dict[theor_drop_val][1]

    output_table = dbc.Table(
        [
            html.Thead(
                html.Tr([
                    html.Th("Theory name", id="ot_theory_name"),
                    dbc.Tooltip(
                        "This column displays the name of the applied theory of decision under risk. In the case of Optimal Anticipation with Savoring and Disappointment and Salience theory, it also displays the additional parameters entered in the top section.",
                        target="ot_theory_name",
                    ),
                    html.Th("Lottery", id="ot_lottery"),
                    dbc.Tooltip(
                        "This column displays the (target and context) lotteries currently analyzed with the theory indicated in the first column. For theories which expect more than the target lottery as inputs, the context-information is derived from the respective columns even if they are currently hidden.",
                        target="ot_lottery",
                    ),
                    html.Th("Utility function", id="ot_utility_function"),
                    dbc.Tooltip(
                        "This column displays the utility function used in the current specification and all its parameters.",
                        target="ot_utility_function",
                    ),
                    html.Th("Auxiliary function", id="ot_auxiliary_function"),
                    dbc.Tooltip(
                        "This column displays current auxiliary function such as the probability weighting function for Cumulative Prospect Theory or the regret function for Regret theory and their respective parameters.",
                        target="ot_auxiliary_function",
                    ),
                    html.Th("Utility", id="ot_utility"),
                    dbc.Tooltip(
                        "This column displays the utility calculated with the current specification of the theory indicated in the preceding columns.",
                        target="ot_utility",
                    ),
                    html.Th("Certainty Equivalent",
                            id="ot_certainty_equivalent"),
                    dbc.Tooltip(
                        "This column displays the certainty equivalent calculated with the current specification of the theory indicated in the preceding columns whenever possible.",
                        target="ot_certainty_equivalent",
                    ),
                    html.Th("Risk Premium", id="ot_risk_premium"),
                    dbc.Tooltip(
                        "This column displays the risk premium calculated with the current specification of the theory indicated in the preceding columns whenever possible.",
                        target="ot_risk_premium",
                    ),
                ])),
            html.Tbody([
                html.Tr(
                    [
                        html.Td(focus_name_params),
                        html.Td(focus_lottery),
                        html.
                        Td(f"Utility function: {fd.um_func_dict[um_drop_val][1]}, Parameters: {dict_print(um_kwargs)}"
                           ),
                        html.Td(intermed_output),
                        html.Td(round(res[0], 4)),
                        html.Td(round(res[1], 4) if res[1] != nan else "nan"),
                        html.Td(
                            round(mean_val -
                                  res[1], 4) if res[1] != nan else "nan"),
                    ],
                    style={
                        "color": plot_color,
                        # "border": "thin solid" + plot_color,
                        "font-weight": "bold",
                    },
                    id="ot_first_row",
                ),
                dbc.Tooltip(
                    "This row displays the values indicated in the column headings for the theory chosen in the first section with all adjustments from the following sections.",
                    target="ot_first_row",
                ),
            ]),
            html.Tbody(
                [
                    html.Tr([
                        html.Td(fd.mf_func_dict["EU"][1]),
                        html.Td(lot_to_str([pays_EU_CPT], [probs_EU_CPT])),
                        html.
                        Td(f"Utility function: {fd.um_func_dict['BU'][1]}, Parameters: {dict_print(bu_kwargs)}"
                           ),
                        html.Td(),
                        html.Td(round(res_eu[0], 4), ),
                        html.Td(round(res_eu[1], 4), ),
                        html.Td(round(mean_val - res_eu[1], 4), ),
                    ]),
                    html.Tr([
                        html.Td(fd.mf_func_dict["CPT"][1]),
                        html.Td(lot_to_str([pays_EU_CPT], [probs_EU_CPT])),
                        html.
                        Td(f"Utility function: {fd.um_func_dict['TKU'][1]}, Parameters: {dict_print(tku_kwargs)}"
                           ),
                        html.
                        Td(f"Probability weighting function: {fd.pw_func_dict['TKW'][1]}, Parameters: {dict_print(tkw_kwargs)}"
                           ),
                        html.Td(round(res_cpt[0], 4), ),
                        html.Td(round(res_cpt[1], 4), ),
                        html.Td(round(mean_val - res_cpt[1], 4), ),
                    ]),
                    html.Tr([
                        html.Td(
                            # CHECK This has to be adjusted manually if SDT standard parameters in main_functions are changed
                            f"{fd.mf_func_dict['SDT'][1]}, Parameters: savoring coefficient - k: 0.5"
                        ),
                        html.Td(lot_to_str([pays_SDT], probs_SDT)),
                        html.
                        Td(f"Utility function: {fd.um_func_dict['RU'][1]}, Parameters: {dict_print(ru_kwargs)}"
                           ),
                        html.Td(
                            f"Bivariate Utility function: {fd.sdt_func_dict['AH'][1]}, Parameters: {dict_print(ah_kwargs)}",
                        ),
                        html.Td(round(res_sdt[0], 4), ),
                        html.Td(round(res_sdt[1], 4), ),
                        html.Td(round(mean_val - res_sdt[1], 4), ),
                    ]),
                    html.Tr([
                        html.Td(fd.mf_func_dict["RDRA"][1]),
                        html.Td(lot_to_str(pays_RDRA, probs_RDRA)),
                        html.
                        Td(f"Utility function: {fd.um_func_dict['LU'][1]}, Parameters: {dict_print(lu_kwargs)}"
                           ),
                        html.Td(
                            f"Gain Loss Utility function: {fd.um_func_dict['RU'][1]}, Parameters: {dict_print(ru_kwargs)}",
                        ),
                        html.Td(round(res_rdra[0], 4), ),
                        html.Td(round(res_rdra[1], 4), ),
                        html.Td(round(mean_val - res_rdra[1], 4), ),
                    ]),
                    html.Tr([
                        html.Td(fd.mf_func_dict["RT"][1]),
                        html.Td(RT_ST_lottery),
                        html.
                        Td(f"Utility function: {fd.um_func_dict['RU'][1]}, Parameters: {dict_print(ru_kwargs)}"
                           ),
                        html.Td(
                            f"Regret function: {fd.rg_func_dict['LS'][1]}, Parameters: {dict_print(ls_kwargs)}",
                        ),
                        html.Td(round(res_rt[0], 4), ),
                        html.Td(round(res_rt[1], 4), ),
                        html.Td(round(mean_val - res_rt[1], 4), ),
                    ]),
                    html.Tr([
                        html.Td(
                            # CHECK This has to be adjusted manually if ST standard parameters in main_functions are changed
                            f"{fd.mf_func_dict['ST'][1]}, Parameters: local thinking - $\\delta$: 0.7"
                        ),
                        html.Td(RT_ST_lottery),
                        html.
                        Td(f"Utility function: {fd.um_func_dict['RU'][1]}, Parameters: {dict_print(ru_kwargs)}"
                           ),
                        html.Td(
                            f"Salience function: {fd.sl_func_dict['OG'][1]}, Parameters: {dict_print(og_kwargs)}",
                        ),
                        html.Td(round(res_st[0], 4), ),
                        html.Td(round(res_st[1], 4), ),
                        html.Td(round(mean_val - res_st[1], 4), ),
                    ]),
                ],
                id="ot_def_rows",
            ),
            dbc.Tooltip(
                "These rows display the values indicated in the column headings for standard specifications of all the theories implemented in the tool. At the moment, only the (target and context) lotteries from the first section can be changed by the user.",
                target="ot_def_rows",
            ),
        ],
        hover=True,
        size="sm",
    )
    return output_table, toast_bool, toast_text
Пример #28
0
row8 = html.Tr([
    html.Td(html.Img(src="/assets/read.png")),
    html.Td(html.Img(src="/assets/readsolv.png")),
    html.Td()
])
row9 = html.Tr([
    html.Td(html.Img(src="/assets/comment.png")),
    html.Td(html.Img(src="/assets/commentsolv.png")),
    html.Td("Rajouter un commentaire dans la fonction")
])
link = html.A("https://jira.sonarsource.com/projects/SONARPY/issues",
              href='https://jira.sonarsource.com/projects/SONARPY/issues',
              target='_blank')

table_body = [
    html.Tbody([row1, row2, row3, row4, row5, row6, row7, row8, row9, link])
]

table = dbc.Table(table_header + table_body, bordered=True)

#######################################################
table_header2 = [
    html.Thead(
        html.Tr([
            html.Th("Catégorie"),
            html.Th("Vulnérabilité"),
            html.Th("Solved")
        ]))
]

row2_2 = html.Tr([
Пример #29
0
row1 = html.Tr([
    html.P("1. Comienza la búsqueda filtrando por el departamento tu interés.",
           className='m-3 lead font-weight-normal text-dark font-home-m')
])
row2 = html.Tr([
    html.
    P("2. En la tabla podrás ver el costo de los contratos adjudicados, y los datos del respectivo financiador.",
      className='m-3 lead font-weight-normal text-dark font-home-m')
])
row3 = html.Tr([
    html.
    P("3. Para más información puedes ir al link de la SECOP ubicado al final de la tabla.",
      className='m-3 lead font-weight-normal text-dark font-home-m')
])

steps_body = [html.Tbody([row1, row2, row3])]

steps_table = html.Table(steps_header + steps_body)

# Filters table
filter_depto_fin = dcc.Dropdown(
    options=[{
        'label': i,
        'value': i
    } for i in df_financiacion_final['Departamento contrato'].fillna(
        'Sin Definir').drop_duplicates()],
    value=None,
    id='filter-depto-fin',
)

# GRAPHS ----------------------
Пример #30
0
                    html.Div([
                        html.I(className="help circle icon"),
                        html.Div(
                            "Tỉnh An Giang không có trong hệ thống dữ liệu của trang web."
                        ),
                    ],
                             className="ui top attached warning icon message"),
                    html.Table([
                        html.Thead([
                            html.Tr([html.Th([])] + [
                                html.Th([subject])
                                for subject in SUBJECTS_REQUIRED
                            ])
                        ]),
                        html.Tbody(
                            make_dash_table(
                                df_all_provinces_description[SUBJECTS_REQUIRED]
                            )),
                    ],
                               className="ui attached table")
                ],
                         className=
                         "ui vertical mastcontent center aligned segment"),
                html.Br([]),

                #Department to enter uni
                html.Div([
                    html.Div([
                        html.I(className="help circle icon"),
                        html.Div("Dữ liệu khối D hiện giờ chưa thể xử lý."),
                    ],
                             className="ui top attached warning icon message"),