Пример #1
0
 def buildTweet(self, text, timeString, topic, senti):
     sentimentDiv = self.buildSentimentDiv(senti)
     timeIso = datetime.datetime.fromtimestamp(
         int(timeString) / 1000).strftime('%A, %d. %B %Y %I:%M%p')
     tweet = html.Div([
         html.Blockquote([
             html.Div([
                 html.Div([
                     html.Img(
                         src='/static/Twitter_Social_Icon_Circle_Color.svg',
                         className='Icon')
                 ],
                          className='Tweet-brand'), sentimentDiv
             ],
                      className='Tweet-header'),
             html.Div([
                 html.P([text], className='Tweet-text'),
                 html.Div(['{} - {}'.format(timeIso, topic.upper())],
                          className='Tweet-metadata')
             ],
                      className='Tweet-body')
         ])
     ],
                      className='EmbeddedTweet',
                      style={'border-color': self.colors[topic]})
     return tweet
Пример #2
0
def quote_block():
    return dbc.Row([
        dbc.Col([
            html.Blockquote(children=[
                html.
                P("116th congress. 1st session s. 1426. to amend the endangered species act of 1973. to establish a procedure for approval of certain settlements. in the senate of the united states may 13, 2019 mr. cornyn (for himself, mr. boozman, mr. crapo, mr. cruz, mr. enzi, mr. lankford, mr. risch, mr. sullivan, and mr. wicker) introduced the following bill; which was read twice and referred to the committee on environment and public works a bill to amend the endangered species act of 1973 to establish a procedure for approval of certain settlements.\n"
                  )
            ])
        ],
                md=8)
    ],
                   justify="center")
Пример #3
0
def generate_table(df, max_rows=30):
    return html.Div(children=[
        html.H3("Tweets by Sentiment"),
        html.Div([
            html.Blockquote(
                children=[
                    html.P(d[1]),
                    html.Span(d[0].strftime("%d/%m/%Y")),
                ],
                style={'box-shadow': ' 1px 1px 4px' + quick_color(d[2])},
                className="row twitter-tweet") for d in df.values.tolist()
        ],
                 className="tweet_storm")
    ])
Пример #4
0
def resume_tweets(df, type='share'):

    list_twt = []

    for i in list(range(30)):

        user = df['id_user'].to_list()[i]
        tweet = int(df['tweet_id'].to_list()[i])
        is_rt = df['is_RT'].to_list()[i]

        link = df['retweeted_url'].to_list()[i]

        if link == None:
            link = df['quote_url'].to_list()[i]
        else:
            pass

        if link == None:
            link = "https://twitter.com/{user}/status/{tweet}"
        else:
            pass

        if type == 'share':
            text = f"#{i+1} Most Shared - Total Shares: {df['count'].to_list()[i]} "
        else:
            text = f"#{i+1} Most Retweeted - Total Shares: {df['count'].to_list()[i]}"
        list_twt.append(
            html.Div([
                html.Div(f"{text}",
                         style={
                             'textAlign': 'center',
                             'fontWeight': 'bold',
                             "direction": "ltr",
                             'fontSize': '18px'
                         }),
                html.Blockquote(html.A(href=link),
                                className="twitter-tweet",
                                style={'width': "498px"})
            ],
                     style={"margin": "48px 0"}))

    list_twt.append(visdcc.Run_js(id="javascript", run="twttr.widgets.load()"))

    return list_twt
Пример #5
0
    def update_contents(self, new_store_contents):

        struct = self.from_data(new_store_contents)

        condenser = StructureCondenser()
        describer = StructureDescriber()

        condensed_structure = condenser.condense_structure(struct)

        description = describer.describe(condensed_structure)

        return html.Blockquote(
            [
                f"{description} – ",
                html.A(
                    f"🤖 robocrys v{robocrys_version}",
                    href="https://github.com/hackingmaterials/robocrystallographer",
                    style={"white-space": "nowrap"},
                ),
            ],
            className="mpc-blockquote",
        )
def update_output(value):
    if value == None:
        return (html.H1(
            children='Twitter Analysis, Please select a Twitter User above.'))

    df, df_2, tweet_counts_by_week = generate_dataframe(value)

    return (html.H1(children='Twitter Analysis: @' + df['user'][0]),
            html.Div(className="tweet_storm twelve columns",
                     children=[
                         html.Blockquote(
                             className="twitter-tweet",
                             children=[
                                 html.H3(children='Most Liked Tweet'),
                                 html.H3(className="twitter-tweet--handle",
                                         children='@' + df['user'][0]),
                                 html.P(children=df['most_liked_tweet'])
                             ]),
                         html.Blockquote(
                             className="twitter-tweet",
                             children=[
                                 html.H3(children='Least Liked Tweet'),
                                 html.H3(className="twitter-tweet--handle",
                                         children='@' + df['user'][0]),
                                 html.P(children=df['least_liked_tweet'])
                             ]),
                         html.Blockquote(
                             className="twitter-tweet",
                             children=[
                                 html.H3(children='Most retweeted Tweet'),
                                 html.H3(className="twitter-tweet--handle",
                                         children='@' + df['user'][0]),
                                 html.P(children=df['most_retweeted_tweet'])
                             ])
                     ]),
            html.Div(
                className="twelve columns",
                children=[
                    html.Div(children=[
                        dcc.Graph(id='num_likes',
                                  figure={
                                      'data': [
                                          go.Bar(x=df['tweet_day_of_week'],
                                                 y=df['likes'],
                                                 marker={'color': '#1DA1F2'},
                                                 name='Num Likes'),
                                          go.Bar(x=df['tweet_day_of_week'],
                                                 y=df['retweet_count'],
                                                 marker={'color': '#F7A52D'},
                                                 name='Num Retweets')
                                      ],
                                      'layout':
                                      go.Layout(hovermode='closest',
                                                title='Likes vs Retweets')
                                  }),
                    ],
                             className='six columns'),
                    html.Div(children=[
                        dcc.Graph(id='num_tweets',
                                  figure={
                                      'data': [
                                          go.Bar(
                                              x=tweet_counts_by_week.index,
                                              y=tweet_counts_by_week['tweets'],
                                              text='Tweets per Week',
                                              marker={'color': '#1DA1F2'})
                                      ],
                                      'layout':
                                      go.Layout(hovermode='closest',
                                                title='Tweets per Week')
                                  }),
                    ],
                             className='six columns'),
                ]),
            html.Div(children=[
                dcc.Graph(id='num_tweets_by_hour',
                          figure={
                              'data': [
                                  go.Bar(x=df_2['tweet_hour'],
                                         y=df_2['tweets'],
                                         text='Tweets per Hour',
                                         marker={'color': '#1DA1F2'})
                              ],
                              'layout':
                              go.Layout(hovermode='closest',
                                        title='Tweets per Hour')
                          }),
            ],
                     className="six columns no_margin--left"),
            html.Div(children=[
                html.H3(children='Tweet Content Analysis'),
                dcc.Slider(id='sentiment_polarity',
                           min=-1,
                           max=1,
                           marks={
                               -1: {
                                   'label': 'Very Negative',
                                   'style': {
                                       'color': '#ce2939'
                                   }
                               },
                               -0.5: 'Slightly Negative',
                               0: 'Neutral',
                               0.5: 'Slightly Positive',
                               1: {
                                   'label': 'Very Positive',
                                   'style': {
                                       'color': '#1876fb'
                                   }
                               }
                           },
                           value=df['sentiment'].mean(),
                           step=0.2,
                           included=False),
            ],
                     className='sliders twelve columns'),
            html.Div(children=[
                dcc.Slider(id='subjectivity',
                           min=-1,
                           max=1,
                           marks={
                               -1: 'Very Subjective',
                               -0.5: 'Slightly Subjective',
                               0: 'Neutral',
                               0.5: 'Slightly Objective',
                               1: 'Very Objective'
                           },
                           value=df['subjectivity'].mean(),
                           step=0.2,
                           included=False)
            ],
                     className='sliders twelve columns'))
app = dash.Dash(external_stylesheets=external_stylesheets)

#Layout app graphs that have to be full screen width are a div on its own, one table left and one right is one div together.

app.layout = html.Div(children=[

    #Title and subtitle
    html.Div([
        html.H1(children="Find your favorite beer"),
        html.H2(children="Enter a beer you like!")
    ]),

    #Introduction text for the users
    html.Div([
        html.Blockquote(
            "In the Netherlands there are a great amount of great breweries, to explore new beers just enter a beer you like, the system would recommend you other beers that are good for you"
        )
    ]),
    dcc.Dropdown(id="selection",
                 options=[{
                     "label": "All",
                     "value": "All"
                 }, {
                     "label": "Texelse bierbrouwerij Overzee IPA",
                     "value": "Overzee IPA"
                 }, {
                     "label": "Texelse bierbrouwerij Skuumkoppe",
                     "value": "Skuumkoppe"
                 }, {
                     "label": "Texelse bierbrouwerij Wit",
                     "value": "Wit"
Пример #8
0
                id="top_N",
                type="number",
                value=10,
                placeholder="input number",
            ),
        dcc.Graph(id='graph')
        ],style={'width': '48%', 'display': 'inline-block'}),

    html.Div([
         html.P("Select the sentence you want to search."),
         dcc.Dropdown(
                id="target_sentence",
                options=[{'label': t, 'value': i} for i,t in enumerate(option_list)],
                value=0
            ),
         html.Blockquote(id='text_output', style={'backgroundColor':"#DCDCDC"}),
         html.H2("Selected references"),
         html.P(["Shift+click will accumulate the selected reference. You can also use ", html.I("Box Select "), "or ", html.I("Lasso Select "), "to select multiple references."]),
        #  html.Table([
        #      html.Tr([html.Th(["URL", "assignee", "priority_date", "abstract"])]),
        #      html.Tr([html.Td(id='table')])
        #      ]),
         html.Div([html.Div(id='table')])
        ],style={'width': '48%', 'float': 'right', 'display': 'inline-block'})
])

@app.callback(
    Output(component_id='graph', component_property='figure'),
    [Input(component_id='top_N', component_property='value'),
    Input(component_id='target_sentence', component_property='value')])
def update_figure(top_N, target_sentence):
app.layout = html.Div(children = [
html.Div(className = "text-center p-3 mb-2 bg-dark text-white",children = [
        html.H1(className = ".text-secondary display-2 ",children = [
            'Mutual Fund - Allocation'
            ]),
        html.P(children = ["Analysis Done by ",html.Mark(html.A('Syed Shahab Uddin', href = 'https://github.com/syedshahab698/'))])
        
        ]),    
html.Div([    
    
    
    html.Div(className = "text-center p-3 mb-2",children = [
        html.Blockquote(className = "blockquote text-center",children = [
            html.P(className = "mb-0", children = """A mutual fund can do for you
                   what you would do for yourself if you had sufficient time, training and money
                   to diversify, plus the temperament to stand back from your money and make rational decisions.
                   """),
                   html.Br(),
           html.Footer(className = "blockquote-footer", children="Venita VanCaspel")
            ])
        ]),
    html.Div(className = "text-center d-inline", children = [
        html.Article(children = [
            html.H3(className = "p-3",children = "INTERESTED MUTUAL FUNDS"),
            html.Article(className = "p-3 d-inline",children =[
                html.P(className = "p-3 mb-0 d-inline",children ="  Edelweiss Balanced Advantage Fund  "),
                html.P(className = "m-3 mb-1 d-inline",children ="  ICICI Pru Balanced Advantage Fund  "),
                html.P(className = "m-3 d-inline",children ="  ICICI Savings Fund  "),
                html.P(className = "m-3 d-inline",children ="  Kotak Low Duration Fund  "),
                html.P(className = "m-3 d-inline",children ="  Tata Balanced Adv Fund  "),
                ] )
            ]),
Пример #10
0
    # Plot of temperature. Dropdown to toggle between °F and °C.
    html.Div([
        html.Div([dcc.Graph(id='temp-vs-time', )], className="eight columns"),
        html.Div([
            html.Div(dcc.Dropdown(id='temp-unit-picker',
                                  options=[{
                                      'label': '°F',
                                      'value': 'temp_f'
                                  }, {
                                      'label': '°C',
                                      'value': 'temp_c'
                                  }],
                                  value='temp_f'),
                     className="row"),
            html.Blockquote(id='curr-sensor-temp', className="row"),
            html.Blockquote(id='curr-outside-temp', className="row")
        ],
                 className="three columns",
                 style={'position': 'relative'}),
    ],
             className="row"),
    html.Div([html.H3('Humidity')], className="row"),

    # Plot of humidity.
    html.Div([
        html.Div([dcc.Graph(id='humid-vs-time', )], className="eight columns"),
        html.Div([], className="four columns")
    ],
             className="row"),
    html.Div([html.H3('Air Quality Index')], className="row"),
Пример #11
0
                     'display': 'inline-block'
                 }),
        html.Div([html.H2(id='jay-true')],
                 style={
                     'width': '33%',
                     'display': 'inline-block'
                 }),
        html.Div([html.H2(id='hamilton-true')],
                 style={
                     'width': '33%',
                     'display': 'inline-block'
                 })
    ]),
    html.Br(),
    html.H2(id='title-name'),
    html.Blockquote(id='paragraph-output-id', style={'textAlign': 'left'})
],
                      style={'textAlign': 'center'})

##### APP OUTPUTS/CALLBACKS


# CONSTITUTION PLACEHOLDER IMAGE
@app.callback(
    Output(component_id='placeholder-image-id', component_property='src'),
    [Input(component_id='dropdown-id', component_property='value')])
def update_true_image(value):
    if value in list(df['Indicator Name']):
        return None
    else:
        src_name = "static/constitution.png"
Пример #12
0
    html.Div(id='page-content'),
], className='navbar navbar-inverse navbar-static-top')

# Define layout
app.layout = html.Div([
    dcc.Location(id='url', refresh=False),
    nav_menu,
    html.Div([
        # HTML code for the homepage
        html.Div([
            html.Img(src=app.get_asset_url('juve.jpg'), className='stadium'),
            html.H1(children='Footy Dash.', id='h1home'),
            html.Blockquote(children='''
            Welcome to Footy Dash, a football data visualization website.
            The data displayed has been curated from various parts of the web, 
            in order to provide readers accurate and concise Football information. 

            *Under Construction* 
            '''),
            html.Footer(children='Created by Salvatore Architetto: https://github.com/salarchitetto', id='home-footer')],
            id='home'),
        html.Div([
            html.Div([
                html.Div([
                    html.P(children='Choose Criteria Here', id='h4stats'),
                    html.Button(id='win_pct_button', n_clicks=0, children='Show win-tie-loss % for your team.',
                                className='btn btn-primary'),
                    dcc.Dropdown(id='countries', options=countryDropdown, placeholder='Please select a country.'),
                    dcc.Dropdown(id='divisions', placeholder='Choose a division', options =[]),
                    dcc.Dropdown(id='indi-teams', placeholder='choose a team', options=[]),
                    html.Br(),
Пример #13
0
def update_bezos_text(n):
    ytd_td = datetime.datetime.now() - datetime.datetime(2020, 1, 1)
    ytd_seconds = ytd_td.total_seconds()
    bezos_secondly = round(amzn_df.iloc[-1].bezos_year / ytd_seconds)
    bezos_tot = bezos_secondly * n
    unemp_secondly = round(
        sum(unemp_df.unemployment[-3:]) / (3 * 7 * 24 * 60 * 60), 1)

    bezos_txt = [
        dbc.Alert([
            f'Hi, you have been on this page for ',
            dbc.Badge(f'{n} seconds', color="primary", className="mr-1"),
            '. In that time:'
        ],
                  color="info")
    ]

    card_content_worth = [
        dbc.CardHeader(f"Bezos' net worth has increased by: "),
        dbc.CardBody([
            html.H3(
                [dbc.Badge(f"US${int(bezos_secondly * n)}", color='success')],
                className="card-title"),
            html.P(
                [
                    f"That is ",
                    dbc.Badge(str(round(bezos_tot / median_us_income, 1)),
                              color='primary'),
                    " typical U.S. incomes' worth of money."
                ],
                className="card-text",
            ),
        ])
    ]

    card_content_unemp = [
        dbc.CardHeader(f"Meanwhile, just in the U.S.:"),
        dbc.CardBody([
            html.H5([
                dbc.Badge(f"{int(unemp_secondly * n)}", color='danger'),
                " unemployment filings were made"
            ],
                    className="card-title"),
            html.P(
                f"{round(sum(unemp_df.unemployment[-3:])/10**6, 1)} million people filed for unemployment in the U.S. in the last 3 weeks. ",
                className="card-text",
            ),
        ])
    ]

    card_content_inc_stats = dbc.CardBody([
        html.Blockquote(
            [
                html.P(
                    html.Small(f"The typical (median) per-person income is:"),
                    className="text-muted"),
                html.
                P(f"US${median_world_income} world-wide, and US${median_us_income} in the United States."
                  ),
                html.Footer(
                    html.Small([
                        'Stats: ',
                        html.
                        A("U.S.",
                          href=
                          "https://fred.stlouisfed.org/series/MEPAINUSA672N"),
                        ', ',
                        html.
                        A("World",
                          href=
                          "https://news.gallup.com/poll/166211/worldwide-median-household-income-000.aspx"
                          )
                    ]), ),
            ],
            className="blockquote",
        )
    ])

    card_content_unemp_stats = dbc.CardBody([
        html.Blockquote(
            [
                html.P(html.Small(
                    f"Typically, 1 to 1.2 million people file for unemployment benefits every month in the United States."
                ),
                       className="text-muted"),
                html.
                P(f"The current figure ({round(sum(unemp_df.unemployment[-3:])/10**6, 1)} million in 3 weeks) is about {round(sum(unemp_df.unemployment[-3:])/(0.9*10**6), 1)} times the normal and unprecedented."
                  ),
                html.Footer(
                    html.Small([
                        html.A("Source",
                               href="https://fred.stlouisfed.org/series/ICSA")
                    ]), ),
            ],
            className="blockquote",
        )
    ])

    card_content_bezos_donations = [
        dbc.CardHeader(f"Bezos' total COVID-19 donations:"),
        dbc.CardBody([
            html.H5([
                "Is about ",
                dbc.Badge(
                    f"{round(100 * 10**6 / (bezos_secondly * 60 * 60 * 24), 2)}",
                    color='warning'), " days' earnings"
            ],
                    className="card-title"),
            html.P(
                [
                    f"He has pledged about US$100m to food banks, while his net worth has increased about ",
                    dbc.Badge(
                        str(round(amzn_df.iloc[-1].bezos_year / 10**9, 1)),
                        color='success'), " billion U.S. dollars this year. "
                ],
                className="card-text",
            ),
        ])
    ]

    card_content_donations_info = dbc.CardBody([
        html.Blockquote(
            [
                html.P(html.Small(
                    f"By contrast, Jack Dorsey, Twitter and Square CEO, has donated $1bn to COVID-19 relief."
                ),
                       className="text-muted"),
                html.
                P(f"Dorsey's donation is estimated to be about 28% of his net worth, vs Bezos' 0.075% donation"
                  ),
                html.Footer(
                    html.Small([
                        html.A("Source",
                               href="https://fred.stlouisfed.org/series/ICSA")
                    ]), ),
            ],
            className="blockquote",
        )
    ])

    cards = dbc.CardColumns([
        dbc.Card(card_content_worth, color="success", outline=True),
        dbc.Card(card_content_inc_stats, color="secondary", outline=True),
        dbc.Card(card_content_unemp, color="danger", outline=True),
        dbc.Card(card_content_unemp_stats, color="warning", outline=True),
        dbc.Card(card_content_bezos_donations, color="warning", outline=True),
        dbc.Card(card_content_donations_info, color="info", outline=True),
    ])

    bezos_txt.append(cards)

    return bezos_txt
Пример #14
0
                     children=[
                         dcc.Markdown(
                             children=JHCCU_TITLE,
                         ),
                     ],    
                 ),
                 dbc.ModalBody(
                     children=[
                         dcc.Markdown(JHCCU_INFO_TEXT),
                     ]
                 ),
                 dbc.ModalFooter(
                     className='text-right',
                     children=[
                         html.Blockquote(
                             html.Cite('created by Jan Macenka',)
                         ),
                         dbc.Button("Close", id="close-info-modal", className="ml-auto"),
                     ]
                 ),
             ],
         ),
         html.Hr(
             className="my-2"
         ),
     ],
 ),
 dcc.Tab(
     id='data-visualization-tab',
     label='Data-Visualization',
     children=[
Пример #15
0
            html.P(
                "This is some card content that we'll reuse",
                className="card-text",
            ),
        ]
    ),
]

card_content_2 = dbc.CardBody(
    [
        html.Blockquote(
            [
                html.P(
                    "A learning experience is one of those things that says, "
                    "'You know that thing you just did? Don't do that.'"
                ),
                html.Footer(
                    html.Small("Douglas Adams", className="text-muted")
                ),
            ],
            className="blockquote",
        )
    ]
)

card_content_3 = [
    dbc.CardImg(src="/assets/images/placeholder286x180.png", top=True),
    dbc.CardBody(
        [
            html.H5("Card with image", className="card-title"),
            html.P(
                "This card has an image on top, and a button below",
Пример #16
0
import dash_core_components as dcc
import dash_html_components as html

WorkspaceBlurb = html.Div([
    html.Blockquote([
        dcc.Markdown('''
        Write, deploy, and scale Dash apps on a Dash Enterprise Kubernetes cluster.
        
        [Pricing](https://plotly.com/get-pricing/) | 
        [Dash Enterprise Demo](https://plotly.com/get-demo/) | 
        [Dash Enterprise Overview](https://plotly.com/dash/)
        '''),
    ])
])
Пример #17
0
PAGE_SIZE = 10

app.layout = html.Div([
    html.Div([], style={
        'width': '5%',
        'display': 'inline-block'
    }),
    html.Div([
        html.Div([
            html.Br(),
            html.H1('Cooking Recipe Dashboard',
                    style={
                        'color': '#003B73',
                        'textAlign': 'left'
                    }),
            html.Blockquote('Individual MA705 Project | Kremena Ivanov',
                            style={'textAlign': 'left'}),
            html.B('What is this dashboard about?',
                   style={
                       'color': '#003B73',
                       'textAlign': 'left'
                   }),
            html.Section(text, style={'textAlign': 'left'}),
            html.Section(text_l1),
            html.Section(text_l2),
            html.Section(text_l3),
        ]),
        html.Hr(),
        html.Div([
            html.B('How to use this dashboard?',
                   style={
                       'color': '#003B73',
Пример #18
0
        html.Img(src='/assets/images/dds/{}-logo.png'.format(vendor)),
        html.Div('Install Dash Enterprise on {}'.format(vendor),
                 className='label')
    ],
                  href='https://plotly.com/dash/{}'.format(vendor),
                  className='azure')


WorkspaceBlurb = html.Div([
    html.Blockquote([
        dcc.Markdown('''
        Dash Enterprise is the fastest way to write & deploy Dash apps and
        Jupyter notebooks. Dash Enterprise can be installed on the Kubernetes
        services of
        [AWS](https://go.plotly.com/dash-aws),
        [Azure](https://go.plotly.com/dash-azure),
        GCP,
        or an
        [on-premise Linux Server](https://plotly.com/dash/on-premises-linux/?utm_source=docs&utm_medium=workspace&utm_campaign=nov&utm_content=linux).
        10% of the Fortune 500 uses Dash Enterprise to productionize AI and data science apps.
        [Find out if your company is using Dash Enterprise](https://go.plotly.com/company-lookup)
        '''),
        html.Div([
            image('Azure'),
            html.Div(className='spacer'),
            image('AWS'),
        ],
                 className='azure-parent')
    ])
])
Пример #19
0
 [
     dbc.CardHeader(html.H2("Blockquotes and text alignment")),
     dbc.CardBody(
         [
             dbc.Row(
                 [
                     dbc.Col(
                         [
                             html.Blockquote(
                                 [
                                     html.P(
                                         "We interrupt this program to annoy you and make things generally more irritating.",
                                         className="mb-0",
                                     ),
                                     html.Footer(
                                         html.Cite(
                                             "Monty Python and the Holy Grail",
                                             title="Source Title",
                                         ),
                                         className="blockquote-footer",
                                     ),
                                 ],
                                 className="blockquote text-left",
                             ),
                         ],
                         className="p-4",
                         width="md-4",
                     ),
                     dbc.Col(
                         [
                             html.Blockquote(
                                 [
Пример #20
0
 html.H4('Attribution',
 style={
     'textAlign': 'left',
     'marginBottom': 25,
     'marginTop': 25,
 }),
 attribution1_md,
 html.Blockquote(
     'Data were provided (in part) by the Electrical Engineering Department, Eindhoven University of Technology, The Netherlands and Kempenhaeghe Epilepsy Center, Heeze, The Netherlands',
     style={
         'borderLeft': '4px solid rgb(98, 186, 181)',
         'paddingLeft': '1rem',
         'paddingRight': '1rem',
         'marginTop': '2rem',
         'marginBottom': '2rem',
         'marginLeft': '10rem',
         'marginRight': '10rem',
         'fontStyle': 'italic',
         'fontSize': '0.85em',
         'backgroundColor': 'rgb(237, 249, 247)',
         'paddingTop': '5px',
         'paddingBottom': '5px'
         
     }
 ),
 attribution2_md,
 html.Blockquote(
     'Heunis, S., Breeuwer, M., Caballero-Gaudes, C., Hellrung, L., Huijbers, W., Jansen, J.F.A., Lamerichs, R., Zinger, S., Aldenkamp, A.P., 2021. rt-me-fMRI: a task and resting state dataset for real-time, multi-echo fMRI methods development and validation. F1000Res 10, 70. https://doi.org/10.12688/f1000research.29988.1',
     style={
         'borderLeft': '4px solid rgb(98, 186, 181)',
         'paddingLeft': '1rem',
         'paddingRight': '1rem',
Пример #21
0
import dash
import dash_html_components as html
import dash_bootstrap_components as dbc

app = dash.Dash(__name__)

app.layout = html.Div(
    dbc.Container(
        html.Blockquote(
            html.P('这是一段由块引用包裹的文字内容' * 10),
            style={
                'background-color': 'rgba(211, 211, 211, 0.25)',
                'text-indent': '3rem'
            }
        )
    )
)

if __name__ == "__main__":
    app.run_server(debug=True)
Пример #22
0
    def update_contents(self, new_store_contents):
        """
        Structure -> mpid -> BibTeX references from MP -> (optional doi lookup
        via Crossref) -> formatting.
        Formatting is very messy right now.
        DOI lookup and (possibly) formatting should be cached in a builder.
        """

        struct = self.from_data(new_store_contents)

        if not isinstance(struct, Structure):
            raise PreventUpdate(
                "Literature mentions can only be retrieved for crystallographic "
                "structures at present and not molecules. Please make a feature "
                "request if this would be useful for you, and it will be "
                "prioritized."
            )

        with MPRester() as mpr:
            mpids = mpr.find_structure(struct)

            if len(mpids) == 0:
                raise PreventUpdate(
                    "No structures in the Materials Project database match this "
                    "crystal structure, so literature mentions cannot be retrieved. "
                    "Please submit this structure to Materials Project if you'd "
                    "like it to be added to the Materials Project database."
                )

            all_references = []
            for mpid in mpids:
                all_references.append(mpr.get_materials_id_references(mpid))
                self.logger.debug(f"Retrieved references for {mpid}.")

        if self.use_crossref:

            cr = Crossref(mailto=CROSSREF_MAILTO)
            individual_references = set()
            for references in all_references:
                individual_references.update(set(references.split("\n\n")))

            # exclude Materials Proect references (these are intended to be
            # references for the structure specifically)
            refs_to_remove = set()
            for ref in individual_references:
                if "Jain2013" in ref:
                    refs_to_remove.add(ref)
            individual_references -= refs_to_remove

            works = [cr.works(query=ref, limit=1) for ref in individual_references]
            self.logger.debug(f"Retrieved {len(works)} works from Crossref.")

            items = [
                work["message"]["items"][0]
                for work in works
                if len(work["message"]["items"]) > 0
            ]

            dois_to_item = {
                item["DOI"]: {
                    "cited-by": item.get("is-referenced-by-count", 0),
                    "score": item["score"],
                    "title": item.get("title", None),
                    "authors": item.get("author", []),
                    "journal": item.get("container-title", [None])[0],
                    "issue": item.get("issue", None),
                    "volume": item.get("volume", None),
                    "pages": item.get("page", None),
                    "date-parts": item.get("issued", {}).get("date-parts", [[None]]),
                }
                for item in items
                if item["score"] > 40
            }

            num_refs = len(dois_to_item)
            sorted_dois = sorted(
                list(dois_to_item.keys()),
                key=lambda doi: -dois_to_item[doi]["cited-by"],
            )

            if self.use_crossref_formatting:
                # use Crossref to retrieve pre-formatted text

                # remove leading "1. " from Science CSL style
                refs = {
                    doi: content_negotiation(ids=doi, format="text", style="science")[
                        3:
                    ]
                    for doi in dois_to_item.keys()
                }
                self.logger.debug(
                    f"Retrieved {len(refs)} formatted references from Crossref."
                )
                md = "  \n\n".join(
                    f"> [{refs[doi]}](https://dx.doi.org/{doi}) "
                    f"Cited by {dois_to_item[doi]['cited-by']}."
                    for doi in sorted_dois
                )
                formatted_references = dcc.Markdown(
                    md, className="mpc-markdown"
                )

            else:
                # else retrieve BibTeX entries to extract a nice author list
                # and perform our own formatting

                entries = {
                    doi: content_negotiation(ids=doi, format="bibtex")
                    for doi in sorted_dois
                }

                formatted_entries = []
                for doi, entry in entries.items():
                    author_string = self._bibtex_entry_to_author_text(entry)
                    journal_div = self._item_to_journal_div(dois_to_item[doi])

                    formatted_entries.append(
                        html.Blockquote(
                            [
                                html.A(
                                    [
                                        html.Div(
                                            [
                                                html.I(
                                                    # necessary since titles can contain HTML for superscripts etc.
                                                    dcc.Markdown(
                                                        dois_to_item[doi]["title"],
                                                        dangerously_allow_html=True
                                                    )
                                                )
                                            ]
                                        ),
                                        html.Div([author_string]),
                                        html.Div(
                                            [
                                                journal_div,
                                                html.Span(
                                                    f" Cited by {dois_to_item[doi]['cited-by']}."
                                                ),
                                            ]
                                        ),
                                    ],
                                    href=f"https://dx.doi.org/{doi}",
                                )
                            ],
                            className="mpc",
                            style={"padding-left": "1rem", "margin-bottom": "1rem"}
                        )
                    )

                formatted_references = html.Div(formatted_entries)
        else:
            # this uses pybtex directly on stored BibTeX entries from MP
            # most-accurate references and faster since no Crossref lookup
            # is required but no dois/hyperlinks available
            all_entries = {}
            for references in all_references:
                all_entries.update(Parser().parse_string(references).entries)
            md = self._pybtex_entries_to_markdown(all_entries)
            formatted_references = dcc.Markdown(md, className="mpc-markdown")
            num_refs = len(all_entries)

        return html.Div(
            [
                Label(f"{num_refs} references found{':' if num_refs>0 else '.'}"),
                formatted_references,
            ],
            style={"max-height": "20rem", "overflow-y": "scroll"},
        )
Пример #23
0
    'underline': {
        'border-bottom': 'thin lightgrey solid',
        'margin-top': '50px'
    }
}

layout = html.Div([
    dcc.Tabs([
        dcc.Tab(label='Dash open-source',
                children=[
                    html.H2('Dash Python User Guide'),
                    html.Blockquote([
                        dcc.Markdown('''
                Dash brings low-code data apps to these languages: 
                
                [Python](dash.plotly.com) | 
                [R](dashr.plotly.com) | 
                [Julia](https://dashjulia.plotly.com) | 
                [.NET](https://github.com/plotly/Dash.NET)
                '''),
                    ]), WorkspaceBlurb,
                    TOC(URLS)
                ]),
        dcc.Tab(label='Dash Enterprise',
                children=[
                    html.Div(TOC([DASH_ENTERPRISE_URLS])),
                    html.Img(
                        src=relpath('/assets/images/dds/app-architecture.jpg'),
                        alt='Dash App Architecture Diagram')
                ])
    ])
])