#!/usr/bin/python3
from datetime import date, timedelta, datetime
from dateutil.relativedelta import relativedelta
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import pandas
from dash.dependencies import Input, Output

# data URL
consegne = 'https://raw.githubusercontent.com/italia/covid19-opendata-vaccini/master/dati/consegne-vaccini-latest.csv'
fascia_anagrafica = 'https://raw.githubusercontent.com/italia/covid19-opendata-vaccini/master/dati/platea.csv'
somministrazioni = 'https://raw.githubusercontent.com/italia/covid19-opendata-vaccini/master/dati/somministrazioni-vaccini-latest.csv'
decessi_contagi = 'https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-andamento-nazionale/dpc-covid19-ita-andamento-nazionale.csv'
decessi_contagi_regioni = 'https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-regioni/dpc-covid19-ita-regioni.csv'
population = 0

last_update = ''  # last update
max_prima_f = ''  # max first dose in 1day
tot_janssenf = ''  # tot only 1 dose format
tot_janssen = ''  # tot only 1 dose
month_last_day_vaccine = ''  # 70% population vaccine date
percent_mese = ''  # percentage
percent_mese_vaccine = ''
percent_mese_death = ''  # percentage death
percent_mese_vaccine_death = ''
pandas.options.mode.chained_assignment = None  # default='warn'

# read csv for url and get date
dc = pandas.read_csv(consegne)
ds = pandas.read_csv(somministrazioni)
ddc = pandas.read_csv(decessi_contagi)
ddcr = pandas.read_csv(decessi_contagi_regioni)
dfe = pandas.read_csv(fascia_anagrafica)
regions = ds['nome_area'].drop_duplicates().tolist()  # all regions

plotly_js_minified = ['https://cdn.plot.ly/plotly-basic-latest.min.js']
app = dash.Dash(__name__, external_scripts=plotly_js_minified,
                meta_tags=[{'name': 'viewport', 'content': 'width=device-width, initial-scale=0.8, maximum-scale=1.2, minimum-scale=0.5'}],
                requests_pathname_prefix='/vaccine/',
                routes_pathname_prefix='/vaccine/')
app.title = 'Dashboard Vaccini'
server = app.server

# chart config
chart_config = {'displaylogo': False, 'displayModeBar': False, 'responsive': True}

# slider buttons (1m, 3m, 6m, all)
slider_button = list([
    dict(count=1,
         label="1m",
         step="month",
         stepmode="backward"),
    dict(count=3,
         label="3m",
         step="month",
         stepmode="backward"),
    dict(count=6,
         label="6m",
         step="month",
         stepmode="backward"),
    dict(step="all")
])

# refresh data
def refresh_data():
    global today, last_update, max_prima_f
    global dc, ds, dfa, ddc, dfe, tot_dfe, ds_dosi
    global tot_prima_dose, tot_seconda_dose, tot_prima, tot_seconda, tot_covid, tot_with_covid
    global percent_mese_death, percent_mese
    # read csv for url and get date
    dc = pandas.read_csv(consegne)
    ds = pandas.read_csv(somministrazioni)
    ddc = pandas.read_csv(decessi_contagi)
    dfe = pandas.read_csv(fascia_anagrafica)
    today = date.today()

    # doses delivered
    dc = dc.groupby('data_consegna').agg({'numero_dosi': 'sum'}).reset_index()
    # doses administered
    ds_dosi = ds.groupby('data_somministrazione').agg({'prima_dose': 'sum', 'seconda_dose': 'sum', 'pregressa_infezione': 'sum'}).reset_index()

    ds_prime_dosi = ds_dosi.loc[ds_dosi['data_somministrazione'] == str(today), 'prima_dose']
    if len(ds_prime_dosi) == 0:
        last_update = date.today()
    else:
        last_update = date.today() - timedelta(days=1)

    # max first
    max_prima = int(max(ds_dosi['prima_dose']))
    max_prima_f = '{:,}'.format(max_prima).replace(',', '.')  # format max first dose
    # percentage death-positive
    date_format = "%Y-%m-%d"  # date format
    ora = datetime.strptime(str(today), date_format)
    mese = ora - relativedelta(months=1)
    # positive
    month_prima_p = ddc.loc[ddc['data'].between(str(mese)[:10], str(ora)[:10]), ['nuovi_positivi']].sum()
    month_pprima_p = ddc.loc[ddc['data'].between(str(mese - relativedelta(months=1))[:10], str(mese)[:10]), ['nuovi_positivi']].sum()
    percent_mese = round((int(month_prima_p) / month_pprima_p) * 100, 2)
    # death
    ddc['nuovi_decessi'] = ddc.deceduti.diff().fillna(ddc.deceduti)
    month_prima_d = ddc.loc[ddc['data'].between(str(mese)[:10], str(ora)[:10]), ['nuovi_decessi']].sum()
    month_pprima_d = ddc.loc[ddc['data'].between(str(mese - relativedelta(months=1))[:10], str(mese)[:10]), ['nuovi_decessi']].sum()
    percent_mese_death = round((int(month_prima_d) / month_pprima_d) * 100, 2)

    # first dose from the start
    tot_prima = ds_dosi.loc[ds_dosi['data_somministrazione'].between('2020-12-27', str(today)), ['prima_dose']].sum()
    tot_prima_dose = '{:,}'.format(int(tot_prima)).replace(',', '.')
    # second dose from the start
    tot_seconda = ds_dosi.loc[ds_dosi['data_somministrazione'].between('2020-12-27', str(today)), ['seconda_dose']].sum()
    tot_seconda_dose = '{:,}'.format(int(tot_seconda)).replace(',', '.')
    # with covid
    tot_covid = ds_dosi.loc[ds_dosi['data_somministrazione'].between('2020-12-27', str(today)), ['pregressa_infezione']].sum()
    tot_with_covid = '{:,}'.format(int(tot_covid)).replace(',', '.')
    # age
    dfa = ds.groupby('fascia_anagrafica').agg({'prima_dose': 'sum', 'seconda_dose': 'sum'}).reset_index()
    tot_dfe = dfe.groupby('fascia_anagrafica').agg({'totale_popolazione': 'sum'}).reset_index()

# dropdown
def get_dropdown_data():
    selections = []
    selections.append(dict(label='Dato Nazionale', value='Dato Nazionale'))
    for reg in regions:
        selections.append(dict(label=reg, value=reg))
    return selections

# total vaccine status
def vaccine_update():
    #refresh_data()
    global tot_janssen, tot_janssenf
    # percentage
    janssen = ds.loc[ds['fornitore'] == 'Janssen'].groupby('data_somministrazione').agg({'prima_dose': 'sum'}).reset_index()
    tot_janssen = janssen.loc[janssen['data_somministrazione'].between('2021-04-05', str(today)), ['prima_dose']].sum()
    prima = int(tot_prima) - int(tot_janssen)
    vaccinati = int(tot_seconda) + int(tot_janssen) + int(tot_covid)
    # percentage
    primadose = round((int(prima)/60360000)*100, 2)
    secondadose = round((int(vaccinati)/60360000)*100, 2)
    tjanssen = round((int(tot_janssen) / 60360000) * 100, 2)
    covid = round((int(tot_covid) / 60360000) * 100, 2)
    # percentage platea
    p_primadose = round((int(prima) / 50773718) * 100, 2)
    p_secondadose = round((int(vaccinati) / 50773718) * 100, 2)
    p_tjanssen = round((int(tot_janssen) / 50773718) * 100, 2)
    p_covid = round((int(tot_covid) / 50773718) * 100, 2)
    # formating
    tot_prima_dose = '{:,}'.format(int(prima)).replace(',', '.')
    tot_vaccinati_dose = '{:,}'.format(int(vaccinati)).replace(',', '.')
    tot_janssenf = '{:,}'.format(int(tot_janssen)).replace(',', '.')
    tot_covid_dosi = '{:,}'.format(int(tot_covid)).replace(',', '.')
    return html.Div([
        html.Div([
            html.Table([
                # Header
                html.Tr([
                    html.Td('Prima dose', style={'font-size': '14px'}),
                ]),
                # Body
                html.Tr([
                    html.Td(
                        html.H1(tot_prima_dose, style={'color': '#F5C05F', 'font-size': '45px'})
                    ),
                ]),
                # Percentage platea
                html.Tr([
                    html.Td(html.B(
                        '' + str(p_primadose) + '% della platea',
                        style={'color': '#F5C05F', 'font-size': '14px'}
                    ))
                ]),
                # Percentage
                html.Tr([
                    html.Td(html.B(
                        '' + str(primadose) + '% della popolazione',
                        style={'color': '#F5C05F', 'font-size': '14px'}
                    ))
                ]),
            ], className='table')
        ], className='container-3'),
        html.Div([
            html.Table([
                # Header
                html.Tr([
                    html.Td('Persone Vaccinate', style={'font-size': '14px'})
                ]),
                # Body
                html.Tr([
                    html.Td(
                        html.H1(tot_vaccinati_dose, style={'color': '#E83A8E', 'font-size': '45px'})
                    )
                ]),
                # Percentage platea
                html.Tr([
                    html.Td(html.B(
                        '' + str(p_secondadose) + '% della platea', style={'color': '#E83A8E', 'font-size': '14px'}
                    ))
                ]),
                # Percentage
                html.Tr([
                    html.Td(html.B(
                        '' + str(secondadose) + '% della popolazione', style={'color': '#E83A8E', 'font-size': '14px'}
                    ))
                ]),
            ], className='table')
        ], className='container-3'),
        html.Div([
            html.Div([
                html.Table([
                    # Header
                    html.Tr([
                        html.Td('Di cui con vaccino monodose', colSpan=2, style={'font-size': '14px'}),
                    ]),
                    # Body
                    html.Tr([
                        html.Td(
                            html.H1(tot_janssenf, style={'color': '#C93E7F', 'font-size': '30px'})
                        ),
                        html.Td([html.B(
                            '' + str(p_tjanssen) + '% della platea', style={'color': '#C93E7F', 'font-size': '12px'}
                        ), html.Br(), html.B(
                            '' + str(tjanssen) + '% della popolazione', style={'color': '#C93E7F', 'font-size': '12px'}
                        )]),
                    ]),
                ], className='table')
            ], className='container-1'),
            html.Div([
                html.Table([
                    # Header
                    html.Tr([
                        html.Td('Di cui con pregressa infezione', colSpan=2, style={'font-size': '14px'}),
                    ]),
                    # Body
                    html.Tr([
                        html.Td(
                            html.H1(tot_covid_dosi, style={'color': '#B33771', 'font-size': '30px'})
                        ),
                        html.Td([html.B(
                            '' + str(p_covid) + '% della platea', style={'color': '#B33771', 'font-size': '12px'}
                        ), html.Br(), html.B(
                            '' + str(covid) + '% della popolazione', style={'color': '#B33771', 'font-size': '12px'}
                        )]),
                    ]),
                ], className='table')
            ], className='container-1')
        ], className='container-3')
    ], className='container-1')

def vaccine_update_bar():
    #refresh_data()
    return html.Div([
        html.Div([
            dcc.Graph(
                figure={
                    'data': [go.Bar(x=[60360000, 50773718, int(tot_prima)-int(tot_janssen), int(tot_seconda)+int(tot_janssen)+int(tot_covid)],
                                    y=['Popolazione', 'Platea', 'Prima dose', 'Vaccinati'],
                                    orientation='h',
                                    marker_color=['#6181E8', '#5EAEFF', '#F5C05F', '#E83A8E'])
                             ],
                    'layout': {
                        'height': 250,  # px
                        'xaxis': dict(
                            rangeslider=dict(visible=False),
                            type=''
                        )
                    },
                },
                config=chart_config
            )
        ], className='bar')
    ], className='container-1')

# dropdown select
def dropdown_vaccine_daily():
    return html.Div([
        html.Div([
            dbc.Container([
                dbc.Row([
                    dbc.Col(
                        dcc.Dropdown(id='dropdown_vaccine_daily',
                                     options=get_dropdown_data(), clearable=False, searchable=False,
                                     persistence=True, persistence_type='session', value='Dato Nazionale'
                                     ), style={'margin-left': 'auto', 'margin-right': 'auto'}, width=12, lg=5,
                        className='mt-2')
                ])
            ])
        ])
    ])

# vaccine horozzonatal bar
@app.callback(
    Output('vaccine_daily', 'children'),
    [Input('dropdown_vaccine_daily', 'value')])
def vaccine_daily(regione):
    # total data
    if regione == 'Dato Nazionale':
        #refresh_data()
        tot_consegne = dc.loc[dc['data_consegna'].between('2020-12-27', str(today)), ['numero_dosi']].sum()
        tot_vaccini = int(tot_prima) + int(tot_seconda)
        # today data
        dc_dosi_consegnate = dc.loc[dc['data_consegna'] == str(today), 'numero_dosi']
        ds_prime_dosi = ds_dosi.loc[ds_dosi['data_somministrazione'] == str(today), 'prima_dose']
        ds_seconde_dosi = ds_dosi.loc[ds_dosi['data_somministrazione'] == str(today), 'seconda_dose']

        # check today data
        if len(dc_dosi_consegnate) == 0 and len(ds_prime_dosi) == 0 and len(ds_seconde_dosi) == 0:
            dc_dosi_consegnate = dc.loc[dc['data_consegna'] == str(date.today() - timedelta(days=1)), 'numero_dosi']
            ds_prime_dosi = ds_dosi.loc[ds_dosi['data_somministrazione'] == str(date.today() - timedelta(days=1)), 'prima_dose']
            ds_seconde_dosi = ds_dosi.loc[ds_dosi['data_somministrazione'] == str(date.today() - timedelta(days=1)), 'seconda_dose']
    else:
        dc1 = pandas.read_csv(consegne)
        ds1 = pandas.read_csv(somministrazioni)
        reg_ds1 = ds1.loc[ds1['nome_area'] == regione]
        ds_dosi1 = reg_ds1.copy().groupby('data_somministrazione').agg({'prima_dose': 'sum', 'seconda_dose': 'sum'}).reset_index()
        tot_prima1 = ds_dosi1.loc[ds_dosi1['data_somministrazione'].between('2020-12-27', str(today)), ['prima_dose']].sum()
        tot_seconda1 = ds_dosi1.loc[ds_dosi1['data_somministrazione'].between('2020-12-27', str(today)), ['seconda_dose']].sum()
        reg_dc1 = dc1.loc[dc1['nome_area'] == regione]
        dc_dosi1 = reg_dc1.copy().groupby('data_consegna').agg({'numero_dosi': 'sum'}).reset_index()

        # data
        tot_consegne = dc_dosi1.loc[dc_dosi1['data_consegna'].between('2020-12-27', str(today)), ['numero_dosi']].sum()
        tot_vaccini = int(tot_prima1) + int(tot_seconda1)
        # today data
        dc_dosi_consegnate = dc_dosi1.loc[dc_dosi1['data_consegna'] == str(today), 'numero_dosi']
        ds_prime_dosi = ds_dosi1.loc[ds_dosi1['data_somministrazione'] == str(today), 'prima_dose']
        ds_seconde_dosi = ds_dosi1.loc[ds_dosi1['data_somministrazione'] == str(today), 'seconda_dose']

        # check today data
        if len(dc_dosi_consegnate) == 0 and len(ds_prime_dosi) == 0 and len(ds_seconde_dosi) == 0:
            dc_dosi_consegnate = dc1.loc[dc1['data_consegna'] == str(date.today() - timedelta(days=1)), 'numero_dosi']
            ds_prime_dosi = ds_dosi1.loc[ds_dosi1['data_somministrazione'] == str(date.today() - timedelta(days=1)), 'prima_dose']
            ds_seconde_dosi = ds_dosi1.loc[ds_dosi1['data_somministrazione'] == str(date.today() - timedelta(days=1)), 'seconda_dose']

    ds_dosi_totali = 0
    tot_consegne = '{:,}'.format(int(tot_consegne)).replace(',', '.')
    tot_vaccini = '{:,}'.format(int(tot_vaccini)).replace(',', '.')

    # formatting data
    if len(dc_dosi_consegnate) == 0:
        dc_dosi_consegnate = 0
    else:
        dc_dosi_consegnate = '{:,}'.format(int(dc_dosi_consegnate)).replace(',', '.')
    if len(ds_prime_dosi) == 0:
        ds_prime_dosi = 0
        ds_dosi_totali = int(ds_prime_dosi)
    else:
        ds_dosi_totali = int(ds_prime_dosi)
        ds_prime_dosi = '{:,}'.format(int(ds_prime_dosi)).replace(',', '.')
    if len(ds_seconde_dosi) == 0:
        ds_seconde_dosi = 0
        ds_dosi_totali = ds_dosi_totali + int(ds_seconde_dosi)
    else:
        ds_dosi_totali = ds_dosi_totali + int(ds_seconde_dosi)
        ds_seconde_dosi = '{:,}'.format(int(ds_seconde_dosi)).replace(',', '.')

    if ds_dosi_totali != 0:
        ds_dosi_totali = '{:,}'.format(int(ds_dosi_totali)).replace(',', '.')

    return html.Div([
        # vaccine
        html.Div([
            html.Table([
                # Header
                html.Tr([
                    html.Td('Vaccini Consegnati', style={'font-size': '14px'}),
                ]),
                # Body
                html.Tr([
                    html.Td(
                        html.H1('+ '+str(dc_dosi_consegnate)+'', style={'color': '#29CF8A', 'font-size': '45px'})
                    )
                ]),
                # Yesterday
                html.Tr([
                    html.Td(html.B(
                        'Totali: '+str(tot_consegne), style={'color': '#29CF8A', 'font-size': '14px'}
                    ))
                ])
            ], className='table')
        ], className='container-4'),

        # doses
        html.Div([
            html.Table([
                # Header
                html.Tr([
                    html.Td('Dosi Somministrate', style={'font-size': '14px'}),
                ]),
                # Body
                html.Tr([
                    html.Td(
                        html.H1('+ ' + str(ds_dosi_totali) + '', style={'color': '#376FDB', 'font-size': '45px'})
                    )
                ]),
                # Yesterday
                html.Tr([
                    html.Td(html.B(
                        'Totali: ' + str(tot_vaccini), style={'color': '#376FDB', 'font-size': '14px'}
                    ))
                ])
            ], className='table')
        ], className='container-4'),

        # first doses
        html.Div([
            html.Table([
                # Header
                html.Tr([
                    html.Td('Prime Dosi', style={'font-size': '14px'}),
                ]),
                # Body
                html.Tr([
                    html.Td(
                        html.H1('+ ' + str(ds_prime_dosi) + '', style={'color': '#F5C05F', 'font-size': '45px'})
                    )
                ]),
                # Yesterday
                html.Tr([
                    html.Td(html.B(
                        'Totali: ' + str(tot_prima_dose), style={'color': '#F5C05F', 'font-size': '14px'}
                    ))
                ])
            ], className='table')
        ], className='container-4'),

        # vaccine
        html.Div([
            html.Table([
                # Header
                html.Tr([
                    html.Td('Persone Vaccinate (Due Dosi)', style={'font-size': '14px'})
                ]),
                # Body
                html.Tr([
                    html.Td(
                        html.H1('+ ' + str(ds_seconde_dosi) + '',
                                style={'color': '#E83A8E', 'font-size': '45px'})
                    )
                ]),
                # Yesterday
                html.Tr([
                    html.Td(html.B(
                        'Totali: ' + str(tot_seconda_dose), style={'color': '#E83A8E', 'font-size': '14px'}
                    ))
                ])
            ], className='table')
        ], className='container-4')
    ], className='container-1')

# vaccine horozzonatal bar
@app.callback(
    Output('vaccine_graph', 'children'),
    [Input('dropdown_vaccine_daily', 'value')])
# vaccine and doses graph
def vaccine_graph(regione):
    if regione == 'Dato Nazionale':
        #refresh_data()
        # vaccine
        ds_pfizer = ds.loc[ds['fornitore'] == 'Pfizer/BioNTech'].groupby('data_somministrazione').agg(
            {'prima_dose': 'sum', 'seconda_dose': 'sum'}).reset_index()
        ds_moderna = ds.loc[ds['fornitore'] == 'Moderna'].groupby('data_somministrazione').agg(
            {'prima_dose': 'sum', 'seconda_dose': 'sum'}).reset_index()
        ds_astra = ds.loc[ds['fornitore'] == 'Vaxzevria (AstraZeneca)'].groupby('data_somministrazione').agg(
            {'prima_dose': 'sum', 'seconda_dose': 'sum'}).reset_index()
        ds_janssen = ds.loc[ds['fornitore'] == 'Janssen'].groupby('data_somministrazione').agg(
            {'prima_dose': 'sum', 'seconda_dose': 'sum'}).reset_index()
    else:
        # vaccine
        ds1 = pandas.read_csv(somministrazioni)
        reg_ds1 = ds1.loc[ds1['nome_area'] == regione]
        ds_dosi1 = reg_ds1.copy().groupby('data_somministrazione').agg(
            {'prima_dose': 'sum', 'seconda_dose': 'sum', 'fornitore': 'last'}).reset_index()
        ds_pfizer = ds_dosi1.loc[ds_dosi1['fornitore'] == 'Pfizer/BioNTech'].groupby('data_somministrazione').agg(
            {'prima_dose': 'sum', 'seconda_dose': 'sum'}).reset_index()
        ds_moderna = ds_dosi1.loc[ds_dosi1['fornitore'] == 'Moderna'].groupby('data_somministrazione').agg(
            {'prima_dose': 'sum', 'seconda_dose': 'sum'}).reset_index()
        ds_astra = ds_dosi1.loc[ds_dosi1['fornitore'] == 'Vaxzevria (AstraZeneca)'].groupby('data_somministrazione').agg(
            {'prima_dose': 'sum', 'seconda_dose': 'sum'}).reset_index()
        ds_janssen = ds_dosi1.loc[ds_dosi1['fornitore'] == 'Janssen'].groupby('data_somministrazione').agg(
            {'prima_dose': 'sum', 'seconda_dose': 'sum'}).reset_index()
    return html.Div([
        dbc.Container([
            dbc.Row(
                dbc.Col(
                    dcc.Graph(
                        figure={
                            'data': [
                                {'x': ds_pfizer['data_somministrazione'],
                                 'y': ds_pfizer['prima_dose'] + ds_pfizer['seconda_dose'],
                                 'type': 'bar',
                                 'name': 'Pfizer',
                                 'marker': dict(color='#95A9DE')},
                                {'x': ds_moderna['data_somministrazione'],
                                 'y': ds_moderna['prima_dose'] + ds_moderna['seconda_dose'],
                                 'type': 'bar',
                                 'name': 'Moderna',
                                 'marker': dict(color='#395499')},
                                {'x': ds_astra['data_somministrazione'],
                                 'y': ds_astra['prima_dose'] + ds_astra['seconda_dose'], 'type': 'bar',
                                 'name': 'AstraZeneca',
                                 'marker': dict(color='#537BE0')},
                                {'x': ds_janssen['data_somministrazione'],
                                 'y': ds_janssen['prima_dose'] + ds_janssen['seconda_dose'],
                                 'type': 'bar',
                                 'name': 'Janssen',
                                 'marker': dict(color='#243561')},
                            ],
                            'layout': {
                                'barmode': 'stack',
                                'xaxis': dict(
                                    rangeselector=dict(buttons=slider_button),
                                    rangeslider=dict(visible=False),
                                    type='date'
                                ),
                                'legend': dict(
                                    orientation="h",
                                    xanchor="center",
                                    x=0.5,
                                    y=-0.2
                                )
                            }
                        },
                        config=chart_config
                    )
                )
            )
        ])
    ], className='container-2')

# vaccine horozzonatal bar
@app.callback(
    Output('dosi_graph', 'children'),
    [Input('dropdown_vaccine_daily', 'value')])
# vaccine and doses graph
def dosi_graph(regione):
    if regione == 'Dato Nazionale':
        #refresh_data()
        prima_seconda = ds.groupby('data_somministrazione').agg({'prima_dose': 'sum', 'seconda_dose': 'sum'}).reset_index()
    else:
        # vaccine
        ds1 = pandas.read_csv(somministrazioni)
        reg_ds1 = ds1.loc[ds1['nome_area'] == regione]
        prima_seconda = reg_ds1.copy().groupby('data_somministrazione').agg({'prima_dose': 'sum', 'seconda_dose': 'sum'}).reset_index()
    return html.Div([
            dbc.Container([
                dbc.Row(
                    dbc.Col(
                        dcc.Graph(
                            figure={
                                'data': [
                                    {'x': prima_seconda['data_somministrazione'], 'y': prima_seconda['prima_dose'],
                                     'type': 'bar',
                                     'name': 'Prima Dose',
                                     'marker': dict(color='#F5C05F')},
                                    {'x': prima_seconda['data_somministrazione'], 'y': prima_seconda['seconda_dose'],
                                     'type': 'bar',
                                     'name': 'Seconda Dose',
                                     'marker': dict(color='#78F5B3')},
                                ],
                                'layout': {
                                    'barmode': 'stack',
                                    'xaxis': dict(
                                        rangeselector=dict(buttons=slider_button),
                                        rangeslider=dict(visible=False),
                                        type='date'
                                    ),
                                    'legend': dict(
                                        orientation="h",
                                        xanchor="center",
                                        x=0.5,
                                        y=-0.2
                                    )
                                }
                            },
                            config=chart_config
                        )
                    )
                )
            ])
        ], className='container-2')

# dropdown select
def dropdown_vaccine_age_bar():
    return html.Div([
        html.Div([
            dbc.Container([
                dbc.Row([
                    dbc.Col(
                        dcc.Dropdown(id='dropdown_vaccine_age_bar',
                                     options=get_dropdown_data(), clearable=False, searchable=False,
                                     persistence=True, persistence_type='session', value='Dato Nazionale'
                                     ), style={'margin-left': 'auto', 'margin-right': 'auto'}, width=12, lg=5,
                        className='mt-2')
                ])
            ])
        ])
    ])

# vaccine # age
@app.callback(
    Output('vaccine_age_bar', 'children'),
    [Input('dropdown_vaccine_age_bar', 'value')])
def vaccine_age_bar(regione):
    if regione == 'Dato Nazionale':
        figure_age = {
            'data': [go.Bar(x=[int(dfa['prima_dose'][0])-int(dfa['seconda_dose'][0]), int(dfa['prima_dose'][1])-int(dfa['seconda_dose'][1]),
                               int(dfa['prima_dose'][2])-int(dfa['seconda_dose'][2]), int(dfa['prima_dose'][3])-int(dfa['seconda_dose'][3]),
                               int(dfa['prima_dose'][4])-int(dfa['seconda_dose'][4]), int(dfa['prima_dose'][5])-int(dfa['seconda_dose'][5]),
                               int(dfa['prima_dose'][6])-int(dfa['seconda_dose'][6]),
                               int(int(dfa['prima_dose'][7])-int(dfa['seconda_dose'][7])) + int(int(dfa['prima_dose'][8])-int(dfa['seconda_dose'][8]))],
                            y=['12-19', '20-29', '30-39', '40-49', '50-59', '60-69', '70-79', '80+'],
                            orientation='h',
                            marker_color='#F5C05F',
                            name='Prima Dose'
                            ),
                     go.Bar(x=[dfa['seconda_dose'][0], dfa['seconda_dose'][1], dfa['seconda_dose'][2],
                               dfa['seconda_dose'][3], dfa['seconda_dose'][4], dfa['seconda_dose'][5],
                               dfa['seconda_dose'][6], int(dfa['seconda_dose'][7]+dfa['seconda_dose'][8])],
                            y=['12-19', '20-29', '30-39', '40-49', '50-59', '60-69', '70-79', '80+'],
                            orientation='h',
                            marker_color='#E83A8E',
                            name='Vaccinati'
                            ),
                     go.Bar(x=[int(tot_dfe.loc[tot_dfe.index[0], 'totale_popolazione']) - int(dfa['prima_dose'][0]),
                               int(tot_dfe.loc[tot_dfe.index[1], 'totale_popolazione']) - int(dfa['prima_dose'][1]),
                               int(tot_dfe.loc[tot_dfe.index[2], 'totale_popolazione']) - int(dfa['prima_dose'][2]),
                               int(tot_dfe.loc[tot_dfe.index[3], 'totale_popolazione']) - int(dfa['prima_dose'][3]),
                               int(tot_dfe.loc[tot_dfe.index[4], 'totale_popolazione']) - int(dfa['prima_dose'][4]),
                               int(tot_dfe.loc[tot_dfe.index[5], 'totale_popolazione']) - int(dfa['prima_dose'][5]),
                               int(tot_dfe.loc[tot_dfe.index[6], 'totale_popolazione']) - int(dfa['prima_dose'][6]),
                               int(tot_dfe.loc[tot_dfe.index[7], 'totale_popolazione']) - int(dfa['prima_dose'][7])],
                            y=['12-19', '20-29', '30-39', '40-49', '50-59', '60-69', '70-79', '80+'],
                            orientation='h',
                            marker_color='#6181E8',
                            name='Non vaccinati'
                            )
                     ],
            'layout': {
                'barmode': 'stack',  # stack data
                'height': 340,  # px
                'xaxis': dict(
                    rangeslider=dict(visible=False),
                    type=''
                ),
                'legend': dict(
                    orientation="h",
                    xanchor="center",
                    x=0.5,
                    y=-0.2
                )
            },
        }
    else:
        if regione == 'Provincia Autonoma Bolzano / Bozen': reg = 'P.A. Bolzano'
        elif regione == 'Provincia Autonoma Trento': reg = 'P.A. Trento'
        elif regione == "Valle d'Aosta / Vallée d'Aoste": reg = "Valle d'Aosta"
        else: reg = regione
        ds1 = pandas.read_csv(somministrazioni)
        dfe1 = pandas.read_csv(fascia_anagrafica)
        reg_ds1 = ds1.loc[ds1['nome_area'] == regione]
        dfa1 = reg_ds1.copy().groupby('fascia_anagrafica').agg({'prima_dose': 'sum', 'seconda_dose': 'sum'}).reset_index()
        reg_dfe1 = dfe1.loc[dfe1['nome_area'] == reg]
        figure_age = {
            'data': [go.Bar(x=[int(dfa1['prima_dose'][0])-int(dfa1['seconda_dose'][0]), int(dfa1['prima_dose'][1])-int(dfa1['seconda_dose'][1]),
                               int(dfa1['prima_dose'][2])-int(dfa1['seconda_dose'][2]), int(dfa1['prima_dose'][3])-int(dfa1['seconda_dose'][3]),
                               int(dfa1['prima_dose'][4])-int(dfa1['seconda_dose'][4]), int(dfa1['prima_dose'][5])-int(dfa1['seconda_dose'][5]),
                               int(dfa1['prima_dose'][6])-int(dfa1['seconda_dose'][6]),
                               int(int(dfa1['prima_dose'][7])-int(dfa1['seconda_dose'][7])) + int(int(dfa1['prima_dose'][8])-int(dfa1['seconda_dose'][8]))],
                            y=['12-19', '20-29', '30-39', '40-49', '50-59', '60-69', '70-79', '80+'],
                            orientation='h',
                            marker_color='#F5C05F',
                            name='Prima Dose'
                            ),
                     go.Bar(x=[dfa1['seconda_dose'][0], dfa1['seconda_dose'][1], dfa1['seconda_dose'][2],
                               dfa1['seconda_dose'][3], dfa1['seconda_dose'][4], dfa1['seconda_dose'][5],
                               dfa1['seconda_dose'][6], int(int(dfa1['seconda_dose'][7]) + int(dfa1['seconda_dose'][8]))],
                            y=['12-19', '20-29', '30-39', '40-49', '50-59', '60-69', '70-79', '80+'],
                            orientation='h',
                            marker_color='#E83A8E',
                            name='Vaccinati'
                            ),
                     go.Bar(x=[int(reg_dfe1.loc[reg_dfe1.index[0], 'totale_popolazione']) - int(dfa1['prima_dose'][0]),
                               int(reg_dfe1.loc[reg_dfe1.index[1], 'totale_popolazione']) - int(dfa1['prima_dose'][1]),
                               int(reg_dfe1.loc[reg_dfe1.index[2], 'totale_popolazione']) - int(dfa1['prima_dose'][2]),
                               int(reg_dfe1.loc[reg_dfe1.index[3], 'totale_popolazione']) - int(dfa1['prima_dose'][3]),
                               int(reg_dfe1.loc[reg_dfe1.index[4], 'totale_popolazione']) - int(dfa1['prima_dose'][4]),
                               int(reg_dfe1.loc[reg_dfe1.index[5], 'totale_popolazione']) - int(dfa1['prima_dose'][5]),
                               int(reg_dfe1.loc[reg_dfe1.index[6], 'totale_popolazione']) - int(dfa1['prima_dose'][6]),
                               int(reg_dfe1.loc[reg_dfe1.index[7], 'totale_popolazione']) - int(int(dfa1['prima_dose'][7]) + int(dfa1['prima_dose'][8]))],
                            y=['12-19', '20-29', '30-39', '40-49', '50-59', '60-69', '70-79', '80+'],
                            orientation='h',
                            marker_color='#6181E8',
                            name='Non vaccinati'
                            )
                     ],
            'layout': {
                'barmode': 'stack',  # stack data
                'height': 340,  # px
                'xaxis': dict(
                    rangeslider=dict(visible=False),
                    type=''
                ),
                'legend': dict(
                    orientation="h",
                    xanchor="center",
                    x=0.5,
                    y=-0.2
                )
            },
        }
    return html.Div([
        dcc.Graph(
            figure=figure_age,
            config=chart_config
        )
    ], className='bar')

# forecast
def previsione():
    global month_last_day_vaccine
    date_format = "%Y-%m-%d"  # date format
    ora = datetime.strptime(str(today), date_format)

    # best day
    l = len(ds_dosi['data_somministrazione'])  # total vaccine day
    best_day = (60360000 - int(tot_prima)) / int(max(ds_dosi['prima_dose']))
    best_last_day = str(ora + timedelta(days=best_day))[:10]
    # 80%
    best_day_80 = (48288000 - int(tot_prima)) / int(max(ds_dosi['prima_dose']))
    best_last_day_80 = str(ora + timedelta(days=best_day_80))[:10]

    # month
    month_prima = ds_dosi.loc[ds_dosi['data_somministrazione'].between(str(ora-relativedelta(months=1))[:10], str(ora)[:10]), ['prima_dose']].sum()
    month_day_passati = (ora - (ora-relativedelta(months=1))).days
    month_day = ((60360000 - int(tot_prima)) / int(month_prima)) * month_day_passati
    month_last_day = str(ora + timedelta(days=month_day))[:10]
    # 80%
    month_day_80 = ((48288000 - int(tot_prima)) / int(month_prima)) * month_day_passati
    #month_day_80 = (48288000 / int(month_prima)) * month_day_passati
    month_last_day_80 = str(ora + timedelta(days=month_day_80))[:10]
    # 70%
    month_day_70 = ((42252000 - int(tot_prima)) / int(month_prima)) * month_day_passati
    #month_day_70 = (42252000 / int(month_prima)) * month_day_passati
    month_last_day_70 = str(ora + timedelta(days=month_day_70))[:10]
    # 60%
    month_day_60 = ((36216000 - int(tot_prima)) / int(month_prima)) * month_day_passati
    #month_day_60 = (36216000 / int(month_prima)) * month_day_passati
    month_last_day_60 = str(ora + timedelta(days=month_day_60))[:10]

    month_last_day_vaccine = month_last_day_70  # last day 70% vaccine

    return html.Div(  # main div
        dbc.Container([
            dbc.Row(
                dbc.Col(
                    dcc.Graph(
                        figure={
                            'data': [
                                {'x': ds_dosi['data_somministrazione'], 'y': (ds_dosi['prima_dose'].cumsum())/60360000, 'type': 'bar', 'name': 'Incremento Prime Dosi'},
                                go.Scatter(x=[ds_dosi['data_somministrazione'][0], '2021-10-30'],
                                           y=[0, 1],
                                           mode='lines',
                                           name='Previsione del Governo',
                                           line=go.scatter.Line(color="#FA5541")),
                                go.Scatter(x=[ds_dosi['data_somministrazione'][l-1], month_last_day_60, month_last_day_70, month_last_day_80, month_last_day],
                                           y=[int(tot_prima)/60360000, 0.6, 0.7, 0.8, 1],
                                           type='scatter',
                                           name='Previsione Mensile',
                                           line=go.scatter.Line(color="#FA924E")),
                                go.Scatter(x=[ds_dosi['data_somministrazione'][l-1], best_last_day_80, best_last_day],
                                           y=[int(tot_prima)/60360000, 0.8, 1],
                                           type='scatter',
                                           name='Previsione Migliore*',
                                           line=go.scatter.Line(color="#FAC35A"))
                            ],
                            'layout': {
                                'xaxis': dict(
                                    rangeslider=dict(visible=False),
                                    type='date'
                                ),
                                'yaxis': dict(
                                    tickformat=',.0%',  # percentage on y axis
                                    range=[0, 1]
                                ),
                                'legend': dict(
                                    orientation="h",
                                    xanchor="center",
                                    x=0.5,
                                    y=-0.2
                                )
                            }
                        },
                        config=chart_config
                    )
                )
            )
        ])
    )

# dropdown
def get_dropdown_data2():
    selections = []
    for reg in regions:
        selections.append(dict(label=reg, value=reg))
    return selections

def dropdown_velocity_dosi_graph():
    return html.Div([
        html.Div([
            dbc.Container([
                dbc.Row([
                    dbc.Col(
                        dcc.Dropdown(id='dropdown_velocity_dosi_graph', multi=True,
                                     options=get_dropdown_data2(), clearable=False, searchable=False,
                                     persistence=True, persistence_type='session', value='Lombardia'
                                     ), style={'margin-left': 'auto', 'margin-right': 'auto'}, width=12, lg=5,
                        className='mt-2')
                ])
            ])
        ])
    ])

# effect contagi
@app.callback(
    Output('velocity_dosi_graph', 'children'),
    [Input('dropdown_velocity_dosi_graph', 'value')])
def velocity_dosi_graph(regione):
    ds1 = pandas.read_csv(somministrazioni)
    data = ['']
    traces = ['']
    if type(regione) == str:
        regione = [regione]

    for reg in regione:
        ds2 = ds1[ds1['nome_area'] == reg]
        ds_dosi_velocity = ds2.groupby('data_somministrazione').agg({'prima_dose': 'sum', 'nome_area': 'last'}).reset_index()
        data.append(ds_dosi_velocity)
    data.pop(0)

    for dati in data:
        traces.append(go.Scatter({'x': dati['data_somministrazione'], 'y': dati['prima_dose'], 'mode': 'lines',
                                  'name': f"{dati['nome_area'].iloc[0]}"}))
    traces.pop(0)

    return html.Div([
        dbc.Container([
            dbc.Row(
                dbc.Col(
                    dcc.Graph(
                        figure={
                            'data': traces,
                            'layout': {
                                'xaxis': dict(
                                    rangeselector=dict(buttons=slider_button),
                                    rangeslider=dict(visible=False),
                                    type='date'
                                ),
                                'legend': dict(
                                    orientation="h",
                                    xanchor="center",
                                    x=0.5,
                                    y=-0.2
                                )
                            }
                        },
                        config=chart_config
                    )
                )
            )
        ])
    ], className='container-1')

# dropdown select
def dropdown_effetti_decessi_contagi_graph():
    return html.Div([
        html.Div([
            dbc.Container([
                dbc.Row([
                    dbc.Col(
                        dcc.Dropdown(id='dropdown_effetti_decessi_contagi_graph',
                                     options=get_dropdown_data(), clearable=False, searchable=False,
                                     persistence=True, persistence_type='session', value='Dato Nazionale'
                                     ), style={'margin-left': 'auto', 'margin-right': 'auto'}, width=12, lg=5,
                        className='mt-2')
                ])
            ])
        ])
    ])

# effect contagi
@app.callback(
    Output('effetti_contagi_graph', 'children'),
    [Input('dropdown_effetti_decessi_contagi_graph', 'value')])
def effetti_contagi_graph(regione):
    if regione == 'Dato Nazionale':
        dec = ddc
        dec['nuovi_positivi_avg'] = ddc['nuovi_positivi'].rolling(30).mean()
    else:
        # edit regions
        if regione == 'Friuli-Venezia Giulia': regione = 'Friuli Venezia Giulia'
        elif regione == 'Provincia Autonoma Bolzano / Bozen': regione = 'P.A. Bolzano'
        elif regione == 'Provincia Autonoma Trento': regione = 'P.A. Trento'
        elif regione == "Valle d'Aosta / Vallée d'Aoste": regione = "Valle d'Aosta"
        ddcr = pandas.read_csv(decessi_contagi_regioni)
        reg_ddcr = ddcr.loc[ddcr['denominazione_regione'] == regione]
        dec = reg_ddcr.copy()
        dec['nuovi_positivi_avg'] = dec['nuovi_positivi'].rolling(30).mean()

    return html.Div([
        dbc.Container([
            dbc.Row(
                dbc.Col(
                    dcc.Graph(
                        figure={
                            'data': [
                                {'x': dec['data'], 'y': dec['nuovi_positivi'], 'type': 'bar', 'name': 'Nuovi Positivi',
                                 'marker': dict(color='#D9615D')},
                                # avg 30 day
                                {'x': dec['data'], 'y': dec['nuovi_positivi_avg'], 'type': 'scatter',
                                 'name': 'Media 30g',
                                 'marker': dict(color='#FF726E')},
                                # line start vaccine
                                go.Scatter(x=['2020-12-27', '2020-12-27'],
                                           y=[0, max(dec['nuovi_positivi'])],
                                           mode='lines',
                                           name='Inizio Vaccini',
                                           hoverinfo='none',
                                           line=go.scatter.Line(color="#4F4747"))
                            ],
                            'layout': {
                                'xaxis': dict(
                                    rangeselector=dict(buttons=slider_button),
                                    rangeslider=dict(visible=False),
                                    type='date'
                                ),
                                'legend': dict(
                                    orientation="h",
                                    xanchor="center",
                                    x=0.5,
                                    y=-0.2
                                )
                            }
                        },
                        config=chart_config
                    )
                )
            )
        ])
    ], className='container-2')

# effect contagi
@app.callback(
    Output('effetti_decessi_graph', 'children'),
    [Input('dropdown_effetti_decessi_contagi_graph', 'value')])
def effetti_decessi_graph(regione):
    if regione == 'Dato Nazionale':
        ded = ddc
        ded['nuovi_decessi'] = ded.deceduti.diff().fillna(ded.deceduti)
        ded['nuovi_decessi'].iloc[121] = 31  # error -31
        # avg
        ded['nuovi_decessi_avg'] = ded['nuovi_decessi'].rolling(30).mean()
    else:
        # edit regions
        if regione == 'Friuli-Venezia Giulia': regione = 'Friuli Venezia Giulia'
        elif regione == 'Provincia Autonoma Bolzano / Bozen': regione = 'P.A. Bolzano'
        elif regione == 'Provincia Autonoma Trento': regione = 'P.A. Trento'
        elif regione == "Valle d'Aosta / Vallée d'Aoste": regione = "Valle d'Aosta"
        ddcr = pandas.read_csv(decessi_contagi_regioni)
        reg_ddcr = ddcr.loc[ddcr['denominazione_regione'] == regione]
        ded = reg_ddcr.copy()
        ded['nuovi_decessi'] = ded.deceduti.diff().fillna(ded.deceduti)
        ded['nuovi_decessi_avg'] = ded['nuovi_decessi'].rolling(30).mean()

    return html.Div([
        dbc.Container([
            dbc.Row(
                dbc.Col(
                    dcc.Graph(
                        figure={
                            'data': [
                                {'x': ded['data'], 'y': ded['nuovi_decessi'], 'type': 'bar', 'name': 'Decessi',
                                 'marker': dict(color='#756B6B')},
                                # avg 30 day
                                {'x': ded['data'], 'y': ded['nuovi_decessi_avg'], 'type': 'scatter', 'name': 'Media 30g',
                                 'marker': dict(color='#C2B0B0')},
                                # line start vaccine
                                go.Scatter(x=['2020-12-27', '2020-12-27'],
                                           y=[0, max(ded['nuovi_decessi'])],
                                           mode='lines',
                                           name='Inizio Vaccini',
                                           hoverinfo='none',
                                           line=go.scatter.Line(color="#1F1C1C"))
                            ],
                            'layout': {
                                'xaxis': dict(
                                    rangeselector=dict(buttons=slider_button),
                                    rangeslider=dict(visible=False),
                                    type='date'
                                ),
                                'legend': dict(
                                    orientation="h",
                                    xanchor="center",
                                    x=0.5,
                                    y=-0.2
                                )
                            }
                        },
                        config=chart_config
                    )
                )
            )
        ])
    ], className='container-2')

# effect contagi
def riduzione_graph():
    ds1 = pandas.read_csv(somministrazioni)
    ddcr = pandas.read_csv(decessi_contagi_regioni)
    date_format = "%Y-%m-%d"  # date format
    ora = datetime.strptime(str(today), date_format)
    traces = ['']

    for reg in regions:
        # contagi
        if reg == 'Friuli-Venezia Giulia': reg1 = 'Friuli Venezia Giulia'
        elif reg == 'Provincia Autonoma Bolzano / Bozen': reg1 = 'P.A. Bolzano'
        elif reg == 'Provincia Autonoma Trento': reg1 = 'P.A. Trento'
        elif reg == "Valle d'Aosta / Vallée d'Aoste": reg1 = "Valle d'Aosta"
        else: reg1 = reg
        # population
        if reg1 == 'Abruzzo': popolazione = 1312000
        elif reg1 == 'Basilicata': popolazione = 562869
        elif reg1 == 'Calabria': popolazione = 1947000
        elif reg1 == 'Campania': popolazione = 5802000
        elif reg1 == 'Emilia-Romagna': popolazione = 4459000
        elif reg1 == 'Friuli Venezia Giulia': popolazione = 1215000
        elif reg1 == 'Lazio': popolazione = 5879000
        elif reg1 == 'Liguria': popolazione = 1551000
        elif reg1 == 'Lombardia': popolazione = 10060000
        elif reg1 == 'Marche': popolazione = 1525000
        elif reg1 == 'Molise': popolazione = 305617
        elif reg1 == 'P.A. Bolzano': popolazione = 520891
        elif reg1 == 'P.A. Trento': popolazione = 538223
        elif reg1 == 'Piemonte': popolazione = 4356000
        elif reg1 == 'Puglia': popolazione = 4029000
        elif reg1 == 'Sardegna': popolazione = 1640000
        elif reg1 == 'Sicilia': popolazione = 5000000
        elif reg1 == 'Toscana': popolazione = 3730000
        elif reg1 == 'Umbria': popolazione = 882015
        elif reg1 == "Valle d'Aosta": popolazione = 125666
        elif reg1 == 'Veneto': popolazione = 4906000
        # data contagi
        ddcr2 = ddcr.loc[ddcr['denominazione_regione'] == reg1]
        ddcr_contagi = ddcr2.loc[ddcr2['data'].between(str(ora-timedelta(days=7))[:10], str(ora)[:10]), ['nuovi_positivi']].sum()
        positive = round((int(ddcr_contagi)*100000)/popolazione, 2)
        # doses
        ds2 = ds1[ds1['nome_area'] == reg]
        ds_dosi_velocity = ds2.groupby('data_somministrazione').agg({'prima_dose': 'sum', 'nome_area': 'last'}).reset_index()
        doses = ds_dosi_velocity.loc[ds_dosi_velocity['data_somministrazione'].between('2020-12-27', str(today)), ['prima_dose']].sum()
        doses_percent = round((int(doses) / popolazione) * 100, 2)
        # traces
        traces.append(go.Scatter({'x': [float(positive)], 'y': [float(doses_percent)], 'mode': 'markers+text', 'marker': dict(color='crimson', size=12), 'text': f"{reg1}", 'textfont':dict(color='#B01B3E'), 'textposition': 'middle right', 'name': f"{reg1}"}))
    traces.pop(0)

    return html.Div([
        dbc.Container([
            dbc.Row(
                dbc.Col(
                    dcc.Graph(
                        figure={
                            'data': traces,
                            'layout': {
                                'xaxis': dict(
                                    rangeslider=dict(visible=False),
                                ),
                                'yaxis': {'title': 'Percentuale di Vaccinati'},
                                'xaxis': {'title': 'Nuovi positivi'},
                                'showlegend': False,
                            }
                        },
                        config=chart_config
                    )
                )
            )
        ])
    ], className='container-1')

def layout():
    refresh_data()
    return html.Div([
        # style
        html.Link(rel="stylesheet", media="screen and (min-width: 900px)", href="./assets/big.css"),
        html.Link(rel="stylesheet", media="screen and (max-width: 900px)", href="./assets/small.css"),
        # vaccine total
        html.Div([html.Br(), html.Br(), html.Center(html.H1('Vaccini')), html.Br(), html.Br()]),
        html.Div([vaccine_update()]),
        html.Div([vaccine_update_bar()]),  # orizzonatl bar
        # text
        html.Div(html.Center(html.I([html.Br(), "L'obiettivo della campagna di vaccinazione della popolazione è prevenire le morti da COVID-19 e raggiungere al più presto ", html.B("l'immunità di gregge"), " per il SARS-CoV2", html.Br(), "La campagna è partita il ", html.B("27 dicembre"), ", vista l'approvazione da parte dell'EMA del primo vaccino anti COVID-19.", html.Br(), "Dopo una fase iniziale, che dovrà essere limitata, per il numero di dosi consegnate, essa si svilupperà in continuo crescendo.", html.Br(), "I vaccini saranno offerti a ", html.B("tutta la popolazione"), ", secondo un ordine di ", html.B("priorità"), ", che tiene conto del rischio di ", html.B("malattia"), ", dei tipi di ", html.B("vaccino"), " e della loro ", html.B("disponibilità")], style={'font-size': 'large'}))),
        # daily data
        html.Div([html.Br(), html.Br(), html.Br(), html.Center(html.H1('Dati del Giorno')), html.Center(html.I('dati aggionati del '+str(last_update), style={'font-size': '14px'})), html.Br()]),
        html.Div([dropdown_vaccine_daily(), html.Br()]),  # dropdown
        html.Div(id='vaccine_daily'),
        # vaccine and doses
        html.Div([html.Br(), html.Br(), html.Center(html.H2('Vaccini & Dosi'))]),
        html.Div([html.Div(id='vaccine_graph'), html.Div(id='dosi_graph')], className='container-1'),
        # image
        html.Div(html.Center([html.Div([html.Img(src='./assets/ddoses.png', width="45", style={'vertical-align': 'bottom'}), html.B(' 2'), ' Dosi: ', html.I('Pfizer, Moderna e AstraZeneca', style={'font-size': '14px'})], className='container-2'), html.Div([html.Img(src='./assets/doses.png', width="30", style={'vertical-align': 'bottom'}), html.B(' 1'), ' Dose:', html.I(' Janssen', style={'font-size': '14px'})], className='container-2'),
                              html.Div([html.Br(), html.Br(), html.Br(), html.H2('Vaccini per fascia di età'), html.I('I dati sono calcolati sulle somministrazioni delle prime dosi', style={'font-size': '14px'})], className='container-1')], className='container-1')),
        html.Div([dropdown_vaccine_age_bar()]),
        html.Div(id='vaccine_age_bar'),
        html.Div([html.Div(id='category_global')], className='container-1'),
        # forecast
        html.Div([html.Br(), html.Br(), html.Br(), html.Center(html.H1('Previsioni')), html.Center(html.I('Il modello utilizza i dati giornalieri sulle somministrazioni delle prime dosi', style={'font-size': '14px'})), html.Center(html.I('*Media basata sul valore massimo di prime dosi fatte in un giorno, ad ora '+str(max_prima_f), style={'font-size': '14px'}))]),
        html.Div([previsione()]),
        # text forecast
        html.Div(html.Center([html.Br(), "Nell'ultimo ", html.B("mese"), " sono state somministrate ", html.Mark([html.B(str(max_prima_f)), " prime dosi"], style={'background-color': '#F5C05F'}),
             " in ", html.B("Italia"), " di cui ", html.Mark([html.B(str(tot_janssenf)), " monodose"], style={'background-color': '#F5C05F'}), html.Br(),
             "A questo ritmo il ", html.B("70% della popolazione"), " sarà vaccinata entro il ", html.Mark([str(month_last_day_vaccine)], style={'background-color': '#F5C05F'})])),
        # velocity
        html.Div([html.Br(), html.Br(), html.Br(), html.Center(html.H2('Velocità vaccinazioni')), html.Center(html.I('I dati sono calcolati sulle somministrazioni delle prime dosi', style={'font-size': '14px'}))]),
        html.Div([dropdown_velocity_dosi_graph()]),
        html.Div([html.Div(id='velocity_dosi_graph')], className='container-1'),
        # effect
        html.Div([html.Br(), html.Br(), html.Br(), html.Center(html.H2('Effetti dei Vaccini nel Tempo')), html.Br()]),
        html.Div([dropdown_effetti_decessi_contagi_graph(), html.Br()]),
        html.Div([html.Div(id='effetti_contagi_graph'), html.Div(id='effetti_decessi_graph')], className='container-1'),
        # text effect
        html.Div(html.Center([html.Div([html.Br(), "Contagi ", html.B("ultimo mese"), " in Italia: ", html.Mark([html.B("%s" %("+" if int(percent_mese) > 100 else "-")+str(float(percent_mese))+'%')], style={'background-color': '#F5C05F'})], className='container-2'),
                              html.Div([html.Br(), "Decessi ", html.B("ultimo mese"), " in Italia: ", html.Mark([html.B("%s" %("+" if int(percent_mese_death) > 100 else "-")+str(float(percent_mese_death))+'%')], style={'background-color': '#F5C05F'})], className='container-2'),
                              html.Div([html.Br(), html.Br(), html.Br(), html.H4('Quanto le vaccinazioni stanno contribuendo veramente alla riduzione dei contagi?'), html.I("I dati sono calcolati sulla percentuale di popolazione vaccinata e sull'incidenza dei contagi, nell'ultima settimana, per 100.000 abitanti", style={'font-size': '14px'})], className='container-1')], className='container-1')),
        # text riduzione
        html.Div([html.Br(), riduzione_graph()]),
    ])

app.layout = layout

if __name__ == '__main__':
    app.run_server(host='0.0.0.0', port=8050, debug=False)


import solc
from web3 import Web3, HTTPProvider
import json

source_file = './contracts/Coin.sol'
artifacts = solc.compile_files([source_file])

print(artifacts.keys())

coin_artifact = artifacts[source_file + ':' + 'Coin']

json.dump(
    coin_artifact['abi'],
    open('web/public/contract_interface.json', 'w'), indent=2)

web3 = Web3(HTTPProvider('http://localhost:8545'))

print('Owner:', web3.eth.accounts[0])

Coin = web3.eth.contract(abi=coin_artifact['abi'],
                         bytecode=coin_artifact['bin'])

tx_hash = Coin.deploy(transaction={'from': web3.eth.accounts[0] })
tx_receipt = web3.eth.getTransactionReceipt(tx_hash)

print('\nRECEIPT:')
for key, value in tx_receipt.items(): print('\t', key, value)

contract_address = tx_receipt['contractAddress']

json.dump(contract_address, open('web/public/contract_address.json', 'w'))


# -*- coding: utf-8 -*-

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('proso_user', '0004_userprofileproperty'),
    ]

    operations = [
        migrations.CreateModel(
            name='UserQuestion',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('identifier', models.SlugField()),
                ('lang', models.CharField(max_length=10)),
                ('content', models.TextField()),
                ('active', models.BooleanField(default=True)),
                ('answer_type', models.CharField(default='o', max_length=1, choices=[('c', 'closed'), ('m', 'mixed'), ('o', 'open')])),
                ('repeat', models.BooleanField(default=False)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='UserQuestionAnswer',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('open_answer', models.CharField(default=None, max_length=100, null=True, blank=True)),
                ('time', models.DateTimeField(auto_now_add=True)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='UserQuestionCondition',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('type', models.CharField(max_length=50)),
                ('value', models.CharField(max_length=50)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='UserQuestionEvent',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('type', models.CharField(max_length=50)),
                ('value', models.CharField(max_length=50)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='UserQuestionPossibleAnswer',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('identifier', models.SlugField()),
                ('active', models.BooleanField(default=True)),
                ('content', models.CharField(max_length=100)),
                ('question', models.ForeignKey(related_name='possible_answers', to='proso_user.UserQuestion')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.AddField(
            model_name='userquestionanswer',
            name='closed_answer',
            field=models.ForeignKey(default=True, blank=True, to='proso_user.UserQuestionPossibleAnswer', null=True),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='userquestionanswer',
            name='question',
            field=models.ForeignKey(related_name='user_answers', to='proso_user.UserQuestion'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='userquestionanswer',
            name='user',
            field=models.ForeignKey(to=settings.AUTH_USER_MODEL),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='userquestion',
            name='conditions',
            field=models.ManyToManyField(to='proso_user.UserQuestionCondition'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='userquestion',
            name='on_events',
            field=models.ManyToManyField(to='proso_user.UserQuestionEvent'),
            preserve_default=True,
        ),
    ]


#1 split the fasta files by genospecies
#2 run clonalframe (using the different species trees based on the concatenated genes)
#3 connect it to the rest of the pipeline
#4 code everything in the gwf manner
#5 update the github analysis
#6 write methodology in the draft
import pandas as pd
import numpy as np
import glob as glob
import os

def parse_pop_map(file_name = '/Users/PM/Desktop/PHD_incomplete/Bjarnicode/scripts/Rhizobium_soiltypes_new.txt'):
	from itertools import izip

	pop_map = {}
	t = pd.read_table(file_name)
	t = t.rename(columns=lambda x: x.strip())
	for strain_id, sara_id, origin, country in izip(t['Seq ID'], t['Strain ID'], t['Genospecies'], t['Origin2']):
		pop_map[str(strain_id)]={'sara_id': sara_id, 'genospecies':origin, 'country':country, 'origin2':origin}
	return pop_map

def parse_fasta(filename, stratify=True, genospecies=None, pop_dict=None):

	file = open(filename, 'r').read() #opening and reading the fasta file, putting it in a object called file
	file_separe = file.split('>') #spliting each entry by the >
	file_separe.remove('')
	parse_dict = {}
	header = []

	# Separating fasta files by genospecie
	if len(file_separe) == 196:

		for entry in file_separe:
			seq = entry.splitlines()
			header = seq[0] #these are the first elements of the list

			strain_name = header.split("|")[1]
			#print strain_name
			gene_name = header.split("|")[0]

			# Modifying header with sequence position
			header = strain_name

			genome_id = seq[0].split('|')[1]

			seq = ''.join(seq[1:]) #joining the sequences

			if stratify == True:
				if pop_dict[strain_name[0:4]]["genospecies"] == genospecies:
					parse_dict[header] = seq
			else:
				parse_dict[header] = seq
	return parse_dict

def write_fasta(tuple_fasta, directory):
	(fasta_name, dict_fasta) = tuple_fasta
	with open(directory+"{}".format(fasta_name), 'w') as f:
		for header, sequences in dict_fasta.items():
			f.write('>{}_{}\n'.format(fasta_name,header))
			chunks = [sequences[i:i+60] for i in range(0, len(sequences), 60)]
			for i in chunks:
				f.write('{}\n'.format(i))
		f.close()

pop_dict = parse_pop_map()

def split_fasta(genospecies, genospecies_dir, pop_dict=pop_dict):
	# Gene alignments:
	genes_path = [(f) for f in glob.glob("/Users/PM/Dropbox/Cavassim_et_al_2019_Rhizobium_data/group_alns/*.fna")]
	for i in genes_path:
		gene_name = os.path.basename(i)
		gene_dict = parse_fasta(i, genospecies=genospecies, pop_dict=pop_dict)
		if len(gene_dict.keys()) > 0:
			write_fasta((gene_name, gene_dict), directory=genospecies_dir)

split_fasta(pop_dict=pop_dict, genospecies="gsA", genospecies_dir="/Users/PM/Dropbox/Cavassim_et_al_2019_Rhizobium_data/")


#!/usr/bin/python3
import os.path, time,sys
"""
using only with 2 arguments:
1 - etalon where checksumm is normal
2 - etalon with wrong checksum, this will be modified!
 """
print(time.ctime())
bint = 4294967295;
maxn = bint;
ff = sys.argv[1] #"smo.img"
sf = sys.argv[2] #"smo1.img"
co = 0
su = 0
def prev(x):
    """

    :param x:

    """
    if (x > maxn):
        x = x%maxn;
        return x;
    else:return x;

def main(ar):
    """

    :param ar:

    """
    co = 0
    su = 0
    with open(ar, 'rb+')as f:
        for l in f.read():
            co = co + 1;
            su = su + co * l;
            su = prev(su);
    print("summ " + ar + " = " + str(su).zfill(10));
    return su;

def menee(sf):
    """

    :param sf:

    """
    co=0
    with open(sf, 'rb+')as f:
        for l in reversed(f.read()):
            f.seek(co+1,2)
            if(l==0):f.write(bytes([255]));break
            else:f.seek(co+1,2)
            co+=1

def prov():
    """ """
    fff=main(ff);
    sff=main(sf);
    if fff==sff:print(" sum2 = sum1");exit();
    if (fff > sff):
        rzn = fff - sff;
        print("difference: "+str(rzn));
        for d in range(255,0,-1):
            co4 = 0
            if (rzn % d == 0):
                with open(sf, 'rb+')as f:
                    for w in f.read():
                        if (d * co4 == rzn ):
                            if(w == 0):
                                print(f.tell());print("value "+str(w)+" * "+str(co4)+" place")
                                f.seek(co4-1); hu=bytes([d]);print("swap zero to: "+str(hu));f.write(hu);print("completed: "+time.ctime());exit();#print(f.tell());
                        co4 = co4 + 1#        print(d);
        menee(sf)
        print("restart")
        prov()
    else:
        print(" sum2 > sum1");
        menee(sf)
        print("restart")
        prov()
prov()


from django.urls import path

from . import views

app_name='blog'

urlpatterns=[
    path('',views.post_list,name='post_list'),
    path('<int:post_id>',views.post_detail,name='post_detail'),
    path('<int:post_id>/share/',views.post_share,name='post_share'),
    path('tag/<slug:tag_slug>/',views.post_list, name='post_list_by_tag'),
    path('search/', views.post_search, name='post_search'),
]


import re

from streamlink.plugin import Plugin, PluginError
from streamlink.stream import HLSStream
from streamlink.compat import unquote_plus, is_py3

QUALITY_WEIGHTS = {
    "src": 1080,
}

class DLive(Plugin):
    """
    Plugin for dlive.tv
    """

    _url_re = re.compile(r"https?://(?:www\.)?dlive\.tv/")
    _playback_re = re.compile(r"""(?<=playbackUrl":")(.+?)(?=")""")
    _livestream_re = re.compile(r""""livestream":null""")
    _username_re = re.compile(r"(?<=user:)(\w|-)+")

    @classmethod
    def can_handle_url(cls, url):
        return cls._url_re.match(url)

    @classmethod
    def stream_weight(cls, key):
        weight = QUALITY_WEIGHTS.get(key)
        if weight:
            return weight, "dlive"

        return Plugin.stream_weight(key)

    def _get_streams(self):
        res = self.session.http.get(self.url)

        m = self._playback_re.search(res.text)

        if m:
            hls_url = m.group(0)

            if is_py3:
                hls_url = bytes(unquote_plus(hls_url), "utf-8").decode(
                    "unicode_escape")
            else:
                hls_url = unquote_plus(hls_url).decode("unicode_escape")
        else:
            if self._livestream_re.search(res.text) is not None:
                raise PluginError('Stream is offline')

            m = self._username_re.search(res.text)
            if m:
                hls_url = "https://live.prd.dlive.tv/hls/live/{}.m3u8".format(
                    m.group(0))
            else:
                raise PluginError('Could not find username')

        return HLSStream.parse_variant_playlist(self.session, hls_url)

__plugin__ = DLive


import requests
import json
import time
import sys
from bs4 import BeautifulSoup
import re

class xiaoiceApi():

    def __init__(self, header_file):
        self.header_file = header_file
        self.headers = {}
        self.loadheaders()

    def loadheaders(self):
        with open(self.header_file) as headers:
            line = headers.readline().strip()
            while line:
                key = line.split(":")[0]
                self.headers[key] = line[len(key)+1:].strip()
                line = headers.readline().strip()

    def chat(self, input_strs):
        if not self.headers:
            return self.dicts("error", "请打开浏览器 复制并将headers放入headers.txt中")
        data = {
            'location':'msgdialog',
            'module':'msgissue',
            'style_id':1,
            'text':input_strs,
            'uid':5175429989,
            'tovfids':'',
            'fids':'',
            'el':'[object HTMLDivElement]',
            '_t':0,
        }

        try:
            #原http的api已改为https的api
            url = 'https://weibo.com/aj/message/add?ajwvr=6'
            page = requests.post(url, data=data, headers=self.headers)
#             self.savePage(page.text, "./tmp/postpage.txt")
            if page.json()['code'] == '100000':
                code, text, res_type = self.loop(input_strs)
                return self.dicts(code, res_type, text)
            else:
                return self.dicts("500", "failed", page.json()['msg'])
        except Exception as e:
            return self.dicts("500", "error", e)

    def dicts(self, status, res_type, text):
        '''
            包装return
        '''
        return {"status":status, "type":res_type, "text":text}

    def loop(self, input_strs):
        '''
            刷新直到获取到回答
        '''
        times = 1
        while times <= 20:
            times += 1
            response = requests.get("https://weibo.com/aj/message/getbyid?ajwvr=6&uid=5175429989&count=1&_t=0" , headers={"Cookie":self.headers["Cookie"]})
            soup = BeautifulSoup(response.json()['data']['html'], "lxml")
            text = soup.find("p", class_='page')
            if text:
                if text.text == input_strs:
                    time.sleep(0.3)
                    continue
            elif "收起" in soup.get_text():
                #返回imgURL
                imgUrl = soup.find(href=re.compile('msget')).get('href')
                return 200, imgUrl, "img"

            elif "mp3" in soup.get_text():
                mp3Url = soup.find(href=re.compile('msget')).get('href')
                return 200, mp3Url,"voice"

            return 200, text.text, "text"
        text = "错误： 已达到最大重试次数"
        return 500, text, "failed"

if __name__ == '__main__':
    xb = xiaoiceApi('header_file/headers_1.txt')