def parse_credentials(n_clicks, api_choice, *func_params): """ Create callbacks for every API login form, based on their \ connectors' function arguments. This reads the various connect \ functions and gets their arguments. **Note that the first argument \ is `self` so we need the rest of the arguments. Args: n_clicks (int): Number of button clicks. api_choice (str): One of the supported APIs. *func_params (list): Depending on the selected api and its \ connector function, the list of arguments \ it needs to receive, in order. Returns: A Dash element or list of elements. """ if n_clicks < 1: raise PreventUpdate() connection = api_connect(api_choice, *func_params) if connection.state == "authenticated": # Success logging in return connection.render_layout(), {"display": "none"} else: raise PreventUpdate()
def update_measure_checklist(selected, select_options, checked): if len(selected) < len(select_options) and len(checked) == 0: raise PreventUpdate() elif len(selected) < len(select_options) and len(checked) == 1: return dcc.Checklist( id='measure-select-all', options=[{ 'label': 'Select All', 'value': 'All' }], value=[], ) elif len(selected) == len(select_options) and len(checked) == 1: raise PreventUpdate() return dcc.Checklist( id='measure-select-all', options=[{ 'label': 'Select All', 'value': 'All' }], value=['All'], )
def add_network_elements(cy_network, _): if not cy_network: raise PreventUpdate() if 'network' not in cy_network: raise PreventUpdate() return [1, cy_network['network']]
def register_user(n_clicks, mobile, email, password, password_confirm): logger.debug("register user real process") if not n_clicks or n_clicks <= 0: raise PreventUpdate() if not mobile or not str(mobile).isdigit(): logger.debug("mobile is not valid") raise PreventUpdate() if password != password_confirm: logger.debug("password not valid") raise PreventUpdate() user_data = { 'email': email, 'tel': mobile, 'password': password, 'roles':["user"] } logger.debug("create club user") user = app_controller.create_club_user(CLUB_NAME, user_data) logger.debug("create club user successful") if user.tel: logger.debug("send code by tel") app_controller.resend_activate_code_by_tel(CLUB_NAME, user.tel) logger.debug("redirect to login") return "/user/login"
def update_checklist(selected, select_options, checked): if len(selected) < len(select_options) and len(checked) == 0: raise PreventUpdate() elif len(selected) < len(select_options) and len(checked) == 1: return dcc.Checklist( id="region-select-all", options=[{ "label": "Select All Regions", "value": "All" }], value=[], ) elif len(selected) == len(select_options) and len(checked) == 1: raise PreventUpdate() return dcc.Checklist( id="region-select-all", options=[{ "label": "Select All Regions", "value": "All" }], value=["All"], )
def update_chart_data(n, fig): if not fig: PreventUpdate() if control.get_value('lock'): # Abort update if chart refresh has locked it PreventUpdate() return view.update_chart(fig)
def redirect(jwt): if not jwt: raise PreventUpdate() user = app_controller.get_club_user_by_jwt(CLUB_NAME, jwt) if not user: raise PreventUpdate() return "/user/profile"
def update_checklist(selected, checked): if len(checked) == 0 and len(selected) < len(loc_options): raise PreventUpdate() elif len(checked) == 1 and len(selected) < len(loc_options): return dcc.Checklist(id="loc-select-all", options=[{"label": " Select All", "value": "All"}], value=[]) elif len(checked) == 1 and len(selected) == len(loc_options): raise PreventUpdate() else: return dcc.Checklist(id="loc-select-all", options=[{"label": " Select All", "value": "All"}], value=["All"])
def callback__weight(test_id, n, n_st): try: if n and n_st == False: print('WEIGHING...') df = getdata.get_dataframe(table=test_id) return str(df['S1'].iloc[-1]) + ' kg', str(df['S2'].iloc[-1]) + ' kg', \ str(df['S3'].iloc[-1])+ ' kg', str(df['S4'].iloc[-1])+ ' kg', \ str(df['S5'].iloc[-1]) + ' kg', str(df['S6'].iloc[-1])+ ' kg', \ str(df['S7'].iloc[-1])+ ' kg' else: raise PreventUpdate() except: raise PreventUpdate()
def store_user_info(msg, mobile_email, password): logger.debug("store user info") if msg: raise PreventUpdate() user = app_controller.get_club_user_by_tel_or_email( CLUB_NAME, mobile_email) if not user: raise PreventUpdate() jwt = app_controller.generate_user_jwt(CLUB_NAME, user) logger.debug("store jwt " + jwt) return jwt
def tester(selected, options_1, checked): if len(selected) < len(options_1) and len(checked) == 0: raise PreventUpdate() elif len(selected) < len(options_1) and len(checked) == 1: return dcc.Checklist(id='select-all', options=[{'label': 'Select All', 'value': 1}], value=[]) elif len(selected) == len(options_1) and len(checked) == 1: raise PreventUpdate() return dcc.Checklist(id='select-all', options=[{'label': 'Select All', 'value': 1}], value=[1])
def update_output_div(input_value: Dict[str, List]) -> Dict[str, Any]: """Update times series plot based on country from country map which user clicks on """ print(input_value) if not input_value: raise PreventUpdate() if "location" not in input_value["points"][0]: raise PreventUpdate() new_plot: Dict[str, Any] = update_time_series_plot(input_value, WORLD_MAP) from pprint import pprint pprint(new_plot) return new_plot
def show_warning_modal(*args): """ This shows a modal with a warning whenever the children of one of the warning-modal divs change. It displays the contents of the div in the modal. """ prop_id = dash.callback_context.triggered[0]['prop_id'] try: children = args[warning_modal_prop_id_names.index(prop_id)] if children: return [True, children] else: raise PreventUpdate() except ValueError: raise PreventUpdate()
def clear_variance_plots(n_clicks): if not n_clicks: raise PreventUpdate('Callback triggered with no action.') plot_data = PCAModel.get_plot_data() plot_data['cumulative_variance_plots'] = [] PCAModel.set_plot_data(plot_data) return [dbc.ListGroup([], id='cumulative-variance-plot-list')]
def clear_loading_plots(n_clicks): if not n_clicks: raise PreventUpdate('Callback triggered with no action.') plot_data = PCAModel.get_plot_data() plot_data['loading_plots'] = [] PCAModel.set_plot_data(plot_data) return [dbc.ListGroup([], id='loading-plot-list')]
def show_selected_file(value,selected_columns,data): if value == 'default': raise PreventUpdate() else: df_table = pd.DataFrame.from_dict(data[value]) df_table = df_table.sort_index() new_header = df_table.iloc[0] df_table = df_table[1:] df_table.columns = new_header if selected_columns is not None: list_of_sel_columns = selected_columns else: list_of_sel_columns = [] table = html.Div([ dash_table.DataTable( id='hidden_view_table', data=df_table.to_dict('rows'), columns=[*[{'name': 'Date', 'id':'Date', "selectable": False}] ,*[{'name': i, 'id':i, "selectable": True} for i in df_table.columns[1:]]], editable=True, virtualization=True, column_selectable="multi", selected_columns=list_of_sel_columns, page_action="native", page_current=0, page_size=8 ), ]) #print(list_of_sel_columns) return table
def update_legend(region, qoi_value, stat_value): legendLayers = [] if region == None or qoi_value == None or stat_value == None: raise PreventUpdate() if qoi_value != None and region != None and stat_value != None: colormap_range = colorMaps['scatterplot']['rangeRGB'] if qoi_value == 'LCOT' or qoi_value == 'All_in_LCOE' or qoi_value == 'Site_LCOE' or qoi_value == 'Dist_Km': colormap_range = colormap_range[::-1] SELECTED_DATA_PATH = pathlib.Path(__file__).parent.joinpath( "./data/" + region + "/").resolve() with open(SELECTED_DATA_PATH.joinpath('map_data_info.json')) as f: map_data_info = json.load(f) the_qoi = stat_value + qoi_value layers = { 'type': "colorLegend", 'id': "dataLayer", 'value': the_qoi, 'title': revQOI_map[qoi_value] + "\n (" + rev_stat_map[stat_value] + ")", "colorMap": { "scale": colorMaps['scatterplot']['scale'], "value": the_qoi, "range": colormap_range, "extent": [map_data_info[the_qoi]['min'], map_data_info[the_qoi]['max']] } } legendLayers.append(layers) return [legendLayers]
def update_nav(pathname): """Create the navbar with the current page set to active""" if pathname is None: # pathname is None on the first load of the app; ignore this raise PreventUpdate("Ignoring first url.pathname callback") # return Navbar(items=server.config['NAV_ITEMS'], current_path=pathname) return navbar(pathname)
def update_profile(codes): if codes is None: print("None") raise PreventUpdate("Empty") print("Updating portfolio graph...", codes) fig_data, index = get_portfolio_figdata(codes) return fig_data, index.to_json()
def update_nav_callback(pathname): """Create the navbar with the current page set to active""" if pathname is None: # pathname is None on the first load of the app; ignore this raise PreventUpdate( "Ignoring first Location.pathname callback") return self.make_nav(pathname)
def generate_side_bar_onload(pathname, sidebar, query_string): if pathname: if debug: print('--> Dash App Loaded!') print('\tAnd this is current path: {}'.format(pathname)) if not sidebar: if pathname: # Attention! query_string includes heading ? symbol selection = parse_qs(query_string[1:]) if debug: print('generate_side_bar_onload: This is the selection: {}'.format(selection)) # we might have selection of wikis and metrics in the query string, # so sidebar should start with those selected. pre_selected_wikis = selection['wikis'] if 'wikis' in selection else [] # change value for network selection from a list to a single string # (first network we got of the query string), # since user can select only one network at a time pre_selected_network = selection['network'][0] if 'network' in selection else None return side_bar.generate_side_bar(available_wikis, available_networks, pre_selected_wikis, pre_selected_network) else: # if app hasn't loaded the path yet, wait to load sidebar later return None; else: raise PreventUpdate("Sidebar already generated! sidebar must be generated only once");
def poll_result(n_intervals, data): result = result_from_tuple(data, app=celery_app) # If the calculation has not completed, do nothing. if not result.ready(): raise PreventUpdate() # On completion, enable button and set text (or stop spinner, etc.), return the result, and stop polling. return False, "Take a nap", result.get(), 0
def generate_side_bar_onload(pathname, sidebar, query_string): if pathname: if debug: print('--> Dash App Loaded!') print('\tAnd this is current path: {}'.format(pathname)) if not sidebar: if pathname: # Attention! query_string includes heading ? symbol selection = parse_qs(query_string[1:]) if debug: print('generate_side_bar_onload: This is the selection: {}'.format(selection)) # we might have selection of wikis and metrics in the query string, # so sidebar should start with those selected. pre_selected_wikis = selection['wikis'] if 'wikis' in selection else [] pre_selected_metrics = selection['metrics'] if 'metrics' in selection else [] return side_bar.generate_side_bar(available_wikis, available_metrics, pre_selected_wikis, pre_selected_metrics) else: # if app hasn't loaded the path yet, wait to load sidebar later return None; else: raise PreventUpdate("Sidebar already generated! sidebar must be generated only once");
def expand_graph(fig, s): if not fig: raise PreventUpdate() if not s: s = {} s["visibility"] = "visible" return s
def update_elements_cache_info(visualisation_session_info, elements_cache_info): if not visualisation_session_info or not draw_poagraph: raise PreventUpdate() if elements_cache_info: poagraph.remove_elements_data_faster(elements_cache_info) new_elem_cache_info = visualisation.get_elem_cache_info(int(visualisation_session_info)) return str(new_elem_cache_info)
def prepare_results_file(n_clicks, results_values, file_format_values): score_plot_data = PCAModel.get_plot_data()['score_plots'] pca_data = PCAModel() if not n_clicks: raise PreventUpdate('Callback triggered with no action.') if not pca_data.results_exist: return '#', 'secondary', dbc.Alert('Results do not exist.', color='warning', dismissable=True) try: path = pca_data.download_results( 'scores' in results_values, 'loadings' in results_values, 'explained_variance' in results_values, 'db_indices' in results_values, file_format_values, score_plot_data) message = dbc.Alert(f'Prepared results file as {path}', color='success', dismissable=True) class_name = 'btn btn-success' except Exception as e: path = '#' message = dbc.Alert([ html.P([html.Strong('Error: '), f'{e}']), html.Strong('Traceback:'), html.P( html.Pre(traceback.format_exc(), className='text-white')) ], color='danger', dismissable=True) class_name = 'btn btn-secondary disabled' return url_for('api.download_temporary_file', path=path), class_name, message
def prepare_plots_file(n_clicks, file_format_values, width, height, units, dpi): plot_data = PCAModel.get_plot_data() pca_data = PCAModel() if not n_clicks: raise PreventUpdate('Callback triggered with no action.') if not pca_data.results_exist: return '#', 'btn btn-secondary disabled', dbc.Alert( 'Results do not exist.', color='warning', dismissable=True) try: path = pca_data.download_plots( plot_data['score_plots'], plot_data['loading_plots'], plot_data['variance_plots'], plot_data['cumulative_variance_plots'], file_format_values, width, height, units, dpi) message = dbc.Alert(f'Prepared plots file as {path}.', color='success', dismissable=True) class_name = 'btn btn-success' except Exception as e: path = '#' message = dbc.Alert([ html.P([html.Strong('Error: '), f'{e}']), html.Strong('Traceback:'), html.P( html.Pre(traceback.format_exc(), className='text-white')) ], color='danger', dismissable=True) class_name = 'btn btn-secondary disabled' return url_for('api.download_temporary_file', path=path), class_name, message
def router_callback(pathname, search): """The router""" if pathname is None: raise PreventUpdate( "Ignoring first Location.pathname callback") page = self.routes.get(pathname, None) if page is None: layout = page_not_found(pathname) elif isinstance(page, Component): layout = page elif callable(page): kwargs = MultiDict(parse_qs(search.lstrip("?"))) layout = page(**kwargs) if not isinstance(layout, Component): msg = ( "Layout function must return a Dash Component.\n\n" f"Function {page.__name__} from module {page.__module__} " f"returned value of type {type(layout)} instead.") raise InvalidLayoutError(msg) else: msg = ( "Page layouts must be a Dash Component or a callable that " f"returns a Dash Component. Received value of type {type(page)}." ) raise InvalidLayoutError(msg) return layout
def update_graph_choice(*inputs): """ Update the value (plot choice) of the respective button and its label. Args: *inputs: The different plots (icons) for all shown/hidden traces \ for every graph type (total: max_traces * graph_types). Returns: list(str): The label and value of the various buttons, per \ trace menu. """ if all(x is None for x in inputs): raise PreventUpdate() triggered = dash.callback_context.triggered[0]["prop_id"] triggered_id = triggered.split(".")[0] # [:-2] to discard n graph_type = triggered_id[:-2] # Get configuration for the graph choice (graph_name, needs_yvar, allows_multi, needs_zvar, func) = graph2d_configs[graph_type] disabled_z = not needs_zvar display_z = "none" if disabled_z else "block" return [ graph2d_configs[graph_type][0], graph_type, { "display": display_z }, disabled_z ]
def map_hover_data(hover_data, pathname, normalize, moving_mean): if hover_data is None: raise PreventUpdate() if pathname == ('/' + IDS.Page.DAILY_STATE): daily_change = False else: daily_change = True voiv_name = str(hover_data['points'][0]['hovertext']) print("Hover over: ", voiv_name.encode('utf-8')) voiv = voivs[unidecode(voiv_name)] plot = plot_single_voiv(voiv, daily_change=daily_change, moving_mean=moving_mean, normalize=normalize != 0) plot.update_layout(yaxis_title="", legend_title="Grupa osób") state = voiv.get_state_daily().iloc[-1:] if DS_WITH_RECOVERY_CASES: badges = [ state.Wyleczeni.values[0], state.Chorzy.values[0], state.Zgony.values[0] ] else: badges = [state.Zarazeni.values[0], state.Zgony.values[0]] badges = list( map(lambda val: 0 if np.isnan(val) else str(int(val)), badges)) return [voiv_name.title(), plot] + badges