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
def get_side_analysis(zip="02150"): return [ html.H2(f"Area: {zip_name_dict[zip]}, {zip}", id="code_title"), html.H2(get_transportation_icons(zip), id="transportation_icons"), html.H2(f"🏢 Municipality tax rate: {zip_tax_dict[zip]}%"), html.H2( f"🌲 Forest coverage: {float(get_attribute(zip, 'Forest')):.2f}%"), html.H2(f"🌊 Water coverage: {float(get_attribute(zip, 'Water')):.2f}%") # dcc.Graph(figure=get_pie(zip), config={'displayModeBar': False}) # html.H4(str(get_amount_of_service()), id="main_info") ]
def layout(self, spa, message='404 Not Found'): return html.Div([ html.Div([ html.Div([ html.Div([ html.H1('Oops!'), html.H2(message), html.Div( 'Sorry, an error has occurred, Requested page not found!', className='error-details'), html.Div([ dcc.Link([ html.Span(className='fa fa-home'), ' Take Me Home' ], href='/', className='btn btn-secondary btn-lg'), dcc.Link([ html.Span(className='fa fa-envelope'), ' Contact Support' ], href='/support', className='btn btn-secondary btn-lg'), ], className='error-actions') ], className='error-template') ], className='col-md-12') ], className='row') ], className='container')
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
def card_content(card_name, card_new_value, card_total_value): card = [ dbc.CardHeader( [ html.H2(card_name, style={'text-align': 'center'}, className="card-sub-header"), ] ), dbc.CardBody( [ html.H4(children=['New : ', f"{int(card_new_value):,}"], #style={'text-align': 'right'}, className="card-sub-body" ), html.H4(children=['Total : ', f"{int(card_total_value):,}"], #style={'text-align': 'right'}, className="card-sub-body2" ), ] ), # dbc.CardFooter( # [ # html.P(f"{int(card_total_value):,}", className="card-sub-footer"), # ] # ), ] return card
def solar(): return html.Div([ html.Div([ html.Div([], className="col-md-2"), html.Div([ html.H2('US Solar Capacity'), html.Br(), dbc.Table.from_dataframe( df, striped=True, bordered=True, hover=True), html.Div(id='output') ], className="col-md-8"), html.Div([], className="col-md-2") ], className='row'), dbc.Row([ dbc.Col([ dcc.Link("Global Warming", href=spa.url_for('warming'), className="btn btn-primary float-end") ], md=12) ]) ], className="container-fluid")
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")]
def view(self): """Returns a dictionary in dash ready format. :return: List of HTML dash ready objects :rtype: list """ games = self.games M = self.M b = self.b contents = [html.H2("M"),pyrplib.style.get_standard_data_table(M,"M")] contents.extend([html.H2("b"),pyrplib.style.get_standard_data_table(b,"b")]) contents.extend([html.H2("r"),pyrplib.style.get_standard_data_table(self.r,"r")]) contents.extend([html.H2("Ranking"),pyrplib.style.get_standard_data_table(self.ranking,"ranking")]) contents.extend([html.H2("Perm"),pyrplib.style.get_standard_data_table(self.perm,"perm")]) return contents
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%"}, )
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])
def make_description(self): description = html.Div([ html.H2("Description"), html.Div("", id="main-content-description") ]) return description
def get_polar_html(old_code="02150", new_code="00100"): # H1 location_string = f"Hey, how about this one? {zip_name_dict[new_code]}, {new_code}" # H2 sell_price_string = get_attribute(postalcode=new_code, column="Sell price") sell_price_string = f"{float(sell_price_string):.2f}" if sell_price_string != "0.0" else "--" rent_ara_price_string = get_attribute(postalcode=new_code, column="Rent price with ARA") rent_ara_price_string = f"{float(rent_ara_price_string):.2f}" if rent_ara_price_string != "0.0" else "--" rent_noara_price_string = get_attribute(postalcode=new_code, column="Rent price without ARA") rent_noara_price_string = f"{float(rent_noara_price_string):.2f}" if rent_noara_price_string != "0.0" else "--" trend_near_future_string = f"{float(get_attribute(new_code, column='Trend near future')):+.2%}" # H3 average_age_string = get_attribute(postalcode=new_code, column="Average age of inhabitants") categories = [ 'Education', 'Services', 'Public Transportation', 'Average Income', 'Population Density' ] fig = go.Figure() fig.add_trace( go.Scatterpolar(r=radar_value(old_code), theta=categories, fill='toself', name='Current location')) fig.add_trace( go.Scatterpolar(r=radar_value(new_code), theta=categories, fill='toself', name='New location')) fig.update_layout(polar=dict(radialaxis=dict(range=[0, 1])), margin={ "r": 20, "t": 50, "l": 20, "b": 20 }) return html.Div( children=[ html.H1(location_string), html.H2(f"🛈 Last 12 months sell price: {sell_price_string} €/m²", id="sell_12"), html. H2(f"🛈 Last 12 months rent price: {rent_ara_price_string} €/m² (including ARA), {rent_noara_price_string} €/m² (private only)", id="rent_12"), html.H3(f"Trend of price: {trend_near_future_string}"), html.H3(f"Average age: {average_age_string} years"), # html.H3(percentage_degree + "% of the people has a higher university degree"), make_dash_table(old_code, new_code), dcc.Graph(figure=fig, id="polar_graph", config={'displayModeBar': False}) ], id="analysis_info")
def make_graph(self): graph = html.Div([ html.Div([ html.H2("Current Service Level"), html.Div(children=[], id="main-content-graph-current") ]) ]) return graph
def set_layout(self): self.application.layout = html.Div([ self.make_header(), self.make_description(), html.H2("Overview"), self.make_menu(), self.make_rate_table() ])
def ticker(): nonlocal div div = html.H2('Hello World', id='hello') test.callback(div.output.children, div.input.n_clicks) def _callback(clicks): return None
def render(self, dashboard): return html.Div(children=[ html.H2(self.title), html.H3(self.meta["timestamp"]), dcc.Markdown(self.description), html.Pre(self.meta["env"]["uname"]), self._render(dashboard) ], className="dashboard-object")
def test_module_component_prefix(): app = Dash(__name__) div = html.H2('Hello World', id='hello') app.callback(div.output.children, div.input.n_clicks) def _callback(clicks): return None assert div.id == 'tests-spa-spa_prefix_test-hello'
def get_project_emissions_bar_chart(): return html.Div( dbc.Col([ html.Br(), html.Br(), html.H2("Emissions Detail", style={"textAlign": "center"}), dcc.Graph(id="project_emissions_bar_chart"), ]), style={"paddingLeft": "3%"}, )
def get_project_time_series(): return html.Div( dbc.Col([ html.Br(), html.Br(), html.H2("Emissions Timeline", style={"textAlign": "center"}), dcc.Graph(id="project_time_series"), ]), style={"paddingLeft": "3%"}, )
def user_view(ctx): table = user_table(ctx, ctx.login_manager) modal_form = user_form(ctx, table, ctx.login_manager) return html.Div([ html.H2('Users'), table, modal_form, ])
def populateBowlingStats(table_data, player, season, match_type, discipline, inter_tav_type): if discipline != "Bowling": return None if not player: return None df_bowling = pd.DataFrame(table_data)#getBattingDataframe() player_name = df_bowling.iloc[player[0]]["name"]#df_batting[df_batting['name'] == player] df_bowling = getBowlingDataframe() df_player = getBowlingPlayer(df_bowling, player_name, inter_tav_type, season, match_type) if df_player.empty: return None overs = df_player['overs'].sum() if not overs: return None runs = df_player['runs'].sum() wickets = df_player['wickets'].sum() if overs: economy = float(runs)/float(overs) else: economy = 0.0 if wickets: average = float(runs)/float(wickets) strike_rate = 6.0*float(overs)/float(wickets) else: average = 0.0 strike_rate = 0.0 return html.Div([ html.Div( [ html.H2(player_name + ' Bowling', className='tavs-stat-title'), html.Div([ dcc.Markdown("Overs: " + "{:.1f}".format(overs)), dcc.Markdown("Wickets: " + "{:,}".format(int(wickets))), dcc.Markdown("Runs: " + "{:,}".format(int(runs))), dcc.Markdown("Average: " + "{:.2f}".format(average)), dcc.Markdown("Economy Rate: " + "{:.2f}".format(economy)), dcc.Markdown("Strike Rate: " + "{:.2f}".format(strike_rate)), ], className='tavs-unit__extra-content'), ], className='tavs-unit', ), ], className='tavs-grid__unit tavs-grid__unit--half')
def cell_clicked_card(cell, data): if cell is None: return dash.no_update row, col = cell["row"], cell["column_id"] selected = data[row][col] if selected is not None: dataset_id = data[row]['Dataset ID'] link = cards_df.set_index('Dataset ID').loc[dataset_id, "Link"] options = cards_df.set_index('Dataset ID').loc[dataset_id, "Options"] if type(options) == str: options = json.loads(options) options_str = json.dumps(options, indent=2) else: options_str = "None" obj = card_class.from_json(link) processed_datasets_df = config.processed_datasets_df.set_index( 'Dataset ID') datasets_df = config.datasets_df.set_index('Dataset ID') unprocessed_source_id = processed_datasets_df.loc[ obj.source_dataset_id, "Source Dataset ID"] description = datasets_df.loc[unprocessed_source_id, "Description"] dataset_name = datasets_df.loc[unprocessed_source_id, "Dataset Name"] index = processed_datasets_df.loc[obj.source_dataset_id, "Index"] unprocessed = pyrplib.dataset.load_unprocessed( unprocessed_source_id, datasets_df) contents = [ html.Br(), html.H2("Source Dataset Name"), html.P(dataset_name), html.H2("Description"), html.P(description), html.H2("Options"), html.Pre(options_str) ] + unprocessed.view_item(index) + obj.view() return html.Div(contents) else: return dash.no_update
def make_header(self): header = html.Div([ html.H2("Authoritative DNS Server Response Time"), dcc.Interval(id="main-content-graph-interval", interval=60 * 1000, n_intervals=0) ], id="main-content-header", style=dict(color=self.text_color)) return header
def view(self): """Returns a dictionary in dash ready format. :return: List of HTML dash ready objects :rtype: list """ contents = [] visuals = self.get_visuals()['dash'] for key in visuals: contents.append(html.H2(key)) contents.append(visuals[key]) return contents
def make_description(self): text = """This tool displays the successful response rate for each DNS server for the past 24 hours. A successful response means that the RTT of the query is less than 1.5 seconds for TCP and less than 0.5 seconds for UDP. For more information, please refer the following tool : """ description = html.Div([ html.H2("Description"), html.Div([text, html.A("https://rtt.dns.mtcq.jp/", href="https://rtt.dns.mtcq.jp/")], id="main-content-description", style=dict(whiteSpace="pre-wrap", display="inline-block")) ]) return description
def app_page_layout(page_layout, app_title="Dash Bio App", app_name="", light_logo=True, standalone=False, bg_color="#506784", font_color="#F3F6FA"): return html.Div( id='main_page', children=[ dcc.Location(id='url', refresh=False), html.Div( id='app-page-header', children=[ html.A(id='dashbio-logo', children=[ html.Img(src='data:image/png;base64,{}'.format( base64.b64encode( open( os.path.join( ASSETSPATH, 'plotly-dash-bio-logo.png'), 'rb').read()).decode())) ], href="/Portal" if standalone else "/dash-bio"), html.H2(app_title), html.A(id='gh-link', children=['View on GitHub'], href="https://github.com/cytham/variantmap", style={ 'color': 'white' if light_logo else 'black', 'border': 'solid 1px white' if light_logo else 'solid 1px black' }), html.Img(src='data:image/png;base64,{}'.format( base64.b64encode( open( os.path.join(ASSETSPATH, 'GitHub-Mark-{}64px.png'). format('Light-' if light_logo else ''), 'rb').read()).decode())) ], style={ 'background': bg_color, 'color': font_color, }), html.Div(id='app-page-content', children=page_layout) ], )
def route2(ctx): btn = html.Button('Go to Page #1', id='btn', className="btn btn-primary btn-block") redirect = dhc.Location(id='redirect') @test.callback(redirect.output.pathname, [btn.input.n_clicks]) def _cb(clicks): red = SpaComponents.NOUPDATE log.info('btn clicks=%s', clicks) if clicks: red = test.url_for('page1') return red return html.Div([html.H2('Page #2'), btn, redirect])
def cell_clicked_processed(cell, data): if cell is None: return dash.no_update row, col = cell["row"], cell["column_id"] selected = data[row][col] if selected is not None: dataset_id = data[row]['Dataset ID'] processed_datasets_df = config.processed_datasets_df.set_index( 'Dataset ID') datasets_df = config.datasets_df.set_index('Dataset ID') link = processed_datasets_df.loc[dataset_id, "Link"] options = processed_datasets_df.loc[dataset_id, "Options"] if type(options) == str: options = json.loads(options) options_str = json.dumps(options, indent=2) else: options_str = "None" short_type = data[row]['Short Type'] if short_type == "D": obj = pyrplib.dataset.ProcessedD.from_json(link).load() description = datasets_df.loc[obj.source_dataset_id, "Description"] dataset_name = datasets_df.loc[obj.source_dataset_id, "Dataset Name"] command = obj.command unprocessed_source_id = obj.source_dataset_id unprocessed = pyrplib.dataset.load_unprocessed( unprocessed_source_id, datasets_df) index = processed_datasets_df.loc[dataset_id, "Index"] description = description.replace("\\n", "\n") contents = [ html.Br(), html.H2(dataset_name), html.H3("Description"), html.Pre(description), html.H3("Command"), html.Pre(command), html.H3("Options"), html.Pre(options_str) ] + [ html.H3("Source Item data") ] + unprocessed.view_item(index) + [html.H3("Data")] + obj.view() return html.Div(contents) else: return dash.no_update
def site_layout(app): # Process browser location change @app.callback([Output('title', 'title'), Output('page-ref', 'children')], [Input('loc', 'pathname')]) def _location_callback(pathname): title = 'My Site: {}'.format(pathname) return title, title return html.Div([ dhc.PageTitle(title='My Site', id='title'), dhc.Location(id='loc'), html.H2(id='page-ref'), dcc.Link('page1', id='page1', href='/page1', refresh=False), dcc.Link('page2', id='page2', href='/page2', refresh=False) ])
def div_topo(): return html.Div( children=[ html.H2('Informações da Cidade de Sousa-PB', style={ 'font-weight': 'bold', }), html.H4('Dados de 1983 até 2018') ], style={ 'textAlign': 'center', 'font-weight': 'bold', 'border': '2px solid lightgreen', 'box-shadow': '0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19)', 'background-color': '#8FBC8F', })