示例#1
0
 def w(*args, **kwargs):
     output_component = f(*args, **kwargs)
     output = [
         *[Br() for i in range(n_before)], output_component,
         *[Br() for i in range(n_after)]
     ]
     return output
示例#2
0
 def hello() -> Div:
     '''
     Returns the hello page
     '''
     return Container([
         Row([
             Col([
                 H1('Hello, World!'),
                 Br(),
                 Input(id='hello_input',
                       value='',
                       type='text',
                       placeholder='Enter name',
                       debounce=True),
                 Br(),
                 Div(id='hello_output'),
                 internal_link('Home', href='/'),
             ])
         ])
     ])
示例#3
0
from dash_core_components import Link
from dash_html_components import Br, Div, H1, H3

from app import url_base_pathname
from modules.utils import colors


layout = Div([
    # title
    H1(
        children='publisher-dash',
        style={
            'textAlign': 'center',
            'color': colors['text']
        }
    ),
    # subtitle
    H3(
        children='Index',
        style={
            'textAlign': 'center',
            'color': colors['text']
        }
    ),
    # Link('Scene', href=f'{url_base_pathname}/scene'),
    Br(),
    Link('Publisher', href=f'{url_base_pathname}/publisher')
])
                     locale=dict(separate_4digits=False))),  # skip-id-check
    dict(id='a',
         name='SI',
         type='numeric',
         format=Format(si_prefix=Prefix.milli).precision(0)),  # skip-id-check
    dict(id='a',
         name='SI+space',
         type='numeric',
         format=Format(si_prefix=Prefix.milli,
                       symbol=Symbol.yes,
                       symbol_suffix=' ').precision(0)),  # skip-id-check
    dict(id='a',
         name='Explicit SI',
         type='numeric',
         format=Format(si_prefix=10**-3).precision(0))  # skip-id-check
]

values = [123, 123, 1234, 12345, 123456789]
data = [dict(a=value) for value in values]

app.layout = Div([
    DataTable(columns=columns_1, data=data),
    Br(),
    DataTable(columns=columns_2, data=data),
    Br(),
    DataTable(columns=columns_3, data=data)
])

if __name__ == '__main__':
    app.run_server(debug=True)
示例#5
0
def historic(app,
             tsa,
             routes_pathname_prefix='/tshistory/',
             request_pathname_prefix='/',
             cachedir=None):

    request_pathname_prefix_adv = request_pathname_prefix + routes_pathname_prefix

    external_stylesheets = [
        'https://codepen.io/chriddyp/pen/bWLwgP.css',
        'https://cdn.rawgit.com/plotly/dash-app-stylesheets/2d266c578d2a6e8850ebce48fdb52759b2aef506/stylesheet-oil-and-gas.css'
    ]

    if request_pathname_prefix != '/':
        dashboard = dash.Dash(
            'tsview',
            server=app,
            routes_pathname_prefix=routes_pathname_prefix,
            requests_pathname_prefix=request_pathname_prefix_adv,
            external_stylesheets=external_stylesheets)
    else:
        dashboard = dash.Dash('tsview',
                              server=app,
                              url_base_pathname=routes_pathname_prefix,
                              external_stylesheets=external_stylesheets)

    dashboard.config['suppress_callback_exceptions'] = True
    if request_pathname_prefix != '/':
        dashboard.config.requests_pathname_prefix = request_pathname_prefix_adv

    if cachedir:
        cacheconfig = {'CACHE_TYPE': 'filesystem', 'CACHE_DIR': cachedir}
    else:
        cacheconfig = {'CACHE_TYPE': 'simple'}
    cache = Cache(dashboard.server, config=cacheconfig)
    cache.init_app(dashboard.server)

    dashboard.layout = Div([
        Location(id='url', refresh=False),

        #Placeholders
        Div(Dropdown(id='idate_slider', value=None), style={'display':
                                                            'none'}),
        Graph(id='ts_snapshot'),
        Button(id='submit-button',
               n_clicks=0,
               children='Show Republications',
               style={
                   'width': '100%',
                   'background-color': '#F7F7F7',
               }),
        Graph(id='ts_by_appdate', hoverData={'points': [{
            'text': None
        }]}),
        html.P('Select an insertion date:',
               style={
                   'font-family': 'Helvetica',
                   "font-size": "100%",
                   'text-align': 'center',
               }),
        Div(id='slider-container'),
        Div([Br()]),
        Div([Br()]),
        html.P(
            'Place the mouse on the graph above to see the versions '
            'of one application date:',
            style={
                'font-family': 'Helvetica',
                "font-size": "100%",
                'text-align': 'center',
            }),
        Graph(id='ts_by_insertdate'),
    ])

    @cache.memoize(timeout=300)
    def _history(id_serie, fromdate, todate):
        return {
            # canonicalize the keys immediately
            dt.strftime('%Y-%m-%d %H:%M:%S'): serie
            for dt, serie in tsa.history(id_serie,
                                         from_value_date=fromdate,
                                         to_value_date=todate).items()
        }

    def history(id_serie, fromdate=None, todate=None):
        return _history(id_serie, fromdate, todate)

    def insertion_dates(id_serie, fromdate=None, todate=None):
        return list(history(id_serie, fromdate, todate).keys())

    def parse_url(url_string):
        if (url_string in (routes_pathname_prefix, request_pathname_prefix_adv)
                or url_string is None or len(url_string.strip('/')) == 0):
            id_serie = ''
        else:
            id_serie = url_string.split('/')[-1]
        return id_serie

    @dashboard.callback(
        dash.dependencies.Output('slider-container', 'children'), [
            dash.dependencies.Input('url', 'pathname'),
            dash.dependencies.Input('submit-button', 'n_clicks')
        ], [dash.dependencies.State('ts_snapshot', 'relayoutData')])
    def adaptable_slider(url_string, n_clicks, graphdata):
        if n_clicks == 0:
            return Slider(id='idate_slider', value=None)

        id_serie = parse_url(url_string)
        fromdate, todate = unpack_dates(graphdata)
        idates = insertion_dates(id_serie, fromdate, todate)
        showlabel = len(idates) < 25
        slider = Slider(id='idate_slider',
                        min=0,
                        max=len(idates) - 1,
                        value=len(idates) - 1,
                        step=None,
                        marks={
                            str(idx): elt if showlabel else ''
                            for idx, elt in enumerate(idates)
                        })
        return slider

    @dashboard.callback(dash.dependencies.Output('ts_snapshot', 'figure'),
                        [dash.dependencies.Input('url', 'pathname')])
    def ts_snapshot(url_string):
        id_serie = parse_url(url_string)
        ts = tsa.get(id_serie)

        if id_serie is None or ts is None:
            return {'data': [], 'layout': {}}

        trace = [
            go.Scatter(x=ts.index,
                       y=ts.values,
                       name=id_serie,
                       mode='lines',
                       line={'color': ('rgb(255, 127, 80)')})
        ]
        layout = go.Layout({
            'yaxis': {
                'fixedrange': True
            },
            'showlegend': True,
            'title': 'Zoom to select the date interval:'
        })

        return {'data': trace, 'layout': layout}

    @dashboard.callback(dash.dependencies.Output('ts_by_appdate', 'figure'), [
        dash.dependencies.Input('idate_slider', 'value'),
        dash.dependencies.Input('submit-button', 'n_clicks')
    ], [
        dash.dependencies.State('url', 'pathname'),
        dash.dependencies.State('ts_snapshot', 'relayoutData')
    ])
    def ts_by_appdate(idx, n_clicks, url_string, graphdata):
        if n_clicks == 0:
            return {'data': [], 'layout': {}}

        fromdate, todate = unpack_dates(graphdata)
        idx = idx if idx else 0

        id_serie = parse_url(url_string)
        ts_final = tsa.get(id_serie,
                           from_value_date=fromdate,
                           to_value_date=todate)
        versions = history(id_serie, fromdate, todate)
        idates = list(versions.keys())

        if idx > len(idates):
            # may happen when the input div are not refreshed at the same time
            idx = len(idates) - 1

        insert_date = idates[idx]
        ts_unti_now = versions[insert_date]

        traces = []
        # all versions
        for idate in idates:
            ts = versions[idate].loc[fromdate:todate]
            # plolty does not plot a line with only one point
            mode = 'lines' if len(ts) > 1 else 'markers'
            color = COLOR_BEFORE if idate <= insert_date else COLOR_AFTER
            traces.append(
                go.Scatter(x=ts.index,
                           y=ts.values,
                           text=[str(elt) for elt in ts.index],
                           name=idate,
                           showlegend=False,
                           mode=mode,
                           line={'color': color},
                           opacity=0.2))

        # final snapshot
        traces.append(
            go.Scatter(x=ts_final.index,
                       y=ts_final.values,
                       name='last',
                       text=[str(elt) for elt in ts_final.index],
                       mode='lines',
                       line={'color': COLOR_LAST},
                       opacity=1))

        # ts as of
        mode = 'lines' if len(ts_unti_now) > 1 else 'markers'
        traces.append(
            go.Scatter(
                x=ts_unti_now.index,
                y=ts_unti_now.values,
                text=[str(elt) for elt in ts_unti_now.index],
                name=str(pd.to_datetime(insert_date)),
                mode=mode,
                line={'color': COLOR_CURRENT},
            ))

        tsminvalue = min(ts.values.min() for ts in versions.values()
                         if len(ts))
        tsmaxvalue = max(ts.values.max() for ts in versions.values()
                         if len(ts))

        return {
            'data':
            traces,
            'layout':
            go.Layout(
                hovermode='closest',
                xaxis={'range': [ts_final.index.min(),
                                 ts_final.index.max()]},
                yaxis={'range': [tsminvalue, tsmaxvalue]},
                title='{} <br>Insertion date : {}'.format(
                    id_serie, insert_date),
                shapes=[{
                    'type': 'line',
                    'x0': insert_date,
                    'y0': tsminvalue,
                    'x1': insert_date,
                    'y1': tsmaxvalue,
                    'line': {
                        'dash': 'dot',
                        'color': 'rgb(0, 0, 0)',
                        'width': 1
                    }
                }])
        }

    @dashboard.callback(
        dash.dependencies.Output('ts_by_insertdate', 'figure'),
        [dash.dependencies.Input('ts_by_appdate', 'hoverData')], [
            dash.dependencies.State('url', 'pathname'),
            dash.dependencies.State('ts_snapshot', 'relayoutData')
        ])
    def ts_by_insertdate(hoverdata, url_string, graphdata):
        id_serie = parse_url(url_string)
        if id_serie is None:
            return {'data': [], 'layout': {}}

        date_str = hoverdata['points'][0]['text']
        if date_str is None:
            return {'data': [go.Scatter()], 'layout': go.Layout()}

        fromdate, todate = unpack_dates(graphdata)

        versions = history(id_serie, fromdate, todate)
        index = []
        values = []

        lastvalue = None
        dt = pd.to_datetime(date_str)
        for idate, ts in sorted(versions.items()):
            if dt in ts.index:
                value = ts[dt]
                if value == lastvalue:
                    continue
                index.append(idate)
                values.append(value)
                lastvalue = value

        traces = [
            go.Scatter(
                x=index,
                y=values,
                name=date_str,
                mode='lines',
                line={'color': ('rgb(20, 180, 40)')},
            )
        ]

        return {
            'data':
            traces,
            'layout':
            go.Layout(
                hovermode='closest',
                title='Application date : {}'.format(date_str),
            )
        }
示例#6
0
def get_layout(app):
    row_0 = Div([
        H2("Upload to Database (excel file)", style={'textAlign': 'left'}),
        Upload(
            id='upload-data',
            children=Div(['Drag and Drop or ',
                          A('Select Files')]),
            style={
                'width': '100%',
                'height': '60px',
                'lineHeight': '60px',
                'borderWidth': '1px',
                'borderStyle': 'dashed',
                'borderRadius': '5px',
                'textAlign': 'center',
                'margin': '10px'
            },
            # Allow multiple files to be uploaded
            multiple=False),
        Loading(
            id="loading",
            children=[Div(id='output-data-upload')],
            type="default",
        ),
    ])
    row_1 = Div([
        Div([
            H2("Text input", style={'textAlign': 'left'}),
            RadioItems(id='radio1',
                       options=[{
                           'label': 'Partial match',
                           'value': 'PMATCH'
                       }, {
                           'label': 'Exact match',
                           'value': 'EMATCH'
                       }],
                       value='EMATCH',
                       labelStyle={
                           'display': 'inline-block',
                       }),
            Input(id="input1", type="text", placeholder="Query"),
            Br(),
            Button('Start text search', id='button')
        ],
            className='col-6'),
        Div([
            H2("Search field", style={'textAlign': 'left'}),
            RadioItems(id='radio2',
                       options=[{
                           'label': 'Chemical name',
                           'value': 'NAME'
                       }, {
                           'label': 'CAS Number',
                           'value': 'CAS'
                       }, {
                           'label': 'IASO Barcode No.',
                           'value': 'BAR'
                       }],
                       value='NAME',
                       labelStyle={
                           'display': 'inline-block',
                       }),
        ],
            className='col-6')
    ],
                className='row')
    row_2 = Div([
        Div([
            H2("Graphical search type", style={'textAlign': 'left'}),
            RadioItems(id='radio3',
                       options=[{
                           'label': 'Similarity ',
                           'value': 'SIM'
                       }, {
                           'label': 'Substructural ',
                           'value': 'SUB'
                       }, {
                           'label': 'Exact ',
                           'value': 'EX'
                       }],
                       value='SIM',
                       labelStyle={
                           'display': 'inline-block',
                       }),
            DashMarvinJS(id='editor',
                         marvin_url=app.get_asset_url('mjs/editor.html'),
                         marvin_width='100%')
        ],
            className='col-6'),
        Div([
            H2("Search results", style={'textAlign': 'left'}),
            DataTable(
                id='table',
                columns=fields1,
                fixed_rows={
                    'headers': True,
                    'data': 0
                },
                row_selectable='single',
                style_data={
                    'whiteSpace': 'normal',
                    'height': 'auto',
                    'width': 'auto'
                },
                style_table={
                    'overflowY': 'hidden',
                    'overflowX': 'hidden',
                    'margin-left': '0px'
                },
                style_cell={
                    'textAlign': 'left',
                    'padding': '5px',
                    'height': 'auto',
                    'padding-left': '17px',
                    'whiteSpace': 'normal',
                    'minWidth': '10px',
                    'maxWidth': '150px'
                },
                style_as_list_view=True,
                style_cell_conditional=[
                    {
                        'if': {
                            'column_id': 'Picture'
                        },
                        'width': '60%'
                    },
                    {
                        'if': {
                            'column_id': 'Brutto formula'
                        },
                        'width': '10%'
                    },
                    {
                        'if': {
                            'column_id': 'Chemical name'
                        },
                        'width': '15%'
                    },
                    {
                        'if': {
                            'column_id': 'CAS No.'
                        },
                        'width': '10%'
                    },
                ],
            )
        ],
            className='col-6')
    ],
                className='row')
    row_3 = DataTable(
        id='table2',
        columns=fields2,
        fixed_rows={
            'headers': True,
            'data': 0
        },
        #row_selectable='single',
        editable=True,
        row_deletable=True,
        style_data={
            'whiteSpace': 'normal',
            'height': 'auto'
        },
        style_table={
            'maxHeight': '500px',
            'overflowY': 'hidden',
            'overflowX': 'hidden',
            'margin-left': '0px'
        },
        style_cell={
            'textAlign': 'left',
            'padding': '10px',
            'padding-left': '20px',
            'height': 'auto',
            'whiteSpace': 'normal',
            'minWidth': '120px',
            'width': '150px'
        },
        #style_cell_conditional=[
        #    {'if': {'column_id': 'Quantity'},
        #     'width': '150px'},
        #   {'if': {'column_id': 'Quantity unit'},
        #     'width': '150px'},
        #],
        style_as_list_view=True)
    row_4 = Div([
        Button('Add Row', id='addrow', n_clicks=0),
        Button('Submit changes', id='submit', n_clicks=0),
        ConfirmDialog(
            id='confirm',
            message=
            'All changes will be applied from now! Are you sure you want to continue?',
        )
    ])

    layout = Div([
        H1("Chemicals Storage", style={'textAlign': 'center'}), row_0,
        Hr(), row_1,
        Hr(), row_2,
        Hr(), row_3,
        Hr(), row_4
    ])
    return layout
示例#7
0
    def update():
        
        if request.endpoint == url_base:
            app.index_string = render_template(
                'data_page.html'
            )
            rv = rv_plot.public
            curr_user = g.user['atype']
            if curr_user == 'admin' or curr_user == 'researcher':
                rv = rv_plot.data
            app.layout = Div([
                Tooltip(
                    "Set the Y axis to a linear or logarithmic scale.",
                    target="log-switch",
                ),
                Tooltip(
                    "Enables data to be separated by order on the spectrograph",
                    target="dim-switch",
                ),
                Tooltip(
                    "The name of the file being displayed",
                    target="click-data",
                    placement="bottom"
                ),
                Tooltip(
                    "Selects which orders of the spectrum to render",
                    target="order-tool",
                ),
                Tooltip(
                    "Reduces the amount of points rendered to the screen",
                    target="res-tool",
                ),
                Tooltip(
                    "Each graph has a tool bar in the upper-right hand corner that appears when you mouse over a graph."
                    "Use the buttons in the tool bar to zoom in, zoom out, reset the axis, save a screen shot, "
                    "and more. Click on a point in the Radial Velocity graph to display the Spectrum graph below."  
                    "Hover over the slider and toggle bottoms below the lower graph to further interact with the"
                    "spectrum data.",
                    target="graph-tool"
                ),
                Loading([
                    Div([
                        Button([
                                I(
                                    className="fas fa-info-circle",
                                ),
                                Span(
                                    ' Info',
                                )
                            ],
                            id='graph-tool',
                            className='btn btn-warning btn-sm',
                        ),
                    ]),
                    Div(
                        id='rv-download-container'
                    ),
                    Button([
                            I(
                                className="fas fa-download",
                            ),
                            Span(
                                " Download Radial Velocities",
                            )
                        ],
                        id='rv-download',
                        className='btn btn-primary btn-sm float-right',
                    ),
                    Download(
                        id='rv-download-data'
                    ),
                    DatePickerRange(
                        id='date-range',
                        className='pt-1 d-flex justify-content-end w-100',
                    ),
                    Graph(
                        id='rv-plot',
                        className="",
                        config={
                            'modeBarButtonsToRemove': ['pan2d', 'lasso2d', 'autoscale']
                        }
                    ),
                    
                ], type="default", className='d-flex justify-content-end w-100'),
                Div(
                    id='rv-data',
                    children=rv[rv_label].to_json(),
                    className='d-none'
                ),
                Div([
                    Pre(id='click-data', className=' d-inline'),
                ]),
                
                
                Br(),
                Br(),
                Div([
                    Loading([
                        Div([
                            Div([
                                Button([
                                        I(
                                            className="fas fa-download",
                                        ),
                                        Span(
                                            " Download 1D",
                                        )
                                    ],
                                    id='1d-spec-download',
                                    className='btn btn-primary btn-sm',
                                ),

                                Download(
                                    id='1d-spec-download-data'
                                ),
                            ], className='pr-2'),
                            Div([
                                Button([
                                    I(
                                        className="fas fa-download",
                                    ),
                                    Span(
                                        " Download 2D",
                                    )],
                                    id='2d-spec-download',
                                    className='btn btn-primary btn-sm',
                                ),

                                Download(
                                    id='2d-spec-download-data'
                                ),
                            ], className=""),
                        ], className="row justify-content-end d-none", id="spec-download-container"),
                        Div(
                            id='spec-data',
                            children=[],
                            className='d-none'
                        ),
                        Graph(
                            id='spec-plot',
                            className="pt-0",
                            config={
                                'modeBarButtonsToRemove': ['pan2d', 'lasso2d', 'autoscale']
                            }
                        ),
                    ], type="default", ),


                    Div([
                        Span([
                            'Order Range\n'
                        ], id='order-tool', className='d-none'),
                        Span([
                            'Resolution\n'
                        ], id='res-tool', className='d-none')
                    ],
                    id='slide-label',
                    className='w-100 text-center'),


                    Div([
                        
                        Slider(
                            min=1,
                            max=200,
                            value=100,
                            marks={
                                1: {'label': '1:1', 'style': {'color': '#77b0b1'}},
                                20: {'label': '20:1'},
                                50: {'label': '50:1'},
                                100: {'label': '100:1'},
                                200: {'label': '200:1', 'style': {'color': '#f50'}}
                            },
                            id='resolution',
                            className='col d-none',
                        ),
                        RangeSlider(
                            id='spec-range',
                            className='col d-none',
                            min=0,
                            max=85,
                            step=1,
                            value=[40, 45],
                            marks={
                                0: {'label': '0'},
                                40: {'label': '40'},
                                45: {'label': '45'},
                                85: {'label': '85'}
                            }
                        ),
                    ], className='row'),
                ], id='spec-container'),
                Br(),
                Div([
                    Div([
                        daq.ToggleSwitch(
                            label='lin/log',
                            id='log-switch',
                            className='d-inline-block',
                            labelPosition='bottom'
                        ),
                    ], className='col text-center'),
                    Div([
                        daq.ToggleSwitch(
                            label='1D / 2D',
                            id='dim-switch',
                            className='d-inline-block',
                            labelPosition='bottom'
                        )
                    ], className='col text-center'),
                ], className="row")
            ])