def generate_table(dataframe, max_rows=10): return html.Table([ html.Thead(html.Tr([html.Th(col) for col in dataframe.columns])), html.Tbody([ html.Tr( [html.Td(dataframe.iloc[i][col]) for col in dataframe.columns]) for i in range(min(len(dataframe), max_rows)) ]), ])
def make_dash_table(old_code, new_code): # Line 2 old_income = get_attribute(old_code, 'Average income of inhabitants') new_income = get_attribute(new_code, 'Average income of inhabitants') result_income = float(new_income) / float(old_income) - 1 if result_income > 0: analysis_income = f"↗ {result_income:.2%} potential increase" elif result_income > -0.15: analysis_income = "Similar income" else: analysis_income = f"↘ {result_income:.2%} easier life" # Line 3 attribute_name = 'Academic degree - Higher level university degree scaled' old_education = float(get_attribute(old_code, attribute_name)) new_education = float(get_attribute(new_code, attribute_name)) result_education = new_education - old_education analysis_education = "↗ Find more skilled fellows" if result_education > 0 else "↘ Less competitions" # for x in old_dict.keys(): # table.append(four_row_list(x, old_dict[x], new_dict[x], "")) # Line 4 # url = "https://avoindata.prh.fi/bis/v1?totalResults=true&maxResults=1&resultsFrom=10000" + \ # "&streetAddressPostCode={:s}&companyRegistrationFrom=1950-01-01" # print("This part takes time (~10s). Comment this part to accelerate. \n(From line 100, reference_function.py)") # old_company_num = eval(requests.get(url.format(old_code)).text.split(',"previous')[0] + '}')['totalResults'] # new_company_num = eval(requests.get(url.format(new_code)).text.split(',"previous')[0] + '}')['totalResults'] # result_company_num = int(new_company_num) - int(old_company_num) # analysis_company_num = "↗ Big town with more opportunities" if result_company_num > 0 else "↘ Peaceful life" return html.Table( [ html.Thead( html.Tr([ html.Th(), html.Th("Current Location"), html.Th("New Location"), html.Th("Significance") ])), html.Tbody([ html.Tr([ html.Td("Income"), html.Td(old_income), html.Td(new_income), html.Td(analysis_income) ]), html.Tr([ html.Td("Education index"), html.Td(f"{old_education:.2%}"), html.Td(f"{new_education:.2%}"), html.Td(analysis_education) ]), # html.Tr([html.Td("Number of companies"), html.Td(old_company_num), # html.Td(new_company_num), html.Td(analysis_company_num)]) ]) ], id="insight_table")
def generate_table(dataframe): return html.Table([ html.Thead(html.Tr([html.Th(col) for col in dataframe.columns])), html.Tbody([ html.Tr( [html.Td(dataframe.iloc[i][col]) for col in dataframe.columns]) for i in range(len(dataframe)) ]) ])
def get_about_html(): text = """ This is the implementation of our Data Science Project. The aim of this project is to provide suggestions on suitable relocation areas in Finland, based on housing prices and demographics. """ return html.Div([ html.H1("About"), html.H3(text, id="about_text"), html.H1("Team"), html.Table([ html.Thead( html.Tr([ html.Th("Letizia"), html.Th("Taige"), html.Th("Roope"), html.Th("Trang"), html.Th("Thong") ])), html.Tbody( html.Tr([ html.Td( html.A(html.Img( src= "https://avatars1.githubusercontent.com/u/45148109?s=200&v=4", alt="Letizia"), href="https://github.com/letiziaia")), html.Td( html.A(html.Img( src= "https://avatars2.githubusercontent.com/u/16875716?s=200&v=4", alt="Taige"), href="https://github.com/xiaoxiaobt")), html.Td( html.A(html.Img( src= "https://avatars2.githubusercontent.com/u/43811718?s=200&v=4", alt="Roope"), href="https://github.com/rooperuu")), html.Td( html.A(html.Img( src= "https://avatars3.githubusercontent.com/u/55182434?s=200&v=4", alt="Trang"), href="https://github.com/trangmng")), html.Td( html.A(html.Img( src= "https://avatars0.githubusercontent.com/u/32213097?s=200&v=4", alt="Thong"), href="https://github.com/trananhthong")) ])) ], id="team_table") ], id="about_info")
def generate_table(dataframe, max_rows=10): """ This is a helper function which generates a Dash HTML table from a pandas dataframe """ return html.Table([ html.Thead(html.Tr([html.Th(col) for col in dataframe.columns])), html.Tbody([ html.Tr( [html.Td(dataframe.iloc[i][col]) for col in dataframe.columns]) for i in range(min(len(dataframe), max_rows)) ]) ])
def get_table(rows: List[List[Any]], header: Optional[List[str]] = None) -> html.Table: """ Create a HTML table from a list of elements. :param rows: list of list of cell contents :return: html.Table """ contents = [] for row in rows: contents.append(html.Tr([html.Td(item) for item in row])) if not header: return html.Table([html.Tbody(contents)], className="table") else: header = html.Thead([html.Tr([html.Th(item) for item in header])]) return html.Table([header, html.Tbody(contents)], className="table")
def process_fmu(fmu_filename): basename, _ = os.path.splitext(fmu_filename) pickle_filename = basename + '.p' fmu_hash = os.path.basename(basename) try: model_description = read_model_description(fmu_filename, validate=False) except Exception as e: alert = dbc.Alert([ html.I(className='fas fa-times me-3'), f"Failed to read model description. {e}" ], id='alert', color='danger', className='mt-3') with open(pickle_filename, 'wb') as f: pickle.dump([alert], f) return platforms = supported_platforms(fmu_filename) with zipfile.ZipFile(fmu_filename, 'r') as zf: nl = filter(lambda n: not n.endswith('/'), zf.namelist()) fmi_types = [] if model_description.modelExchange: fmi_types.append('Model Exchange') if model_description.coSimulation: fmi_types.append('Co-Simulation') def na(attr): value = getattr(model_description, attr) if value: return value else: return html.Span('n/a', className='text-muted') rows = [ dbc.Row([ dbc.Col(html.Span("FMI Version"), width=4), dbc.Col(html.Span(model_description.fmiVersion), width=8), ], className='py-1'), dbc.Row([ dbc.Col("FMI Type", width=4), dbc.Col(', '.join(fmi_types), width=8), ], className='py-1'), dbc.Row([ dbc.Col("Model Name", width=4), dbc.Col(model_description.modelName, width=8), ], className='py-1'), dbc.Row([ dbc.Col("Platforms", width=4), dbc.Col(', '.join(platforms), width=8), ], className='py-1'), dbc.Row([ dbc.Col(html.Span("Continuous States"), width=4), dbc.Col(html.Span(model_description.numberOfContinuousStates), width=8), ], className='py-1'), dbc.Row([ dbc.Col(html.Span("Event Indicators"), width=4), dbc.Col(html.Span(model_description.numberOfEventIndicators), width=8), ], className='py-1'), dbc.Row([ dbc.Col(html.Span("Model Variables"), width=4), dbc.Col(html.Span(len(model_description.modelVariables)), width=8), ], className='py-1'), dbc.Row([ dbc.Col(html.Span("Generation Date"), width=4), dbc.Col(na('generationDateAndTime'), width=8) ], className='py-1'), dbc.Row([ dbc.Col(html.Span("Generation Tool"), width=4), dbc.Col(na('generationTool'), width=8) ], className='py-1'), dbc.Row([ dbc.Col(html.Span("Description"), width=4), dbc.Col(na('description'), width=8) ], className='py-1'), dbc.Row([ dbc.Col(html.Span("SHA256"), width=4), dbc.Col(html.Span(fmu_hash), width=8), ], className='py-1'), dbc.Row([ dbc.Col(html.Span("File Size"), width=4), dbc.Col(html.Span(f'{os.path.getsize(fmu_filename)} bytes'), width=8), ], className='py-1'), ] try: problems = validate_fmu(fmu_filename) except Exception as e: problems = [str(e)] if problems: alert = dbc.Alert([ html.P([ html.I(className='fas fa-exclamation-circle me-3'), f"Validation failed. {len(problems)} {'problem was' if len(problems) == 1 else 'problems were'} found:" ]), html.Ul([html.Li(problem) for problem in problems]) ], id='alert', color='danger', className='mt-3') else: alert = dbc.Alert([ html.I(className='fas fa-check me-3'), "Validation passed. No problems found." ], id='alert', color='success', className='mt-3') variables = [] table_header = [ html.Thead( html.Tr([ html.Th("Type"), html.Th("Name"), html.Th("Causality"), html.Th("Start", className='text-right'), html.Th("Unit"), html.Th("Description") ])) ] for variable in model_description.modelVariables: unit = variable.unit if unit is None and variable.declaredType is not None: unit = variable.declaredType.unit if variable.type == 'Boolean': color = '#c900c9' elif variable.type == 'Binary': color = '#ab0000' elif variable.type.startswith(('Int', 'Enum')): color = '#c78f00' elif variable.type.startswith(('Real', 'Float')): color = '#0000bf' else: # String color = '#00a608' variables.append( html.Tr([ html.Td( html.Small(variable.type, style={ 'color': color, 'border': '1px solid ' + color, 'border-radius': '1em', 'padding': '0 0.5em 0 0.5em', })), html.Td(variable.name), # html.Td(variable.variability), html.Td(variable.causality), html.Td(variable.start, className='text-right'), html.Td(unit), html.Td(variable.description, className='text-muted') ])) table = dbc.Table(table_header + [html.Tbody(variables)], borderless=True, size='sm') tabs = dbc.Tabs([ dbc.Tab(rows, label="Model Info", className='p-4'), dbc.Tab(table, label="Variables", className='p-4'), dbc.Tab(html.Pre('\n'.join(nl)), label="Files", className='p-4'), ], id='tabs') with open(pickle_filename, 'wb') as f: pickle.dump([alert, tabs], f)
# -*- coding: utf-8 -*- import datetime from dash import html from datasources import hdx_connect layout = html.Div(children=[ html.H3('Data Sources'), html.Table([ html.Thead([ html.Tr([ html.Th('Dataset'), html.Th('Source'), html.Th('Type'), html.Th('Files'), html.Th('Last Update') ]) ]), html.Tbody([ html.Tr([ html.Td('Joint Malnutrition Estimate (UNICEF, WB, WHO)'), html.Td( html.A('Humanitarian Data Exchange', href='https://data.humdata.org/', target='_blank')), html.Td('CSV File'), html.Td( html.A( 'https://data.humdata.org/dataset/' 'child-malnutrition-joint-country-dataset-unicef-who-world-bank-group-2017',
def _generate_table_from_df(cls, df, float_format=None, columns=None, header=True, index=False, index_label=None, date_format=None, **table_kwargs): """ Generate a Table component from a dataframe. Parameters ---------- df : pandas.DataFrame DataFrame to render as a table. float_format : str, optional Format to use for floating point numbers. columns : sequence, optional Columns to render. header : boolean or list(str) or dict(str: str), optional Write out the column names. If a list of strings is given it is assumed to be aliases for the columns names (and hence must be the same length as df.columns). A dict can be passed to rename some columns, the format is {'<current_name>': '<new_name>'}. The dictionary need not have an entry for every column. index : boolean, optional Render the row names (index). index_label : str, optional Column label for index column if desired. If None is passed, but both header and index are True, then the index name is used. date_format : str, optional Format string for datetime objects. **table_kwargs : Keyword arguments Additional arguments to pass to the table component. See dash_bootstrap_components.Table for details. """ import numpy as np import pandas as pd if columns is not None: df = df.loc[:, columns] if float_format is not None: for c in df.select_dtypes(["float"]).columns: df[c] = df[c].map(lambda x: "{1:{0}}".format(float_format, x)) if date_format is not None: for c in df.select_dtypes(["datetime"]).columns: df[c] = df[c].map(lambda x: x.strftime(date_format)) if index: df = df.reset_index() if index_label is not None: df = df.rename(columns={"index": index_label}) if header: if isinstance(header, (tuple, list, np.ndarray, pd.Index)): try: df.columns = header except ValueError: raise ValueError( "If specifying column names with a sequence, the number " "of names must exactly match the number of columns.") elif isinstance(header, dict): df = df.rename(columns=header) # Get the actual headers n_levels = df.columns.nlevels header_values = [ list(df.columns.get_level_values(level)) for level in range(n_levels) ] # The sizes of consecutive header groups at each level header_spans = [[ len(list(group)) for _, group in groupby(level_values) ] for level_values in header_values] # The positions of header changes for each level as an integer header_breaks = [[ sum(level_spans[:i]) for i in range(1, len(level_spans) + 1) ] for level_spans in header_spans] # Include breaks from higher levels header_breaks = [ sorted(set(reduce(add, header_breaks[:level])).union({0})) for level in range(1, n_levels + 1) ] # Go from header break positions back to cell spans header_spans = [ reversed([ level_breaks[i] - level_breaks[i - 1] for i in range(len(level_breaks) - 1, 0, -1) ]) for level_breaks in header_breaks ] table = [ html.Thead([ html.Tr(children=[ html.Th( header_values[level][pos], colSpan=span, ) for pos, span in zip(header_breaks[level], header_spans[level]) ]) for level in range(n_levels) ]) ] else: table = [] table.append( html.Tbody([ html.Tr([html.Td(df.iloc[i, j]) for j in range(len(df.columns))]) for i in range(len(df)) ])) return cls(table, **table_kwargs)
import dash_bootstrap_components as dbc from dash import html from .util import make_subheading table_header = html.Thead( html.Tr([ html.Th("#"), html.Th("First name"), html.Th("Last name"), ])) table_body = html.Tbody([ html.Tr([ html.Th("1", scope="row"), html.Td("Tom"), html.Td("Cruise"), ]), html.Tr([ html.Th("2", scope="row"), html.Td("Jodie"), html.Td("Foster"), ]), html.Tr([ html.Th("3", scope="row"), html.Td("Chadwick"), html.Td("Boseman"), ]), ]) table = html.Div(
import dash_bootstrap_components as dbc from dash import html table_header = [ html.Thead(html.Tr([html.Th("First Name"), html.Th("Last Name")])) ] row1 = html.Tr([html.Td("Arthur"), html.Td("Dent")]) row2 = html.Tr([html.Td("Ford"), html.Td("Prefect")]) row3 = html.Tr([html.Td("Zaphod"), html.Td("Beeblebrox")]) row4 = html.Tr([html.Td("Trillian"), html.Td("Astra")]) table_body = [html.Tbody([row1, row2, row3, row4])] table = dbc.Table(table_header + table_body, bordered=True)