Пример #1
0
def update_output(_, movie1, movie2):
    if movie1 and movie2:
        db = MovieRecsDB(RUN_ID)
        ret = [html.H2("Recommendations")]
        return ret + [html.P(rec) for rec in db.get_recs(movie1, movie2)]
    else:
        return [html.P("Choose movies to see recommendations")]
Пример #2
0
def get_country_table(df, year):
    return html.Div([
        html.H3('Needs -  Data from {0}'.format(year)),
        html.Table([
            html.Tr([
                html.Th([col], style={'text-align': 'center'}) for col in [
                    '',
                    html.I(className="fas fa-percent fa-lg"),
                    html.I(className="fas fa-child fa-lg"),
                    html.I(className="fas fa-box fa-lg")
                ]
            ])
        ] + [
            html.Tr([
                html.Th(col['title']),
                html.Td(df[col['type']]),
                html.
                Td(functions.format_number_col(df[col['type'] + '_children'])),
                html.Td(get_needs_kg(df, col['type']))
            ],
                    style={'color': col['color']}) for col in [
                        {
                            'title': 'Severe Wasting',
                            'type': 'severe_wasting',
                            'color': SEVERE_WASTING_COLOR
                        },
                        {
                            'title': 'Moderate Wasting',
                            'type': 'moderate_wasting',
                            'color': MODERATE_WASTING_COLOR
                        },
                        {
                            'title': 'Overall Wasting',
                            'type': 'wasting',
                            'color': WASTING_COLOR
                        },
                        {
                            'title': 'Stunting',
                            'type': 'stunting',
                            'color': STUNTING_COLOR
                        },
                        {
                            'title': 'Overweight',
                            'type': 'overweight',
                            'color': OVERWEIGHT_COLOR
                        },
                        {
                            'title': 'Underweight',
                            'type': 'underweight',
                            'color': UNDERWEIGHT_COLOR
                        },
                    ]
        ]),
        html.Div(children=[
            html.P('Source : ' + df['source'].astype(str)),
            html.P('By : ' + df['report_author'].astype(str))
        ],
                 style={'font-size': 'x-small'})
    ],
                    style={'font-size': 'small'})
Пример #3
0
def test_cbpu002_multi_output_no_update(dash_duo):
    app = Dash(__name__)

    app.layout = html.Div([
        html.Button("B", "btn"),
        html.P("initial1", "n1"),
        html.P("initial2", "n2"),
        html.P("initial3", "n3"),
    ])

    @app.callback(
        [
            Output("n1", "children"),
            Output("n2", "children"),
            Output("n3", "children")
        ],
        [Input("btn", "n_clicks")],
    )
    def show_clicks(n):
        # partial or complete cancellation of updates via no_update
        return [
            no_update if n and n > 4 else n,
            no_update if n and n > 2 else n,
            # make a new instance, to mock up caching and restoring no_update
            copy(no_update),
        ]

    dash_duo.start_server(app)

    dash_duo.multiple_click("#btn", 10, 0.2)

    dash_duo.wait_for_text_to_equal("#n1", "4")
    dash_duo.wait_for_text_to_equal("#n2", "2")
    dash_duo.wait_for_text_to_equal("#n3", "initial3")
Пример #4
0
def getCards(df):
    summaryProvider = []
    for idx, r in df.iterrows():
        if ' - ' not in r[0]:
            summaryProvider.append(
                html.Div([
                    dbc.Card([
                        dbc.CardHeader(r[0]),
                        dbc.CardBody([
                            html.H4(r[1], className="card-title"),
                            html.P("of tests taken, passed",
                                   className="card-text"),
                        ]),
                    ], )
                ],
                         style={"display": "inline-block"}))

    summaryProviderMulti = []
    for idx, r in df.iterrows():
        if ' - ' in r[0]:
            summaryProviderMulti.append(
                html.Div([
                    dbc.Card([
                        dbc.CardHeader(r[0]),
                        dbc.CardBody([
                            html.H4(r[1], className="card-title"),
                            html.P("of tests taken, passed",
                                   className="card-text"),
                        ]),
                    ], )
                ],
                         style={"display": "inline-block"}))
    return summaryProvider, summaryProviderMulti
Пример #5
0
def current_readings_viewer(tab, n_intervals):
    if tab != 'current-readings':
        return

    n = n_intervals or 0  # n_intervals is initially None
    n += 1

    children = []
    margin_right = cfg.value('current_readings/margin_right', '16px')
    for serial, data in now().json.items():
        b = f'{serial} [{data["report_number"]}] - {data["alias"]} @ {data["datetime"][11:]}'
        children.append(html.B(b))
        if data['error']:
            children.append(html.P(data['error']))
        elif 'temperature2' in data:
            for sensor in ['1', '2']:
                p = []
                for key in 'temperature' + sensor, 'humidity' + sensor, 'dewpoint' + sensor:
                    p.append(html.I(key + ':', style={'color': 'grey'}))
                    p.append(
                        html.Span(f'{data[key]:.2f}',
                                  style={'margin-right': margin_right}))
                children.append(html.P(p))
        else:
            p = []
            for key in ['temperature', 'humidity', 'dewpoint']:
                p.append(html.I(key + ':', style={'color': 'grey'}))
                p.append(
                    html.Span(f'{data[key]:.2f}',
                              style={'margin-right': margin_right}))
            children.append(html.P(p))
    return html.Div(
        children=children,
        style={'fontSize': cfg.value('current_readings/font_size', '24px')})
Пример #6
0
def exclude_start():
    return html.Div([
        html.P('Exclude the first points',style={'display':'inline-block','margin-right':20}),
        dcc.Input(id='exclude_npt', value='0', type='text', size='2'),
        html.P(' points',style={'display':'inline-block','margin-right':5}),
    ],
        style={'width': '10%', 'display': 'inline-block'}
    )
Пример #7
0
def indicator(color, text, id_value):
    """returns top indicator div
    """
    return html.Div(
        [
            html.P(text, className="twelve columns indicator_text"),
            html.P(id=id_value, className="indicator_value"),
        ],
        className="four columns indicator",
    )
Пример #8
0
def update_connection_db(n, v):
    db.connect_client()
    db.MONGO_DB = v
    db.connect_db()
    # print("value", v)
    sidebar_log = html.P(f"{db.MONGO_DB} ({db.MONGO_URL})")
    infobox = []
    if db.MONGO_CL is not None and db.MONGO_DB is not None:
        infobox.append(html.H2("Connection successful"))
        list_cl = list(db.MONGO_CL.list_collection_names())
        if "Measurements" in list_cl:
            infobox.append(html.P(f"Measurements present"))
            if db.DB_SAT:
                infobox.append(html.P(f"Num satelites {len(db.DB_SAT)}"))
                infobox.append(html.P(f"Num sites     {len(db.DB_SITE)}"))
        else:
            infobox.append(html.P(f"Measurements NOT present"))
            infobox.append(html.P(f"Num satelites N/A"))
            infobox.append(html.P(f"Num sites     N/A"))

        if "States" in list_cl:
            infobox.append(html.P(f"State present"))
        else:
            infobox.append(html.P(f"States NOT present"))
    return db.check_db(), sidebar_log, infobox
Пример #9
0
 def format_pulsar_paramters(self):
     pp = self._record["pulsar_parameters"]
     return html.Div(children=[
         html.H3("Pulsar Parameters"),
         html.Br(),
         html.P(["Period: {} ms".format(pp["period"])]),
         html.P(
             dcc.Markdown("Dispersion measure: {} pc cm<sup>-3</sup>".
                          format(pp["dm"]),
                          dangerously_allow_html=True)),
         html.P("Binary: {}".format(pp["binary"])),
         html.Br()
     ])
Пример #10
0
def layout():
    if db.MONGO_CL == None:
        return html.Div([html.P("First you will need to select a DB in the Db Info menu")])
    else:
        return html.Div(
            [
                # dropdown_type,
                dropdown_site(db.DB_SITE),
                dropdown_sat(db.DB_SAT),
                dropdown_key_x(),
                    html.Div(children=[util.namedSlider(
                        name='Symbol size',
                        id='symbol_size',
                        min=1,
                        max=8,
                        step=1,
                        value=3,
                        marks={i: str(i) for i in range(1, 9)},
                    )],
                         style={'width': '20%', 'display': 'inline-block'}
                         ),

                # dropdown_key_y(),
                dcc.Input(
                    id="input_min",
                    type="number",
                    placeholder="Min Value",
                ),
                dcc.Input(
                    id="input_max",
                    type="number",
                    placeholder="Max value",
                ),
                exclude_start(),
                html.P("Color Scale"),
                dcc.Dropdown(
                    id='colorscale',
                    options=[{"value": x, "label": x}
                             for x in colorscales],
                    value='viridis'
                ),
                update_button,

                dcc.Graph(
                    id='plot_polar',
                    figure=get_empty_graph("select information first")
                )
            ]
        )
Пример #11
0
def validate_input(v: Validator, input_dict: dict):
    passed = v.validate(input_dict)
    if passed:
        return passed, None
    else:
        error_message_str = v.errors
    return passed, html.P('INPUT ERROR: {}'.format(error_message_str))
Пример #12
0
def show_distribution_info(distribution: str) -> list:
    """Get a brief summary of the selected distribution.

    Parameters
    ----------
    distribution : str
        The name of the current distribution

    Returns
    -------
    list
        A brief summary of the distribution, and a link to it's page on
        Wikipedia.
    """
    dist_data = distribution_data[distribution]
    summary = [
        html.P(paragraph) for paragraph in dist_data["summary"].split(">")
    ]
    wiki_link = [
        html.A(
            "Learn more...",
            className="wiki-link",
            href=dist_data["wiki_link"],
        )
    ]
    return [summary + wiki_link]
Пример #13
0
def test_rdmo004_multi_output_circular_dependencies(dash_duo):
    app = Dash(__name__)
    app.layout = html.Div(
        [dcc.Input(id="a"),
         dcc.Input(id="b"),
         html.P(id="c")])

    @app.callback(Output("a", "value"), [Input("b", "value")])
    def set_a(b):
        return ((b or "") + "X")[:100]

    @app.callback(
        [Output("b", "value"), Output("c", "children")], [Input("a", "value")])
    def set_bc(a):
        return [a, a]

    dash_duo.start_server(
        app,
        debug=True,
        use_debugger=True,
        use_reloader=False,
        dev_tools_hot_reload=False,
    )

    # the UI still renders the output triggered by callback.
    # The new system does NOT loop infinitely like it used to, each callback
    # is invoked no more than once.
    dash_duo.wait_for_text_to_equal("#c", "X")

    err_text = dash_duo.find_element("span.dash-fe-error__title").text
    assert err_text == "Circular Dependencies"
Пример #14
0
def test_rdpr001_persisted_dps(dash_dcc):
    app = Dash(__name__, suppress_callback_exceptions=True)
    app.layout = html.Div(
        [
            html.Button("fire callback", id="btn", n_clicks=1),
            html.Div(children=[html.Div(id="container"), html.P("dps", id="dps-p")]),
        ]
    )

    # changing value of date with each callback to verify
    # persistenceTransforms is stripping the time-part from the date-time
    @app.callback(Output("container", "children"), [Input("btn", "n_clicks")])
    def update_output(value):
        return dcc.DatePickerSingle(
            id="dps",
            min_date_allowed=datetime(2020, 1, 1),
            max_date_allowed=datetime(2020, 1, 7),
            date=datetime(2020, 1, 3, 1, 1, 1, value),
            persistence=True,
            persistence_type="session",
        )

    @app.callback(Output("dps-p", "children"), [Input("dps", "date")])
    def display_dps(value):
        return value

    dash_dcc.start_server(app)

    dash_dcc.select_date_single("dps", day="2")
    dash_dcc.wait_for_text_to_equal("#dps-p", "2020-01-02")
    dash_dcc.find_element("#btn").click()
    dash_dcc.wait_for_text_to_equal("#dps-p", "2020-01-02")

    assert dash_dcc.get_logs() == []
Пример #15
0
def init_dashboard(server):
    dash_app = dash.Dash(
        server=server,
        routes_pathname_prefix="/",
        external_stylesheets=[dbc.themes.SUPERHERO],
    )
    
    dash_app.title = 'Covid-19 Dashboard'
    
    #lo Create Layout
    dash_app.layout = dbc.Container(
        [
            html.H1("USA Covid-19 Dashboard"),
            html.P(children=['Last updated: ',last_update], style={'text-align': 'right'}),
            html.Hr(),
            dbc.Tabs(
                [
                    dbc.Tab(label="Overview", tab_id="tab-1"),
                    dbc.Tab(label="Testing", tab_id="tab-3"),
                    dbc.Tab(label="Hospitalizations", tab_id="tab-4"),
                    dbc.Tab(label="Deaths", tab_id="tab-5"),
                    dbc.Tab(label="Vaccination", tab_id="tab-2"),
                    dbc.Tab(label="About", tab_id="tab-6"),
                    ],
                id = 'tabs',
                active_tab = 'tab-1',
                ),
            html.Div(id="tab-content", className="p-4"),
            html.Br(),
            html.Div(id="drop_figure"),
            ]
        )
    init_callbacks(dash_app)
    
    return dash_app.server
Пример #16
0
def namedSlider(name, **kwargs):
    return html.Div(
        # style={'padding': '10px 10px 15px 4px'},
        children=[
            html.P(f'{name}:'),
            html.Div(dcc.Slider(**kwargs), style={'margin-left': '3px'})
        ])
Пример #17
0
def parse_data(content, name, date):
    if content is None:
        return None, None

    try:
        df = parse_contents(content, name, date)
        validate_df(df)
    except ValueError as e:
        return None, html.P(str(e), className="error")

    nrows = len(df)
    fitness = df.iloc[:, -1]
    msg = "Found {} experiments, with fitness from {} to {}.".format(
        nrows, fitness.min(), fitness.max())

    return df.to_json(date_format='iso', orient='split'), html.P(msg)  # pylint: disable=no-member
Пример #18
0
 def run(self, test_case):
     response = HttpClient(test_case["API"]).method(test_case["Method"])(test_case["Body"])
     self.html_response = html.Div(
         [
             html.H1("Test Case : {}".format(test_case["API"]), style={"text-align": "center", "color": "red"}),
             dbc.Row(
                 [
                     dbc.Col(
                         html.H2("Method : {}".format(test_case["Method"]),
                                 style={"text-align": "left", "color": "yellow"}),
                         style={"width": 6}
                     ),
                     dbc.Col(
                         html.H2("Status : {}".format(response.status_code),
                                 style={"text-align": "right", "color": "green"}),
                         style={"width": 6}
                     ),
                 ],
             ),
             html.P("Response : {}".format(response.body))
         ]
     )
     test_case["ResponseBody"] = response.body
     test_case["StatusCode"] = response.status_code
     test_case["Status"] = response.status
     return self.html_response
Пример #19
0
def render_page_content(pathname):
    if pathname == "/":
        return html.P("This is the content of the home page!")
    elif pathname == "/page-1":
        return html.P("This is the content of page 1. Yay!")
    elif pathname == "/page-2":
        return html.P("Oh cool, this is page 2!")
    # If the user tries to reach a different page, return a 404 message
    return html.Div(
        [
            html.H1("404: Not found", className="text-danger"),
            html.Hr(),
            html.P(f"The pathname {pathname} was not recognised..."),
        ],
        className="p-3 bg-light rounded-3",
    )
Пример #20
0
def test_dvui002_disable_ui_config(dash_duo):
    app = Dash(__name__)
    app.layout = html.Div(
        [
            html.P(id="tcid", children="Hello Disable UI"),
            dcc.Graph(id="broken", animate=3),  # error ignored by disable
        ]
    )

    dash_duo.start_server(
        app,
        debug=True,
        use_reloader=False,
        use_debugger=True,
        dev_tools_hot_reload=False,
        dev_tools_ui=False,
    )

    dash_duo.wait_for_text_to_equal("#tcid", "Hello Disable UI")
    logs = str(wait.until(dash_duo.get_logs, timeout=1))
    assert (
        "Invalid argument `animate` passed into Graph" in logs
    ), "the error should present in the console without DEV tools UI"

    assert not dash_duo.find_elements(
        ".dash-debug-menu"
    ), "the debug menu icon should NOT show up"
    dash_duo.percy_snapshot("devtools - disable dev tools UI - no debug menu")
Пример #21
0
def render_page_content(pathname):
    if pathname == "/":
        return html.P("This is the home page!")
    elif pathname == "/calendar":
        return html.P("This is your calendar... not much in the diary...")
    elif pathname == "/messages":
        return html.P("Here are all your messages")
    # If the user tries to reach a different page, return a 404 message
    return html.Div(
        [
            html.H1("404: Not found", className="text-danger"),
            html.Hr(),
            html.P(f"The pathname {pathname} was not recognised..."),
        ],
        className="p-3 bg-light rounded-3",
    )
Пример #22
0
def update_reports_list(iso_code):
    reports = reliefweb_api.get_reports_for_country(iso_code)
    if not reports:
        return ''
    images = [
        html.A(children=[
            html.Img(src=report['thumbnail'],
                     style={
                         'height': '180px',
                         'padding': '3',
                         'marginRight': 40,
                         'marginLeft': 40,
                         'boxShadow': '10px 10px 5px 0px #656565',
                         'background': '#FFF'
                     }),
            html.P(report['title'][0:50],
                   style={
                       'font-size': 'small',
                       'text-align': 'center'
                   })
        ],
               href=report['file'],
               target='_blank') for report in reports
    ]
    return html.Div([
        html.H3('Humanitarian Reports'),
        html.Div(children=images,
                 style={
                     'display': 'flex',
                     'align': 'middle',
                     'flexDirection': 'row',
                     'justifyContent': 'center'
                 })
    ])
Пример #23
0
def test_dvui007_other_before_request_func(dash_thread_server, dash_br):
    # won't use `bash_br`, because it expects an dash app, but it gets an static html page.
    # we take only the selenium driver from `bash_br`, this driver has already been set-up.
    driver = dash_br.driver

    app = Dash(__name__)
    app.layout = html.Div(
        [html.P(id="just_an_id", children="You should never see this")]
    )

    # create alternative response, for the endpoint '/'
    # servering an alternative response, will disable further `before_request` functions e.g. those by dash
    @app.server.before_request
    def create_an_alternative_response():
        if flask.request.endpoint == "/":
            return flask.Response(
                '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n'
                "<title>Alternative repsonse</title>\n"
                '<h1 id="alternative_id">Alternative response header</h1>\n',
                200,
                mimetype="text/html",
            )

    dash_thread_server.start(
        app,
        debug=True,
        use_reloader=False,
        use_debugger=True,
        dev_tools_hot_reload=False,
    )

    driver.get(dash_thread_server.url)
    driver.find_element_by_id("alternative_id")
Пример #24
0
def test_dvui001_disable_props_check_config(dash_duo):
    app = Dash(__name__)
    app.layout = html.Div(
        [
            html.P(id="tcid", children="Hello Props Check"),
            dcc.Graph(id="broken", animate=3),  # error ignored by disable
        ]
    )

    dash_duo.start_server(
        app,
        debug=True,
        use_reloader=False,
        use_debugger=True,
        dev_tools_hot_reload=False,
        dev_tools_props_check=False,
    )

    dash_duo.wait_for_text_to_equal("#tcid", "Hello Props Check")
    assert dash_duo.find_elements("#broken svg.main-svg"), "graph should be rendered"

    # open the debug menu so we see the "hot reload off" indicator
    dash_duo.find_element(".dash-debug-menu").click()
    sleep(1)  # wait for debug menu opening animation

    dash_duo.percy_snapshot("devtools - disable props check - Graph should render")
Пример #25
0
def create_and_plot_sample(distribution: str, size: int, *parameters) -> tuple:
    """Create a sample of the specified distribution using the provided
    parameters, then plot a histogram & violin-plot, and compute descriptive
    statistics.

    Parameters
    ----------
    distribution : str
        The name of the currently selected distribution
    size : int
        The set sample size
    *parameters : int, float
        1 or 2 parameter values, depending on the distribution

    Returns
    -------
    tuple
        A histogram, a violin_plot, an ecdf-plot, a table of summary
        statistics, the currently specified parameters and a csv file with the
        sample data for download.
    """
    sample = process_random_sample(distribution, size, parameters)

    histogram = plotting.plot_histogram(sample["data"], distribution)
    violin_plot = plotting.plot_violin(sample["data"], distribution)
    ecdf_plot = plotting.plot_ecdf(sample["data"], distribution)

    summary_statistics = sample["summary_statistics"]
    summary_statistics_table = [html.Th("Summary Statistics")] + [
        html.Tr([html.Td(f"{name}:"), html.Td(value)])
        for name, value in summary_statistics.items()
    ]

    parameters = sample["parameters"]
    param_dict = {
        distribution_data[distribution].get(f"param{idx}"): value
        for idx, value in enumerate(parameters, start=1)
    }
    param_dict["Sample Size"] = size
    parameter_info = [
        html.H3("Parameters: "),
        html.P([
            ", ".join([f"{key}: {value}" for key, value in param_dict.items()])
        ]),
    ]

    sample_csv_download = {
        "content": sample["data"].to_csv(index=False),
        "filename": f"{distribution}-sample.csv",
        "type": "text/csv",
    }
    return (
        histogram,
        violin_plot,
        ecdf_plot,
        summary_statistics_table,
        parameter_info,
        sample_csv_download,
    )
Пример #26
0
def NamedDropdown(name, **kwargs):
    return html.Div(
        style={"margin": "10px 0px"},
        children=[
            html.P(children=f"{name}", style={"margin-left": "3px"}),
            dcc.Dropdown(**kwargs),
        ],
    )
Пример #27
0
def make_scatter_menu(id_index): #, colnames, current_options):
    print('** make_scatter_menu')

    return dbc.Offcanvas(
        [html.P("Dropdowns for setting data input, X, Y, color, size:"),

         dbc.Row([dbc.Col('Title:'),
                  dbc.Col(dcc.Input(id={'type': 'scatter_inputtext', 'index': id_index, 'property': 'title'},
                                    placeholder='Enter title here',
                                    #value=''),
                                    ),
                          width=7)],
                 justify='start'),

         dbc.Row([dbc.Col('Data:'),
                  dbc.Col(dcc.Dropdown(id={'type': 'scatter_dropdown', 'index': id_index, 'property': 'dataset'},
                                       #options=[dict(label='Lifehistory', value='Lifehistory'),
                                       #         dict(label='Load file...', value='_load_file')],
                                       #value='Lifehistory'
                                       ),
                          width=7)],
                 justify='start'),

         dbc.Row([dbc.Col('X:'),
                  dbc.Col(dcc.Dropdown(id={'type': 'scatter_dropdown', 'index': id_index, 'property': 'x'}, ),
                                       #options=[{'label': c, 'value': c} for c in df_records[0].keys()],
                                       #value='logAdultWeight'),
                          width=7)],
                 justify='start'),
         dbc.Row([dbc.Col('Y:'),
                  dbc.Col(dcc.Dropdown(id={'type': 'scatter_dropdown', 'index': id_index, 'property': 'y'},),
                                       #options=[{'label': c, 'value': c} for c in df_records[0].keys()],
                                       #value='MaxLifespan'),
                          width=7)],
                 justify='start'),

         # dbc.Row([dbc.Col('Color:'),
         #          dbc.Col(dcc.Dropdown(id={'type':'scatter_dropdown', 'index':id_index, 'property':'color'},
         #                               options=[{'label': c, 'value': c} for c in df.columns]),
         #                  width=7)],
         #         justify='start'),
         #
         # dbc.Row([dbc.Col('Size:'),
         #          dbc.Col(dcc.Dropdown(id={'type':'scatter_dropdown', 'index':id_index, 'property':'size'},
         #                               options=[{'label': c, 'value': c} for c in df.columns]),
         #                  width=7)],
         #         justify='start'),
         dbc.Row(dbc.Col(' ')),
         dbc.Row(dbc.Col(
             dbc.Button("Apply", size="sm", n_clicks=0,
                        id={'type': 'scatter_configure_ok', 'index': id_index}),
             class_name="g-2"))

         ],
        title="Menu: Scatter item",
        is_open=False,
        id={'type': 'scatter_menu', 'index': id_index}
    )
Пример #28
0
    def generate_with_id(id, data=None):
        if data is None:
            data = [{"x": [0, 1, 2, 3, 4], "y": [0, 0.5, 1, 0.5, 0]}]

        return html.Div([
            html.P(id),
            dcc.Graph(id=id, figure=dict(data=data)),
            html.Div(id="output_{}".format(id)),
        ])
Пример #29
0
    def submit_config(self, clicks, *form_args):
        msg = html.Div(children=[])
        args = self.running_args

        if not clicks:
            return msg

        for dest, value in zip(
            [state.component_id for state in self.config_states], form_args):
            # find corresponding action
            for action in Runner.parser._actions:
                # ignore immutable args
                if action.dest in self.immutable_args:
                    continue

                if action.dest == dest:
                    # boolean values are returned as lists, check if id is set
                    if isinstance(value, list):
                        args.__dict__[dest] = (dest in value)
                        continue

                    try:
                        args.__dict__[dest] = literal_eval(value)
                    except (ValueError, SyntaxError):
                        args.__dict__[dest] = value
                    except Exception as e:
                        msg.children.append(
                            html.
                            P(f"Error: value for '{dest}' invalid ({repr(e)})."
                              ))
                        return msg

        # write config to actual location
        try:
            Runner.parser.write_config(args, open(self.running_args.config,
                                                  "w"))
        except Exception as e:
            msg.children.append(html.P(str(e)))
            return msg

        self._update_values()
        msg.children.append(
            html.P(f"Config successfully written to '{args.config}'."))
        return msg
Пример #30
0
    def welcomePage(self):
        title = html.H1(
            "Recount",
            style={
                "marginBottom": "-1rem",
                "fontSize": "8rem",
                "fontWeight": "bold",
            },
        )
        subtext_title = html.Strong("Gonna check dat budget!",
                                    style={"fontSize": "3rem"})
        upper_welcome = html.Div([title, subtext_title],
                                 style={"textAlign": "center"})

        welcome = html.H2([html.Br(), "Welcome"],
                          style={
                              "fontSize": "6rem",
                              "fontWeight": "bold"
                          })
        paraf1 = html.P([
            "Bonjour et bienvenu sur ",
            html.Strong("Recount"),
            ", une application qui permet de visualiser ses dépenses.",
        ])
        paraf2 = html.P([
            html.Br(),
            "La ",
            "version 0.1",
            " viens de sortir, et ",
            html.Strong("vous avez été choisi pour la tester!"),
        ])
        paraf3 = html.P([
            "Testez, jouez avec les données, et faites moi des retours par mail quand vous le souhaitez à ",
            html.A("*****@*****.**"),
        ])
        paraf4 = html.P([
            "Si vous voulez un petit ",
            html.Strong("tuto"),
            " pour vous lancer, j'ai préparé ",
            html.A("celui-ci."),
        ])
        paraf5 = html.P([
            html.Br(),
            "Niveau sécurité, tout les fichiers sont chiffrés et les connexions sécurisées. Mais je ne vais pas mentir : tout est cadenassé, mais les clefs ne sont pas cachées. Il faut partir du principe qu'",
            html.Strong("une fuite de données peut arriver TRÈS facilement."),
            " Si cela vous dérange d'entrer vos dépenses personnelles, utilisez les données de l'exemple ou inventez vos propres données.",
        ])
        paraf6 = html.P([
            html.Br(),
            "Je reste joignable sur mon téléphone, mail ou via facebook."
        ])
        paraf7 = html.P([html.Br(), "Amusez vous bien!"])

        list_parafs = [paraf1, paraf2, paraf3, paraf4, paraf5, paraf6, paraf7]
        for i in range(len(list_parafs)):
            list_parafs[i].style = {"fontSize": "xx-large"}
        parafs = html.Div(list_parafs)

        return html.Div([upper_welcome, welcome, parafs])