Esempio n. 1
0
def update_case_description(case_no):
    '''
    Return the content inside the 'New Case' card
    '''
    selected_case = cases_df[cases_df['case_no'] == case_no].iloc[0].to_dict()
    output = [
        html.Hr(),
        html.P(f'#{selected_case["case_no"]} ({selected_case["status"]})'),
        html.H5(f'Age {selected_case["age"]} {selected_case["gender"]}'),
        html.P([
            html.Span('Confirmed date: '),
            html.Strong(selected_case["confirmation_date"])
        ]),
        html.P([
            html.Span('Place of residence: '),
            html.Strong(selected_case["citizenship_en"])
        ]),
        html.P([
            html.Span('Hospital admitted: '),
            html.Strong(selected_case["hospital_en"])
        ]),
        html.Hr(),
        html.P(selected_case["detail_en"])
    ]
    return output
Esempio n. 2
0
def update_run_report(run):
    data = []
    figure = {}
    if run != "":

        samples = import_data.get_sample_component_status(run)
        header = html.Tr(
            [html.Th(html.Strong("Sample"))] +
            list(map(lambda x: html.Th(html.Strong(x)), COMPONENTS)))
        rows = [header]

        for name, s_components in samples.items():
            row = []
            row.append(html.Td(name))
            for component in COMPONENTS:
                if component in s_components.keys():
                    s_c = s_components[component]
                    row.append(
                        html.Td(s_c[1], className="status-{}".format(s_c[0])))
                else:
                    row.append(html.Td("None", className="status-0"))
            rows.append(html.Tr(row))
        table = html.Table(rows)
        return [table]

    return []
Esempio n. 3
0
def update_totals_div(data): 
    data = json.loads(data)
    
    return [
        row(html.Strong(["Total volume per year: %d" % data["yearly_total_samples"]])),
        row(html.Strong(["Total GB per year: %d" % data["yearly_total_gb"]]))
    ]
Esempio n. 4
0
def print_dataset_metadata(sel_dataset, sel_standardized):
    if sel_standardized == 'Standardized':
        dataset_name = dict_si_to_std.get(sel_dataset, sel_dataset)
        dff = metadata[metadata['column_ID_std'] == dataset_name]
    else:
        dataset_name = dict_std_to_si.get(sel_dataset, sel_dataset)
        dff = metadata[metadata['column_ID_SI'] == dataset_name]
    text = [
        html.Strong('Summary'),
        html.Span(': ' + dff['meaning'].values[0]),
        html.Br(),
        html.Br(),
        html.Strong('Original Publication:'),
        html.Br(),
        html.A(dff['paper_title'].values[0],
               href=dff['paper_URL'].values[0],
               target='_blank'),
        html.Br(),
        html.Br(),
        html.Strong('Mtb strain'),
        html.Span(': ' + dff['Mtb strain'].values[0]),
        html.Br(),
        html.Br(),
        html.Strong('No of control replicates'),
        html.Span(': ' + str(dff['num replicates control'].values[0])),
        html.Br(),
        html.Br(),
        html.Strong('No of experimental replicates'),
        html.Span(': ' + str(dff['num replicates experimental'].values[0]))
    ]
    return text
Esempio n. 5
0
        def post_collection(n_clicks, filter_by, ignore_by, join_on,
                            left_collection_id, name, analysis_ids):
            CollectionEditorDashboard.check_clicks(n_clicks)
            filter_by_query = ' | '.join(
                filter_by) if filter_by is not None else None
            ignore_by_query = ' & '.join(
                ignore_by) if ignore_by is not None else None
            try:
                editor_data = CollectionEditorModel(True)
                new_collection = editor_data.post_collection(
                    filter_by_query, ignore_by_query, join_on,
                    left_collection_id, name, analysis_ids)
                return [
                    dbc.Alert([
                        'Posted results as ',
                        html.A(f'Collection {new_collection.id}.',
                               href=url_for('collections.render_collection',
                                            collection_id=new_collection.id))
                    ],
                              dismissable=True,
                              color='success')
                ]

            except Exception as e:
                return [
                    dbc.Alert([
                        html.P([html.Strong('Error: '), f'{e}']),
                        html.Strong('Traceback:'),
                        html.P(
                            html.Pre(traceback.format_exc(),
                                     className='text-white'))
                    ],
                              color='danger',
                              dismissable=True)
                ]
Esempio n. 6
0
 def get_net_summary():
     return html.Div(
         [
             html.H2("Across All Projects", style={"textAlign": "center"}),
             html.H4(
                 [
                     "Net Power Consumption : ",
                     html.Strong(
                         id="net_power_consumption",
                         style={"fontWeight": "normal", "color": "green"},
                     ),
                 ],
                 style={"textAlign": "left", "float": "left"},
             ),
             html.H4(
                 [
                     "Net Carbon Equivalent : ",
                     html.Strong(
                         id="net_carbon_equivalent",
                         style={"fontWeight": "normal", "color": "green"},
                     ),
                 ],
                 style={"textAlign": "right", "float": "right"},
             ),
         ],
         style={"paddingLeft": "1.4%", "paddingRight": "1.4%"},
     )
Esempio n. 7
0
def get_side_panel_intro():
    side_panel_intro_style = {
        "padding": "40px 20px",
        "fontSize": "1em",
        "lineHeight": "1.13em"
    }
    stldsa_link_style = {
        "color": "red",
        "fontWeight": "bold",
        "font": "Roboto"
    }
    side_panel_intro = html.Div(
        children=[
            html.Strong("On March 2,"),
            " St Louis City will have primary elections for several offices, including mayor and more than half of the Board of Aldermen.",
            html.Br(),
            html.Br(),
            html.A("St Louis DSA ",
                   href="https://stldsa.org",
                   style=stldsa_link_style),
            " is proud to provide this tool to the voters of St Louis. You can use the options below to view campaign contributions for our mayoral candidates. We hope that in democratizing access to this information, voters will be best able to decide who they would like to represent them.",
            html.Br(),
            html.Br(),
            html.Strong(
                "Hover over or click the bar graph below to get started:"),
            # html.Br(), html.Br(),
            # html.Em("Full disclosure: St Louis DSA has endorsed Megan Green for 15th Ward Alder.")
        ],
        style=side_panel_intro_style)
    return side_panel_intro
Esempio n. 8
0
 def prepare_results_file(n_clicks, results_values, file_format):
     opls_data = OPLSModel()
     if not n_clicks:
         raise PreventUpdate('Callback triggered with no action.')
     if not opls_data.results_file_ready:
         return '#', 'secondary', dbc.Alert('Results do not exist.',
                                            color='warning',
                                            dismissable=True)
     try:
         path = opls_data.download_results('metrics' in results_values,
                                           'loadings' in results_values,
                                           'scores' in results_values,
                                           'weights' in results_values,
                                           file_format)
         message = dbc.Alert(f'Prepared results file as {path}',
                             color='success',
                             dismissable=True)
         class_name = 'btn btn-success'
     except Exception as e:
         path = '#'
         message = dbc.Alert([
             html.P([html.Strong('Error: '), f'{e}']),
             html.Strong('Traceback:'),
             html.P(
                 html.Pre(traceback.format_exc(),
                          className='text-white'))
         ],
                             color='danger',
                             dismissable=True)
         class_name = 'btn btn-secondary disabled'
     return url_for('api.download_temporary_file',
                    path=path), class_name, message
Esempio n. 9
0
def generate_table_row(df_headline, df_urls, df_s_score, df_r_score):
    # print(type(df_s_score))

    if(float(df_s_score) > 0):
        cols = '#45df7e'
    elif(float(df_s_score) == 0):
        cols = 'white'
    else:
        cols = '#da5657'

    tr_script = html.Tr(
        [
            html.Td(
                html.A(
                    df_headline,
                    # "IMF flags trade war threat and warns of global economic slowdown",
                    href=df_urls,
                    # href="https://www.ft.com/content/8753e45c-1c91-11e9-b126-46fc3ad87c65",
                    target="_blank",
                ), style={'padding': '0px', 'border-bottom': '1px solid #777777'}
            ),
            html.Td(
                html.Strong(df_r_score, style={'padding': '0px', 'color': 'white'}), style={'width': '50px', 'padding': '0px', 'text-align': 'center'}),
            html.Td(
                html.Strong(df_s_score, style={'padding': '0px', 'color': cols, 'min-width': '15px'}), style={'width': '15px', 'padding': '0px', 'text-align': 'center'})
        ]
    )
    return tr_script
Esempio n. 10
0
 def sidebar(self):
     data = self.data[self.filters]
     return [
         html.Div([
             html.Strong(className='f3 lh-copy pa0 ma0 header-font',
                         children="{:,.0f}".format(data["charities"])),
             html.Span(className='f5 lh-copy pa0 ma0',
                       children=' local charities')
         ]),
         html.Div([
             html.Strong(className='f3 lh-copy pa0 ma0 header-font', children='£{}'.format(
                 scale_value(list(
                     data["financial"].items())[-1][1]["spending"])
             )),
             html.Br(),
             html.Span(className='f5 lh-copy pa0 ma0', children=' total spending by local charities in {}'.format(
                 list(data["financial"].items())[-1][0]
             ))
         ]),
         # html.Div([
         #     html.Strong(className='f4 lh-copy pa0 ma0 header-font',
         #                 children='£{:,.0f}'.format(data["income"])),
         #     html.Span(className='f5 lh-copy pa0 ma0',
         #               children=' total latest spending')
         # ]),
         self._fig_topstats(),
         self._fig_spendingchart(),
     ]
Esempio n. 11
0
        def post_collection(n_clicks, name, analysis_ids):
            CollectionProcessingDashboard.check_clicks(n_clicks)
            try:
                editor_data = CollectionProcessingModel(True)
                new_collection = editor_data.post_collection(
                    name, analysis_ids)
                return [
                    dbc.Alert([
                        'Posted results as ',
                        html.A(f'Collection {new_collection.id}.',
                               href=url_for('collections.render_collection',
                                            collection_id=new_collection.id))
                    ],
                              dismissable=True,
                              color='success')
                ]

            except Exception as e:
                return [
                    dbc.Alert([
                        html.P([html.Strong('Error: '), f'{e}']),
                        html.Strong('Traceback:'),
                        html.P(
                            html.Pre(traceback.format_exc(),
                                     className='text-white'))
                    ],
                              color='danger',
                              dismissable=True)
                ]
Esempio n. 12
0
def update_time_clock(input_data):
    exchange = 'NYSE'
    MktTimeDict = GetTimeToMktOpen( datetime.now(pytz.utc), exchange)
    d,h,m,s = MktTimeDict['d-h-m-s']

    if MktTimeDict['status'] == 'open':
        nextAction = f'until {exchange} close'
        cols = '#45df7e'
    else:
        nextAction = f'until {exchange} open'
        cols = '#da5657'

    msg = f'{h}:{"{:02d}".format(m)}:{"{:02d}".format(s)}'
    if d > 0:
        msg = f'{d} days {msg}'

    #print(f'{msg} {nextAction}')
    return [
        html.Div([
            html.Div([
                html.Strong('Status: ', style={'color':'white', 'font-size':'18px'})
            ], className="col s3"),
            html.Div([
                html.Strong(MktTimeDict["status"], style={'color':cols, 'font-size':'18px'})
            ], className="col s9"),
        ], className="row borders row-margin-reduce"),
        html.Div([
            html.Strong(f'{msg} {nextAction}', style={'color':'white', 'font-size':'18px', 'padding':'10px'})
        ], className="row borders row-margin-reduce")
    ]
Esempio n. 13
0
def candidate_funding_details(clicked_name, mec_df):
    funding_detail_box_style = {
        "margin": "12px",
        "border": "2px solid black",
        "padding": "10px",
        "height": "80%",
    }
    donation_stats = mec_query.get_contribution_stats_for_candidate(
        clicked_name)
    return html.Div(
        children=[
            html.P([
                html.Strong("Total monetary donations:"),
                str(donation_stats["total_collected"]),
            ]),
            html.P([
                html.Strong("Number of donations:"),
                str(donation_stats["num_donations"]),
            ]),
            html.P([
                html.Strong("Average donation:"),
                str(donation_stats["average_donation"]),
            ]),
        ],
        style=funding_detail_box_style,
    )
Esempio n. 14
0
 def get_cloud_recommendation(
     self,
     on_cloud: str,
     cloud_provider_name: str,
     cloud_emissions_barchart_data: pd.DataFrame,
 ):
     if on_cloud == "N":
         return html.H4()
     cloud_emissions_project_region = cloud_emissions_barchart_data.iloc[
         0, :]
     cloud_emissions_minimum_region = cloud_emissions_barchart_data.iloc[
         1, :]
     if (cloud_emissions_minimum_region.emissions >
             cloud_emissions_project_region.emissions):
         return html.H4([
             f"Already running on {cloud_provider_name}'s least emissions region ",
             html.Strong(
                 f"{cloud_emissions_project_region.region}",
                 style={
                     "fontWeight": "normal",
                     "color": "green"
                 },
             ),
         ])
     else:
         return (
             html.H4([
                 "Had this been run in ",
                 html.Strong(
                     f"{cloud_emissions_minimum_region.region}",
                     style={
                         "fontWeight": "normal",
                         "color": "green"
                     },
                 ),
                 " region, ",
             ]),
             html.H4([
                 "then the emitted carbon would have been ",
                 html.Strong(
                     f"{'{:.1f}'.format(cloud_emissions_minimum_region.emissions)} kg",
                     style={
                         "fontWeight": "normal",
                         "color": "green"
                     },
                 ),
             ]),
             html.H4([
                 "Reducing the current  emissions by ",
                 html.Strong(
                     f"{'{:.1f}'.format(cloud_emissions_project_region.emissions - cloud_emissions_minimum_region.emissions)} kg",
                     style={
                         "fontWeight": "normal",
                         "color": "green"
                     },
                 ),
             ]),
         )
Esempio n. 15
0
def profile_values(trigger):
    if current_user.is_authenticated and trigger:
        return [
            ['Username: '******'Email: ', html.Strong(current_user.email)],
            current_user.username,
            '',
            ''
        ]
Esempio n. 16
0
def infoblock(drug, rmse=0):

    return html.Div([
        html.H3([
            html.Strong(drug.name),
            html.Span(f" ({drug.target})")
        ]),
        html.Hr(),
        html.P(["Monotherapy response ", html.Strong("POOR FIT: RMSE > 0.3")], style={'color': 'red'})
            if rmse > 0.3 else html.P("Monotherapy response")
    ])
Esempio n. 17
0
def training_tab_details(skills_gap, OnetCodeSource, OnetCodeTarget):
    details = []
    details.append(
        html.P(children=[
            html.Strong("Typical Education Title of {}".format(
                skills_gap["CurrentOccupationTitle"])),
            html.Br(), skills_gap["CurrentEducationTitle"],
            html.Br(),
            html.Strong("Typical Education Title of {}".format(
                skills_gap["TargetOccupationTitle"])),
            html.Br(), skills_gap["TargetEducationTitle"]
        ]))
    return details
Esempio n. 18
0
    def select_wikis_and_metrics_control(wikis_dropdown_options, metrics_dropdown_options):
        return html.Div(
                    id='wikis-and-metrics-control',
                    className='selector',
                    children=[
                        html.Div(id='first-row',
                            className='row',
                            children=[
                                html.Span(
                                'You are comparing:',
                                className='two columns comparing-label'
                                ),

                                html.Div(id='wikis-selection-div',
                                    children=[
                                        html.Strong('Wikis:',
                                            className='one column dropdown-label',
                                        ),

                                        dcc.Dropdown(
                                            id='wikis-selection-dropdown',
                                            className='four columns wikis-selection-dropdown-cls',
                                            options=wikis_dropdown_options,
                                            multi=True,
                                            searchable=False,
                                            value=[ option['value'] for option in wikis_dropdown_options ]
                                        ),
                                    ]
                                ),

                                html.Div(id='metrics-selection-div',
                                    children=[
                                        html.Strong('Metrics:',
                                            className='one column dropdown-label',
                                        ),

                                        dcc.Dropdown(
                                            id='metrics-selection-dropdown',
                                            className='four columns',
                                            options=metrics_dropdown_options,
                                            multi=True,
                                            searchable=False,
                                            value=[ option['value'] for option in metrics_dropdown_options ]
                                        ),
                                    ]
                                )
                            ],
                        )
                    ]
                );
Esempio n. 19
0
def update_layout(tap_node):
    # print(tap_node)
    # print(tap_edge)
    if not tap_node:
        return meeples, "Clique em um nó."

    return (tap_node['img-src'], [
        html.Strong('Título: '),
        tap_node['title'],
        html.Br(),
        html.Strong('Ano: '),
        tap_node['year'],
        html.Br(),
        html.Strong('Idade recomendada: '),
        tap_node['age'],
        html.Br(),
        html.Strong('Jogadores: '),
        tap_node['players'],
        html.Br(),
        html.Strong('Tempo de jogo: '),
        tap_node['time'],
        'min',
        html.Br(),
        html.Strong('Nota (ludopedia): '),
        tap_node['notarank'],
        html.Br(),
        html.Strong('Domínio: '),
        tap_node['dominio'],
        html.Br(),
        html.Strong('Conexões: '),
        str(tap_node['node_size']),
        html.Br(),
    ])
Esempio n. 20
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'))
Esempio n. 21
0
 def prepare_plot(n_clicks, figure, file_format, width, height, units, dpi):
     VisualizationDashboard.check_clicks(n_clicks)
     viz_data = VisualizationModel(False)
     try:
         path = viz_data.save_figure(figure, file_format, width, height, units, dpi)
         message = dbc.Alert(f'Prepared plots file as {path}.', color='success', dismissable=True)
         class_name = 'btn btn-success'
     except Exception as e:
         path = '#'
         message = dbc.Alert([html.P([html.Strong('Error: '), f'{e}']),
                              html.Strong('Traceback:'),
                              html.P(html.Pre(traceback.format_exc(), className='text-white'))],
                             color='danger', dismissable=True)
         class_name = 'btn btn-secondary disabled'
     return url_for('api.download_temporary_file', path=path), class_name, message
Esempio n. 22
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)
Esempio n. 23
0
 def get_regional_emissions_comparison():
     return html.Div(
         dbc.Col(
             [
                 html.Br(),
                 html.Br(),
                 html.H2(
                     [
                         "Emissions Across Regions in ",
                         html.Strong(
                             id="country_name",
                             style={
                                 "fontWeight": "normal",
                                 "color": "green"
                             },
                         ),
                     ],
                     style={
                         "textAlign": "center",
                         "marginLeft": "12%"
                     },
                 ),
                 dcc.Graph(id="regional_emissions_comparison_choropleth"),
             ],
             id="regional_emissions_comparison_component",
         ),
         style={"marginLeft": "-12%"},
     )
Esempio n. 24
0
    def group_wikis_in_accordion(wikis, wikis_category, wiki_category_descp):

        wikis_options = [{
            'label': wiki['name'],
            'value': wiki['url']
        } for wiki in wikis]

        return gdc.Accordion(
            id=generate_wikis_accordion_id(wikis_category) + '-accordion',
            className='aside-category',
            label=wikis_category,
            itemClassName='metric-category-label',
            childrenClassName='metric-category-list',
            accordionFixedWidth='300',
            defaultCollapsed=False if wikis else True,
            children=[
                html.Strong(wiki_category_descp, style={'fontSize': '14px'}),
                dcc.Checklist(id=generate_wikis_accordion_id(wikis_category),
                              className='aside-checklist-category',
                              options=wikis_options,
                              values=[],
                              labelClassName='aside-checklist-option',
                              labelStyle={'display': 'block'})
            ],
            style={'display': 'flex'})
def generate_random_image(image_culture):
    # printing image culture name
    to_return = html.P(children=[
        html.Span("Correct image culture is: "),
        html.Strong(image_culture)
    ], style={'fontSize': '18px'})
    return to_return
Esempio n. 26
0
    def group_wikis_in_accordion(wikis, wikis_category, wiki_category_descp,
                                 selected_wikis_value):

        wikis_options = [{
            'label': wiki['name'],
            'value': wiki['url']
        } for wiki in wikis]

        # add pre-selected wikis (likely, from url query string),
        # if any, to the accordion which is going to be created.
        if selected_wikis_value:
            wikis_values_checklist = list(
                set(selected_wikis_value) & set(map(lambda w: w['url'], wikis))
            )  # take values (url) of pre-selected wikis for this wiki category
        else:
            wikis_values_checklist = []

        return gdc.Accordion(
            id=generate_wikis_accordion_id(wikis_category) + '-accordion',
            className='aside-category',
            label=wikis_category,
            itemClassName='metric-category-label',
            childrenClassName='metric-category-list',
            accordionFixedWidth='300',
            defaultCollapsed=False if wikis else True,
            children=[
                html.Strong(wiki_category_descp, style={'fontSize': '14px'}),
                dcc.Checklist(id=generate_wikis_accordion_id(wikis_category),
                              className='aside-checklist-category',
                              options=wikis_options,
                              values=wikis_values_checklist,
                              labelClassName='aside-checklist-option',
                              labelStyle={'display': 'block'})
            ],
            style={'display': 'flex'})
Esempio n. 27
0
    def zip_click(feature, n_clicks, contest):
        contest_name = mec_query.get_standard_contest_name(contest)
        class_name = "displayNone"
        header_text = "Error"
        card_contents = bootstrap_stuff.get_floatbox_card_contents("zip")

        if feature:
            header_text = f"ZIP Code {feature['properties']['ZCTA5CE10']}"
            body_contents = [
                html.Strong("Total monetary donations: "),
                html.Span(
                    locale.currency(
                        feature["properties"]["total_monetary_donations_" +
                                              contest_name],
                        grouping=True,
                    )),
            ]
            class_name = "floatbox"
            card_contents = bootstrap_stuff.get_floatbox_card_contents(
                "zip", header_text, body_contents)

        if n_clicks:
            class_name = "displayNone"

        return [card_contents, class_name]
Esempio n. 28
0
    def precinct_click(feature, n_clicks, contest):
        contest_name = mec_query.get_standard_contest_name(contest)
        class_name = "displayNone"
        header_text = "Error"
        card_contents = bootstrap_stuff.get_floatbox_card_contents("precinct")

        if feature:
            # print(feature["properties"])
            if ("WARD10" in feature["properties"]
                    and feature["properties"]["WARD10"]):  # STL City precinct
                header_text = f"STL City: Ward {feature['properties']['WARD10']}, Precinct {feature['properties']['PREC10']}"
            elif feature["properties"]["PRECINCTID"]:  # STL County precinct
                header_text = (
                    f"STL County: Precinct {feature['properties']['PRECINCTID']}"
                )
            body_contents = [
                html.Strong("Total monetary donations: "),
                html.Span(
                    locale.currency(
                        feature["properties"]["total_monetary_donations_" +
                                              contest_name],
                        grouping=True,
                    )),
            ]
            class_name = "floatbox"
            card_contents = bootstrap_stuff.get_floatbox_card_contents(
                "precinct", header_text, body_contents)

        if n_clicks:
            class_name = "displayNone"

        return [card_contents, class_name]
Esempio n. 29
0
    def neighborhood_click(feature, n_clicks, contest):
        contest_name = mec_query.get_standard_contest_name(contest)
        class_name = "displayNone"
        header_text = "Error"
        card_contents = bootstrap_stuff.get_floatbox_card_contents(
            "neighborhood")

        if feature:
            print(feature)
            if ("NHD_NAME" in feature["properties"]
                    and feature["properties"]["NHD_NAME"]):
                header_text = feature["properties"]["NHD_NAME"]
            else:
                header_text = feature["properties"]["MUNICIPALI"].title()
            body_contents = [
                html.Strong("Total monetary donations: "),
                html.Span(
                    locale.currency(
                        feature["properties"]["total_monetary_donations_" +
                                              contest_name],
                        grouping=True,
                    )),
            ]
            class_name = "floatbox"
            card_contents = bootstrap_stuff.get_floatbox_card_contents(
                "neighborhood", header_text, body_contents)

        if n_clicks:
            class_name = "displayNone"

        return [card_contents, class_name]
Esempio n. 30
0
def to_statistic(val, label):
    return html.Div([
        html.Strong(val, className='f3 b', style={}),
        html.Div(label, className=''),
    ],
                    className='pa3 tc',
                    style={})