import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

# external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__)  # , external_stylesheets=external_stylesheets

app.layout = html.Div([
    dcc.Input(id='num', type='number', value=5),
    html.Table([
        html.Tr([html.Td(['x', html.Sup(2)]),
                 html.Td(id='square')]),
        html.Tr([html.Td(['x', html.Sup(3)]),
                 html.Td(id='cube')]),
        html.Tr([html.Td([2, html.Sup('x')]),
                 html.Td(id='twos')]),
        html.Tr([html.Td([3, html.Sup('x')]),
                 html.Td(id='threes')]),
        html.Tr([html.Td(['x', html.Sup('x')]),
                 html.Td(id='x^x')]),
    ]),
])


@app.callback([
    Output('square', 'children'),
    Output('cube', 'children'),
    Output('twos', 'children'),
    Output('threes', 'children'),
Esempio n. 2
0
    def render_app_info(self, app_id, environ, seq_job_data):
        if environ is None:
            raise PreventUpdate

        app_data = kvstore.client.get(app_id)
        if not app_data:
            raise PreventUpdate
        app_info = ApplicationMetrics.from_json(kvstore.client.get(app_id))
        active_executors_count = len([e for e in app_info.executor_metrics if e.isActive])

        containers = f"{active_executors_count} / {len(app_info.executor_metrics)}"
        jobs_running = f"{len([x for x in app_info.jobs_stages.values() if x.job.status == 'RUNNING'])}"

        job_start_times = np.array([x.job.submissionTime for x in seq_job_data])
        job_endtimes = np.array([x.job.completionTime for x in seq_job_data])
        job_durations = job_endtimes - job_start_times

        levels = (5, 75, 95)
        perc_values = [np.percentile(job_durations, level) for level in levels]
        perc_table = html.Table(
            [
                html.Tr(
                    [html.Th(str(level)) for level in levels]
                ),
                html.Tr(
                    [html.Td(str(v)) for v in perc_values]
                )
            ]
        )

        fig = Figure(
            data={
                "x": list(range(len(job_durations))),
                "y": [x.seconds for x in sorted(job_durations)],
            }
        )
        perc_graph = dcc.Graph(figure=fig)
        p_data = html.Div([perc_table, perc_graph])

        common_style = {"width": "180px", "margin": "6px"}

        wide_style = common_style.copy()
        wide_style["width"] = "500px"

        job_id = seq_job_data[-1].job.jobId
        scores = graphitestore.client.load(
            [f"aliasByNode(hybrid_metrics.app.{app_id}.job_group.*.test.skewness_score, 4)"],
            since="now-1h",
            until="now",
            lastrow=True,
        )

        return dbc.Col([
            dbc.Row(
                children=[
                    dbc.Card(
                        [html.H5("Containers"), html.P(containers)],
                        body=True,
                        style=common_style
                    ),
                    dbc.Card(
                        [html.H5("Jobs Running"), html.P(jobs_running)],
                        body=True,
                        style=common_style
                    ),
                ]),
            dbc.Row(
                [
                    dbc.Card([
                        html.H6(f"S.T. for {name}"),
                        html.P(f"{score:.2f}", style={"font-size": "12pt"}),
                    ], style={**common_style, "padding": "3px"})
                    for name, (score, *_) in scores[0].items() if name.startswith("job_group")
                ]
            ),
            dbc.Row(dbc.Card(
                [html.H5("Jobs run time stats"), p_data],
                body=True,
                style=wide_style
            ))
        ])
Esempio n. 3
0
    ],className = 'row'),

#Note here the slider value of 1 should correspond to days_recorded days displayed on the graph due to labelling weirdness
    dcc.Slider(
        id='time-slider',
        min=1,
        max=5,
        value=1,
        step=None,
        marks={5:'1 day', 4:'3 days', 3:'1 week', 2:'2 weeks', 1:'1 month'}
    ),

    dcc.Markdown(children=markdown_text_middle ),

    html.Table(children = [html.Tr([html.Th(string) for string in ['Score','Range','Low','High']]) ] +
                            [html.Tr([html.Th(string) for string in ['Polarity','-1 to 1','Negative emotion','Positive Emotion']]),
                            html.Tr([html.Th(string) for string in ['Subjectivity', '0 to 1', 'Objective', 'Subjective']])]
                           , className = 'u-full-width'),

    dcc.Markdown(children=markdown_text_below),
],className = 'container')

@app.callback(
    dash.dependencies.Output('test-top-1-polarity', 'figure'),
    [dash.dependencies.Input('1-or-10', 'value'), dash.dependencies.Input('pol-or-sub', 'value'),
     dash.dependencies.Input('time-slider','value'),
     dash.dependencies.Input('series-plot', 'values')])
def update_figure(oneORten,polORsub,timevalue,plottedseries):
    #dictionary to tranlate the value of the time slider to a number of days
    time_dict = { 5:1, 4:3, 3:7, 2:14, 1:30}
Esempio n. 4
0
 html.Table([html.Tr([html.Td(
                     dcc.Graph(
                         id='network-graph',
                         figure={
                             'data': graph_traces(random_graph),
                             'layout': go.Layout(
                                 title = 'Network Graph',
                                 titlefont_size=16,
                                 showlegend=False,
                                 hovermode='closest',
                                 xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
                                 yaxis=dict(showgrid=False, zeroline=False, showticklabels=False)
                             )
                         }
                     )
     ),
                     html.Td(#properties and update button
                         html.Table([html.Tr([html.Td(
                                                 html.Div([html.H5('Selected Node'),html.P(id='selected-node', children = '')])
                                     )]),
                                     html.Tr([html.Td(
                                                 html.Div([html.H5('x'),dcc.Input(id='node-x', type='number', placeholder='x', value='')])
                                     )]),
                                     html.Tr([html.Td(
                                                 html.Div([html.H5('y'),dcc.Input(id='node-y', type='number', placeholder='y', value='')])
                                     )]),
                                     html.Tr([html.Td(
                                                 html.Div([html.H5('Outgoing edges'),
                                                         dcc.Dropdown(id='node-property',
                                                                     options=[{'label': str(n), 'value': n} for n in random_graph],
                                                                     value=[],
                                                                     multi=True)
                                                         ])
                                     )]),
                                     html.Tr([html.Td(
                                                 html.Button('Update', id='update-button')
                                     )])
                             ])
                     )])])
Esempio n. 5
0
 html.Div(
     style={'margin-top': '100px', 'margin-bottom': '100px'},
     children=[
     html.H6("OLS Regression Results"),
     html.Table([
         html.Tr([
             html.Td(
                 style={'font-weight':'bold'},
                 children=['Dep. Variable']),
             html.Td(id='dep-var'),
             html.Td(
                 style={'font-weight':'bold'},
                 children=['No. Observations']),
             html.Td(id='num-obs'),
             html.Td(
                 style={'font-weight':'bold'},
                 children=['R-squared']),
             html.Td(id='r-sq'),
             html.Td(
                 style={'font-weight':'bold'},
                 children=['F-statistic']),
             html.Td(id='f-stat'),
             html.Td(
                 style={'font-weight':'bold'},
                 children=['Log-Likelihood']),
             html.Td(id='log-like'),
             ]),
         html.Tr([
             html.Td(
                 style={'font-weight':'bold'},
                 children=['Model']),
             html.Td(id='model'),
Esempio n. 6
0
                               },
                               {
                                   'label': 'ETH',
                                   'value': 'df_eth'
                               },
                           ],
                           value='df_btc'),
              html.P(),
              html.Button(id='botton-update-market-data',
                          children='Update'),
              html.H6(style=style_section_header,
                      children='Market Indicators'),
              html.Table(children=[
                  html.Tr(children=[
                      html.Th('Asset'),
                      html.Th('Index 0'),
                      html.Th('Index 1'),
                  ]),
                  html.Tr(children=[
                      html.Td('ETH'),
                      html.Td('Number 0'),
                      html.Td('Number 1'),
                  ]),
                  html.Tr(children=[
                      html.Td('BTC'),
                      html.Td('Number 1'),
                      html.Td('Number 2'),
                  ]),
              ]),
          ]),
 html.Div(
Esempio n. 7
0
            dbc.Col([
                dropdown2,
            ]),
        ]),
    ],
                  fluid=True,
                  style={'textAlign': 'left'}),
])

#ANOVA table
table_header = [
    html.Thead(
        html.Tr([
            html.Th(""),
            html.Th("df"),
            html.Th("sum_sq"),
            html.Th("mean_sq"),
            html.Th("F"),
            html.Th("PR(>F)")
        ]))
]
row1 = html.Tr([
    html.Td("C(type)"),
    html.Td("2.0"),
    html.Td("632.84"),
    html.Td("316.42"),
    html.Td("262.28"),
    html.Td("8.391599e-71"),
])
row2 = html.Tr([
    html.Td("Residual"),
    html.Td("357.0"),
Esempio n. 8
0
 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,
             max=10,
             step=0.0000001,
             placeholder='z'
         )
     ),
     html.Td(
         dbc.Input(
             id='v-'+elem.replace(' ', '-'),
             type='number',
             placeholder='Velocity (km/s)',
             value=0
         )
     )
 ])
Esempio n. 9
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),
                            )
                        ]),
                    ])
                )
            ])
        ]
Esempio n. 10
0
def generate_table(dataframe):
    """Generate dash table for pandas dataframe.

    Parameters
    ----------
    dataframe: pandas.DataFrame

    Returns
    -------
    table: html.Table
    """
    rows = []
    cols_to_retain = [
        "experiment_accession",
        "experiment_title",
        "run_accession",
        "ribotricer_orfs",
        "ribotricer_metagene_5p",
        "ribotricer_metagene_3p",
        "ribotricer_metagene_plot",
        "ribotricer_protocol",
        "ribotricer_bam_summary",
    ]
    dataframe = dataframe.loc[:, cols_to_retain]
    for i in range(len(dataframe)):
        row = []
        for col in dataframe.columns:
            value = dataframe.iloc[i][col]
            if (col in [
                    "ribotricer_orfs",
                    "ribotricer_metagene_5p",
                    "ribotricer_metagene_3p",
                    "ribotricer_metagene_plot",
                    "ribotricer_protocol",
                    "ribotricer_bam_summary",
            ] and str(value) != "nan"):
                try:
                    cell = html.Td(
                        html.A(
                            href="/download?value=" + value,
                            children=[html.I(className="fa fa-download")],
                        ),
                        style={"text-align": "center"},
                    )
                except:
                    print(value)
            else:
                cell = html.Td(children=value)
            row.append(cell)
        rows.append(html.Tr(row))
    return html.Table(
        # Header
        [html.Tr([html.Th(col) for col in dataframe.columns])] + rows,
        style={
            "width": "100%",
            "margin-right": "auto",
            "margin-left": "10%",
            "align": "center",
            "display": "inline-block",
        },
    )
Esempio n. 11
0
    4: 'Life and earth sciences',
    5: 'Mathematics and computer sciense'
}

## load papers
df_tiab = pd.read_excel(f'{data_dir}/待判别62clusters.xlsx',
                        sheet_name='主要论文与关键词')
target_clusters = list(df_tiab['micro_level_field_id'].unique())

df_ins = pd.read_excel(f'{data_dir}/待判别62clusters.xlsx', sheet_name='主要机构')
# formulate marker text

df_map['journals'] = df_map['journals'].apply(lambda x: x.split(';'))
df_map['keywords'] = df_map['keywords'].apply(lambda x: x.split(';'))
df_map['journals_tab'] = df_map['journals'].apply(
    lambda x: [html.Tr(f"{x[i].strip()}") for i in range(len(x))])
df_map['keywords_tab'] = df_map['keywords'].apply(
    lambda x: [html.Tr(f"{x[i].strip()}") for i in range(len(x))])
df_map['idx'] = df_map['id']
df_map.set_index('idx', inplace=True)

df_map = df_map[df_map['id'].isin(target_clusters)]


def text(row):
    journals = ["代表性期刊:"] + [f"{jour}" for jour in row['journals']] + ['', '']
    terms = ["代表性关键词:"] + [f"{term}" for term in row['keywords']]
    #y = [f'N:{row["N"]}',f'CSI:{row["CSI"]}',f'IF:{row["IF"]}',y]
    y = [f'主题编号:{row["label"]}', ''] + journals + terms
    y = '<br>'.join(y)
    return y
Esempio n. 12
0
def generate_table():
    global MH01_rules
    global MH02_rules
    global MH03_rules
    global rule_broken
    global rule_broken_index
    global count, time, maxval
    global groupm
    global machlist
    global groupl
    global DispRules
    MH01_rules = list(MH01.columns[MH01.columns.str.contains('rule')].values)
    MH02_rules = list(MH02.columns[MH02.columns.str.contains('rule')].values)
    MH03_rules = list(MH03.columns[MH03.columns.str.contains('rule')].values)
    rule_broken = breakdetect()
    rule_broken_index = pd.to_numeric(prov_index(rule_broken))
    count, time, maxval = Timegen()
    DispRules = pd.DataFrame(Rules.iloc[rule_broken_index, :])
    DispRules.drop(labels=['Value'], axis=1, inplace=True)
    DispRules = DispRules.assign(Count=count, Last_Occurence=time, Max=maxval)
    DispRules.sort_values(['Important', 'Count'],
                          ascending=False,
                          kind='mergesort',
                          inplace=True)
    groupm = list(DispRules.groupby('Machine'))
    machlist = list()
    groupl = list()
    for i in range(len(groupm)):
        machlist.append(groupm[i][0])
        groupl.append(len(groupm[i][1]))
    return html.Table(
        # Header
        [
            html.Tr([
                html.Th(col,
                        style={
                            'textAlign': 'Center',
                            'fontFamily': 'Arial',
                            'fontSize': '16',
                            'color': 'rgb(88, 88, 101)'
                        }) for col in
                DispRules.columns[~DispRules.columns.str.contains('Important')]
            ])
        ] +

        # Body
        [
            html.Tr([
                html.Td(DispRules.iloc[i][col],
                        style={
                            'textAlign': 'Center',
                            'fontFamily': 'Arial',
                            'fontSize': '12',
                            'color': coldec(i),
                            'fontWeight': '800'
                        }) for col in
                DispRules.columns[~DispRules.columns.str.contains('Important')]
            ]) for i in range(len(DispRules))
        ],
        style={
            'marginLeft': '10',
            'backgroundColor': 'rgb(230,230,210)',
            'paddingTop': '15',
            'paddingRight': '10',
            'paddingLeft': '3',
            'border-radius': '15px',
            'border': 'solid',
            'borderColor': 'rgb(220,220,200)'
        })
Esempio n. 13
0
def df_to_table(df):
    return html.Table([html.Tr([html.Th(col) for col in df.columns])] + [
        html.Tr([html.Td(df.iloc[i][col]) for col in df.columns])
        for i in range(len(df))
    ])
Esempio n. 14
0
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div([
    # The memory store reverts to the default on every page refresh
    dcc.Store(id='memory'),
    # The local store will take the initial data
    # only the first time the page is loaded
    # and keep it until it is cleared.
    dcc.Store(id='local', storage_type='local'),
    # Same as the local store but will lose the data
    # when the browser/tab closes.
    dcc.Store(id='session', storage_type='session'),
    html.Table([
        html.Thead([
            html.Tr(html.Th('Click to store in:', colSpan="3")),
            html.Tr([
                html.Th(html.Button('memory', id='memory-button')),
                html.Th(html.Button('localStorage', id='local-button')),
                html.Th(html.Button('sessionStorage', id='session-button'))
            ]),
            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'),
Esempio n. 15
0
import dash
import dash_html_components as html
import dash_bootstrap_components as dbc

app = dash.Dash(__name__)

app.layout = html.Div(
    dbc.Container(
        dbc.Table([
            html.Thead(html.Tr([html.Th('字段1'), html.Th('字段2')])),
            html.Tbody([
                html.Tr([html.Th('1'), html.Td('test')]),
                html.Tr([html.Th('2'), html.Td('test')]),
                html.Tr([html.Td('3'), html.Td('test')])
            ])
        ],
                  striped=True),
        style={
            'margin-top': '50px'  # 设置顶部留白区域高度
        }))

if __name__ == '__main__':
    app.run_server(debug=True)
Esempio n. 16
0
def get_data_list(data):
    contents = []
    for title, value in data.items():
        contents.append(html.Tr([html.Td(Label(title)), html.Td(value)]))
    return html.Table([html.Tbody(contents)], className="table")
Esempio n. 17
0
                # url_base_pathname='/stdhd/',
                # requests_pathname_prefix='/stdcheck/',
                external_stylesheets=external_stylesheets)
# auth = dash_auth.BasicAuth(
#     app,
#     VALID_USERNAME_PASSWORD_PAIRS
# )

app.layout = html.Div([
    html.H2('Welcome to DUSKASH'),
    html.H6('This site provides toolkits to plot charts. You only need to upload specific format excel/csv. And you will get 2d/3d chart after several mouse clicking.'),
    html.Div([
        html.Table([
            html.Tr([
                html.Th('Tools'),
                html.Th('Description'),
                html.Th('Version')]
            ),
            html.Tr([   # row of s2d
                html.Td(
                    html.A('S2d', href='/s2d/'),
                ),
                html.Td('After upload the dataset, it returns a 2d scatter chart. No classification fuction, but you can plot multiple features on the screen'
                ),
                html.Td(
                    '1.2'
                )], className='active'
            ),
            html.Tr([   # row of m2d
                html.Td(
                    html.A('M2d', href='/m2d/'),
Esempio n. 18
0
def get_table(rows):
    contents = []
    for row in rows:
        contents.append(html.Tr([html.Td(item) for item in row]))
    return html.Table([html.Tbody(contents)], className="table")
def fubukiSolver(n_clicks, position, posValue, r1, r2, r3, c1, c2, c3):
    '''
    Function to solve fubuki puzzle by checking prefilled values with the 
    combined values of each permutations. Brute-force approach.
    
    @param n_clicks the click amount for Button that when user hits the button, @callback is fired. 
    @param position the position on the puzzle user want to set value
    @param posValu the value for the defined position
    @param r1-r3 R1 through R3 values defined by user
    @param c1-c3 C1 through C3 values defined by user
    '''
    resOut = []
    n = 0  #to count number of solutions
    myList = np.arange(1, 10, dtype=int)  #Create a list from 1 - 9 of type int
    newList = np.delete(myList, np.where(
        myList ==
        posValue))  #delete the prefilled value and its position given by user
    permList = permutations(
        newList)  #to calculate all permutations for 9 numbers
    myPrefilledVals = np.array(
        [r1, r2, r3, c1, c2,
         c3])  #put all the user-filled values into an array

    #iterate through all permutations to make comparisons
    for orderList in permList:
        orderList = np.insert(orderList, position, posValue)
        row1 = sum(orderList[0:3])
        row2 = sum(orderList[3:6])
        row3 = sum(orderList[6:9])
        col1 = orderList[0] + orderList[3] + orderList[6]
        col2 = orderList[1] + orderList[4] + orderList[7]
        col3 = orderList[2] + orderList[5] + orderList[8]
        #put all combinations into an array
        solution = np.array([row1, row2, row3, col1, col2, col3])
        '''Condition to check if solution matches the prefilledVals
            If it does, n increments and resOut append its solution'''
        if (solution == myPrefilledVals).all():
            n = n + 1
            resOut.append(orderList[0:3])
            resOut.append(orderList[3:6])
            resOut.append(orderList[6:9])

    myResults = np.array(resOut)
    ##Create a pandas DataFrame to be input into html.Table() later on
    dataframe = pd.DataFrame(
        myResults,
        columns=['C1', 'C2', 'C3'],
        index=['R{0}'.format(i) for i in range(1,
                                               len(resOut) + 1)])
    '''To check: if there are solutions, then table will be generated, 
        Otherwise, return there is no result'''
    if n > 0:

        for i in range(n):
            return html.Table(
                # Header
                [html.Tr([html.Th(col) for col in dataframe.columns])] +

                # Body
                [
                    html.Tr([
                        html.Td(dataframe.iloc[i][col])
                        for col in dataframe.columns
                    ]) for i in range(min(len(dataframe), len(dataframe)))
                ])
    else:
        return 'There is no solution'
Esempio n. 20
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)
def update_modal(data, year):
    # if black frame of treemap, don't update
    if data is None:
        return dash.no_update
    # if no currentpath or country is chosen, don't update
    elif data['points'][0].get('currentPath') is None:
        return dash.no_update

    elif data['points'][0]['currentPath'] == '/':
        if data['points'][0].get('label') is None:
            return dash.no_update
        else:
            label_slct = data['points'][0]['label']
            if year == '2018':
                dff = df[df["Country"] == label_slct]
            if year == '2019':
                dff = df19[df19["Country"] == label_slct]
            extract_country_index = dff[dff['Country'] ==
                                        label_slct].index.values.tolist()
            borders = [
                1 if i in extract_country_index else 4 for i in range(len(dff))
            ]

            # build map
            fig = px.choropleth(dff,
                                locations="iso_alpha",
                                hover_name="Country",
                                scope='africa',
                                projection='natural earth').update_traces(
                                    marker_line_width=borders,
                                    showlegend=False).update_layout(
                                        margin=dict(t=25, r=0, l=5, b=20))

            # create the table
            table_header = [html.Thead(html.Tr([html.Th(label_slct)]))]
            rows = []
            for x in dff["notes"]:
                if pd.isnull(x):
                    continue
                rows.append(html.Tr([html.Td(x)]))

            table_body = [html.Tbody(rows)]

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

    # if axis of intervention is chosen (country is parent), don't update
    elif data['points'][0]['parent'] in df.Country.unique():
        label_slct = data['points'][0]['label']
        parent_slct = data['points'][0]['parent']
        if year == '2018':
            dff = df[(df["Axis of intervention"] == label_slct)
                     & (df["Country"] == parent_slct)]
        if year == '2019':
            dff = df19[(df19["Axis of intervention"] == label_slct)
                       & (df19["Country"] == parent_slct)]
            # make selected countries' borders on map thicker
        extract_country_index = dff[dff['Country'] ==
                                    parent_slct].index.values.tolist()
        borders = [
            1 if i in extract_country_index else 4 for i in range(len(dff))
        ]

        # build map
        fig = px.choropleth(dff,
                            locations="iso_alpha",
                            hover_name="Country",
                            scope='africa',
                            projection='natural earth').update_traces(
                                marker_line_width=borders,
                                showlegend=False).update_layout(
                                    margin=dict(t=25, r=0, l=5, b=20))

        # create the table
        table_header = [html.Thead(html.Tr([html.Th(label_slct)]))]
        rows = []
        for x in dff["notes"]:
            if pd.isnull(x):
                continue
            rows.append(html.Tr([html.Td(x)]))

        table_body = [html.Tbody(rows)]

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

    # if Region is chosen, build table
    else:
        label_slct = data['points'][0]['label']
        parent_slct = data['points'][0]['parent']
        print(label_slct), print(parent_slct), print(data)
        if year == '2018':
            dff = df[(df.Region == label_slct)
                     & (df["Axis of intervention"] == parent_slct)]
        if year == '2019':
            dff = df19[(df19.Region == label_slct)
                       & (df19["Axis of intervention"] == parent_slct)]
        # make selected countries' borders on map thicker
        extract_country = data['points'][0]['currentPath']
        extract_country = extract_country.split('/')[1]
        extract_country_index = dff[dff['Country'] ==
                                    extract_country].index.values.tolist()
        borders = [
            1 if i in extract_country_index else 4 for i in range(len(dff))
        ]

        # build map
        fig = px.choropleth(dff,
                            locations="iso_alpha",
                            hover_name="Country",
                            scope='africa',
                            projection='natural earth').update_traces(
                                marker_line_width=borders,
                                showlegend=False).update_layout(
                                    margin=dict(t=25, r=0, l=5, b=20))

        # create the table
        table_header = [html.Thead(html.Tr([html.Th(label_slct)]))]
        rows = []
        for x in dff["notes"]:
            if pd.isnull(x):
                continue
            rows.append(html.Tr([html.Td(x)]))

        table_body = [html.Tbody(rows)]

        return fig, dbc.Table(table_header + table_body, bordered=True)
Esempio n. 22
0
                                        style=tab_style,
                                        selected_style=tab_selected_style),
                                dcc.Tab(id='cat2',
                                        label='Financial Markets',
                                        value='cat-2',
                                        style=tab_style,
                                        selected_style=tab_selected_style),
                            ]),

                        ## displayed below category tabs ##
                        html.Div(id='categories-content',
                                 children=[
                                     html.Table(
                                         style={'border-spacing': 7},
                                         children=[
                                             html.Tr(id='radio-label',
                                                     children='Radio:'),
                                             dcc.RadioItems(id='radio'),
                                             html.Tr([
                                                 html.Div(
                                                     id='dropdown1_label',
                                                     children="Dropdown1:"),
                                                 dcc.Dropdown(id='dropdown1'),
                                             ]),
                                             html.Tr([
                                                 html.Div(
                                                     id='dropdown2_label',
                                                     children="Dropdown2:"),
                                                 dcc.Dropdown(id='dropdown2'),
                                             ]),
                                         ]),
                                     dcc.Markdown(markdown_paragraph),
Esempio n. 23
0
def html_status_tables():

    # Process scanning
    ps_config = CONFIG["ps"]

    # Add this process into the
    ptable_header = [
        html.Tr([
            html.Th(label, className=table_header_style) for label in [
                "Process Group", "Running?", "PIDs", "Description", "Ports",
                "CPU"
            ]
        ])
    ]
    ptable_rows = []

    for pname, pinfo in ps_config.items():

        pq = pinfo["query"]
        plist = ps_query(pq)

        if plist:
            running = True
            pids_formatted = ",".join(str(p.pid) for p in plist)
            plist_cpu = sum([p.cpu_percent(interval=interval)
                             for p in plist]) / psutil.cpu_count()
            plist_cpu = f"{plist_cpu}%"
        else:
            if pname == "dsmt_app":
                running = True
                pids_formatted = os.getpid()
                plist_cpu = psutil.Process(pids_formatted).cpu_percent(
                    interval=interval) / psutil.cpu_count()
                plist_cpu = f"{plist_cpu}%"
            else:
                running = False
                pids_formatted = "null"
                plist_cpu = "null"

        ptable_rows.append(
            html.Tr([
                html.Td(pname, className=monospace_style),
                html.Td(check_img if running else x_img),
                html.Td(pids_formatted),
                html.Td(pinfo['description']),
                html.Td(",".join([str(port) for port in pinfo["ports"]])),
                html.Td(plist_cpu)
            ]))

    proc_table = html.Table(ptable_header + ptable_rows, className=table_style)
    proc_div = html.Div(
        [html.Div("Processes", className=header_style), proc_table],
        className=box_style)

    # Docker with default configuration running locally
    if CONFIG["docker"]:
        dtable_header = [
            html.Tr([
                html.Th(label, className=table_header_style) for label in
                ["Container Name", "Running?", "Status", "Image", "Ports"]
            ])
        ]
        dtable_rows = []

        client = docker.from_env()
        for c in client.containers.list(all=True):

            running = True if c.status == "running" else False
            if c.ports:
                ports = []
                for cport, hportset in c.ports.items():
                    hport = hportset[0]["HostPort"] if hportset else "null"
                    ports.append(f"{cport} (container) -> {hport}")
                ports_html = html.Div([html.Div(port) for port in ports])
            else:
                ports_html = "null"

            dtable_rows.append(
                html.Tr([
                    html.Td(c.name, className=monospace_style),
                    html.Td(check_img if running else x_img),
                    html.Td(c.status),
                    html.Td(c.image.attrs["RepoTags"][0]),
                    html.Td(ports_html),
                ]))

        docker_table = html.Table(dtable_header + dtable_rows,
                                  className=table_style)
        docker_div = html.Div([
            html.Div("Docker containers", className=header_style), docker_table
        ],
                              className=box_style)
    else:
        docker_div = html.Div(children='')

    # SystemD services
    stable_header = [
        html.Tr([
            html.Th(label, className=table_header_style) for label in [
                "Service name", "Running?", "Main PID", "Description", "Ports",
                "CPU"
            ]
        ])
    ]
    stable_rows = []
    for sname, sinfo in CONFIG["systemd"].items():
        squery = sinfo["query"]
        info = os.popen(f'systemctl status {squery}').read()
        infolist = [i.strip() for i in info.split("\n")]

        desc_dirty = infolist[0]
        status_dirty = [i for i in infolist if "Active: " in i][0]
        running = True if "(running) since" in status_dirty else False

        if running:
            pid_dirty = [i for i in infolist
                         if "Main PID:" in i][0].replace("Main PID: ", "")
            pid_clean = int(pid_dirty.split(" ")[0].strip())
        else:
            pid_dirty = "null"
            pid_clean = "null"

        try:
            cpu_usage = psutil.Process(pid_clean).cpu_percent(
                interval=interval)
            cpu_usage = f"{cpu_usage}%"
        except:
            cpu_usage = "N/A"

        stable_rows.append(
            html.Tr([
                html.Td(sname, className=monospace_style),
                html.Td(check_img if running else x_img),
                html.Td(pid_dirty),
                html.Td(f"{sinfo['description']} ({desc_dirty})"),
                html.Td(", ".join([str(port) for port in sinfo["ports"]])),
                html.Td(cpu_usage)
            ]))

    systemd_table = html.Table(stable_header + stable_rows,
                               className=table_style)
    systemd_div = html.Div(
        [html.Div("SystemD services", className=header_style), systemd_table],
        className=box_style)
    return html.Div(
        id="display",
        children=[proc_div, divider, docker_div, divider, systemd_div])
Esempio n. 24
0
                         className='color-text'),
                 dcc.Tab(label='Compare the models',
                         value='compare-models',
                         className='color-text')
             ]),
    html.Div(id='regression-layout')
]

about_the_author_layout = html.Table([
    html.Tbody([
        html.Tr([
            html.Td(html.Div(html.Img(src=app.get_asset_url('photo.jpeg'),
                                      className='photo'),
                             className='photo-div'),
                    rowSpan=3),
            html.Td(
                html.Table([
                    html.Tr(html.Td(html.H3('Inês Andrade Rainho'))),
                    html.Tr(html.Td(html.H4('IST Student Number: 90396'))),
                    html.Tr(html.Td(html.H4('*****@*****.**')))
                ]))
        ])
    ])
])
# -- END


# callbacks
# callback for the button with dropdown menu
@app.callback(Output('dropdown_menu', 'children'),
              Input('button_dropdown', 'n_clicks'))
def toggle_dropdown(n_clicks):
Esempio n. 25
0
def createTierMappingMenus(eafFilename):
    print("=== createTierMappingMenus: %s [exists: %s]" %
          (eafFilename, os.path.exists(eafFilename)))
    dropDownMenus = html.H5("☠️ failure in extracting tierIDs from %s" %
                            eafFilename)

    if (os.path.exists(eafFilename)):
        tmpDoc = etree.parse(eafFilename)
        userProvidedTierNamesToAssignToStandardTiers = [
            tier.attrib["TIER_ID"] for tier in tmpDoc.findall("TIER")
        ]
        print(userProvidedTierNamesToAssignToStandardTiers)

        tierChoices = userProvidedTierNamesToAssignToStandardTiers

        dropDownMenus = html.Table(
            id="tierMappingMenus",
            children=[
                html.Tr([
                    html.Th("Standard interlinear tiers", className="first"),
                    html.Th("(e.g., from Totonac)", className="second"),
                    html.Th("Select ELAN tier", className="third")
                ]),
                html.Tr([
                    html.Td(children=[
                        html.Div("line", style={'display': 'inline-block'}),
                        html.Div("*",
                                 style={
                                     'display': 'inline-block',
                                     'color': 'red'
                                 })
                    ]),
                    html.Td("tanhe:x’a'ha:ma:lhtzá'"),
                    html.Td(createPulldownMenu("speech", tierChoices))
                ]),
                html.Tr([
                    html.Td("alternate transcription"),
                    html.Td("taŋʔeːš’a̰ʔaːmaːɬtsá̰"),
                    html.Td(createPulldownMenu("transcription2", tierChoices))
                ]),
                html.Tr([
                    html.Td("morphological analysis"),
                    html.Td("taŋʔeː–š’a̰ʔáː–maːɬ=tsá̰"),
                    html.Td(createPulldownMenu("morpheme", tierChoices))
                ]),
                html.Tr([
                    html.Td("morpheme glosses"),
                    html.Td(children=[
                        html.Div("basin–", style={'display': 'inline-block'}),
                        html.Div("shine", style={'display': 'inline-block'}),
                        html.Div("–prog",
                                 style={
                                     'font-variant': 'small-caps',
                                     'display': 'inline-block'
                                 }),
                        html.Div("=now",
                                 style={
                                     'font-variant': 'small-caps',
                                     'display': 'inline-block'
                                 })
                    ]),
                    html.Td(createPulldownMenu("morphemeGloss", tierChoices))
                ]),
                html.Tr([
                    html.Td(children=[
                        html.Div("translation",
                                 style={'display': 'inline-block'}),
                        html.Div("*",
                                 style={
                                     'display': 'inline-block',
                                     'color': 'red'
                                 })
                    ]),
                    html.Td("‘The horizon is growing light.’"),
                    html.Td(createPulldownMenu("translation", tierChoices))
                ]),
                html.Tr([
                    html.Td("second translation"),
                    html.Td("‘Está aclarando donde sale el sol.’"),
                    html.Td(createPulldownMenu("translation2", tierChoices))
                ])
            ],
            className="tiermap")

    saveTierMappingChoicesButton = html.Button(
        'save', id='saveTierMappingSelectionsButton', className="button")

    tierMappingChoicesResultDisplay = html.Span(
        id="tierMappingChoicesResultDisplay",
        children="",
        style={
            "border": 1,
            "margin-left": 10
        })
    requiredTiersFootnote = html.Span("*Required",
                                      id='requiredTiersFootnote',
                                      className="warningfootnote")

    children = [
        dropDownMenus,
        html.Br(), saveTierMappingChoicesButton,
        tierMappingChoicesResultDisplay, requiredTiersFootnote
    ]

    enclosingDiv = html.Div(children=children)
    return (enclosingDiv)
Esempio n. 26
0
   # Begin of First Tr
 html.Tr(
     #Begin Tr children
     children=[
         # Begin Th
         
         html.Th(style={'width':'30%'},
             # Begin Th children
             children=[
                 html.H3('the graph')
             # End of Th children   
             ]
         
         # End of Th - Notice a comma is placed here to separate the next Th
         ),
         # Begin of Th
         html.Th(style={'width':'70%'},
             # Begin of Th children
             children=[
                 html.H3('correlation')
             # End of Th children    
             ]
         
         # End of Th
         )
         
     # End of Tr children    
     ]
 # End of First Tr - Notice a comma is placed here to separate the next Tr
 ),
 #########################################################################
Esempio n. 27
0
player_df = player_df.sort_values(by=['last'])

weeks = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
players = player_df['name'].values.tolist()

style = {'padding': '1em'}

layout = html.Div([
    html.Table(
        [
            html.Col(style={'width': '400px'}),
            html.Col(style={'width': '100px'}),
            html.Col(style={'width': '400px'}),
            html.Thead(),
            # Row 1 - Header
            html.Tr(),
            html.Th(dcc.Markdown("""
            #### Select a Week
            """),
                    colSpan='3'),
            html.Tbody(),
            # Row 2 - Week
            html.Tr(),
            html.Td(),
            html.Td(
                dcc.Dropdown(id='week_no',
                             options=[{
                                 'label': week,
                                 'value': week
                             } for week in weeks],
                             value=1,
Esempio n. 28
0
                html.Tr([
                    html.Td([
                        html.Div(
                            id='intro',
                            className="section",
                            children=[
                                html.Table([
                                    html.Tr(
                                        [
                                            html.Td([
                                                html.Label("Search"),
                                            ]),
                                            html.Td(
                                                [html.Label("Gene:")],
                                                style={'text-align': 'right'}),
                                            html.Td([
                                                dcc.Input(
                                                    type='text',
                                                    placeholder="E.g.: DDR1",
                                                    spellCheck='false',
                                                    size='20',
                                                    id='sel-gene',
                                                ),
                                            ]),
                                            #
                                            html.Td(
                                                [
                                                    html.Label("Dataset:"),
                                                ],
                                                style={'text-align': 'right'}),
                                            html.Td(
                                                [
                                                    selector('Dataset',
                                                             id='sel-dataset'),
                                                    # Riccardo I need to change the width of dataset selector
                                                ],
                                                style={'width': '60px'}),

                                            #
                                            html.Td(
                                                [
                                                    html.Label('Keyword'),
                                                ],
                                                style={'text-align': 'right'}),
                                            html.Td([
                                                dcc.Input(
                                                    type='text',
                                                    placeholder=
                                                    "E.g.: cell cycle",
                                                    spellCheck='false',
                                                    size='20',
                                                    id='sel-functions',
                                                ),
                                            ])
                                            #html.Button('Search', id='searchBtn', n_clicks_timestamp=0),
                                        ], ),
                                    #]
                                ]),
                            ]),
                        html.Tr([

                            #    html.Div(
                            #        id='report',
                            #        className="container section",
                            #        children=[
                            #            html.P("""
                            #            Click on the small arrows besides column names to sort by that column.
                            #            """),
                            html.Div(
                                id='table-container',
                                children=[table()],
                            ),
                            #        ]
                            #    ),
                        ]),
                    ])
                ])
Esempio n. 29
0
# dictionary comprehension to shorten state abbreviation
shorthand = {x: y for x, y in zip(states, usa)}
shorthand[''] = ''

# Dash Web Layout Creator
app = dash.Dash(__name__)
# Browser tab title
app.title = "TESTING"

# Start of Dash HTML Loading
app.layout = html.Div([
    # Description of template table
    # HTML Table tag
    html.Table(
        # TR = Table Row, creates title that spans two columns
        [html.Tr(html.Th("HELP", colSpan='2'))] +
        # TR for each variable
        [
            html.Tr([
                html.Td("Increment"),
                html.Td(("Count of sizes to buy. MUST BE INCLUDED."))
            ])
        ] + [
            html.Tr([
                html.Td("Size"),
                html.Td(("Dollar Amount of bonds to buy (min $10k)."
                         " MUST BE INCLUDED."))
            ])
        ] + [
            html.Tr([
                html.Td("General Market"),
Esempio n. 30
0
        Enter a host to view its open ports
    '''),
    html.Br(),
    dcc.Input(
        placeholder='Enter a host...',
        type='text',
        value='',
        id='port_host_input'
        ),


    html.Button(id='port_search_button_state', n_clicks=0, children='Search'),

    #define the port table
    html.Table(id='port_data', children =[
        html.Tr(),
        html.Th(children='Port Number'),
        html.Th(children='Service')
        ]
    ),
    
    html.Div(children=' Geolocation', style ={'textAlign': 'center', 
	'color': '#3A2BDA'}),
    
	html.Div([ 
       dcc.Graph(figure=fig1)
	   
	]),

    # send ip address to the map
    html.Div([