Exemple #1
0
def serve_sal_layout():

    current_user = User()
    depts = current_user.salary_access()

    if depts:

        logger.log_access(has_access=True)

        # Create a list of dropdown options based on user permissions
        # Do this here to call salary_access only once
        dept_dropdown_options = []
        for option in ALL_DEPT_DROPDOWN_OPTIONS:
            if option['value'].strip('_') in depts:
                dept_dropdown_options.append(option)

        layout = html.Div([
            serve_navbar(),
            html.Div(
                [
                    header,
                    html.Div(id='test-div'),
                    serve_filters(dept_dropdown_options),
                    chart,
                    table,
                ],
                className='container pb-5',
            ),
        ])

    else:

        # Log that a user accesssed this view and was NOT authorized
        logger.log_access(has_access=False)

        no_access_alert = dbc.Alert([
            html.H5('You don\'t have access to this page.',
                    className='alert-heading'),
            html.P(
                'Please reach out to Timur Gulyamov (tg2648) to get access.',
                className='mb-0',
            ),
        ],
                                    color='warning',
                                    className='mt-3')

        layout = html.Div([
            serve_navbar(),
            html.Div([no_access_alert], className='container'),
        ])

    return layout
Exemple #2
0
 def update_table(n_clicks, element, mode, num):
     print('update')
     t0 = time.time()
     result = []
     if num != None:
         result = make_table('medicodeset', element, mode, num)
     else:
         result = make_table(None, element, mode, num)
     t1 = time.time()
     exec_time = t1 - t0
     alert_msg = f"Processing done. Total time: {exec_time}"
     alert = dbc.Alert(alert_msg, color="success", dismissable=True)
     return result + [alert]
Exemple #3
0
    def run_mint(n_clicks, wdir):
        if n_clicks is None:
            raise PreventUpdate

        def set_progress(x):
            fsc.set('progress', x)

        mint = Mint(verbose=True, progress_callback=set_progress)
        mint.peaklist_files = T.get_peaklist_fn( wdir )
        mint.ms_files = T.get_ms_fns( wdir )
        mint.run()
        mint.export( T.get_results_fn(wdir) )
        return dbc.Alert('Finished running MINT', color='success')
Exemple #4
0
def display_output(value):

    if value:
        # Get the ticker symbol from dataframe by passing selected row and column which has the tickers
        ticker = value["TICKER"]
        fig, info_text = update_graph(ticker)
        chart = html.Div([
            dbc.Alert(info_text, color="primary"),
            dcc.Graph(figure=fig),
        ])
        return chart, True
    else:
        return "", False
Exemple #5
0
def SuccessChangePasswordAlert(username):
    return dbc.Alert([
        html.H4('Success',
                className="alert-heading",
                style={'text-align': "center"}),
        html.P("You have successfully changed %s's password!" % username,
               style={'text-align': "center"}),
    ],
                     dismissable=False,
                     color='success',
                     fade=True,
                     is_open=True,
                     id='success-change-password-alert')
Exemple #6
0
def SuccessLoginAlert(username):
    return dbc.Alert([
        html.H4('Success',
                className="alert-heading",
                style={'text-align': "center"}),
        html.P(["You have successfully logged in as '%s'." % username],
               style={'text-align': "center"}),
    ],
                     dismissable=False,
                     color='success',
                     fade=True,
                     is_open=True,
                     id='success-login-alert')
Exemple #7
0
def upload_data(contents, n_click, save, url_input):
    """Change url and load data into datastore when upload chat or go to saved chat url key."""
    ctx = dash.callback_context
    url, datasets, alert = dash.no_update, dash.no_update, dash.no_update
    if ctx.triggered[0]['prop_id'] == 'upload-data.contents':
        content_type, content = contents.split(',')
        if content_type == 'data:text/plain;base64':
            content_decoded = base64.b64decode(content)
            url, datasets = chat_parser.load_parsed_data(content_decoded, 'upload', save)
            if url == 'not_supported':
                supported_language = ', '.join([lang['language'] for lang in settings.LANGUAGE.values()])
                alert = dbc.Alert('Language not supported. Currently supported languages: {}.'.format(supported_language), dismissable=True, color='danger')
                url = dash.no_update
            else:
                url = url + settings.FROM_LANDING_PAGE
        else:
            alert = dbc.Alert('Wrong file type, please upload txt file from exported Whatsapp chat.', dismissable=True, color='danger')
    elif ctx.triggered[0]['prop_id'] == 'url-submit.n_clicks':
        url, datasets = chat_parser.load_parsed_data(url_input, 'url')
        if url != 'not_found':
            url = url + settings.FROM_LANDING_PAGE
    return url, datasets, alert
Exemple #8
0
def SuccessLogoutAlert():
    return dbc.Alert([
        html.H4('Success',
                className="alert-heading",
                style={'text-align': "center"}),
        html.P(["You have successfully logged out"],
               style={'text-align': "center"}),
    ],
                     dismissable=False,
                     color='danger',
                     fade=True,
                     is_open=True,
                     id='success-logout-alert')
Exemple #9
0
 def ms_convert(n_clicks, rows, wdir):
     target_dir = os.path.join(wdir, 'ms_files')
     if n_clicks is None:
         raise PreventUpdate
     fns = [row['MS-file'] for row in rows]
     fns = [fn for fn in fns if not fn.endswith('.feather')]
     fns = [os.path.join(target_dir, fn) for fn in fns]
     n_total = len(fns)
     for i, fn in enumerate(fns):
         fsc.set('progress', int(100 * (i + 1) / n_total))
         new_fn = convert_ms_file_to_feather(fn)
         if os.path.isfile(new_fn): os.remove(fn)
     return dbc.Alert('Files converted to feather format.', color='info')
Exemple #10
0
def update_montage_io(button_io, button_nio):
    if int(button_io) == 0 and int(button_nio) == 0:
        child = html.Div([
            html.Br(),
            html.H4('Bitte Montage des Bauteils durchführen!'),
            html.Br(),
        ])
    elif int(button_io) > int(button_nio):
        child = html.Div([
            html.Br(),
            html.H4('Die Montage des Bauteils war erfolgreich!'),
            html.Br(),
            dbc.Alert(
                [
                    html.A("Neues Bauteil anmelden.",
                           href="/",
                           className="alert-link"),
                ],
                color="primary",
                style={'font-size': '150%'},
            ),
        ])
    else:
        child = html.Div([
            html.Br(),
            html.H4('Die Montage des Bauteils ist fehlgeschlagen!'),
            html.Br(),
            dbc.Alert(
                [
                    html.A("Neues Bauteil anmelden.",
                           href="/",
                           className="alert-link"),
                ],
                color="primary",
                style={'font-size': '150%'},
            ),
        ])
    return [child]
Exemple #11
0
def update_anomalies(n):
    unresolved = connection.get_unresolved_anomalies()
    resolved = connection.get_resolved_anomalies()
    children = []

    children.append(html.H1("Unresolved"))
    for idx, row in unresolved.iterrows():
        if row['severity'] == 'high':
            color = 'danger'
        elif row['severity'] == 'medium':
            color = 'warning'
        else:
            color = 'info'
        children.append(dbc.Alert(f"{(row['name']) if row['name'].lower() != 'node' else ('Node ' + str(row['node_id']))} has an unresolved {row['type']} anomaly: "
                                  f"{row['message']} ({row['time']})", color=color))

    children.append(html.Br())
    children.append(html.H1("Resolved"))
    for idx, row in resolved.iterrows():
        children.append(dbc.Alert(f"{(row['name']) if row['name'].lower() != 'node' else ('Node ' + str(row['node_id']))} had a {row['type']} anomaly: "
                                  f"{row['message']} ({row['time']})", color='dark'))
    children.append(html.Br())
    return html.Div(children)
def display_rebalance_output(n_clicks, text_area: str, results):
    if not n_clicks:
        raise PreventUpdate
    if not text_area:
        raise PreventUpdate
    if not results:
        raise PreventUpdate
    try:
        portfolio = json.loads(text_area)
    except (Exception):
        return dbc.Alert("Invalid JSON format", color="danger"),
    min_vol = results[MIN_VOL]['Expected Weights']
    max_sharpe = results[MAX_SHARPE]['Expected Weights']
    symbols = portfolio.keys()
    with open('config.json', 'r') as file:
        config = json.load(file)['crypto']
    api_key = config['crypto_compare_api_key']
    url = 'https://min-api.cryptocompare.com/data/pricemulti'
    params = {"fsyms": ','.join(symbols), "tsyms": "USD", "api_key": api_key}
    exchange_rate = requests.get(url, params=params).json()
    usd_price = {key: value['USD'] for key, value in exchange_rate.items()}
    display_result = {}
    results = pd.DataFrame({"a": portfolio, 'usd_price': usd_price})
    results['holding'] = results['a'] * results['usd_price']
    results['w'] = results['holding'] / results['holding'].sum()
    total_asset_value = results['holding'].sum()
    for entry in [('Maximmum Sharpe Ratio', max_sharpe),
                  ('Minimmum Volatitly', min_vol)]:
        results['ew'] = pd.Series(entry[1])
        results['ew_r'] = results['ew'] - results['w']
        results['ew_usd'] = results['ew_r'] * \
            results['holding'].sum()
        results['ew_a'] = results['ew_usd'] / results['usd_price']
        display_result[entry[0]] = results['ew_a'].to_dict()
    return [html.H4(f'Total Asset Value: ${total_asset_value:.4f}'),
            html.Hr()] +\
        [dbc.Row(dbc.Col([
            html.H5(name),
            dbc.ListGroup([
                dbc.ListGroupItem([
                    dbc.ListGroupItemHeading(f"{value:.5f} {key}"),
                    dbc.ListGroupItemText(f"{value*usd_price[key]:=.2f} USD"),
                ]) for key, value in ew.items()
            ], horizontal=True),
            html.Hr()
        ]),
            align='center', justify='center'
        ) for name, ew in display_result.items()] +\
        [dbc.Label("* positive value is for buy" +
                   " and negative value is for sell")]
Exemple #13
0
 def alert_success(dist_state, step_idx):
     step_idx, attempt, first_callback = json.loads(step_idx)
     distribution = Table.load(dist_state)
     instructions_txt, test = steps[step_idx]
     if first_callback:
         alert = html.Div()
         step_idx, attempt, first_callback = 0, 0, False
     elif test(distribution):
         alert = dbc.Alert('Step {} complete'.format(step_idx + 1),
                           color='success',
                           style={'text-align': 'center'})
         step_idx, attempt = step_idx + 1, 0
         instructions_txt = (success_txt if step_idx == len(steps) else
                             steps[step_idx][0])
     else:
         alert = dbc.Alert('Please reread the instructions and try again.',
                           color='danger',
                           style={'text-align': 'center'})
         step_idx, attempt = step_idx, attempt + 1
     return (json.dumps([step_idx, attempt, first_callback]), [
         alert,
         html.P([html.B('Step {}.'.format(step_idx + 1)), instructions_txt])
     ])
Exemple #14
0
def FailChangePasswordAlert(username):
    return dbc.Alert([
        html.H4('Error',
                className="alert-heading",
                style={'text-align': "center"}),
        html.P("Something went wrong and we couldn't change %s's password!" %
               username,
               style={'text-align': "center"}),
    ],
                     dismissable=False,
                     color='danger',
                     fade=True,
                     is_open=True,
                     id='fail-change-password-alert')
def profile_save_changes(n_clicks, username, password, confirm):
    if n_clicks:
        email = current_user.email
        data_changes = []
        if username != current_user.username:
            data_changes.append('Username changed.')
            Users().change_user(username=username, email=email)
        if Users().set_password(password) != current_user.password:
            data_changes.append('Password changed.')
            Users().change_password(password=password, email=email)
        if data_changes:
            data_changes.append('Changes saved successfully.')
            text_alert = ' '.join(data_changes)
            return 1, [dbc.Alert(text_alert, color='success')]
Exemple #16
0
def build_filters_tab4():
    return [
        dbc.Col([
            dbc.Row(dbc.Alert(
                "La salud mental también se considera importante para el análisis debido a los riesgos asociados a los hechos de victimización de este tipo de población. En este sentido, determinar la probabilidad de desarrollar una de estas enfermedades a partir de los atributos sociodemográficos y las comorbilidades puede ser útil para impulsar la creación de políticas públicas de prevención y tratamiento en las víctimas y el público en general.",
                color="primary"),
                    id="RIP-definition"),
        ],
                id="ripandchecklist"),
        dbc.Col(
            [html.P('Enfermedades'),
             generate_dropdown_mode2('dropdown_tab4')],
            id="left-section-filters"),
    ]
def login_auth(n_clicks,email,pw):
    '''
    check credentials
    if correct, authenticate the session
    otherwise, authenticate the session and send user to login
    '''
    if n_clicks is None or n_clicks==0:
        return no_update,no_update
    credentials = {'user':email,"password":pw}
    if authenticate_user(credentials):
        session['authed'] = True
        return '/home',''
    session['authed'] = False
    return no_update,dbc.Alert('Incorrect credentials.',color='danger',dismissable=True)
Exemple #18
0
def ContactForgotPsswrdAlert():
    return dbc.Alert([
        html.H4('Info', className="alert-heading"),
        html.
        P("If you forgot your password, make sure to fill in with your registered username on the 'Name' input field "
          "and the same email address you provided when registering on the 'Email' input field. If we find this "
          "username and email address registered in our site, we will send you an email with further instructions to "
          "recover your password."),
    ],
                     dismissable=False,
                     color='danger',
                     fade=True,
                     is_open=True,
                     id='forgot-psswrd-alert')
Exemple #19
0
def display_hover_data(hoverData):
    if hoverData:
        country = hoverData['points'][0]['hovertext']
        fig2 = px.bar(df[df.location == country],
                      x="date",
                      y="new_cases",
                      title="New cases per day in " + country)
        fig2.update_layout(showlegend=False, height=900)
        barfig = dcc.Graph(figure=fig2)
        return barfig
    else:
        return dbc.Alert(
            "Hover over a country to see the daily number of cases for that country",
            color='info')
Exemple #20
0
    def add_metab(n_clicks, rows, ms_mode, wdir):
        if n_clicks is None:
            raise PreventUpdate
        if ms_mode is None:
            return dbc.Alert('Please select ionization mode.', color='warning')

        targets = T.get_targets(wdir)

        for row in rows:
            charge = int(row['Charge'])
            if (ms_mode == 'Negative') and (charge > 0):
                continue
            if (ms_mode == 'Positive') and (charge < 0):
                continue
            if charge == 0:
                if ms_mode == 'Negative':
                    targets.loc[
                        row['ChEBI Name'],
                        'mz_mean'] = row['Monoisotopic Mass'] - M_PROTON
                elif ms_mode == 'Positive':
                    targets.loc[row['ChEBI Name'], 'mz_mean'] = row[
                        'Monoisotopic Mass']  #+ M_PROTON
            else:
                targets.loc[row['ChEBI Name'],
                            'mz_mean'] = row['Monoisotopic Mass']

            targets.loc[row['ChEBI Name'], 'mz_width'] = 10
            targets.loc[row['ChEBI Name'], 'rt'] = -1
            targets.loc[row['ChEBI Name'], 'rt_min'] = 0
            targets.loc[row['ChEBI Name'], 'rt_max'] = 15
            targets.loc[row['ChEBI Name'], 'intensity_threshold'] = 0

        T.write_targets(targets, wdir)
        n_peaks = len(targets)
        n_new = len(rows)
        return dbc.Alert(f'{n_new} peaks added, now {n_peaks} peaks defined.',
                         color='info')
Exemple #21
0
def display_page(pathname, bio_network, json_df, json_enrichment_results,
                 network_params):
    """Navigates to the selected app page. Generates vis layout depending on BioNetwork type."""
    if pathname == '/':
        return home.layout, no_update
    elif pathname == '/menu':
        return menu.layout, no_update
    elif pathname == '/vis':
        if bio_network:
            # Load JSON data
            network = json_graph.node_link_graph(json.loads(bio_network))
            network_df = pd.read_json(json_df)
            enrichment_results = pd.read_json(json_enrichment_results)
            # Create cyto network for visualization
            cyto_network = vis.make_cyto_elements(network)
            # Generate layout using generated data
            vis_layout = vis.make_vis_layout(network_df, enrichment_results,
                                             cyto_network, network_params)
            return vis_layout, json.dumps(cyto_network)
        else:
            return dbc.Alert('Warning: You need to build a network first.',
                             color='warning',
                             style={
                                 'display': 'inline-block',
                                 'margin': '10px'
                             }), no_update
    elif pathname == '/user_guide':
        return user_guide.layout, no_update
    elif pathname == '/about':
        return about.layout, no_update
    else:
        return dbc.Alert('Page not found.',
                         color='danger',
                         style={
                             'display': 'inline-block',
                             'margin': '10px'
                         }), no_update
Exemple #22
0
 def perform_opls(n_clicks, scale_by_queries, model_by_queries,
                  ignore_by_queries, pair_on, pair_with_queries, target,
                  regression_type, multiclass_behavior,
                  min_n_components, cross_val_k, inner_test_alpha,
                  outer_test_alpha, permutations, inner_permutations,
                  outer_permutations):
     OPLSDashboard.check_clicks(n_clicks)
     scale_by = ' | '.join(
         scale_by_queries
     ) if scale_by_queries and len(scale_by_queries) else None
     model_by = ' | '.join(
         model_by_queries
     ) if model_by_queries and len(model_by_queries) else None
     ignore_by = ' & '.join(
         ignore_by_queries
     ) if ignore_by_queries and len(ignore_by_queries) else None
     pair_on = pair_on if pair_on and len(pair_on) else None
     pair_with = ' | '.join(
         pair_with_queries) if pair_with_queries and len(
             pair_with_queries) and pair_on else None
     opls_data = OPLSModel()
     try:
         if target is None:
             raise ValueError('Please select a target variable (y).')
         message, name, message_color = opls_data.submit_job(
             model_by, ignore_by, scale_by, pair_on, pair_with, target,
             regression_type, multiclass_behavior, min_n_components,
             cross_val_k, inner_test_alpha, outer_test_alpha,
             permutations, inner_permutations, outer_permutations)
         badges = opls_data.get_results_collection_badges()
     except Exception as e:
         log_internal_exception(e)
         message = [
             html.P([html.Strong('Error: '), f'{e}']),
             html.Strong('Traceback:'),
             html.P(
                 html.Pre(traceback.format_exc(),
                          className='text-white'))
         ]
         message_color = 'danger'
         badges = [
             html.Span([
                 dbc.Badge('None',
                           className='badge-pill',
                           color='warning'), ' '
             ])
         ]
     return (dbc.Alert(message, color=message_color, dismissable=True),
             html.Div(badges, id='loaded-results-collection'))
Exemple #23
0
def render_content(tab):
    if tab == 'tab-1':
        return html.Div([
            dcc.Graph(figure=statepredictorGraph(), style={"height": "36rem"})
        ])
    elif tab == 'tab-2':
        return html.Div(
            [dcc.Graph(figure=stateActive(), style={"height": "36rem"})])
    elif tab == 'tab-3':
        return html.Div(
            [dcc.Graph(figure=stateRecovered(), style={"height": "36rem"})])
    elif tab == 'tab-4':
        return html.Div(
            [dcc.Graph(figure=stateDeseased(), style={"height": "36rem"})])

    elif tab == 'tab-5':
        return html.Div([
            html.Div(
                dbc.Alert([
                    html.H4("Preface"),
                    html.
                    P("Public Affairs Centre (PAC) engages in action research focussing on Sustainable Development Goals"
                      "(SDG) in the context of India.PAC is a not for profit Think Tank"
                      " established in 1994"
                      " with a mandate to"
                      " improve the quality of governance in India.The Centre is also a pioneer in deploying innovative Social"
                      " Accountability Tools (SAT) to measure the quality and adequacy of public services.Over the years, its"
                      " scope of work has expanded to include the whole gamut of research-advocacy-action to lead evidence-"
                      " based research on governance across sectors, geographies and populations in India."
                      " PAC was one of the first civil society-led institutional initiatives to mobilise demand for good"
                      " governance in India.Dr.Samuel Paul (Founder Chairman) was instrumental in establishing PAC with a"
                      " select group of friends.PAC is registered under Karnataka Societies Registration Act 1960 as a Society."
                      " Designing and Editing by: PEC"),
                    html.H4("Disclaimer"),
                    html.
                    P("The CODR COVID-19 DASHBOARD is based on data available in the public domain. While every care is taken to develop an accurate prediction model, the model is prone to complex, evolving, and heterogeneous epidemiology of the COVID-19 disease. The predictions are subjected to an error rate of 10% or less, acceptable under prediction norms in Artificial Intelligence and Machine Learning."
                      ),
                    html.
                    P("The website and its contents herein, including analysis, mapping, and predictions are subjected to Copyright 2020 PAC."
                      ),
                    html.
                    P("Suggested Citation - Public Affairs Centre, Centre for Open Data Research. CODR COVID-19 DASHBOARD [Internet]. http://codrindia.in/. [cited Date]. Available from: http://codrindia.in"
                      )
                ],
                          color="active"))
        ])

    elif tab == 'tab-6':
        return html.Div([html.H3('Tab content 2')])
Exemple #24
0
 def meta_apply(n_clicks, data, selected_rows,
               data_filtered, action, column, value, 
               value_bool, wdir):
     '''
     This callback saves applies the column actions and 
     saves the table to the harddrive.
     '''
     if (n_clicks is None) or (data is None) or (len(data) == 0):
         raise PreventUpdate
     if action == 'Set' and column == 'PeakOpt':
         value = value_bool
     df = pd.DataFrame(data)
     if 'index' in df.columns:
         df = df.set_index('index')
     else:
         df = df.reset_index()
     prop_id = dash.callback_context.triggered[0]['prop_id']
     if prop_id == 'meta-apply.n_clicks':
         if action == 'Set':
             filtered_rows = [r for r in data_filtered['rows'] if r is not None]
             filtered_ndx = [r['index'] for r in filtered_rows]
             if selected_rows == []:
                 # If nothing is selected apply to all visible rows
                 ndxs = filtered_ndx
             else:
                 # If something is selected only apply to selected rows
                 ndxs = [r['index'] for r in selected_rows if r['index'] in filtered_ndx]
             if len(ndxs) == 0 or column is None:
                 # If no column is selected just save the table.
                 T.write_metadata(df, wdir )
                 return dbc.Alert('Metadata saved.', color='info'), 'Applied'
             df.loc[ndxs, column] = value
         elif action == 'create_column': df[value] = ''
         elif action == 'delete_column': del df[column]
     T.write_metadata(df, wdir )
     return dbc.Alert('Metadata saved.', color='info'), 'Applied'
Exemple #25
0
def init_dashboard_2(server):
    """Create a Plotly Dash dashboard."""
    dash_app = dash.Dash(
        server=server,
        routes_pathname_prefix="/dashapp2/",
        external_stylesheets=[dbc.themes.MATERIA],
    )
    dash_app.layout = dbc.Container(
        dbc.Row(
            dbc.Col(
                dbc.Alert("This is another app", color="success"),
                className="mt-5",
            )))

    return dash_app.server
Exemple #26
0
def update_output_div(n_clicks, stop_time, *values):

    try:
        start_values = dict(zip(names, values))

        result = simulate_fmu(filename=args.fmu_filename,
                              start_values=start_values,
                              stop_time=stop_time,
                              output=args.output_variables)

        fig = create_plotly_figure(result=result)

        return dcc.Graph(figure=fig)
    except Exception as e:
        return dbc.Alert("Simulation failed. %s" % e, color='danger'),
Exemple #27
0
def get_state_details():
    return dbc.Card([
        dbc.CardBody([
            dbc.Row(
                [dbc.Alert("Citywise visitors", color="info")],
                justify="start",
            ),
            html.Br(),
            dbc.Row(
                [
                    dbc.Col(dbc.Alert('Select State to view cities',
                                      color='secondary',
                                      style={'text-align': 'center'}),
                            width=4),
                    dbc.Col(state_dropdown, width=6)
                ],
                justify="start",
            ),
            html.Br(),
            dbc.Row([dbc.Col(state_cities_graph, width=12)], justify='center')
        ])
    ],
                    style={"width": "90%"},
                    inverse=True)
Exemple #28
0
def ContactBugAlert():
    return dbc.Alert([
        html.H4('Info', className="alert-heading"),
        html.P([
            "If you suspect a bug, you can also create an issue on the our ",
            html.A(html.U("Github repository"),
                   href=UrlIndex.GITHUB.value,
                   className="alert-link")
        ]),
    ],
                     dismissable=False,
                     color='danger',
                     fade=True,
                     is_open=True,
                     id='bug-alert')
Exemple #29
0
        def perform_pca(n_clicks, scale_by_queries, model_by_queries,
                        ignore_by_queries, pair_on, pair_with_queries,
                        project_by_queries):
            if not n_clicks:
                raise PreventUpdate('Callback triggered without click.')
            scale_by = ' | '.join(
                scale_by_queries
            ) if scale_by_queries and len(scale_by_queries) else None
            model_by = ' | '.join(
                model_by_queries
            ) if model_by_queries and len(model_by_queries) else None
            project_by = ' | '.join(
                project_by_queries
            ) if project_by_queries and len(project_by_queries) else None
            ignore_by = ' & '.join(
                ignore_by_queries
            ) if ignore_by_queries and len(ignore_by_queries) else None
            pair_on = pair_on if pair_on and len(pair_on) else None
            pair_with = ' | '.join(
                pair_with_queries) if pair_with_queries and len(
                    pair_with_queries) and pair_on else None
            pca_data = PCAModel()
            try:
                message, name, message_color = pca_data.perform_analysis(
                    model_by, ignore_by, scale_by, pair_on, pair_with,
                    project_by)
                pc_options = pca_data.get_pc_options()
                all_pc_options = [option['value'] for option in pc_options]
                ten_pc_options = [
                    option['value'] for option in pc_options[:10]
                ]
            except Exception as e:
                message = [
                    html.P([html.Strong('Error: '), f'{e}']),
                    html.Strong('Traceback:'),
                    html.P(
                        html.Pre(traceback.format_exc(),
                                 className='text-white'))
                ]
                message_color = 'danger'
                name = ''
                pc_options = []
                all_pc_options = []
                ten_pc_options = []

            return (dbc.Alert(message, color=message_color, dismissable=True),
                    pc_options, 0, pc_options, 1, pc_options, pc_options,
                    ten_pc_options, pc_options, all_pc_options, name)
Exemple #30
0
def display_table(dropdown_value_1, dropdown_value_2, dropdown_value_3, n_clicks):
    # dff = df[(df['Cat'].str.contains(dropdown_value_1)) & (df['ConcernedCountriesCode'].str.contains(dropdown_value_2))]
    cnx = sqlite3.connect('data.db')
    data_rate = pd.read_sql_query("SELECT * FROM data_rate WHERE reporter='" + dropdown_value_1 + "' AND substr(hs,1,6)='" + dropdown_value_3 + "'", cnx)
    data_type = pd.read_sql_query("SELECT * FROM data_type WHERE reporter='" + dropdown_value_1 + "' AND partner in (" + dropdown_value_2 + ", '000')", cnx)
    dff = pd.merge(data_rate, data_type, on=['reporter','type_code'])
    cnx.close()

    return html.Div([
            dbc.Alert('Importer: '+ dropdown_value_1 + ' Exporter: ' + dropdown_value_2 + ' HS: ' + dropdown_value_3),
            dash_table.DataTable(
                    id='tab',
                    columns=[
                        {"name": i, "id": i, "deletable": False, "selectable": False} for i in dff.columns
                    ],
                    data = dff.to_dict('records'),
                    editable=False,
                    # filter_action="native",
                    sort_action="native",
                    sort_mode="multi",
                    column_selectable=False,
                    row_selectable=False,
                    row_deletable=False,
                    selected_columns=[],
                    selected_rows=[],
                    page_action="native",
                    page_current= 0,
                    page_size= 20,
                    style_cell={
                    'height': 'auto',
                    'minWidth': '50px', 'maxWidth': '180px',
                    'whiteSpace': 'normal',
                    'textAlign': 'left',
                    },
                    style_cell_conditional=[
                        {'if': {'column_id': 'Symbol'},
                         'width': '100px'},
                        {'if': {'column_id': 'Member'},
                         'width': '70px'},
                        {'if': {'column_id': 'ReportDate'},
                         'width': '90px'},
                        {'if': {'column_id': 'Topic'},
                         'width': '200px'},
                        {'if': {'column_id': 'ParaID'},
                         'width': '40px'},
                    ]
                )
])