Пример #1
0
def tree_callback_demo(selectedKeys, checkedKeys, halfCheckedKeys):
    return [
        fac.AntdTitle('selectedKeys:', level=5),
        html.Pre(str(selectedKeys)),
        fac.AntdTitle('checkedKeys:', level=5),
        html.Pre(str(checkedKeys)),
        fac.AntdTitle('halfCheckedKeys:', level=5),
        html.Pre(str(halfCheckedKeys))
    ]
Пример #2
0
 def display_output(react_value, flow_value):
     return html.Div([
         "You have entered {} and {}".format(react_value, flow_value),
         html.Hr(),
         html.Label("Flow Component Docstring"),
         html.Pre(dash_flow_example.ExampleFlowComponent.__doc__),
         html.Hr(),
         html.Label("React PropTypes Component Docstring"),
         html.Pre(dash_flow_example.ExampleReactComponent.__doc__),
         html.Div(id="waitfor"),
     ])
Пример #3
0
    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
Пример #4
0
 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")
Пример #5
0
 def view(self):
     """
     Standard view function for a dataset
     """
     data = self.dash_ready_data()
     if len(data) == 1:
         html_comps = []
         for j in range(len(data.columns)):
             d = data.iloc[0,j]
             html_comps.append(html.H3(data.columns[j]))
             if type(d) == pd.DataFrame:
                 html_comps.append(style.get_standard_data_table(d,f"data_view_{j}"))
             elif type(d) == list:
                 html_comps.append(html.Pre("\n".join(d)))
             else:
                 html_comps.append(html.Pre(d))
         return html_comps
     else:
         return [style.get_standard_data_table(data.reset_index(),"data_view")]
Пример #6
0
def view_item(item, id):
    """Helper function to view a single item.
    """
    html_comps = []
    j = 0
    for index in item.index:
        html_comps.append(html.H4(index))
        d = item[index]
        if type(d) == pd.DataFrame:
            html_comps.append(get_standard_data_table(d,
                                                      f"data_view_item_{j}"))
        elif type(d) == list:
            html_comps.append(html.Pre("\n".join([str(di) for di in d])))
        elif d is None:
            html_comps.append(html.Pre("None"))
        else:
            html_comps.append(html.Pre(d))
        j += 1

    return html_comps
Пример #7
0
def table_callback_demo(currentData, recentlyChangedRow, sorter, filter,
                        pagination):

    ctx = dash.callback_context

    return [
        fac.AntdTitle('本次回调由{}所触发'.format(
            ctx.triggered[0]['prop_id'].split('.')[-1]),
                      level=3),
        fac.AntdDivider(),
        fac.AntdTitle('currentData:', level=5),
        html.Pre(str(currentData)),
        fac.AntdTitle('recentlyChangedRow:', level=5),
        html.Pre(str(recentlyChangedRow)),
        fac.AntdTitle('sorter:', level=5),
        html.Pre(str(sorter)),
        fac.AntdTitle('filter:', level=5),
        html.Pre(str(filter)),
        fac.AntdTitle('pagination:', level=5),
        html.Pre(str(pagination))
    ]
def load_data_by_type(filetype, contents):
    children = []
    _type, payload = contents.split(",")
    if filetype in {"csv", "xlsx", "xls"}:
        children = [load_table(filetype, payload)]
    elif filetype in {"png", "svg"}:
        children = [html.Img(src=contents)]

    children += [
        html.Hr(),
        html.Div("Raw Content", id="raw-title"),
        html.Pre(payload, style=pre_style),
    ]
    return html.Div(children)
Пример #9
0
    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
Пример #10
0
 def cell_clicked_dataset(cell, data):
     if cell is None:
         return dash.no_update
     row, col = cell["row"], cell["column_id"]
     selected = data[row][col]
     dataset_id = data[row]['Dataset ID']
     dataset_name = data[row]['Dataset Name']
     datasets_df = config.datasets_df.set_index('Dataset ID')
     links = datasets_df.loc[dataset_id, 'Download links']
     loader = datasets_df.loc[dataset_id, 'Loader']
     description = str(datasets_df.loc[dataset_id, 'Description'])
     if selected is not None:
         unprocessed = pyrplib.dataset.load_unprocessed(
             dataset_id, datasets_df)
         description = description.replace("\\n", "\n")
         description_html = [html.H3("Description"), html.Pre(description)]
         contents = [
             html.Br(), html.H2(dataset_name)
         ] + description_html + [html.H3("Data")] + unprocessed.view()
         return html.Div(contents)
     else:
         return dash.no_update
Пример #11
0
def test_inin026_graphs_in_tabs_do_not_share_state(dash_duo):
    app = Dash(__name__, suppress_callback_exceptions=True)

    app.layout = html.Div([
        dcc.Tabs(
            id="tabs",
            children=[
                dcc.Tab(label="Tab 1", value="tab1", id="tab1"),
                dcc.Tab(label="Tab 2", value="tab2", id="tab2"),
            ],
            value="tab1",
        ),
        # Tab content
        html.Div(id="tab_content"),
    ])
    tab1_layout = [
        html.Div([
            dcc.Graph(
                id="graph1",
                figure={
                    "data": [{
                        "x": [1, 2, 3],
                        "y": [5, 10, 6],
                        "type": "bar"
                    }]
                },
            )
        ]),
        html.Pre(id="graph1_info"),
    ]

    tab2_layout = [
        html.Div([
            dcc.Graph(
                id="graph2",
                figure={
                    "data": [{
                        "x": [4, 3, 2],
                        "y": [5, 10, 6],
                        "type": "bar"
                    }]
                },
            )
        ]),
        html.Pre(id="graph2_info"),
    ]

    @app.callback(Output("graph1_info", "children"),
                  Input("graph1", "clickData"))
    def display_hover_data(hover_data):
        return json.dumps(hover_data)

    @app.callback(Output("graph2_info", "children"),
                  Input("graph2", "clickData"))
    def display_hover_data_2(hover_data):
        return json.dumps(hover_data)

    @app.callback(Output("tab_content", "children"), Input("tabs", "value"))
    def render_content(tab):
        return tab2_layout if tab == "tab2" else tab1_layout

    dash_duo.start_server(app)

    dash_duo.find_element("#graph1:not(.dash-graph--pending)").click()

    until(lambda: '"label": 2' in dash_duo.find_element("#graph1_info").text,
          timeout=3)

    dash_duo.find_element("#tab2").click()

    dash_duo.find_element("#graph2:not(.dash-graph--pending)").click()

    until(lambda: '"label": 3' in dash_duo.find_element("#graph2_info").text,
          timeout=3)
Пример #12
0
                                    value='grid',
                                    clearable=False),
                                drc.NamedRadioItems(
                                    name='Expand',
                                    id='radio-expand',
                                    options=drc.DropdownOptionsList(
                                        'followers', 'following'),
                                    value='followers')
                            ]),
                    dcc.Tab(
                        label='JSON',
                        children=[
                            html.Div(style=styles['tab'],
                                     children=[
                                         html.P('Node Object JSON:'),
                                         html.Pre(id='tap-node-json-output',
                                                  style=styles['json-output']),
                                         html.P('Edge Object JSON:'),
                                         html.Pre(id='tap-edge-json-output',
                                                  style=styles['json-output'])
                                     ])
                        ])
                ]),
        ])
])


# ############################## CALLBACKS ####################################
@app.callback(Output('tap-node-json-output', 'children'),
              [Input('cytoscape', 'tapNode')])
def display_tap_node(data):
    return json.dumps(data, indent=2)
Пример #13
0
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)
Пример #14
0
def div_increase_vs_user_div_vs_reco_volume(msd_dataset, local_scheduler=False, alpha=2):
    """Interactive plot of the recommendation diversity vs the user diversity 
    for different number of latent factors"""

    n_iterations = N_ITERATIONS
    n_factors = OPT_N_FACTORS
    regularization = OPT_REGULARIZATION
    n_recommendations_values = N_RECOMMENDATIONS_VALUES

    # make sure that all the dependencies of the task are completed by running
    # it in the scheduler
    data_task = ComputeDiversityIncreaseVsUserDiversityVsRecoVolume(
        dataset=msd_dataset,
        alpha=alpha,
        model_n_iterations=n_iterations,
        model_n_factors=n_factors,
        model_regularization=regularization,
        n_recommendations_values=n_recommendations_values
    )
    luigi.build([data_task], local_scheduler=local_scheduler, log_level='INFO')
    # then retrieve the data
    merged = data_task.run()

    fig = px.scatter(
        merged,
        x='diversity',
        y='diversity_increase',
        hover_data=['user'],
        custom_data=['n_recommendations'],
        animation_frame='n_recommendations',
        animation_group='user',
        # marginal_x='histogram',
        # marginal_y='histogram',
        color='volume',
        color_continuous_scale=px.colors.sequential.Viridis,
        width=float('inf'),
        height=900,
        title='Effect of recommendations on user diversity',
        labels={
            'diversity': 'User individual diversity',
            'diversity_increase': 'Diversity increase',
            'volume': 'log10(volume)',
        }
    )
    fig.update_layout(coloraxis_colorbar=dict(
        title='volume',
        tickvals=[1, 1.477, 2, 2.477, 3],
        ticktext=['10', '30', '100', '300', '1000'],
    ))

    app = dash.Dash()
    app.layout = html.Div([
        # Graphs container
        html.Div([
            html.Div([
                dcc.Graph(
                    id='basic-interactions',
                    figure=fig
                ),
            ], style={'width': '50%'}),

            html.Div([
                dcc.Graph(id='listened-tag-distribution'),
                dcc.Graph(id='recommended-tag-distribution'),
            ], style={'width': '50%'})

        ], style={'display': 'flex'}),

        # Data container
        html.Div([
            dcc.Markdown("""
                **Click Data**

                Click on points in the graph.
            """),
            html.Pre(id='click-data'),
        ]),
    ])

    @app.callback([
        Output('click-data', 'children'),
        Output('listened-tag-distribution', 'figure'),
        Output('recommended-tag-distribution', 'figure')
    ],
        Input('basic-interactions', 'clickData'))
    def handle_click_data(click_data):
        if click_data:
            point = click_data['points'][0]
            user_id = point['id']
            n_recommendations = int(point['customdata'][0])
            diversity = point['x']
            increase = point['y']

            user_info, listened_tag_distribution, recommended_tag_distribution = AnalyseUser(
                user_id=user_id,
                dataset=msd_dataset,
                model_n_iterations=n_iterations,
                model_n_factors=n_factors,
                model_regularization=regularization,
                n_recommendations=n_recommendations
            ).run()

            user_info['organic_diversity'] = diversity
            user_info['diversity_increase'] = increase

            # reorder the dict for better readability in the webpage
            keys = [
                'user_id',
                'organic_diversity',
                'diversity_increase',
                'model_n_iterations',
                'model_n_factors',
                'model_regularization',
                'model_user_fraction',
                'n_listened',
                'n_listened_tags',
                'n_recommended_items',
                'n_recommended_tags',
                'n_common_tags',
                'listened_items',
                'listened_tags',
                'recommended_items',
                'recommended_tags',
                'common_tags'
            ]
            user_info = {key: user_info[key] for key in keys}

            listened_tags_fig = px.bar(
                listened_tag_distribution,
                title='Listened tags weight distribution',
                labels={'value': 'Normalized weight', 'tag': 'Tag name'}
            )
            listened_tags_fig.update_xaxes(range=[0, 30])
            listened_tags_fig.update_layout(xaxis_tickangle=45)

            recommended_tags_fig = px.bar(
                recommended_tag_distribution,
                title='Recommended tags weight distribution',
                labels={'value': 'Normalized weight', 'tag': 'Tag name'}
            )
            recommended_tags_fig.update_xaxes(range=[0, 30])
            recommended_tags_fig.update_layout(xaxis_tickangle=45)

        else:
            user_info = {}
            listened_tags_fig = px.bar(
                title='Listened tags weight distribution')
            recommended_tags_fig = px.bar(
                title='Recommended tags weight distribution')

        return json.dumps(user_info, indent=2), listened_tags_fig, recommended_tags_fig

    app.run_server(debug=True, use_reloader=False)
Пример #15
0
                    },
                    id='图片编辑功能',
                    className='div-highlight'
                ),

                html.Div(
                    [
                        fac.AntdPictureUpload(
                            id='picture-upload-demo',
                            apiUrl='/upload/',
                            fileMaxSize=1,
                            buttonContent='点击上传图片'
                        ),

                        fac.AntdSpin(
                            html.Pre(id='picture-upload-demo-output'),
                            text='回调中'
                        ),

                        fac.AntdDivider(
                            '回调示例',
                            lineColor='#f0f0f0',
                            innerTextOrientation='left'
                        ),

                        fac.AntdCollapse(
                            fuc.FefferySyntaxHighlighter(
                                showLineNumbers=True,
                                showInlineLineNumbers=True,
                                language='python',
                                codeStyle='coy-without-shadows',
Пример #16
0
    def raw_data_chart(self):
        app = dash.Dash(__name__)

        max_index = len(self.df)

        fig = make_subplots(specs=[[{'secondary_y': True}]])
        # Add traces
        fig.add_trace(go.Scatter(x=self.df['Duration'],
                                 y=self.df['Inlet_Pressure'] * 1e-6,
                                 name='Eingangsdruck',
                                 line_color='blue'),
                      secondary_y=False)
        fig.add_trace(go.Scatter(x=self.df['Duration'],
                                 y=self.df['Outlet_Pressure'] * 1e-6,
                                 name='Ausgangsdruck',
                                 line_color='blue'),
                      secondary_y=False)
        fig.add_trace(go.Scatter(x=self.df['Duration'],
                                 y=self.df['Confining_Pressure'] * 1e-6,
                                 name='Manteldruck',
                                 line_color='black',
                                 visible='legendonly'),
                      secondary_y=False)
        fig.add_trace(go.Scatter(x=self.df['Duration'],
                                 y=self.df['Temperature'] - 273.15,
                                 name='Temperatur',
                                 line_color='red'),
                      secondary_y=True)
        fig.add_vline(x=self.df.iloc[self.start]['Duration'], line_dash='dot')
        fig.add_vline(x=self.df.iloc[self.stop - 1]['Duration'],
                      line_dash='dot')

        fig.update_layout(
            xaxis=dict(showexponent='all', exponentformat='power'))
        fig.update_xaxes(title_text='Messdauer in s', type='log')
        fig.update_yaxes(title_text='Druck in MPa', secondary_y=False)
        fig.update_yaxes(title_text='Temperatur in °C',
                         secondary_y=True,
                         range=[12, 16],
                         showgrid=False)

        app.layout = html.Div([
            html.Div([
                html.H1(self.name),
                html.Button('Calculate', id='button'),
                dcc.Graph(id='measurement_plot',
                          figure=fig,
                          style={
                              'width': '70%',
                              'height': '70vh'
                          }),
                html.Pre(id='click_x_value', hidden=True),
                html.Div([
                    html.H4('Beginn der Messung'),
                    dcc.Slider(
                        id='slider_start',
                        min=1,
                        max=max_index,
                        value=self.start,
                    ),
                    dcc.Input(
                        id='input_start',
                        type='number',
                        min=1,
                        max=max_index,
                        value=self.start,
                    )
                ],
                         style={
                             'width': '25%',
                             'display': 'inline-block'
                         }),
                html.Div([
                    html.H4('Ende der Messung'),
                    dcc.Slider(
                        id='slider_stop',
                        min=0,
                        max=max_index,
                        value=self.stop,
                    ),
                    dcc.Input(
                        id='input_stop',
                        type='number',
                        min=0,
                        max=max_index,
                        value=self.stop,
                    )
                ],
                         style={
                             'width': '25%',
                             'display': 'inline-block'
                         })
            ]),
        ])

        @app.callback(Output('measurement_plot', 'figure'),
                      Input('slider_start', 'value'),
                      Input('slider_stop', 'value'))
        def update_xaxis(x1, x2):
            x1 = self.df.iloc[x1]['Duration']
            x2 = self.df.iloc[x2 - 1]['Duration']
            x_min = np.log(x1) / np.log(10)
            x_max = np.log(x2) / np.log(10)
            fig.update_xaxes(range=[x_min, x_max])
            fig.update_layout(transition_duration=500)
            print(self.start, self.stop, len(self.df))
            return fig

        @app.callback(Output('slider_start', 'value'),
                      Output('input_start', 'value'),
                      Output('click_x_value', 'children'),
                      Input('slider_start', 'value'),
                      Input('input_start', 'value'),
                      Input('measurement_plot', 'clickData'))
        def start_value(input_value, slider_value, clickData):
            ctx = dash.callback_context
            trigger_id = ctx.triggered[0]['prop_id'].split('.')[0]
            value = self.start

            if trigger_id == 'slider_start':
                value = input_value
            elif trigger_id == 'input_start':
                value = slider_value
            else:
                try:
                    x = clickData['points'][0]['x']
                    value = self.df.index[self.df['Duration'] == x][0]
                except:
                    pass

            return value, value, value

        @app.callback(Output('slider_stop', 'value'),
                      Output('input_stop', 'value'),
                      Input('slider_stop', 'value'),
                      Input('input_stop', 'value'))
        def stop_value(input_value, slider_value):
            ctx = dash.callback_context
            trigger_id = ctx.triggered[0]['prop_id'].split('.')[0]
            value = input_value if trigger_id == 'slider_stop' else slider_value
            return value, value

        app.run_server(debug=True)
Пример #17
0
                    [
                        fac.AntdSpin(
                            html.Pre('[]', id='select-demo-output'),
                            text='回调中'
                        ),
                        fac.AntdSelect(
                            id='select-demo',
                            placeholder='请选择国家:',
                            mode='multiple',
                            options=[
                                {'label': '中国', 'value': '中国'},
                                {'label': '美国', 'value': '美国'},
                                {'label': '俄罗斯', 'value': '俄罗斯'},
                                {'label': '德国', 'value': '德国', 'disabled': True},
                                {'label': '加拿大', 'value': '加拿大'}
                            ],
                            style={
                                # 使用css样式固定宽度
                                'width': '200px'
                            }
                        ),

                        fac.AntdDivider(
                            '回调示例',
                            lineColor='#f0f0f0',
                            innerTextOrientation='left'
                        ),

                        fac.AntdCollapse(
                            fuc.FefferySyntaxHighlighter(
                                showLineNumbers=True,
                                showInlineLineNumbers=True,
                                language='python',
                                codeStyle='coy-without-shadows',
                                codeString='''
html.Pre('[]', id='select-demo-output'),
fac.AntdSelect(
    id='select-demo',
    placeholder='请选择国家:',
    mode='multiple',
    options=[
        {'label': '中国', 'value': '中国'},
        {'label': '美国', 'value': '美国'},
        {'label': '俄罗斯', 'value': '俄罗斯'},
        {'label': '德国', 'value': '德国', 'disabled': True},
        {'label': '加拿大', 'value': '加拿大'}
    ],
    style={
        # 使用css样式固定宽度
        'width': '200px'
    }
)
...
@app.callback(
    Output('select-demo-output', 'children'),
    Input('select-demo', 'value'),
    prevent_initial_call=True
)
def button_callback_demo(value):

    return str(value)'''
                            ),
                            title='点击查看代码',
                            is_open=False,
                            ghost=True
                        )

                    ],
Пример #18
0
 html.Div(
     [
         fac.AntdSpace([
             'multiple:',
             fac.AntdSwitch(id='dragger-upload-demo-is-multiple',
                            checked=False,
                            checkedChildren='True',
                            unCheckedChildren='False')
         ],
                       style={'marginBottom': '5px'}),
         fac.AntdDraggerUpload(id='dragger-upload-demo',
                               apiUrl='/upload/',
                               fileMaxSize=1,
                               text='拖拽上传示例',
                               hint='点击或拖拽文件至此处进行上传'),
         fac.AntdSpin(html.Pre(id='dragger-upload-demo-output'),
                      text='回调中'),
         fac.AntdDivider(
             '回调示例', lineColor='#f0f0f0', innerTextOrientation='left'),
         fac.AntdParagraph([
             fac.AntdText(
                 '  这个例子展示了在满足文件体积限制的前提下,每次上传任务执行后,对成功或失败状态进行记录的相关参数信息,'
             ),
             fac.AntdText('注意!', strong=True),
             fac.AntdText('当'),
             fac.AntdText('multiple=True', code=True),
             fac.AntdText('或'),
             fac.AntdText('directory=True', code=True),
             fac.AntdText('时,'),
             fac.AntdText('lastUploadTaskRecord', code=True),
             fac.AntdText('参数会返回列表格式以记录每个文件的信息')