Esempio n. 1
0
def plot_data(selected_year, selected_district):

    # filter data based on user selection
    dff = df[df.Year == selected_year]
    dff = dff[dff.District == selected_district]

    # build scatter plot
    fig, ax = plt.subplots()
    ax.scatter(x=dff.Damage, y=dff.Graffiti, s=dff.Drugs)
    ax.set_xlabel("Damage")
    ax.set_ylabel("Graffiti")
    ax.grid(color='lightgray', alpha=0.7)
    html_scatter = mpld3.fig_to_html(fig)

    # build bar plot
    fig, ax = plt.subplots()
    ax.bar(x=dff.Location, height=dff.Robbery)
    ax.set_xlabel(selected_district)
    ax.set_ylabel("Robbery")
    ax.grid(color='lightgray', alpha=0.7)
    html_bar = mpld3.fig_to_html(fig)

    # build DataTable
    mytable = dash_table.DataTable(
        id='table',
        columns=[{
            "name": i,
            "id": i
        } for i in dff.columns],
        data=dff.to_dict('records'),
    )

    return html_scatter, html_bar, mytable
Esempio n. 2
0
def test_cbsc003_callback_with_unloaded_async_component(dash_duo):
    app = Dash()
    app.layout = html.Div(children=[
        dcc.Tabs(children=[
            dcc.Tab(children=[
                html.Button(id="btn", children="Update Input"),
                html.Div(id="output", children=["Hello"]),
            ]),
            dcc.Tab(children=dash_table.DataTable(id="other-table")),
        ])
    ])

    @app.callback(Output("output", "children"), [Input("btn", "n_clicks")])
    def update_out(n_clicks):
        if n_clicks is None:
            raise PreventUpdate

        return "Bye"

    dash_duo.start_server(app)

    dash_duo.wait_for_text_to_equal("#output", "Hello")
    dash_duo.find_element("#btn").click()
    dash_duo.wait_for_text_to_equal("#output", "Bye")
    assert dash_duo.get_logs() == []
Esempio n. 3
0
def get_standard_data_table(df, id):
    """Returns a dash data table with standard configuration.
    """
    if type(df) == pd.Series:
        df = df.to_frame().reset_index()
    df = df.fillna("")

    def get_datatypes(dtype):
        if 'float' in dtype or 'double' in dtype or 'int' in dtype:
            return 'numeric'
        elif 'datetime' in dtype:
            return 'datetime'
        return 'text'

    dataset_table = dash_table.DataTable(
        id=id,
        columns=[{
            "name": i,
            "id": i,
            'presentation': 'markdown',
            "type": get_datatypes(str(df[i].dtype))
        } for i in df.columns],
        data=df.to_dict("records"),
        is_focused=True,
        style_table={
            'height': 500,
            'overflowY': 'scroll',
        },
        style_header={
            'backgroundColor': 'white',
            'fontWeight': 'bold',
            "border": "1px solid white",
        },
        style_cell={
            'whiteSpace': 'normal',
            'height': 'auto',
            'textAlign': 'left'
        },
        sort_action="native",
        sort_mode="multi",
        filter_action='native',
        filter_options={'case': 'insensitive'},
        style_data={
            "backgroundColor": '#E3F2FD',
            "border-bottom": "1px solid #90CAF9",
            "border-top": "1px solid #90CAF9",
            "border-left": "1px solid #E3F2FD",
            "border-right": "1px solid #E3F2FD"
        },
        style_data_conditional=[{
            "if": {
                "state": "selected"
            },
            "backgroundColor": '#E3F2FD',
            "border-bottom": "1px solid #90CAF9",
            "border-top": "1px solid #90CAF9",
            "border-left": "1px solid #E3F2FD",
            "border-right": "1px solid #E3F2FD",
        }])
    return dataset_table
Esempio n. 4
0
def display_plot_data_tb(display_check, jsonized_df_export, test_passed):
    if display_check == ['display']:
        if test_passed is True:
            dataset = json.loads(jsonized_df_export[0])
            df_to_export = pd.read_json(dataset, orient='split')
            df_tb_div_list = [
                html.Hr(),
                dt.DataTable(
                    id=app_id_dict['df_export_tb'],
                    data=df_to_export.to_dict('records'),
                    columns=[{
                        'name': each_col,
                        'id': each_col
                    } for each_col in df_to_export.columns],
                    export_format='csv',
                    style_data_conditional=[striped_rows],
                    fixed_rows={
                        'headers': True,
                        'data': 0
                    },
                    style_table={
                        'maxHeight': '300',
                        'overflowY': 'scroll',
                    },
                )
            ]
            return [df_tb_div_list]
        else:
            return [None]
    else:
        return [None]
Esempio n. 5
0
def make_component_table(ckey, data):
    ckey = None if not ckey in data.keys() else ckey 
    if ckey is not None:
        cdict = data[ckey]
        if ckey == 'system':
            cdict = copy(data[ckey])
            cdict.pop('dates', None)
        else:
            cdict = copy(data[ckey]['settings'])
            cdict.pop('styling', None)
        
        df = pd.DataFrame({
            "Component property": [key for key in cdict.keys()],
            "Property value" :  [value for value in cdict.values()],
        }
        )
        
        table = html.Div([
                dash_table.DataTable(
                    columns=[
                        {"name": df.columns[0], "id": df.columns[0], "editable": False},
                        {"name": df.columns[1], "id": df.columns[1], "editable": True},
                    ],
                    data= df.to_dict('records')
                )], style = {'visibility': 'visible'}
                
            )
        
    else:
        table = html.Div([
                ], style = {'visibility': 'hidden'}
        )
    
    return table
Esempio n. 6
0
def make_datatable(df, dataset):
    global table_index
    table_index += 1

    return dash_table.DataTable(
        id={'type': 'datatable_table', 'dataset': dataset, 'index': table_index},
        columns=[
            (dict(name=i, id=i, hideable=False, type='numeric',
                  format=Format(precision=4, scheme=Scheme.fixed, trim=Trim.yes))
             if i != 'Species' else
             dict(name=i, id=i))
            # {"name": i, "id": i, "hideable": True}
            for i in df.columns
            if i not in ['numIndex', 'id']

        ],
        data=df.to_dict('records'),  # the contents of the table
        filter_action="native",  # allow filtering of data by user ('native') or not ('none')
        sort_action="native",  # enables data to be sorted per-column by user or not ('none')
        sort_mode="single",  # sort across 'multi' or 'single' columns
        # column_selectable="multi",  # allow users to select 'multi' or 'single' columns
        row_selectable="multi",  # allow users to select 'multi' or 'single' rows
        # row_deletable=True,  # choose if user can delete a row (True) or not (False)
        page_size=8,  # number of rows visible per page
        style_cell={  # ensure adequate header width when text is shorter than cell's text
            #        'minWidth': 95, 'maxWidth': 95, 'width': 95,
            'fontSize': 12, 'font-family': 'sans-serif'

        },
        style_data={  # overflow cells' content into multiple lines
            'whiteSpace': 'normal',
            'height': 'auto'}

    )
Esempio n. 7
0
def get_datatable(data, color_scheme=cfg.COLOR_SCHEME, editable=False):
    # type: (List[Dict], Dict[str, str], bool) -> dash_table.DataTable
    '''
    Gets a Dash DataTable element using given data.
    Assumes dict element has all columns of table as keys.

    Args:
        data (list[dict]): List of dicts.
        color_scheme (dict, optional): Color scheme dictionary.
            Default: COLOR_SCHEME.
        editable (bool, optional): Whether table is editable. Default: False.

    Returns:
        DataTable: Table of data.
    '''
    cs = copy(cfg.COLOR_SCHEME)
    cs.update(color_scheme)

    cols = []  # type: Any
    if len(data) > 0:
        cols = data[0].keys()
    cols = [{'name': x, 'id': x} for x in cols]

    return dash_table.DataTable(
        data=data,
        columns=cols,
        id='datatable',
        fixed_rows=dict(headers=True),
        sort_action='native',
        sort_mode='multi',
        cell_selectable=editable,
        editable=editable,
    )
Esempio n. 8
0
def show_file(complete_filename, filename):
    try:
        print(f'Importing event log: {complete_filename}')
        framework.import_log(complete_filename, filename)
    except Exception as e:
        print(e)
        return html.Div([f'Error when processing file: {complete_filename}.'])

    div_file_info = html.Div([
        html.H5(
            f'First {framework.MAX_TRACES} traces of the file: {filename}'),
        html.
        H5(f'Total of cases: {framework.current_log.total_of_cases} and Median case duration: '
           f'{round(framework.current_log.median_case_duration_in_hours, 2)} hrs'
           ),
        dash_table.DataTable(
            data=framework.current_log.first_traces.to_dict('records'),
            columns=[{
                'name': i,
                'id': i
            } for i in framework.current_log.first_traces.columns],
            style_cell={'textAlign': 'left'},
            style_as_list_view=True,
            sort_action="native",
            sort_mode='multi',
            page_action="native",
            page_current=0,
            page_size=20,
        ),
    ])
    return div_file_info
Esempio n. 9
0
def create_params_table(table_name="", data={}, columns=None, **kwargs):
    style_table = {"overflowX": "scroll"}
    style_cell = {
        "minWidth": "0px",
        "maxWidth": "180px",
        "whiteSpace": "normal",
        "font_size": "14px",
    }
    css = [{
        "selector":
        ".dash-cell div.dash-cell-value",
        "rule":
        "display: inline; white-space: inherit; overflow: inherit; text-overflow: inherit;",
    }]

    # if data is null, return early
    if len(data) == 0:
        output_info_table = dash_table.DataTable(
            id=table_name,
            style_table=style_table,
            style_cell=style_cell,
            css=css,
        )
        return output_info_table

    # convert dict into pandas
    elif type(data) == dict and len(data) > 0:
        data_pd = pd.DataFrame.from_dict(data)
        data = data_pd.reset_index().astype(str)

    if columns is None:
        columns = [{"name": i, "id": i} for i in data.columns]
    else:
        columns = [{"name": i, "id": i} for i in columns]

    data = data.to_dict("records")

    output_info_table = dash_table.DataTable(
        id=table_name,
        columns=columns,
        data=data,
        style_table=style_table,
        style_cell=style_cell,
        css=css,
        **kwargs,
    )
    return output_info_table
Esempio n. 10
0
 def layout(self) -> html.Div:
     return html.Div(
         style={"marginLeft": "10px", "height": "90vh"},
         children=[
             html.Div(
                 children=[
                     html.Label(
                         "Tornado Plot",
                         style={
                             "textAlign": "center",
                             "font-weight": "bold",
                         },
                     ),
                     wcc.RadioItems(
                         vertical=False,
                         id=self.ids("plot-or-table"),
                         options=[
                             {"label": "Show bars", "value": "bars"},
                             {
                                 "label": "Show table",
                                 "value": "table",
                             },
                         ],
                         value="bars",
                     ),
                 ],
             ),
             html.Div(
                 style={"overflowY": "auto", "height": "60vh"},
                 children=[
                     html.Div(
                         id=self.ids("graph-wrapper"),
                         style={},
                         children=wcc.Graph(
                             id=self.ids("tornado-graph"),
                             config={"displayModeBar": False},
                         ),
                     ),
                     html.Div(
                         id=self.ids("table-wrapper"),
                         style={"display": "none"},
                         children=dash_table.DataTable(
                             id=self.ids("tornado-table"),
                             style_cell={
                                 "whiteSpace": "normal",
                                 "height": "auto",
                             },
                         ),
                     ),
                 ],
             ),
             html.Hr(style={"marginTop": "10px"}),
             self.settings_layout,
             dcc.Store(id=self.ids("storage"), storage_type="session"),
             dcc.Store(id=self.ids("click-store"), storage_type="session"),
             dcc.Store(id=self.ids("high-low-storage"), storage_type="session"),
             dcc.Store(id=self.ids("client-height-pixels"), storage_type="session"),
         ],
     )
Esempio n. 11
0
 def layout(self) -> dash_table.DataTable:
     return dash_table.DataTable(
         columns=[{"name": i, "id": i} for i in self.df.columns],
         data=self.df.to_dict("records"),
         sort_action="native" if self.sorting else "none",
         filter_action="native" if self.filtering else "none",
         page_action="native" if self.pagination else "none",
     )
Esempio n. 12
0
def update_output(season, home, away):
    if season == 'All':
        data = df.query('((HomeTeam==@home & AwayTeam==@away) | (HomeTeam==@away & AwayTeam==@home))')
    else:
        data = df.query('Season==@season & ((HomeTeam==@home & AwayTeam==@away) | (HomeTeam==@away & AwayTeam==@home))')
    data_1 = data.to_dict('rows')
    columns =  [{"name": i, "id": i,} for i in (df.columns)]
    return dt.DataTable(data=data_1, columns=columns)
Esempio n. 13
0
def main(unused_argv):
    # TODO: Make this a more efficient query.
    sessions = queries.GetSessions()
    points_columns = queries.GetPointsColumns() + [
        'front_brake_pressure_percentage', 'rear_brake_pressure_percentage',
        'racing_line', 'gsum', 'time_delta'
    ]
    tracks = queries.GetTracks()
    app.layout = html.Div(
        style={'display': 'grid'},
        children=[
            dcc.Location(id='url', refresh=False),
            dcc.Link('Home', href='/'),
            dcc.Link('Clear', href='/track=None&points=None'),
            dcc.Dropdown(
                id='track-dropdown',
                options=[{
                    'label': i,
                    'value': i
                } for i in tracks],
                searchable=False,
                clearable=False,
                style={'width': '50%'},
            ),
            dcc.Dropdown(
                id='points-dropdown',
                options=[{
                    'label': i,
                    'value': i
                } for i in points_columns],
                clearable=False,
                multi=True,
            ),
            dash_table.DataTable(
                id='sessions-table',
                columns=[{
                    'name': i,
                    'id': i
                } for i in sessions.columns],
                filter_action='native',
                sort_action='native',
                sort_mode='single',
                sort_by=[{
                    'column_id': 'lap_time',
                    'direction': 'asc'
                }, {
                    'column_id': 'session_time',
                    'direction': 'desc'
                }],
                row_selectable='multi',
                page_action='native',
                page_current=0,
                page_size=10,
            ),
            html.Div(id='graphs'),
        ],
    )
    app.run_server(host='0.0.0.0', debug=FLAGS.debug)
Esempio n. 14
0
 def get_project_data(df: pd.DataFrame, project_name) -> dt.DataTable:
     project_df = df[df.project_name == project_name]
     project_df = project_df.sort_values(by="timestamp")
     project_data = project_df.to_dict("rows")
     columns = [{
         "name": column,
         "id": column
     } for column in project_df.columns]
     return dt.DataTable(data=project_data, columns=columns)
Esempio n. 15
0
def simple_table(names=("a", "b"), **props_override):
    props = dict(
        id="table",
        columns=table_columns(names),
        data=[{"c0": 0, "c1": 1}, {"c0": 2, "c1": 3}],
        persistence=True,
    )
    props.update(props_override)
    return dt.DataTable(**props)
Esempio n. 16
0
 def layout(self) -> html.Div:
     """Returns a table with dataframe columns and clickable color column
     Add this to the layout of the plugin"""
     return html.Div(
         style={
             "fontSize": "0.8em",
             "height": "600px",
             "fontColor": "black",
         },
         children=[
             dcc.Store(
                 id=self.color_store_id,
                 data=list(self._dframe["COLOR"].values),
                 storage_type="session",
             ),
             wcc.FlexBox(
                 style={"display": "flex"},
                 children=[
                     html.Div(
                         style={
                             "flex": 2,
                             "overflowY": "scroll",
                             "height": "550px"
                         },
                         children=dash_table.DataTable(
                             id={
                                 "id": self._uuid,
                                 "element": "table"
                             },
                             fixed_rows={"headers": True},
                             columns=self._columns,
                             style_header={
                                 "opacity": 0.5,
                             },
                             data=self._dframe.to_dict("records"),
                             style_data_conditional=self.
                             data_style_in_table,
                         ),
                     ),
                     html.Div(
                         id={
                             "id": self._uuid,
                             "element": "pickerwrapper"
                         },
                         style={"flex": 1},
                         children=[
                             html.Label(
                                 "Click on a table row to get a color picker",
                                 style={"padding": "15px"},
                             )
                         ],
                     ),
                 ],
             ),
         ],
     )
Esempio n. 17
0
def get_table(df: DataFrame):

    grouped = df[["confirmed", "name"]].groupby("name")

    df = grouped.sum()
    df["increase"] = grouped.last()
    df["increase"] = df["increase"].apply(get_increase_str)

    df.sort_values("confirmed", ascending=False, inplace=True)

    df.reset_index(inplace=True)

    table = dash_table.DataTable(
        id="cases-table",
        data=df.to_dict("records"),
        columns=[
            {"name": "Регион", "id": "name"},
            {"name": "Случаев", "id": "confirmed"},
            {"name": "За сегодня", "id": "increase"},
        ],
        merge_duplicate_headers=True,
        style_header={
            "fontWeight": "700",
            "whiteSpace": "normal",
            "height": "auto",
        },
        style_data={
            "whiteSpace": "normal",
            "height": "auto",
        },
        style_cell={
            "backgroundColor": "#22252b",
            "color": "#bdbdbd",
            "border": "2px solid #1a1c23",
            "textAlign": "right",
            "fontFamily": "'Roboto Slab', sans-serif",
            "padding": "5px",
        },
        style_cell_conditional=[
            {
                "if": {"column_id": "name"},
                "textAlign": "left",
            },
        ],
        style_data_conditional=[
            {
                "if": {"column_id": "increase"},
                "color": "rgb(250,170,0,0.7)",
            },
        ],
        editable=False,
        row_selectable=False,
        column_selectable=False,
    )

    return table
Esempio n. 18
0
def get_key_value_table(
    data, id_='key-value', header='', editable=False, key_order=None
):
    # type (dict, Optional(str), str, bool, Optional(List[str])) -> DataTable
    '''
    Gets a Dash DataTable element representing given dictionary.

    Args:
        data (dict): Dictionary.
        id_ (str, optional): CSS id. Default: 'key-value'.
        header (str, optional): Table header title. Default: ''.
        editable (bool, optional): Whether table is editable. Default: False.
        key_order (list[str], optional): Order in which keys will be displayed.
            Default: None.

    Returns:
        DataTable: Tablular representation of given dictionary.
    '''
    data = rpb.BlobETL(data).to_flat_dict()

    # determine keys
    keys = sorted(list(data.keys()))
    if key_order is not None:
        diff = set(key_order).difference(keys)
        if len(diff) > 0:
            diff = list(sorted(diff))
            msg = f'Invalid key order. Keys not found in data: {diff}.'
            raise KeyError(msg)

        keys = set(keys).difference(key_order)
        keys = sorted(list(keys))
        keys = key_order + keys

    # transform data
    data = [dict(key=k, value=data[k]) for k in keys]

    cols = []  # type: Any
    if len(data) > 0:
        cols = data[0].keys()
    cols = [{'name': x, 'id': x} for x in cols]

    table = dash_table.DataTable(
        data=data,
        data_previous=data,
        columns=cols,
        id=f'{id_}-table',
        sort_action='native',
        sort_mode='multi',
        page_action='none',
        cell_selectable=True,
        editable=editable,
    )
    head = html.Div(className='key-value-table-header', children=header)
    return html.Div(
        id=id_, className='key-value-table-container', children=[head, table]
    )
Esempio n. 19
0
def create_graph1(data):
    dff = pd.DataFrame(data)
    # 2. convert string like JSON to pandas dataframe
    # dff = pd.read_json(data, orient='split')
    my_table = dash_table.DataTable(columns=[{
        "name": i,
        "id": i
    } for i in dff.columns],
                                    data=dff.to_dict('records'))
    return my_table
Esempio n. 20
0
def populate_checklist(data, day):
    if day is None:
        return html.H1("Please choose a day on bargraph page!")
    dff = pd.DataFrame(data)
    dff = dff[dff["day"] == day]
    my_table = dash_table.DataTable(
                    id='table',
                    columns=[{"name": i, "id": i} for i in dff.columns],
                    data=dff.to_dict('records'),
                )
    return my_table
Esempio n. 21
0
def test_cbsc007_parallel_updates(refresh, dash_duo):
    # This is a funny case, that seems to mostly happen with dcc.Location
    # but in principle could happen in other cases too:
    # A callback chain (in this case the initial hydration) is set to update a
    # value, but after that callback is queued and before it returns, that value
    # is also set explicitly from the front end (in this case Location.pathname,
    # which gets set in its componentDidMount during the render process, and
    # callbacks are delayed until after rendering is finished because of the
    # async table)
    # At one point in the wildcard PR #1103, changing from requestQueue to
    # pendingCallbacks, calling PreventUpdate in the callback would also skip
    # any callbacks that depend on pathname, despite the new front-end-provided
    # value.

    app = Dash()

    app.layout = html.Div([
        dcc.Location(id="loc", refresh=refresh),
        html.Button("Update path", id="btn"),
        dash_table.DataTable(id="t", columns=[{
            "name": "a",
            "id": "a"
        }]),
        html.Div(id="out"),
    ])

    @app.callback(Output("t", "data"), [Input("loc", "pathname")])
    def set_data(path):
        return [{"a": (path or repr(path)) + ":a"}]

    @app.callback(Output("out", "children"),
                  [Input("loc", "pathname"),
                   Input("t", "data")])
    def set_out(path, data):
        return json.dumps(data) + " - " + (path or repr(path))

    @app.callback(Output("loc", "pathname"), [Input("btn", "n_clicks")])
    def set_path(n):
        if not n:
            raise PreventUpdate

        return "/{0}".format(n)

    dash_duo.start_server(app)

    dash_duo.wait_for_text_to_equal("#out", '[{"a": "/:a"}] - /')
    dash_duo.find_element("#btn").click()
    # the refresh=True case here is testing that we really do get the right
    # pathname, not the prevented default value from the layout.
    dash_duo.wait_for_text_to_equal("#out", '[{"a": "/1:a"}] - /1')
    if not refresh:
        dash_duo.find_element("#btn").click()
        dash_duo.wait_for_text_to_equal("#out", '[{"a": "/2:a"}] - /2')
Esempio n. 22
0
 def target_points_tab_layout(self) -> dash_table.DataTable:
     df = self.df_well_target_points.get_targetpoints_df()
     return dash_table.DataTable(
         id=self.ids("target-point-table"),
         columns=[{
             "name": i,
             "id": i
         } for i in df.columns],
         data=df.to_dict("records"),
         sort_action="native",
         filter_action="native",
     )
def create_datatable(df):
    return [
        dash_table.DataTable(
            id='datatable',
            columns=[{
                'name': n,
                'id': i
            } for n, i in zip([
                'Term', 'Subj', 'Nmbr', 'CRN', 'Sec', 'S', 'Cam', 'Title',
                'Credit', 'Enrl', 'Days', 'Time', 'Loc', 'Instructor'
            ], [*df.columns])],
            style_header={
                'backgroundColor': 'rgb(230, 230, 230)',
                'fontWeight': 'bold',
            },
            style_cell={
                'font-family': 'sans-serif',
                'font-size': '1rem'
            },
            style_cell_conditional=[{
                'if': {
                    'column_id': i
                },
                'textAlign': 'left',
                'minWidth': w,
                'width': w,
                'maxWidth': w,
                'whiteSpace': 'normal'
            } for i, w in zip([*df.columns], [
                '9%', '5%', '5.5%', '5.5%', '4.5%', '3.5%', '4.5%', '19.5%',
                '5.5%', '4.5%', '5.5%', '9%', '7.5%', '11%'
            ])],
            fixed_rows={
                'headers': True,
                'data': 0
            },
            page_size=5000,
            virtualization=True,
            data=df.to_dict('records'),
            # editable=True,
            filter_action='native',
            sort_action='native',
            sort_mode='multi',
            # row_selectable='multi',
            # row_deletable=True,
            selected_rows=[],
            style_data={
                'whiteSpace': 'normal',
                'height': 'none',
            },
        )
    ]
Esempio n. 24
0
def make_table(data):
    table = dash_table.DataTable(
        id="data",
        columns=[{'id': 'activity', 'name': 'name'}],
        data=json_to_list(data),
        page_size=10,
        page_current=0,
        virtualization=True,
        fixed_rows={'headers': True},
        style_cell={'minWidth': 95, 'width': 95, 'maxWidth': 95},
        style_table={'height': 300},  # default is 500,
    )
    return table
Esempio n. 25
0
def test_cbmt003_chain_with_table(dash_duo):
    # see https://github.com/plotly/dash/issues/1071
    app = Dash(__name__)
    app.layout = html.Div(
        [
            html.Div(id="a1"),
            html.Div(id="a2"),
            html.Div(id="b1"),
            html.H1(id="b2"),
            html.Button("Update", id="button"),
            dash_table.DataTable(id="table"),
        ]
    )

    @app.callback(
        # Changing the order of outputs here fixes the issue
        [Output("a2", "children"), Output("a1", "children")],
        [Input("button", "n_clicks")],
    )
    def a12(n):
        return "a2: {!s}".format(n), "a1: {!s}".format(n)

    @app.callback(Output("b1", "children"), [Input("a1", "children")])
    def b1(a1):
        return "b1: '{!s}'".format(a1)

    @app.callback(
        Output("b2", "children"),
        [Input("a2", "children"), Input("table", "selected_cells")],
    )
    def b2(a2, selected_cells):
        return "b2: '{!s}', {!s}".format(a2, selected_cells)

    dash_duo.start_server(app)

    dash_duo.wait_for_text_to_equal("#a1", "a1: None")
    dash_duo.wait_for_text_to_equal("#a2", "a2: None")
    dash_duo.wait_for_text_to_equal("#b1", "b1: 'a1: None'")
    dash_duo.wait_for_text_to_equal("#b2", "b2: 'a2: None', None")

    dash_duo.find_element("#button").click()
    dash_duo.wait_for_text_to_equal("#a1", "a1: 1")
    dash_duo.wait_for_text_to_equal("#a2", "a2: 1")
    dash_duo.wait_for_text_to_equal("#b1", "b1: 'a1: 1'")
    dash_duo.wait_for_text_to_equal("#b2", "b2: 'a2: 1', None")

    dash_duo.find_element("#button").click()
    dash_duo.wait_for_text_to_equal("#a1", "a1: 2")
    dash_duo.wait_for_text_to_equal("#a2", "a2: 2")
    dash_duo.wait_for_text_to_equal("#b1", "b1: 'a1: 2'")
    dash_duo.wait_for_text_to_equal("#b2", "b2: 'a2: 2', None")
Esempio n. 26
0
    def notebookHome(self):
        # TODO: better first call
        example = UserFilesAccess.shortExample
        example_data = pandas.read_excel(example)

        notebook = dash_table.DataTable(
            id=self.notebook,
            columns=[
                {
                    "name": column,
                    "id": column,
                    "editable": False,
                    "hideable": True,
                    "renamable": True,
                }
                if column == "ID"
                else {
                    "name": column,
                    "id": column,
                    "type": "numeric",
                    "hideable": True,
                    "renamable": True,
                }
                if (column == "Amount" or column == "Reimbursement")
                else {
                    "name": column,
                    "id": column,
                    "type": "datetime",
                    "hideable": True,
                    "renamable": True,
                }
                if column == "Date"
                else {
                    "name": column,
                    "id": column,
                    "hideable": True,
                    "renamable": True,
                }
                for column in example_data.columns
            ],
            editable=True,
            row_deletable=True,
            export_columns="all",
            export_format="xlsx",
            export_headers="display",
        )
        notebook_div = html.Div(
            id=self.notebook_div, children=notebook, style={"display": "none"},
        )
        return notebook_div
Esempio n. 27
0
def makeTable(id, df, height=300, row_selectable='single', defaultRow=0):
    """
	defaultRow: row index selected on __init__
	"""
    if df is None:
        statDict = {'tmp': 'empty'}
        df = pd.DataFrame(columns=['Idx', 'Error'])
        #df['idx'] = [i for i in range(len(statDict.keys()))]
        #df['error'] = [x for x in statDict.keys()]

    #
    columns = [{"name": i, "id": i} for i in df.columns]
    data = df.to_dict('records')

    ret = dash_table.DataTable(
        id=id,
        persistence=True,
        columns=columns,
        data=data,
        row_selectable=row_selectable,
        fixed_rows={'headers': True},  # on scroll, keep headers at top
        selected_rows=[defaultRow],  # default selected row
        style_header={
            'backgroundColor': 'rgb(30, 30, 50)',
            'fontWeight': 'bold',
        },
        style_cell={
            'textAlign': 'left',
            'fontSize': 11,
            'font-family': 'sans-serif',
            'color': 'white',  # dark theme
            'backgroundColor': 'rgb(30, 30, 30)',  # dark theme
        },
        style_data_conditional=[{
            'if': {
                'row_index': 'odd'
            },
            #'backgroundColor': 'rgb(50, 50, 50)' # dark theme
            'backgroundColor': 'rgb(50, 50, 50)'  # light theme
        }],
        # CSS styles to be applied to the outer table container
        style_table={
            'height': height,  # hard coding height
            'overflowX': 'auto',
            'overflowY': 'auto',
            #'width': width
        })
    return ret
Esempio n. 28
0
 def display_output(n_clicks, column_list):
     """Renders wellpoints table from csv file"""
     wellpoints_df = self.df_well_target_points.update_wellpoints_df(
         column_list)
     return html.Div([
         dash_table.DataTable(
             id=self.ids("well-points-table"),
             columns=[{
                 "name": i,
                 "id": i
             } for i in wellpoints_df.columns],
             data=wellpoints_df.to_dict("records"),
             sort_action="native",
             filter_action="native",
         ),
     ])
Esempio n. 29
0
    def get_dict_input(
        self,
        kwarg_label: str,
        default: Optional[Any] = None,
        state: Optional[dict] = None,
        label: Optional[str] = None,
        help_str: str = None,
        key_name: str = "key",
        value_name: str = "value",
    ):
        """

        :param kwarg_label:
        :param default:
        :param state:
        :param label:
        :param help_str:
        :param key_name:
        :param value_name:
        :return:
        """

        state = state or {}
        default = default or state.get(kwarg_label) or {}

        dict_input = dt.DataTable(
            id=self.id(kwarg_label, is_kwarg=True, hint="dict"),
            columns=[
                {
                    "id": "key",
                    "name": key_name
                },
                {
                    "id": "value",
                    "name": value_name
                },
            ],
            data=[{
                "key": k,
                "value": v
            } for k, v in default.items()],
            editable=True,
            persistence=False,
        )

        return add_label_help(dict_input, label, help_str)
Esempio n. 30
0
    def make_rate_table(self):

        probe_group = [dict(name="Measured From %s" % each["value"],
                            id=each["value"].replace("-", "")) 
                       for each in self.dao_dnsprobe.make_probe_group()]

        columns = [dict(name="Address Family", id="af"),
                   dict(name="Nameserver", id="dst_name"),
                   dict(name="Transport", id="proto")] + probe_group

        soa_table = dash_table.DataTable(
            id="main-content-table",
            filter_action="native",
            columns=columns,
            style_data_conditional=[],
            data=[])

        return soa_table