Esempio n. 1
0
def createlayout():
#     st.sidebar.title("Menu")
    query_params = st.experimental_get_query_params()
    app_check = st.experimental_get_query_params()

    session_state = SessionState.get(first_query_params=query_params)
    first_query_params = session_state.first_query_params

    app_check = {k: v[0] if isinstance(v, list) else v for k, v in app_check.items()}
    st.sidebar.title("Menu")
    page_list = ["Homepage", "Gender Gap", "Popular YouTubers"]
#     default_selectbox = int(app_check["selectbox"]) if "selectbox" in app_check else 0
    default_selectbox = int(app_check["selectbox"]) if "selectbox" in app_check else 0
    app_mode = st.sidebar.selectbox("Please select a page", page_list,index = default_selectbox)
    if app_mode:
#         app_check["selectbox"] = page_list.index(app_mode)
#         st.experimental_set_query_params(**app_check)
        app_check["selectbox"] = page_list.index(app_mode)
        st.experimental_set_query_params(**app_check)
#     app_mode = st.sidebar.selectbox("Please select a page", ["Homepage", "Gender Gap", "Popular YouTubers"])
        if app_mode == "Homepage":
            homepage()
        elif app_mode == "Gender Gap":
            gendergap.load_page()
        elif app_mode == "Popular YouTubers":
            youtube_earnings.load_page()
Esempio n. 2
0
 def set_url_fields():
     """Reflect parameters to the url query string."""
     values = {}
     for key, parameter in streamlit.session_state._parameters.items():
         if Parameters.is_set_all() or parameter.touched:
             values[key] = parameter.to_str(parameter.value)
     streamlit.experimental_set_query_params(**values)
Esempio n. 3
0
def get_set_multiselection(widget,
                           name='ConfirmedDeath',
                           label='Select Type',
                           options=['Death_Rate', 'Confirmed', 'Death'],
                           default_choices=['Death_Rate', 'Confirmed'],
                           key=None):
    '''
    can use as widget:

    st.multiselect
    st.sidebar.multiselect

    '''

    params = st.experimental_get_query_params()
    if not isinstance(params, dict): params = {}

    default_choices = params[name] if name in params else default_choices
    # default_indices = get_indices(options, default_choices)
    selections = widget(label=label,
                        options=options,
                        default=default_choices,
                        key=key)

    dict_selections = {name: selections}
    params = {**params, **dict_selections}

    st.experimental_set_query_params(**params)

    return selections
Esempio n. 4
0
    def get_and_set_active_app(self):

        query_params = st.experimental_get_query_params()
        maybe_default_view_id = self.get_maybe_active_view_id(query_params)
        logger.debug('url view id: %s', maybe_default_view_id)

        modules_by_id = self.list_modules()
        logger.debug('loaded mods: %s', modules_by_id)

        view = None
        if len(modules_by_id.keys()) == 0:
            pass
        else:
            if len(modules_by_id.keys()) == 1:
                view_id = list(modules_by_id.values())[0]['id']
                view = modules_by_id[view_id]
            else:
                sorted_mods = sorted(modules_by_id.values(),
                                     key=lambda nfo: nfo['index'])
                view_id = st.sidebar.selectbox(
                    '', [nfo['id'] for nfo in sorted_mods],
                    index=0 if maybe_default_view_id is None else
                    modules_by_id[maybe_default_view_id]['index'],
                    format_func=(lambda id: modules_by_id[id]['name'].upper()))
                view = modules_by_id[view_id]
                query_params[self.VIEW_APP_ID_VAR] = view_id
                st.experimental_set_query_params(**query_params)

        return view
Esempio n. 5
0
def run():
    st.set_page_config(page_title="Data Engineering QAQC", page_icon="📊")
    st.sidebar.markdown(
        """
        <div stule="margin-left: auto; margin-right: auto;">
        <img style='width:40%; margin: 0 auto 2rem auto;display:block;'
            src="https://raw.githubusercontent.com/NYCPlanning/logo/master/dcp_logo_772.png">
        </div>
        """,
        unsafe_allow_html=True,
    )

    datasets_list = list(datasets.keys())
    query_params = st.experimental_get_query_params()

    if query_params:
        name = query_params["page"][0]
    else:
        name = "Home"

    name = st.sidebar.selectbox("select a dataset for qaqc",
                                datasets_list,
                                index=datasets_list.index(name))

    st.experimental_set_query_params(
        page=datasets_list[datasets_list.index(name)])

    app = datasets[name]
    app()
Esempio n. 6
0
def get_set_selection(widget,
                      name='visualisation',
                      label='Select Maps or Timeseries',
                      options=['Maps', 'Timeseries'],
                      key=None):
    '''
    can use as widget:

    st.selectbox
    st.sidebar.selectbox
    st.radio
    st.sidebar.radio

    '''

    params = st.experimental_get_query_params()
    if not isinstance(params, dict): params = {}

    default_choice = params[name][0] if name in params else -1
    default_index = get_index(options, default_choice)
    selection = widget(label=label,
                       options=options,
                       index=default_index,
                       key=key)

    dict_selection = {name: selection}

    params = {**params, **dict_selection}

    st.experimental_set_query_params(**params)

    return selection
Esempio n. 7
0
def new_game():
    st.experimental_set_query_params()
    st.game_id = generate(8)
    st.experimental_set_query_params(round_number=1,
                                     game_id=st.game_id,
                                     prev_offer=0)
    session.run_id += 1
Esempio n. 8
0
def ensure_src_data_loaded():
    """
  Get source data file location from URL and try to load/decrypt it.
  Returns parsed source data as an object, or None if there was an error.
  If data could not be loaded, an appropriate error message and prompt will be added to UI.
  """

    # Source data location passed in as query param (https://.../?src=)
    qps = st.experimental_get_query_params()
    src_qp = qps.get('src', [None])[0]
    pwd_qp = qps.get('pwd', [None])[0]

    # Password in URL is base 64 encoded
    if pwd_qp:
        try:
            pwd_qp = base64.b64decode(pwd_qp).decode('ascii')
        except:
            pwd_qp = None

    # Error if no source data file specified
    if src_qp is None:
        st.write(
            '<font color="red">No source file specified. Please reload this page using the link that was provided.</font>',
            unsafe_allow_html=True)
        return None

    # Placeholder for error message and password prompt if needed
    pwd_field = None
    # st_error = st.empty()
    # with st_error.beta_container():
    #   pwd_err_field = st.empty()
    #   pwd_field = st.text_input('Enter password:'******'', type='password')
    #   pwd_submit = st.button('Submit')

    # Prefer user input to query param
    pwd = pwd_field or pwd_qp

    # Update URL to include current password
    if pwd:
        qps['pwd'] = base64.b64encode(pwd.encode('ascii')).decode('ascii')
        st.experimental_set_query_params(**qps)

    # Fetch/decrypt data
    data = None
    try:
        data = load_data(src_qp, pwd)
    except FileNotFoundError:
        st_error.write('<font color="red">Could not locate the data file ' +
                       src_qp + '</font>',
                       unsafe_allow_html=True)
    except ValueError as e:
        pwd_err_field.write(
            '<font color="red">Incorrect password for specified data file.</font>',
            unsafe_allow_html=True)

    # Remove error message/prompt on success
    # if data is not None:
    #   st_error.empty()

    return data
Esempio n. 9
0
def page_work(state_container, page_flip: bool):
    '''Main page workhorse'''

    if not state_container.helpSessionState:
        state_container.helpSessionState = HelpSessionState()

    state = state_container.helpSessionState

    url_params = st.experimental_get_query_params()
    help_on = url_params.get('help_on', [''])[0]

    if not help_on:
        st.info('Nothing to show help about')
        st.stop()

    helpdir = os.path.dirname(
        find_spec('suzieq.gui.pages').loader.path) + '/help'

    page_help_on = help_sidebar(state, helpdir)

    helptext = ''
    with open(f'{helpdir}/{help_on}.md', 'r') as f:
        helptext = f.read()

    if helptext:
        st.markdown(helptext)

    st.experimental_set_query_params(
        **{'page': '_Help_', 'help_on': help_on})
Esempio n. 10
0
def swap_app(app):
    st.experimental_set_query_params(app=app)
    session_state.app = app

    # Not sure why this is needed. The `set_query_params` doesn't
    # appear to work if a rerun is undergone immediately afterwards.
    time.sleep(0.01)
    st.experimental_rerun()
def main():
    title = "Music Genre Classifier"
    st.title(title)
    image = Image.open('./presentation/turntable-2154823_1920.jpg')
    st.image(image, use_column_width=True)

    if st.button('Record'):
        with st.spinner('Recording...'):
            signal = sd.rec(int(6 * RECORD_SR),
                            samplerate=RECORD_SR,
                            channels=1,
                            blocking=True,
                            dtype='float64')
            #sd.wait()
            signal = signal.reshape(signal.shape[0])
            #st.write(signal.shape)
            #st.write(signal)

            new_num_samples = round(
                len(signal) * float(DESIRED_SR) / RECORD_SR)
            signal = sps.resample(signal, new_num_samples)

            # st.write(signal.shape)
            # st.write(type(signal))
            # st.write(signal)

            st.experimental_set_query_params(signal=signal)

        st.success("Recording completed")

    app_state = st.experimental_get_query_params()

    if st.button('Play'):
        try:
            signal = np.array(app_state["signal"], dtype='float')
            # st.write(type(signal))
            # st.write(signal.shape)
            temp_file = io.BytesIO()
            write(temp_file, 22050, signal)
            st.audio(temp_file, format='audio/wav')
        except:
            st.write("Please record sound first")

    if st.button('Classify'):
        with st.spinner("Thinking..."):
            signal = np.array(app_state["signal"], dtype='float')
            # st.write(type(signal))
            # st.write(signal.shape)
            # st.write(signal)
            pred = model.predict(get_harm_perc(signal))
        st.success("Classification completed")
        labels[np.argmax(pred)]
Esempio n. 12
0
def page_work(state_container, page_flip: bool):
    '''Main page workhorse'''

    if not state_container.searchSessionState:
        state_container.searchSessionState = SearchSessionState()

    state = state_container.searchSessionState

    search_sidebar(state)

    if page_flip or (state_container.search_text != state.search_text):
        query_str = build_query(state, state_container.search_text)
    else:
        query_str = ''

    if query_str:
        if state.table == "address":
            df = gui_get_df(state_container.sqobjs[state.table],
                            view="latest",
                            columns=['default'],
                            address=query_str.split())
        else:
            df = gui_get_df(state_container.sqobjs[state.table],
                            view="latest",
                            columns=['default'])
            if not df.empty:
                df = df.query(query_str).reset_index(drop=True)

        expander = st.beta_expander(
            f'Search for {state_container.search_text}', expanded=True)
        with expander:
            if not df.empty:
                st.dataframe(df)
            else:
                st.info('No matching result found')

    for count, prev_res in enumerate(reversed(state.prev_results)):
        psrch, prev_df = prev_res
        if psrch == state_container.search_text:
            continue
        expander = st.beta_expander(f'Search for {psrch}', expanded=True)
        with expander:
            if not prev_df.empty:
                st.dataframe(prev_df)
            else:
                st.info('No matching result found')

    if query_str and (state_container.search_text != state.search_text):
        state.prev_results.append((state_container.search_text, df))
        state.search_text = state_container.search_text

    st.experimental_set_query_params(**asdict(state))
Esempio n. 13
0
def main_sync_state():
    '''Sync search & page state on main Suzieq GUI page'''
    wsstate = st.session_state

    if wsstate.search_text != wsstate.search:
        wsstate.search_text = wsstate.search
        wsstate.page = wsstate.sq_page = 'Search'

    if wsstate.page != wsstate.sq_page:
        wsstate.page = wsstate.sq_page
        st.experimental_set_query_params(**{'Page': wsstate.page})
        if wsstate.page != 'Search':
            wsstate.search_text = ''
Esempio n. 14
0
def run_pomodoro(pomodoro_queries):
    """
    Runs the complete loop of a pomodoro.
    This means 25 min for working and 5 min 
    for resting
    
    Args:
        pomodoro_queries: Pomodoro object. It controls all the 
            queries to the Pomodoro database
    """

    hour = pomodoro_queries.get_date_hour()
    # Save the value in the url for later use
    st.experimental_set_query_params(starting_hour=hour)
    timer(minutes=25, mode="work")
    timer(minutes=5, mode="rest")
Esempio n. 15
0
def update_query_params(state: SessionState):
    """
    update url query parameters based on current session state
    """
    params = [
        'emb_id', 'time_from', 'time_to', 'debug', 'n_results', 'search_type',
        'scope', 'query', 'query_cause', 'query_effect', 'doc_results',
        'umique_docs', 'top_n_ranking'
    ]
    updated_states = {}

    for param in params:
        if state[param]:
            updated_states[param] = state[param]

    st.experimental_set_query_params(**updated_states)
Esempio n. 16
0
    def _render(self, layout: dict) -> None:

        state = self._state

        if not state.table:
            return
        sqobj = get_sqobject(state.table)
        try:
            df = gui_get_df(state.table,
                            namespace=state.namespace.split(),
                            start_time=state.start_time,
                            end_time=state.end_time,
                            view=state.view, columns=state.columns)
        except Exception as e:  # pylint: disable=broad-except
            st.error(e)
            st.stop()

        if not df.empty:
            if 'error' in df.columns:
                st.error(df.iloc[0].error)
                st.experimental_set_query_params(**asdict(state))
                st.stop()
                return
        else:
            st.info('No data returned by the table')
            st.experimental_set_query_params(**asdict(state))
            st.stop()
            return

        if state.query:
            try:
                show_df = df.query(state.query).reset_index(drop=True)
                query_str = state.query
            except Exception as ex:  # pylint: disable=broad-except
                st.error(f'Invalid query string: {ex}')
                st.stop()
                query_str = ''
        else:
            show_df = df
            query_str = ''

        if not show_df.empty:
            self._draw_summary_df(layout, sqobj, query_str)
            self._draw_assert_df(layout, sqobj)

        self._draw_table_df(layout, show_df)
def authenticate(header=None, stop_if_unauthenticated=True):
    query_params = st.experimental_get_query_params()
    authorization_code = query_params.get("code", [None])[0]

    if authorization_code is None:
        authorization_code = query_params.get("session", [None])[0]

    if authorization_code is None:
        login_header(header=header)
        if stop_if_unauthenticated:
            st.stop()
        return
    else:
        logout_header(header=header)
        strava_auth = exchange_authorization_code(authorization_code)
        logged_in_title(strava_auth, header)
        st.experimental_set_query_params(session=authorization_code)

        return strava_auth
Esempio n. 18
0
def get_set(widget, session_state, name, key=None, *args, **kwargs):

    if key == None:
        key = name
        kwargs['key'] = key

    params = st.experimental_get_query_params()
    if not isinstance(params, dict): params = {}

    selection = widget(**kwargs)

    dict_selection = {name: selection}

    params = {**params, **dict_selection}
    params = limit_2_allowed_keys(session_state, params)

    st.experimental_set_query_params(**params)

    return selection
def exchange_authorization_code(authorization_code):
    response = httpx.post(url="https://www.strava.com/oauth/token",
                          json={
                              "client_id": STRAVA_CLIENT_ID,
                              "client_secret": STRAVA_CLIENT_SECRET,
                              "code": authorization_code,
                              "grant_type": "authorization_code",
                          })
    try:
        response.raise_for_status()
    except httpx.HTTPStatusError:
        st.error(
            "Something went wrong while authenticating with Strava. Please reload and try again"
        )
        st.experimental_set_query_params()
        st.stop()
        return

    strava_auth = response.json()

    return strava_auth
Esempio n. 20
0
def query_params():
    st.write("""
    # Introducing Query Params

    We have added to our experimental namespace the ability to get and set
    query parameters. With these query params, you can bookmark or share your app
    in various states. Thanks [@zhaoooyue](https://github.com/zhaoooyue) for the
    contribution!
    """)
    with st.echo("below"):
        radio_list = ['Eat', 'Sleep', 'Both']
        query_params = st.experimental_get_query_params()

        # Query parameters are returned as a list to support multiselect.
        # Get the first item in the list if the query parameter exists.
        default = int(
            query_params["activity"][0]) if "activity" in query_params else 0
        activity = st.radio("What are you doing at home during quarantine?",
                            radio_list,
                            index=default)
        if activity:
            st.experimental_set_query_params(
                activity=radio_list.index(activity))
Esempio n. 21
0
    def set_field(self, field: str, val):
        field = self.prefix + field
        query_params = st.experimental_get_query_params()
        logger.debug('params at set: %s', query_params.items())
        logger.debug('rewriting field %s val %s as %s', field, val,
                     urllib.parse.quote(json.dumps(val), safe=''))

        query_params = st.experimental_set_query_params(
            **{
                **{k: v[0]
                   for k, v in query_params.items()},
                **{
                    field: urllib.parse.quote(json.dumps(val), safe='')
                }
            })
Esempio n. 22
0
def main():
    st.set_page_config(page_title="DEAL OR NO DEAL",
                       page_icon="🤑",
                       initial_sidebar_state="expanded")
    st.sidebar.title('DEAL OR NO DEAL')
    selected_banker = st.sidebar.selectbox(
        'Pick your Banker', ['Random Forest', 'LightGBM', 'XGBoost'], 0)
    if st.sidebar.button('New Game'):
        new_game()
    st.sidebar.markdown("""
    This is a simulation of the Deal or No Deal Banker's offers. The code for this project can be found at [my Github](https://github.com/jstock29/dealnodeal) and the data that I painstakingly collected from over 100 episodes of the show is on [my Kaggle](https://www.kaggle.com/jaredstock/deal-or-no-deal-game-data).
    
    You can see what the RoboBanker will offer by simulating a board at various rounds. Each round you should pick the correct number of values from the board:
    
    1. Pick 6 - 6 Total
    2. Pick 5 - 11 Total
    3. Pick 4 - 15 Total
    4. Pick 3 - 18 Total
    5. Pick 2 - 20 Total
    6. Pick 1 - 21 Total
    7. Pick 1 - 22 Total
    8. Pick 1 - 23 Total
    9. Pick 1 - 24 Total
    10. Pick 1 -25 Total
    
    After each round you can see what my RoboBanker is offering you and decide if that's a deal you want to take or not. I will not give you that money though.
    
    FYI: Anonymous game data is sent to my database so I can maybe do stuff with it later. I don't know why that would sketch you out, this is all fake, but there you go.
    """)

    st.sidebar.caption('Jared Stock | NYC | 2021')

    app_state = st.experimental_get_query_params()
    game_id = app_state['game_id'][0]
    round_number = int(app_state['round_number'][0])
    prev_offer = float(app_state['prev_offer'][0])
    offer = 0.

    # st.write(app_state)
    st.header('Board')
    st.write('')
    col1, col2, col3 = st.beta_columns(3)
    l_cols = VALUES[:len(VALUES) // 2]
    r_cols = VALUES[len(VALUES) // 2:]
    model = joblib.load(f'bankers/{selected_banker}.pkl')

    with col1:
        values_1 = [
            st.checkbox(str(val), key=session.run_id)
            for val in VALUES[:len(VALUES) // 2]
        ]
        left_sum = sum(
            [val for i, val in enumerate(l_cols) if not values_1[i]])
    with col2:
        values_2 = [
            st.checkbox(str(val), key=session.run_id)
            for val in VALUES[len(VALUES) // 2:]
        ]
        right_sum = sum(
            [val for i, val in enumerate(r_cols) if not values_2[i]])
    values = values_1 + values_2
    choices = [val for i, val in enumerate(VALUES) if values[i]]
    remaining = [val for i, val in enumerate(VALUES) if not values[i]]
    remaining_bigs = [_ for _ in remaining if _ in BIG_VALUES]

    average = np.average(remaining)
    _max = max(remaining)

    if right_sum == 0:
        balance = (left_sum / L_SUM)
    elif left_sum == 0:
        balance = (right_sum / R_SUM)
    else:
        balance = (right_sum / R_SUM) / (left_sum / L_SUM)
    ev = expected_value(remaining)

    with col3:
        st.subheader('Info')
        st.write(f'Round: {round_number}')
        st.write(f'Picked: {len(choices)}')
        st.write(f'Previous Offer: {prev_offer}')
        st.write(f'Expected Value: {round(ev, 0)}')
        st.write(
            f'Probability of having a big value: {round(len(remaining_bigs) / len(remaining) * 100, 1)}%'
        )

    st.subheader('Banker Offer')

    if len(choices) > 5:
        X = pd.DataFrame({
            'Round': [round_number],
            'Board Average': [ev],
            'Previous Offer': [prev_offer]
        })

        p = model.predict(X)
        offer = float(p[0])

        st.write(f'Offer: ${round(float(offer), 2)}')

        if offer / ev <= 1:
            st.progress(offer / ev)
        else:
            st.progress(1)
        st.caption(
            f'Offer % of Expected Value: {round((offer / ev) * 100, 2)}%')

    else:
        st.info('Pick values to see offers')

    col14, col15 = st.beta_columns(2)
    if len(choices) == 6 or len(choices) == 11 or len(choices) == 15 or len(
            choices) == 18 or len(choices) >= 20:
        with col14:
            if st.button('Deal!'):
                round_data = {
                    "Game ID":
                    game_id,
                    "Round":
                    round_number,
                    "Remaining Values":
                    str(remaining),
                    "Board Value":
                    sum(remaining),
                    "Board Average":
                    round(average, 0),
                    "Board Balance":
                    round(balance, 3),
                    "Probability of Big Value":
                    round(len(remaining_bigs) / len(remaining), 3),
                    "Previous Offer":
                    prev_offer,
                    "Offer":
                    round(offer, 0),
                    "Offer Percent of Average":
                    round(offer / average, 4),
                    "model":
                    selected_banker,
                    "datetime":
                    datetime.datetime.now(),
                    "Deal":
                    True
                }
                df = pd.DataFrame(round_data, index=[0])
                populate_round(df, 'player_games')
        with col15:
            if st.button('No Deal!'):
                round_data = {
                    "Game ID":
                    game_id,
                    "Round":
                    round_number,
                    "Remaining Values":
                    str(remaining),
                    "Board Value":
                    sum(remaining),
                    "Board Average":
                    round(average, 0),
                    "Board Balance":
                    round(balance, 3),
                    "Probability of Big Value":
                    round(len(remaining_bigs) / len(remaining), 3),
                    "Previous Offer":
                    prev_offer,
                    "Offer":
                    round(offer, 0),
                    "Offer Percent of Average":
                    round(offer / average, 4),
                    "model":
                    selected_banker,
                    "datetime":
                    datetime.datetime.now(),
                    "Deal":
                    False
                }
                round_number += 1
                st.experimental_set_query_params(round_number=round_number,
                                                 game_id=game_id,
                                                 prev_offer=round(offer, 0))
                df = pd.DataFrame(round_data, index=[0])
                populate_round(df, 'player_games')
    data = get_data('player_games')
    data = data.loc[data['Game ID'] == game_id]
    if st.checkbox('Show data'):
        st.write(data)

    visualization.single_line(data, game_id, width=600, height=400)
Esempio n. 23
0
def page_work(state_container, page_flip: bool):
    '''The main workhorse routine for the XNA page'''

    if not state_container.statusSessionState:
        state_container.statusSessionState = StatusSessionState()

    state = state_container.statusSessionState
    draw_sidebar_status(state, state_container.sqobjs)

    col1, mid, col2 = st.beta_columns([2, 1, 2])
    with col1:
        dev_gr = st.empty()
    with col2:
        if_gr = st.empty()
    col3, mid, col4 = st.beta_columns([2, 1, 2])
    with col3:
        bgp_gr = st.empty()
    with col4:
        ospf_gr = st.empty()

    # Get each of the summarize info
    if state.namespace:
        ns = [state.namespace]
    else:
        ns = []
    dev_df = gui_get_df(state_container.sqobjs['device'],
                        namespace=ns,
                        columns=['*'])
    if not dev_df.empty:
        dev_status = dev_df.groupby(by=['namespace', 'status'])['hostname'] \
                           .count() \
                           .reset_index() \
                           .rename({'hostname': 'count'}, axis=1)

        dev_chart = alt.Chart(dev_status, title='Devices') \
                       .mark_bar(tooltip=True) \
                       .encode(y='status', x='count:Q', row='namespace',
                               color=alt.Color(
                                   'status',
                                   scale=alt.Scale(domain=['alive', 'dead'],
                                                   range=['green', 'red']))
                               )
        dev_gr.altair_chart(dev_chart)
    else:
        dev_gr.info('No device info found')

    if_df = gui_get_df(state_container.sqobjs['interfaces'],
                       namespace=ns,
                       columns=['*'])
    if not if_df.empty:
        if_df['state'] = np.where(
            (if_df.state == "down") & (if_df.adminState == "down"),
            "adminDown", if_df.state)

        if_status = if_df.groupby(by=['namespace', 'state'])['hostname'] \
                         .count() \
                         .reset_index() \
                         .rename({'hostname': 'count'}, axis=1)

        if_chart = alt.Chart(if_status, title='Interfaces') \
                      .mark_bar(tooltip=True) \
                      .encode(y='state', x='count:Q', row='namespace',
                              color=alt.Color(
                                  'state',
                                  scale=alt.Scale(domain=['up', 'adminDown',
                                                          'down'],
                                                  range=['green', 'orange',
                                                         'red']))
                              )
        if_gr.altair_chart(if_chart)
    else:
        if_gr.info('No Interface info found')

    bgp_df = gui_get_df(state_container.sqobjs['bgp'],
                        namespace=ns,
                        columns=['*'])

    if not bgp_df.empty:
        bgp_status = bgp_df.groupby(by=['namespace', 'state'])['hostname'] \
                           .count() \
                           .reset_index() \
                           .rename({'hostname': 'count'}, axis=1)

        bgp_chart = alt.Chart(bgp_status, title='BGP') \
                       .mark_bar(tooltip=True) \
                       .encode(y='state', x='count:Q', row='namespace',
                               color=alt.Color(
                                   'state',
                                   scale=alt.Scale(
                                       domain=['Established',
                                               'NotEstd', 'dynamic'],
                                       range=['green', 'red', 'orange']))
                               )
        bgp_gr.altair_chart(bgp_chart)

    ospf_df = gui_get_df(state_container.sqobjs['ospf'],
                         namespace=ns,
                         columns=['*'])
    if not ospf_df.empty:
        ospf_df['state'] = np.where(ospf_df.ifState == "adminDown",
                                    "adminDown", ospf_df.adjState)

        ospf_status = ospf_df.groupby(by=['namespace', 'state'])['hostname'] \
                             .count() \
                             .reset_index() \
                             .rename({'hostname': 'count'}, axis=1)

        ospf_chart = alt.Chart(ospf_status, title='OSPF') \
                        .mark_bar(tooltip=True) \
                        .encode(y='state', x='count:Q', row='namespace',
                                color=alt.Color(
                                    'state',
                                    scale=alt.Scale(
                                        domain=['full', 'fail',
                                                'adminDown', 'passive'],
                                        range=['green', 'red', 'orange', 'peach']))
                                )
        ospf_gr.altair_chart(ospf_chart)

    sqdf = gui_get_df(state_container.sqobjs['sqPoller'],
                      columns=['namespace', 'hostname', 'timestamp'],
                      service='device',
                      namespace=ns)
    if not sqdf.empty:
        hosts = sqdf.groupby(by=['namespace'])['hostname'] \
                    .nunique() \
                    .reset_index() \
                    .rename({'hostname': '#devices'}, axis=1)
        times = sqdf.groupby(by=['namespace'])['timestamp'] \
                    .max().reset_index() \
                          .rename({'timestamp': 'lastPolledTime'}, axis=1)
        pstats = times.merge(hosts, on=['namespace'])

        st.subheader('Poller Status')
        st.dataframe(pstats)

    st.experimental_set_query_params(**{})
Esempio n. 24
0
        dbname=st.secrets['dbname']))

session = SessionState.get(run_id=0)


def generate(random_chars=12, alphabet="0123456789abcdef"):
    r = random.SystemRandom()
    return ''.join([r.choice(alphabet) for i in range(random_chars)])


query_params = st.experimental_get_query_params()
if not hasattr(st, 'game_id') or not query_params:
    st.game_id = generate(8)
    session.game_id = st.game_id
    st.experimental_set_query_params(round_number=1,
                                     game_id=st.game_id,
                                     prev_offer=0)


def main():
    st.set_page_config(page_title="DEAL OR NO DEAL",
                       page_icon="🤑",
                       initial_sidebar_state="expanded")
    st.sidebar.title('DEAL OR NO DEAL')
    selected_banker = st.sidebar.selectbox(
        'Pick your Banker', ['Random Forest', 'LightGBM', 'XGBoost'], 0)
    if st.sidebar.button('New Game'):
        new_game()
    st.sidebar.markdown("""
    This is a simulation of the Deal or No Deal Banker's offers. The code for this project can be found at [my Github](https://github.com/jstock29/dealnodeal) and the data that I painstakingly collected from over 100 episodes of the show is on [my Kaggle](https://www.kaggle.com/jaredstock/deal-or-no-deal-game-data).
    
Esempio n. 25
0
        if INITIAL_SELECTION and dataset == INITIAL_SELECTION:
            selection = i
        datasets.append(dataset)

    if selection is not None:
        option = st.sidebar.selectbox("Dataset",
                                      datasets,
                                      index=selection,
                                      format_func=lambda a: a)
    else:
        option = st.sidebar.selectbox("Dataset",
                                      datasets,
                                      format_func=lambda a: a)
    print(option)
    app_state["dataset"] = option
    st.experimental_set_query_params(**app_state)

    # Side bar Configurations.
    configs = get_confs(option)
    conf_avail = len(configs) > 0
    conf_option = None
    if conf_avail:
        start = 0
        for i, conf in enumerate(configs):
            if conf.name == app_state.get("config", None):
                start = i
        conf_option = st.sidebar.selectbox("Subset",
                                           configs,
                                           index=start,
                                           format_func=lambda a: a.name)
        app_state["config"] = conf_option.name
Esempio n. 26
0

sections = list(map(lambda d: d.value, Section))
section_i = 0
section_param = st.experimental_get_query_params().get("section")
if section_param and section_param[0] in sections:
    section_i = sections.index(section_param[0])

section = st.sidebar.radio("Section", sections, index=section_i)

st.sidebar.markdown("""
Made by [Alex Garcia](https://twitter.com/agarcia_me) 🦒
""")

if section == Section.INTRO.value:
    st.experimental_set_query_params(section=Section.INTRO.value)

    st.write("""
# Introducing [`streamlit-observable`](https://github.com/asg017/streamlit-observable)!

👋🏼 Hello! This Streamlit app is an introduction to the [`streamlit-observable`](https://github.com/asg017/streamlit-observable) 
library - a Streamlit custom component for embeding [Observable notebooks](https://observablehq.com)
into Streamlit apps. You can render, re-use, and recycle any Observable notebook
found on [observablehq.com](https://observablehq.com), 
giving you access to hundreds of data visualizations,
maps, charts, and animations that you can embed into any Streamlit app!

👈🏼Check out the sidebar for a deep-dive into different ways you can use 
`streamlit-observable` in your apps. Each example has a checkbox that looks like this:"""
             )
Esempio n. 27
0
st.title("FacDB QAQC")


def get_branches():
    url = "https://api.github.com/repos/nycplanning/db-facilities/branches"
    response = requests.get(url).json()
    return [r["name"] for r in response]


branches = get_branches()
query_params = st.experimental_get_query_params()
default = query_params["branch"][0] if "branch" in query_params else "develop"
branch = st.sidebar.selectbox("Select a Branch",
                              branches,
                              index=branches.index(default))
st.experimental_set_query_params(branch=branch)
table_style = st.sidebar.radio("Dataframe Display Style",
                               ("plotly", "streamlit"))


def plotly_table(df):
    fig = go.Figure(data=[
        go.Table(
            header=dict(
                values=list(df.columns),
                line_color="darkslategray",
                fill_color="gray",
                font=dict(color="white", size=12),
                align="center",
            ),
            cells=dict(
Esempio n. 28
0
    predictor = st.button("Make a Prediction 🔥")
    prediction = st.empty()
    
    upload_options = ['Choose existing', 'Upload','URL']

    query_params = st.experimental_get_query_params()
    # Query parameters are returned as a list to support multiselect.
    # Get the second item (upload) in the list if the query parameter exists.
    # Setting default page as Upload page, checkout the url too. The page state can be shared now!
    default = 0

    activity = choose.selectbox("Choose existing sample or try your own:", upload_options, index=default)

    if activity:
        # updating url based on set activity 
        st.experimental_set_query_params(activity=upload_options.index(activity))
        
        if activity == 'Choose existing':
            selected_sample = upload.selectbox("Pick from existing samples", (list(sample_images_dict.keys())))
            IMAGE_PATH = sample_images_dict[selected_sample]
            image = image_from_url(IMAGE_PATH)
            img_file_buffer = None

        elif activity == 'Upload':
            image = None

            # You can specify more file types below if you want
            img_file_buffer = upload.file_uploader("Upload image", type=['jpeg', 'png', 'jpg', 'webp'], multiple_files = True)

            IMAGE_PATH = img_file_buffer
            try:
Esempio n. 29
0
def main():
    st.title("COVID SCRIPTS of René Smit")

    #    [n. name in menu, module name]
    options = [
        ["0. welcome", "welcome"],
        ["1. covid dashboard", "covid dashboard rcsmit"],
        ["2. plot hosp ic per age", "plot hosp ic streamlit"],
        [
            "3. false positive rate covid test",
            "calculate false positive rate covid test streamlit"
        ], ["4. number of cases interactive", "number of cases interactive"],
        ["5. ifr from prevalence", "calculate_ifr_from_prevalence_streamlit"],
        ["6. fit to data", "fit to data streamlit"],
        ["7. SEIR hobbeland", "SEIR hobbeland"],
        ["8. show contactmatrix", "show contactmatrix"],
        ["9. r getal per provincie", "r getal per provincie"],
        ["10. Cases from suspectibles", "cases_from_susp_streamlit"],
        ["11. Fit to data OWID", "fit_to_data_owid_streamlit_animated"],
        [
            "12. Calculate R per country owid",
            "calculate_r_per_country_owid_streamlit"
        ], ["13. Covid dashboard OWID/Google or Waze", "covid dashboard owid"],
        [
            "14. Dag verschillen per leeftijd",
            "dag_verschillen_casus_landelijk"
        ], ["15. Calculate spec./abs. humidity from rel. hum", "rh2q"],
        ["16. R getal per leeftijdscategorie", "r_number_by_age"],
        ["17. Show rioolwaardes", "show_rioolwater"],
        ["18. SIR model met leeftijdsgroepen", "SIR_age_structured_streamlit"],
        [
            "19. grafiek pos testen per leeftijdscat",
            "grafiek pos testen per leeftijdscategorie streamlit"
        ], ["20. per provincie per leeftijd", "perprovincieperleeftijd"],
        ["21. kans om covid op te lopen", "kans_om_covid_op_te_lopen"],
        ["22. Data per gemeente", "vacc_inkomen_cases"],
        ["23. VE Israel", "israel_zijlstra"],
        ["24. Hosp/death NL", "cases_hospital_decased_NL"],
        ["25. VE Nederland", "VE_nederland_"],
        ["26. Scatterplots QoG OWID", "qog_owid"],
        ["27. VE & CI calculations", "VE_CI_calculations"],
        ["28. VE scenario calculator", "VE_scenario_calculator"],
        ["29. VE vs inv. odds", "VE_vs_inv_odds"],
        [
            "30. Fit to data Levitt",
            "fit_to_data_owid_levitt_streamlit_animated"
        ],
        [
            "31. Aerosol concentration in room by @hk_nien",
            "aerosol_in_room_streamlit"
        ], ["32. Compare two variants", "compare_two_variants"],
        ["33. Scatterplot OWID", "scatterplots_owid"],
        ["34. Playing with R0", "playing_with_R0"]
    ]

    query_params = st.experimental_get_query_params(
    )  # reading  the choice from the URL..

    choice = int(
        query_params["choice"][0]
    ) if "choice" in query_params else 0  # .. and make it the default value

    if choice == 99:  #sandbox
        try:
            module = dynamic_import("various_test_and_sandbox")
        except Exception as e:
            st.error(f"Module not found or error in the script\n")
            st.warning(f"{e}")
            st.stop()
        try:
            module.main()
        except Exception as e:
            st.error(
                f"Function 'main()' in module '{module}' not found or error in the script"
            )
            st.warning(f"{e}")
            st.warning(traceback.format_exc())
            st.stop()
        st.stop()

    menuchoicelist = [options[n][0] for n, l in enumerate(options)]

    with st.sidebar.expander(
            'MENU: Choose a script | scroll down for options/parameters',
            expanded=True):
        menu_choice = st.radio("", menuchoicelist, index=choice)

    st.sidebar.markdown("<h1>- - - - - - - - - - - - - - - - - </h1>",
                        unsafe_allow_html=True)
    st.experimental_set_query_params(choice=menuchoicelist.index(
        menu_choice))  # setting the choice in the URL

    for n, l in enumerate(options):
        if menu_choice == options[n][0]:
            m = options[n][1].replace(
                " ", "_")  # I was too lazy to change it in the list
            try:
                module = dynamic_import(m)
            except Exception as e:
                st.error(f"Module '{m}' not found or error in the script\n")
                st.warning(f"{e}")
                st.stop()
            try:
                module.main()
            except Exception as e:
                st.error(
                    f"Function 'main()' in module '{m}' not found or error in the script"
                )
                st.warning(f"{e}")
                st.warning(traceback.format_exc())
                st.stop()
app_state = st.experimental_get_query_params()

if app_state != {}:
    nInput = app_state['nInput'][0]
    context = int(app_state['context'][0])

if nInput != "":
    placeTitle.markdown(
        f"<div style='font-size:30px;color:grey;font-family:orbitron;'>\
    <center><b>Talk with Jarvis</b></center></div>",
        unsafe_allow_html=True)

    nInput = nInput.lower().replace(" ", "")
    st.experimental_set_query_params(**{
        "nInput": nInput,
        "context": str(context)
    })

    if nInput not in os.listdir():
        os.system(f"mkdir {nInput}")
    st.markdown("---")

    try:
        f = open(f"{nInput}/step.txt")
        step = int(f.read())
        f.close()
    except:
        f = open(f"{nInput}/step.txt", "w")
        f.write("0")
        f.close()