问:
How to use relayoutData in the dash app to zoom into graph and maintain the zoom for new data
I have build a dash application. There are two graphs in the dashboard. So I was trying to implement relayoutdata function in the dashboard so that user can zoom in those graphs and maintain the zoom by not reloading the graphs and preserve the state for new data points.

The code which I was trying to implement is below -

Thanks for any help in advance!

```<code>#callback for buttons

@app.callback(dash.dependencies.Output('buttons', 'children'),
              [dash.dependencies.Input('button-1', 'n_clicks'),
               dash.dependencies.Input('button-2', 'n_clicks'),
               dash.dependencies.Input('button-4', 'n_clicks')
              ])

def displayClick(btn1,btn2,btn4):
    changed_id = [p['prop_id'] for p in dash.callback_context.triggered][0]
    if 'button-2' in changed_id:
        return html.Div(children = [

        html.Div(dcc.Dropdown(
                id = 'lineSelect1',
                options = lineOptions,
                placeholder = 'Select Line',
                clearable=False,
                style = dropdownStyle,
            )), html.Div(dcc.DatePickerRange(
        id='date_picker',
        min_date_allowed=date(2020, 1, 1),
        max_date_allowed=date.today()+timedelta(days=1),
        initial_visible_month=date.today()-timedelta(days=1),
        start_date=date.today()-timedelta(days=1),
        end_date=date.today(),
        style = dropdownStyle1

    )),
            html.Div(id='AlarmHistory'),
        ])

    elif 'button-4' in changed_id:
        path = "C:/Users/ISLAMS/Downloads/Work/Project Fusion/Plating Lines Code/Lincoln Files/"
        extension = 'xlsx'
        os.chdir(path)
        result = glob.glob('*.{}'.format(extension))
        result = [sub.replace('.xlsx','') for sub in result]
        sheetOptions = [{'label' :i,'value' :i } for i in result]

        return html.Div([

        dcc.Dropdown(
                id = 'sheetSelect1',
                options = sheetOptions,
                value = result[0],
                placeholder = 'Select Line',
                clearable=False,
                style = dropdownStyle1,
            ),

         html.Div(id='editTable'),

     ])
    else:
        return html.Div([
            dcc.Dropdown(
                id = 'lineSelect',
                options = lineOptions,
                multi = True,
                placeholder = 'Select Lines',
                clearable=True,
                value = td2[0].unique(),
                style = dropdownStyle,
            ),
            html.Br(),
            html.Div(id='table'),
            dcc.Interval(id='refresh-table',
                        interval = 120000,
                        n_intervals = 0,
                        max_intervals=99999999999),
        ])

#call back for All Plating Lines

@app.callback(
    dash.dependencies.Output('table', 'children'),
    [dash.dependencies.Input('lineSelect', 'value'),
    dash.dependencies.Input('refresh-table', 'n_intervals'),])

def filter_table(input,num):
    if num == 99999999999:
        raise PreventUpdate
    else:
        print ("The code is inside the function")
        df2 = pd.read_sql_query(query_3, engine)
        df2['location'] = df2['location'].replace(regex='AmpsActual',value='')
        df2['line'] = np.where(df2.location.str[3] == '1' ,df2.line+' 1',df2.line)
        df2['line'] = np.where(df2.location.str[3] == '2' ,df2.line+' 2',df2.line)

        tableData = df2.pivot_table('alarmflag',['line','linespeed'],'location',aggfunc = 'first')
        tableData = pd.DataFrame(tableData.to_records())
        tableData.columns = [hdr.replace("('alarmflag',","").replace(")","") for hdr in tableData.columns]

        td1 = tableData
        td1['linespeed'] = td1['linespeed'].round(1)
        td1['linespeed'] = td1['linespeed'].astype(str)

        for j in td1.columns:
            if j not in ['line','linespeed']:
                td1[j] = j + td1[j]

        sort0_cols = td1.columns[td1.columns.str.contains(pat="EC")  ]
        sort1_cols = td1.columns[td1.columns.str.contains(pat="Ni")  ]
        sort2_cols = td1.columns[td1.columns.str.contains(pat="Ag")  ]
        sort3_cols = td1.columns[td1.columns.str.contains(pat="Sn")  ]
        sort4_cols = td1.columns[(~td1.columns.str.contains(pat="EC") & ~td1.columns.str.contains(pat="Ni") &
                                  ~td1.columns.str.contains(pat="Ag") & ~td1.columns.str.contains(pat="Sn") &
                                  ~td1.columns.str.contains(pat="line") ) ]
        td1 = pd.concat([td1['line'],td1['linespeed'],td1[sort0_cols],td1[sort1_cols],td1[sort2_cols],td1[sort3_cols],td1[sort4_cols]],axis=1)
        td1['new'] = td1.apply(lambda x: ','.join(x.dropna()),axis=1)
        td2 = td1['new'].apply(lambda x:pd.Series(x.split(',')))
        td2.rename(columns = {0:'line'},inplace=True)

        df = pd.DataFrame(data = td2)
        dfFiltered = pd.DataFrame()
        temp = input

        dfFiltered = df[df.line.isin(temp)]

        return html.Div([
            dash_table.DataTable(
                id='tab',
                columns = [{"name": i, "id": i} for i in dfFiltered.columns],
                data = dfFiltered.to_dict('records'),

                style_cell={'maxWidth': 0,
                            'overflow': 'hidden',
                            'textOverflow': 'ellipsis',
                            'textAlign': 'center',
                            'font-family': 'Verdana',
                            'margin':'10px',
                            'font-weight': 'bold',
                            },
                style_header = {'display': 'none'},
                style_data_conditional = ([{'if':{'filter_query': '{{{col}}} is blank'.format(col=col),
                                                  'column_id' : col},
                                            'backgroundColor': 'white',
                                            'color': 'white' } for col in dfFiltered.columns] +
                                          [{'if':{'filter_query': '{{{col}}} contains "."'.format(col=col),
                                                  'column_id' : col},
                                            'backgroundColor': '#CC0000',
                                            'color': 'white' } for col in dfFiltered.columns] +
                                          [{'if':{'filter_query': '{{{col}}} contains "`"'.format(col=col),
                                                  'column_id' : col},
                                            'backgroundColor': 'white',
                                            'color': 'green' } for col in dfFiltered.columns] +
                                          [{'if':{'filter_query': '{{{col}}} contains " "'.format(col=col),
                                                  'column_id' : col},
                                            'backgroundColor': '#D3D3D3',
                                            'color': 'black' } for col in dfFiltered.columns]
                                           +  [{'if':{
                                                   'column_id' : 1},
                                             'backgroundColor': '#D3D3D3',
                                             'color': 'black' }]
                                          ),
                )
            ,   dcc.Graph(id="graph3", style={"width": "50%", "display": "inline-block"}),
            dcc.Graph(id="graph4", style={"width": "50%", "display": "inline-block"}),])

#call back for selection on All Plating Lines

@app.callback(
    [Output('graph3', 'figure'),Output('graph4', 'figure')],
    [Input('tab', 'derived_virtual_data'),Input('tab', 'active_cell')])

def show_graph(rows, selection):

    dff = pd.DataFrame(rows)

    if selection is None:
        n_intervals = 0
        return {}, {}
    else:
        n_intervals = 99999999999
        loc = dff.iloc[selection['row']][selection['column']-1]
        loc = loc.replace('.','').replace('`','').replace(' ','').replace('AmpsActual','')
        input1 = loc + 'AmpsActual'
        t1 = dff.iloc[selection['row']]['line']
        input2 = t2 = t1[:3]
        t1 = 'USMLXLIUP_' + t2

        cnxn_1 = mysql.connector.connect(AWS Credentials)
        cursor = cnxn_1.cursor()

        query_4 = """Select COLUMN_NAME from information_schema.columns where TABLE_NAME = '{}'
        and TABLE_SCHEMA = 'ppqa' and
        (COLUMN_NAME like '{}%' or COLUMN_NAME = 'DateTime' )
        order by ORDINAL_POSITION"""

        table_columns = pd.read_sql_query(query_4.format(t1,loc), cnxn_1)

        col_list = [i for i in table_columns['COLUMN_NAME']]
        col_string = ', '.join([str(i) for i in col_list])

        query_5 = """SELECT {},  '{}' as line, NOW() as lastrefreshdate
                FROM ppqa.{}
                where DateTime >= now() - interval 24 hour
                order by DateTime"""

        df = pd.read_sql_query(query_5.format(col_string,t2,t1), cnxn_1)

        if len(df) == 0:
            return {}, {}
        else:
            df['data point i'] = df.index + 1
            filename = t2
            volt_col = input1.replace('Amp','Volt')

            tolerance_inputs = pd.read_excel("/home/sislam/Sohail Islam/Adhoc/Project Fusion/Notebook/Lincoln Plating Lines/Files/"+filename +".xlsx", sheet_name = 'Sheet1')

            current_tolerance = int(tolerance_inputs["Current Tolerance for " + input1].loc[0])
            voltage_tolerance = int(tolerance_inputs["Voltage Tolerance for Standard Deviation for " + volt_col].loc[0])

            standard_dev_15_rows = df[df['data point i'] <= 15][volt_col].std()

            df['rolling_average']  = df[volt_col].rolling(15).mean()

            def func_voltage_mu_o(df):
                if df['data point i'] <= 15:
                    return (df[volt_col])
                else:
                    return (df['rolling_average'])

            df['voltage_mu_o'] = df.apply(func_voltage_mu_o, axis = 1)

            if input1.startswith("Ni"):
                Voltage_SD = 0.045
            elif input1.startswith("Sn"):
                Voltage_SD = 0.050
            elif input1.startswith("ECln"):
                Voltage_SD = 0.055
            elif input1.startswith("Ag"):
                Voltage_SD = 0.055
            else:
                Voltage_SD = 0.055

            df['voltage_sigma'] =  Voltage_SD

            fig=go.Figure()
            fig.add_trace(go.Scatter(x=df['DateTime'],y=df[loc+'AmpsSetpoint'],name = 'Current Set Point',line=dict(color='black',width=4,dash='dash')))
            fig.add_trace(go.Scatter(x=df['DateTime'],y=df[input1],name = 'Actual Current',line=dict(color='black',width=4)))
            fig.add_trace(go.Scatter(x=df['DateTime'],y=df[loc+'AmpsSetpoint']+df[loc+'AmpsSetpoint']*current_tolerance/100,name = 'Upper Limit',line=dict(color='red',width=4)))
            fig.add_trace(go.Scatter(x=df['DateTime'],y=df[loc+'AmpsSetpoint']-df[loc+'AmpsSetpoint']*current_tolerance/100,name = 'Lower Limit',line=dict(color='red',width=4)))
            fig.update_layout(title= input2+' '+input1[:5]+ ' : Current Vs Time',xaxis_title = 'Time',yaxis_title = 'Current (Amp)')

            fig2=go.Figure()
            fig2.add_trace(go.Scatter(x=df['DateTime'],y=df[loc+'VoltsActual'],name = 'Actual Voltage',line=dict(color='black',width=4)))
            fig2.add_trace(go.Scatter(x=df['DateTime'],y=df['voltage_mu_o'] + df['voltage_sigma'] * voltage_tolerance,name = 'Voltage Red UCL',line=dict(color='red',width=4)))
            fig2.add_trace(go.Scatter(x=df['DateTime'],y=df['voltage_mu_o'] - df['voltage_sigma'] * voltage_tolerance,name = 'Voltage Red LCL',line=dict(color='red',width=4)))
            fig2.update_layout(title= input2+' '+input1[:5]+ ' : Voltage Vs Time',xaxis_title = 'Time',yaxis_title = 'Voltage (Volt)')

            return fig, fig2

@app.callback(
    Output('refresh-table','n_intervals'),
    Input('tab', 'active_cell'))

def stop( selection):
    if selection is None:
        n_intervals = 0
        return n_intervals
    else:
        n_intervals = 99999999999
        return n_intervals    '''
</code>```

答:
The best way is to use the  dcc.Graph: uirevision feature new to dash_core_components.  dash-core-components==0.39.0rc4. This will preserve the zoom area through a callback without resetting unless the uirevesion is changed.

https://community.plotly.com/t/preserving-ui-state-like-zoom-in-dcc-graph-with-uirevision-with-dash/15793?page=2

Body:
I have build a dash application. There are two graphs in the dashboard. So I was trying to implement relayoutdata function in the dashboard so that user can zoom in those graphs and maintain the zoom by not reloading the graphs and preserve the state for new data points.

The code which I was trying to implement is below -

Thanks for any help in advance!

#callback for buttons

@app.callback(dash.dependencies.Output('buttons', 'children'),
              [dash.dependencies.Input('button-1', 'n_clicks'),
               dash.dependencies.Input('button-2', 'n_clicks'),
               dash.dependencies.Input('button-4', 'n_clicks')
              ])

def displayClick(btn1,btn2,btn4):
    changed_id = [p['prop_id'] for p in dash.callback_context.triggered][0]
    if 'button-2' in changed_id:
        return html.Div(children = [

        html.Div(dcc.Dropdown(
                id = 'lineSelect1',
                options = lineOptions,
                placeholder = 'Select Line',
                clearable=False,
                style = dropdownStyle,
            )), html.Div(dcc.DatePickerRange(
        id='date_picker',
        min_date_allowed=date(2020, 1, 1),
        max_date_allowed=date.today()+timedelta(days=1),
        initial_visible_month=date.today()-timedelta(days=1),
        start_date=date.today()-timedelta(days=1),
        end_date=date.today(),
        style = dropdownStyle1

    )),
            html.Div(id='AlarmHistory'),
        ])

    elif 'button-4' in changed_id:
        path = "C:/Users/ISLAMS/Downloads/Work/Project Fusion/Plating Lines Code/Lincoln Files/"
        extension = 'xlsx'
        os.chdir(path)
        result = glob.glob('*.{}'.format(extension))
        result = [sub.replace('.xlsx','') for sub in result]
        sheetOptions = [{'label' :i,'value' :i } for i in result]

        return html.Div([

        dcc.Dropdown(
                id = 'sheetSelect1',
                options = sheetOptions,
                value = result[0],
                placeholder = 'Select Line',
                clearable=False,
                style = dropdownStyle1,
            ),

         html.Div(id='editTable'),

     ])
    else:
        return html.Div([
            dcc.Dropdown(
                id = 'lineSelect',
                options = lineOptions,
                multi = True,
                placeholder = 'Select Lines',
                clearable=True,
                value = td2[0].unique(),
                style = dropdownStyle,
            ),
            html.Br(),
            html.Div(id='table'),
            dcc.Interval(id='refresh-table',
                        interval = 120000,
                        n_intervals = 0,
                        max_intervals=99999999999),
        ])

#call back for All Plating Lines

@app.callback(
    dash.dependencies.Output('table', 'children'),
    [dash.dependencies.Input('lineSelect', 'value'),
    dash.dependencies.Input('refresh-table', 'n_intervals'),])

def filter_table(input,num):
    if num == 99999999999:
        raise PreventUpdate
    else:
        print ("The code is inside the function")
        df2 = pd.read_sql_query(query_3, engine)
        df2['location'] = df2['location'].replace(regex='AmpsActual',value='')
        df2['line'] = np.where(df2.location.str[3] == '1' ,df2.line+' 1',df2.line)
        df2['line'] = np.where(df2.location.str[3] == '2' ,df2.line+' 2',df2.line)

        tableData = df2.pivot_table('alarmflag',['line','linespeed'],'location',aggfunc = 'first')
        tableData = pd.DataFrame(tableData.to_records())
        tableData.columns = [hdr.replace("('alarmflag',","").replace(")","") for hdr in tableData.columns]

        td1 = tableData
        td1['linespeed'] = td1['linespeed'].round(1)
        td1['linespeed'] = td1['linespeed'].astype(str)

        for j in td1.columns:
            if j not in ['line','linespeed']:
                td1[j] = j + td1[j]

        sort0_cols = td1.columns[td1.columns.str.contains(pat="EC")  ]
        sort1_cols = td1.columns[td1.columns.str.contains(pat="Ni")  ]
        sort2_cols = td1.columns[td1.columns.str.contains(pat="Ag")  ]
        sort3_cols = td1.columns[td1.columns.str.contains(pat="Sn")  ]
        sort4_cols = td1.columns[(~td1.columns.str.contains(pat="EC") & ~td1.columns.str.contains(pat="Ni") &
                                  ~td1.columns.str.contains(pat="Ag") & ~td1.columns.str.contains(pat="Sn") &
                                  ~td1.columns.str.contains(pat="line") ) ]
        td1 = pd.concat([td1['line'],td1['linespeed'],td1[sort0_cols],td1[sort1_cols],td1[sort2_cols],td1[sort3_cols],td1[sort4_cols]],axis=1)
        td1['new'] = td1.apply(lambda x: ','.join(x.dropna()),axis=1)
        td2 = td1['new'].apply(lambda x:pd.Series(x.split(',')))
        td2.rename(columns = {0:'line'},inplace=True)

        df = pd.DataFrame(data = td2)
        dfFiltered = pd.DataFrame()
        temp = input

        dfFiltered = df[df.line.isin(temp)]

        return html.Div([
            dash_table.DataTable(
                id='tab',
                columns = [{"name": i, "id": i} for i in dfFiltered.columns],
                data = dfFiltered.to_dict('records'),

                style_cell={'maxWidth': 0,
                            'overflow': 'hidden',
                            'textOverflow': 'ellipsis',
                            'textAlign': 'center',
                            'font-family': 'Verdana',
                            'margin':'10px',
                            'font-weight': 'bold',
                            },
                style_header = {'display': 'none'},
                style_data_conditional = ([{'if':{'filter_query': '{{{col}}} is blank'.format(col=col),
                                                  'column_id' : col},
                                            'backgroundColor': 'white',
                                            'color': 'white' } for col in dfFiltered.columns] +
                                          [{'if':{'filter_query': '{{{col}}} contains "."'.format(col=col),
                                                  'column_id' : col},
                                            'backgroundColor': '#CC0000',
                                            'color': 'white' } for col in dfFiltered.columns] +
                                          [{'if':{'filter_query': '{{{col}}} contains "`"'.format(col=col),
                                                  'column_id' : col},
                                            'backgroundColor': 'white',
                                            'color': 'green' } for col in dfFiltered.columns] +
                                          [{'if':{'filter_query': '{{{col}}} contains " "'.format(col=col),
                                                  'column_id' : col},
                                            'backgroundColor': '#D3D3D3',
                                            'color': 'black' } for col in dfFiltered.columns]
                                           +  [{'if':{
                                                   'column_id' : 1},
                                             'backgroundColor': '#D3D3D3',
                                             'color': 'black' }]
                                          ),
                )
            ,   dcc.Graph(id="graph3", style={"width": "50%", "display": "inline-block"}),
            dcc.Graph(id="graph4", style={"width": "50%", "display": "inline-block"}),])

#call back for selection on All Plating Lines

@app.callback(
    [Output('graph3', 'figure'),Output('graph4', 'figure')],
    [Input('tab', 'derived_virtual_data'),Input('tab', 'active_cell')])

def show_graph(rows, selection):

    dff = pd.DataFrame(rows)

    if selection is None:
        n_intervals = 0
        return {}, {}
    else:
        n_intervals = 99999999999
        loc = dff.iloc[selection['row']][selection['column']-1]
        loc = loc.replace('.','').replace('`','').replace(' ','').replace('AmpsActual','')
        input1 = loc + 'AmpsActual'
        t1 = dff.iloc[selection['row']]['line']
        input2 = t2 = t1[:3]
        t1 = 'USMLXLIUP_' + t2

        cnxn_1 = mysql.connector.connect(AWS Credentials)
        cursor = cnxn_1.cursor()

        query_4 = """Select COLUMN_NAME from information_schema.columns where TABLE_NAME = '{}'
        and TABLE_SCHEMA = 'ppqa' and
        (COLUMN_NAME like '{}%' or COLUMN_NAME = 'DateTime' )
        order by ORDINAL_POSITION"""

        table_columns = pd.read_sql_query(query_4.format(t1,loc), cnxn_1)

        col_list = [i for i in table_columns['COLUMN_NAME']]
        col_string = ', '.join([str(i) for i in col_list])

        query_5 = """SELECT {},  '{}' as line, NOW() as lastrefreshdate
                FROM ppqa.{}
                where DateTime >= now() - interval 24 hour
                order by DateTime"""

        df = pd.read_sql_query(query_5.format(col_string,t2,t1), cnxn_1)

        if len(df) == 0:
            return {}, {}
        else:
            df['data point i'] = df.index + 1
            filename = t2
            volt_col = input1.replace('Amp','Volt')

            tolerance_inputs = pd.read_excel("/home/sislam/Sohail Islam/Adhoc/Project Fusion/Notebook/Lincoln Plating Lines/Files/"+filename +".xlsx", sheet_name = 'Sheet1')

            current_tolerance = int(tolerance_inputs["Current Tolerance for " + input1].loc[0])
            voltage_tolerance = int(tolerance_inputs["Voltage Tolerance for Standard Deviation for " + volt_col].loc[0])

            standard_dev_15_rows = df[df['data point i'] <= 15][volt_col].std()

            df['rolling_average']  = df[volt_col].rolling(15).mean()

            def func_voltage_mu_o(df):
                if df['data point i'] <= 15:
                    return (df[volt_col])
                else:
                    return (df['rolling_average'])

            df['voltage_mu_o'] = df.apply(func_voltage_mu_o, axis = 1)

            if input1.startswith("Ni"):
                Voltage_SD = 0.045
            elif input1.startswith("Sn"):
                Voltage_SD = 0.050
            elif input1.startswith("ECln"):
                Voltage_SD = 0.055
            elif input1.startswith("Ag"):
                Voltage_SD = 0.055
            else:
                Voltage_SD = 0.055

            df['voltage_sigma'] =  Voltage_SD

            fig=go.Figure()
            fig.add_trace(go.Scatter(x=df['DateTime'],y=df[loc+'AmpsSetpoint'],name = 'Current Set Point',line=dict(color='black',width=4,dash='dash')))
            fig.add_trace(go.Scatter(x=df['DateTime'],y=df[input1],name = 'Actual Current',line=dict(color='black',width=4)))
            fig.add_trace(go.Scatter(x=df['DateTime'],y=df[loc+'AmpsSetpoint']+df[loc+'AmpsSetpoint']*current_tolerance/100,name = 'Upper Limit',line=dict(color='red',width=4)))
            fig.add_trace(go.Scatter(x=df['DateTime'],y=df[loc+'AmpsSetpoint']-df[loc+'AmpsSetpoint']*current_tolerance/100,name = 'Lower Limit',line=dict(color='red',width=4)))
            fig.update_layout(title= input2+' '+input1[:5]+ ' : Current Vs Time',xaxis_title = 'Time',yaxis_title = 'Current (Amp)')

            fig2=go.Figure()
            fig2.add_trace(go.Scatter(x=df['DateTime'],y=df[loc+'VoltsActual'],name = 'Actual Voltage',line=dict(color='black',width=4)))
            fig2.add_trace(go.Scatter(x=df['DateTime'],y=df['voltage_mu_o'] + df['voltage_sigma'] * voltage_tolerance,name = 'Voltage Red UCL',line=dict(color='red',width=4)))
            fig2.add_trace(go.Scatter(x=df['DateTime'],y=df['voltage_mu_o'] - df['voltage_sigma'] * voltage_tolerance,name = 'Voltage Red LCL',line=dict(color='red',width=4)))
            fig2.update_layout(title= input2+' '+input1[:5]+ ' : Voltage Vs Time',xaxis_title = 'Time',yaxis_title = 'Voltage (Volt)')

            return fig, fig2

@app.callback(
    Output('refresh-table','n_intervals'),
    Input('tab', 'active_cell'))

def stop( selection):
    if selection is None:
        n_intervals = 0
        return n_intervals
    else:
        n_intervals = 99999999999
        return n_intervals    '''


来源: stackexchange

问:
Azure redis cache SetString multiplexer error
I'm attempting to use Azure redis cache to reduce hits to my database, but I'm stuck on something very weird. My WebMethod looks as such.

```<code>[WebMethod]
public static string HistoricalData(string searchterm, string topicId)
    {
        string constr = ConfigurationManager.ConnectionStrings["Azure"].ConnectionString;
        var lazyConnection = new Lazy<ConnectionMultiplexer>(() => {
            string cacheConnection = ConfigurationManager.ConnectionStrings["CacheConnection"].ToString();
            return ConnectionMultiplexer.Connect(cacheConnection);
        });

        JavaScriptSerializer json = new JavaScriptSerializer();
        List<HistoricalGraph> hg = new List<HistoricalGraph>();

        json.MaxJsonLength = Int32.MaxValue;

        IDatabase cache = lazyConnection.Value.GetDatabase();
        var cachedCategory = cache.StringGet(topicId).ToString();

        if (cachedCategory == null){
            using (SqlConnection conn = new SqlConnection(constr))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand("my_sp", conn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@Type", "GetData");
                    cmd.Parameters.AddWithValue("@Topic", searchterm);

                    using (SqlDataReader r = cmd.ExecuteReader())
                    {
                        if (r.HasRows)
                        {
                            while (r.Read())
                            {
                                hg.Add(new HistoricalGraph
                                {
                                    asin = r.GetValue(0).ToString() ?? "",
                                    title = r.GetValue(1).ToString() ?? "",
                                    tagBrand = r.GetValue(2).ToString() ?? "",
                                    TagFieldValue1 = r.GetValue(3).ToString() ?? "",
                                    TagFieldValue2 = r.GetValue(4).ToString() ?? "",
                                    TagFieldValue3 = r.GetValue(5).ToString() ?? "",
                                    TagFieldValue4 = r.GetValue(6).ToString() ?? "",
                                    TagFieldValue5 = r.GetValue(7).ToString() ?? "",
                                    pack = r.GetValue(8).ToString() ?? "",
                                    date = r.GetValue(9).ToString() ?? "",
                                    avgPrice = r.GetValue(10).ToString() ?? "",
                                    units = r.GetValue(11).ToString() ?? "",
                                    revenue = r.GetValue(12).ToString() ?? "",
                                    image = r.GetValue(13).ToString() ?? ""
                                });
                            }

                        }
                    }
                }
            }
            System.Diagnostics.Debug.WriteLine("From SQL");

            var serializedData = json.Serialize(hg);
            cache.StringSet(topicId, serializedData).ToString(); //Errors here

            return serializedData;
        }
        else
        {
            System.Diagnostics.Debug.WriteLine("From Redis Cache");

            return cachedCategory.ToString();
        }
    }
</code>```

StackExchange redis throws a multiplexer error that isn't very descriptive, but the kicker is if i reload the page it successfully pulls the json data from my redis cache. The json string is on average about 8MB. Any thoughts or suggestions on this issue would be greatly appreciated.

答:
Check if you are storing data in JSON format or not.
Next, you need to Deserialize the json data under topicId value</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm attempting to use Azure redis cache to reduce hits to my database, but I'm stuck on something very weird. My WebMethod looks as such.

[WebMethod]
public static string HistoricalData(string searchterm, string topicId)
    {
        string constr = ConfigurationManager.ConnectionStrings["Azure"].ConnectionString;
        var lazyConnection = new Lazy<ConnectionMultiplexer>(() => {
            string cacheConnection = ConfigurationManager.ConnectionStrings["CacheConnection"].ToString();
            return ConnectionMultiplexer.Connect(cacheConnection);
        });

        JavaScriptSerializer json = new JavaScriptSerializer();
        List<HistoricalGraph> hg = new List<HistoricalGraph>();

        json.MaxJsonLength = Int32.MaxValue;

        IDatabase cache = lazyConnection.Value.GetDatabase();
        var cachedCategory = cache.StringGet(topicId).ToString();

        if (cachedCategory == null){
            using (SqlConnection conn = new SqlConnection(constr))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand("my_sp", conn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@Type", "GetData");
                    cmd.Parameters.AddWithValue("@Topic", searchterm);

                    using (SqlDataReader r = cmd.ExecuteReader())
                    {
                        if (r.HasRows)
                        {
                            while (r.Read())
                            {
                                hg.Add(new HistoricalGraph
                                {
                                    asin = r.GetValue(0).ToString() ?? "",
                                    title = r.GetValue(1).ToString() ?? "",
                                    tagBrand = r.GetValue(2).ToString() ?? "",
                                    TagFieldValue1 = r.GetValue(3).ToString() ?? "",
                                    TagFieldValue2 = r.GetValue(4).ToString() ?? "",
                                    TagFieldValue3 = r.GetValue(5).ToString() ?? "",
                                    TagFieldValue4 = r.GetValue(6).ToString() ?? "",
                                    TagFieldValue5 = r.GetValue(7).ToString() ?? "",
                                    pack = r.GetValue(8).ToString() ?? "",
                                    date = r.GetValue(9).ToString() ?? "",
                                    avgPrice = r.GetValue(10).ToString() ?? "",
                                    units = r.GetValue(11).ToString() ?? "",
                                    revenue = r.GetValue(12).ToString() ?? "",
                                    image = r.GetValue(13).ToString() ?? ""
                                });
                            }

                        }
                    }
                }
            }
            System.Diagnostics.Debug.WriteLine("From SQL");

            var serializedData = json.Serialize(hg);
            cache.StringSet(topicId, serializedData).ToString(); //Errors here

            return serializedData;
        }
        else
        {
            System.Diagnostics.Debug.WriteLine("From Redis Cache");

            return cachedCategory.ToString();
        }
    }

StackExchange redis throws a multiplexer error that isn't very descriptive, but the kicker is if i reload the page it successfully pulls the json data from my redis cache. The json string is on average about 8MB. Any thoughts or suggestions on this issue would be greatly appreciated.


问:
How to obtain a subset of Azure app registrations
I'm looking to create a powershell script that identifies (and sends an e-mail) for any app registration secrets that are going to expire.  I know how to obtain a list of ALL of our app registrations by running one of the below commands

```<code>Get-AzureADApplication -all $true
</code>```

Or alternatively by finding one app registration

```<code>Get-AzureADApplication -filter "displayName -eq 'Our App Name'"
</code>```

I'm interested in obtaining the object IDs of only a small subset of app registrations (like only 10) which I can then loop through to find the expiry dates.

I'm fine with the send e-mail piece, but does anyone know if this is possible to extract the subset of app registrations from azure?

答:
If you only want 10, you can use the -Top parameter.

```<code>Get-AzureADApplication -Top 10
</code>```

You can also use the -Top parameter with the -Filter parameter. I like to use the combination of StartsWith to filter:

```<code>Get-AzureADApplication -Top 10 -Filter "startswith(displayName,'ABC')"
</code>```

Body:
I'm looking to create a powershell script that identifies (and sends an e-mail) for any app registration secrets that are going to expire.  I know how to obtain a list of ALL of our app registrations by running one of the below commands

Get-AzureADApplication -all $true

Or alternatively by finding one app registration

Get-AzureADApplication -filter "displayName -eq 'Our App Name'"

I'm interested in obtaining the object IDs of only a small subset of app registrations (like only 10) which I can then loop through to find the expiry dates.

I'm fine with the send e-mail piece, but does anyone know if this is possible to extract the subset of app registrations from azure?

Body:
If you only want 10, you can use the -Top parameter.

Get-AzureADApplication -Top 10

You can also use the -Top parameter with the -Filter parameter. I like to use the combination of StartsWith to filter:

Get-AzureADApplication -Top 10 -Filter "startswith(displayName,'ABC')"


问:
Drupal 7.17 - Do I have to remove these files after installation?
A site I'm currently managing has Drupal 7.17 on it.  I'm noticing the following files in the root of the website:

```<code>install.php
CHANGELOG.txt
INSTALL.txt
INSTALL.mysql.txt
INSTALL.pgsql.txt
LICENSE.txt
MAINTAINERS.txt
UPGRADE.txt
</code>```

Researching this, tells me that as of Drupal 7.16, they fixed a security issue that would allow arbitrary code to run in install.php that would allow the re-installation of Drupal that someone could run.  But basically, I am wondering if any of these files (if left in the server root) could cause problems in Drupal 7.17?  Do I have to remove these files for security reasons?  Or is this no longer a security risk whatsoever in Drupal 7.17?

I understand that we shouldn't remove the upgrade.php file, but just curious on the rest of these files.

Thanks, and this is probably a dumb question, but just felt the need to ask anyways.  Usually I remove these files when I install software on websites, but not sure how Drupal uses and/or misuses these files.

答:
I would love to hear an update and more recent thoughts on this question, and here is why.....

I was just working with a newly updated Drupal site to Drupal 8.9.20 running the Open Social distribution as a logged-in user with no admin privileges. This is my ACTIVE PRODUCTION site!

I deleted a node (News Article) I was trying to embed from a website that refuses to connect on some of their metadata ie: image #1, and after submitting on the delete link, the browser switched to install.php, which as you know sites in the document root.

I was of course shocked to see this and after considering the even innocent response a user might get that lead them to reinstall THEIR App, this could be very dangerous, of course.

So, since the last reply on this references Drupal versions from 2014, I was
just wondering your thoughts in this day and age on what are the latest recommendations!

Thanks

ContentLicense: CC BY-SA 3.0

Body:
A site I'm currently managing has Drupal 7.17 on it.  I'm noticing the following files in the root of the website:

install.php
CHANGELOG.txt
INSTALL.txt
INSTALL.mysql.txt
INSTALL.pgsql.txt
LICENSE.txt
MAINTAINERS.txt
UPGRADE.txt

Researching this, tells me that as of Drupal 7.16, they fixed a security issue that would allow arbitrary code to run in install.php that would allow the re-installation of Drupal that someone could run.  But basically, I am wondering if any of these files (if left in the server root) could cause problems in Drupal 7.17?  Do I have to remove these files for security reasons?  Or is this no longer a security risk whatsoever in Drupal 7.17?

I understand that we shouldn't remove the upgrade.php file, but just curious on the rest of these files.

Thanks, and this is probably a dumb question, but just felt the need to ask anyways.  Usually I remove these files when I install software on websites, but not sure how Drupal uses and/or misuses these files.


问:
Firebase auth email verification is useless because the user can access the app even if he doesn't click the confirmation link
I am struggling with the email verification on my flutter app. When i tried to implement the functionality, even if the user didn't validate his account, he was able to use his account with no problems. How can I do it so that the user can't access the app while the confirmation link isn't clicked so that people couldn't use emails they don't have access to? Here is the code

```<code>//On this file, I store all the login and sign in functionalities:
class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final googleSignIn = GoogleSignIn();

  GoogleSignInAccount? _user;

  // create user object based on firebase user

  Users? _userFromFirebaseUser(User? user) {
    return user != null ? Users(uid: user.uid) : null;
  }

  // auth change user stream
  Stream<Users?> get user {
    return _auth.authStateChanges().map(_userFromFirebaseUser);
  }
  //register with email & psswrd
  Future registerWithEmailAndPassword(String email, String password) async {
    try {
      UserCredential result = await _auth.createUserWithEmailAndPassword(
          email: email, password: password);

      User? user = result.user;

      return _userFromFirebaseUser(user);
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

  //sign out
  Future signOut() async {
    try {
      return await _auth.signOut();
    } catch (e) {
      print(e.toString());
      return null;
    }
  }
}
</code>```

This is the main.dart file:

```<code>void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return StreamProvider<Users?>.value(
      initialData: null,
      value: AuthService().user,
      child: MaterialApp(
        home: Wrapper(),
      ),
    );
  }
}
</code>```

The wrapper file leads either to the authentication page or to the homepage:

```<code>class Wrapper extends StatelessWidget {
  const Wrapper({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final user = Provider.of<Users?>(context);

    //return either home or authenticate
    if (user == null) {
      return Authenticate();
    } else {
      return Home();
    }
  }
}
</code>```

答:
You're right that there is a user created. You'll want to require emailVerified on your security rules and ui.

Then the issue of the user created, using that email: create a cloud function that evaluates your users at a time interval to check for emailVerified. At whatever age you decide, delete the user.

There's not much you can do here. Email verification is so spotty with spam filters, and phone numbers are transient enough to be problematic.  I'm trying to get away from email, email/password entirely and require google and apple login only, which provides a verified email.

Body:
I am struggling with the email verification on my flutter app. When i tried to implement the functionality, even if the user didn't validate his account, he was able to use his account with no problems. How can I do it so that the user can't access the app while the confirmation link isn't clicked so that people couldn't use emails they don't have access to? Here is the code

//On this file, I store all the login and sign in functionalities:
class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final googleSignIn = GoogleSignIn();

  GoogleSignInAccount? _user;

  // create user object based on firebase user

  Users? _userFromFirebaseUser(User? user) {
    return user != null ? Users(uid: user.uid) : null;
  }

  // auth change user stream
  Stream<Users?> get user {
    return _auth.authStateChanges().map(_userFromFirebaseUser);
  }
  //register with email & psswrd
  Future registerWithEmailAndPassword(String email, String password) async {
    try {
      UserCredential result = await _auth.createUserWithEmailAndPassword(
          email: email, password: password);

      User? user = result.user;

      return _userFromFirebaseUser(user);
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

  //sign out
  Future signOut() async {
    try {
      return await _auth.signOut();
    } catch (e) {
      print(e.toString());
      return null;
    }
  }
}

This is the main.dart file:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return StreamProvider<Users?>.value(
      initialData: null,
      value: AuthService().user,
      child: MaterialApp(
        home: Wrapper(),
      ),
    );
  }
}

The wrapper file leads either to the authentication page or to the homepage:

class Wrapper extends StatelessWidget {
  const Wrapper({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final user = Provider.of<Users?>(context);

    //return either home or authenticate
    if (user == null) {
      return Authenticate();
    } else {
      return Home();
    }
  }
}


问:
Which table exactly is the "left" table and "right" table in a JOIN statement (SQL)?
What makes a given table the left table?

Is it that the table is indicated in the "From" part of the query?

Or, is it the left table because it is on the left hand side of the = operator?

Are the following equivalent

```<code>SELECT *
FROM left_table
LEFT JOIN right_table ON left_table.right_id = right_table.id
</code>```

and

```<code>SELECT *
FROM left_table
LEFT JOIN right_table on right_table.left_id = left_table.id
</code>```

???

Thanks

答:
CREATE TABLE ORDERS (

ORDERID INT,

CUSTOMERID INT,

ORDERDATE DATE

);

INSERT INTO ORDERS VALUES (10123,10,DATE '16-08-20');

INSERT INTO ORDERS VALUES (10122,11,DATE '14-09-20');

INSERT INTO ORDERS VALUES (10121,12,DATE '10-10-20');

CREATE TABLE CUSTOMERS (

CUSTOMERID INT,

CUSTOMERNAME VARCHAR(20),

COUNTRY VARCHAR(20)

);

INSERT INTO CUSTOMERS VALUES (11 , 'BUDDHA','INDIA');

INSERT INTO CUSTOMERS VALUES (12 , 'JOHNWIK','UNITED STATES');

INSERT INTO CUSTOMERS VALUES (100, 'SERENA','UNITED KINGDOM');

discussing LEFT JOIN query:

select orders.orderid, customers.customername, orders.orderdate from orders
inner join customers on orders.customerid = customers.customerid;

If you want to know exact left and right tables. From left to right the table attached with from is [left] and table attached with join is [right].

Happy Hacking !!!

ContentLicense: CC BY-SA 2.5

Body:
What makes a given table the left table?

Is it that the table is indicated in the "From" part of the query?

Or, is it the left table because it is on the left hand side of the = operator?

Are the following equivalent

SELECT *
FROM left_table
LEFT JOIN right_table ON left_table.right_id = right_table.id

and

SELECT *
FROM left_table
LEFT JOIN right_table on right_table.left_id = left_table.id

???

Thanks


问:
Alpine Error x-data .catch is not defined
H there,
im trying to get Alpine with webpack to run but allways get an error and dont know how to go about.

My Webpack config:

```<code>const path                 = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const isProduction         = 'production' === process.env.NODE_ENV;
const { VueLoaderPlugin } = require('vue-loader')
const webpack = require('webpack');

// Set the build prefix.
let prefix = isProduction ? '.min' : '';

const config = {
    entry: {
        main: './source/js/main.js',
        admin: './source/js/admin.js',
        admin_head: './source/js/admin_head.js',
        classic: './source/js/classic.js',
    },
    output: {
        filename: `[name]${prefix}.js`,
        path: path.resolve(__dirname, 'dist')
    },
    mode: process.env.NODE_ENV,
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader'
            },
            {
                test: /\.js$/,
                loader: 'babel-loader',
                options: {
                    presets: [
                        [
                            "@babel/preset-env"
                        ]
                    ]
                }
            },
            {
                test: /\.s[ac]ss$/i,
                use: [
                    'vue-style-loader',
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                    'sass-loader',
                    {
                        loader: 'postcss-loader',
                        options: {
                            postcssOptions: {
                                plugins: [
                                    require('postcss-import'),
                                    require('tailwindcss')('tailwind.js'),
                                    require('postcss-nested'),
                                    require('autoprefixer'),
                                ]
                            }
                        }
                    }
                ],
            },
        ]
    },
    plugins: [
        new VueLoaderPlugin(),
        new MiniCssExtractPlugin(),
        new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
    ],
    resolve: {
        alias: {
            vue: process.env.NODE_ENV == 'production' ? 'vue/dist/vue.min.js' : 'vue/dist/vue.js'
        }
    }
}
module.exports = config
</code>```

My Script File:

```<code>    $(function (){
        $('.color-picker').wpColorPicker();
    })
})(jQuery)

import Alpine from 'alpinejs'
Alpine.start();
</code>```

The script is loaded in the footer with defer:

```<code><script defer src="https://ir.test/wp-content/plugins/real-time-comments/dist/admin_head.js?ver=1.1.1"></script>
</code>```

And in a php file ive:

```<code><div x-data="{ tab:'main' }">
                <div class="bg-white grid grid-cols-6 gap-5">
                    <div class="pt-10 px-5">
                        <img src="<?php echo RTC_URL ?>dist/images/logo-full.svg" class="border-none w-full h-auto"/>
                        <div class="flex flex-col w-full mt-10">
                            <div @click="tab = 'main'"
                                 :class="tab == 'main' ? 'border-b-2 border-plugin border-plugin font-bold' : 'border-b border-gray-500'"
                                 class="px-5 py-3 cursor-pointer">
                                <?php _e( 'Main settings', 'real-time-comments' ) ?>
                            </div>
                            <div @click="tab = 'pusher'"
                                 :class="tab == 'pusher' ? 'border-b-2 border-plugin border-plugin font-bold' : 'border-b border-gray-500'"
                                 class="px-5 py-3 cursor-pointer">
                                <?php _e( 'Pusher API settings', 'real-time-comments' ) ?>
                            </div>
                            <div @click="tab = 'layout'"
                                 :class="tab == 'layout' ? 'border-b-2 border-plugin border-plugin font-bold' : 'border-b border-gray-500'"
                                 class="px-5 py-3 cursor-pointer">
                                <?php _e( 'Layout settings', 'real-time-comments' ) ?>
                            </div>
                        </div>

                    </div>
                    <div class="col-span-5">
                        <form method="post" action="options.php">
                            <div>
                                <div class="p-5 bg-gray-200">
                                    <div x-show.transition="tab == 'main'">
                                        <?php settings_fields( 'rtc_main_settings_section' ); ?>
                                        <?php do_settings_sections( 'rtc_main_settings_page' ); ?>
                                    </div>
                                    <div x-show.transition="tab == 'pusher'">
                                        <?php settings_fields( 'rtc_pusher_settings_section' ); ?>
                                        <?php do_settings_sections( 'rtc_pusher_settings_page' ); ?>
                                    </div>
                                    <div x-show.transition="tab == 'layout'">
                                        <?php settings_fields( 'rtc_layout_settings_section' ); ?>
                                        <?php do_settings_sections( 'rtc_layout_settings_page' ); ?>
                                    </div>
                                </div>
                            </div>
                            <input type="submit" name="submit" id="submit"
                                   class="block w-full text-center bg-plugin py-3 text-center text-white my-10 shadow-lg hover:shadow cursor-pointer"
                                   value="<?php echo __( 'save', 'real-time-comments' ) ?>">
                        </form>
                    </div>
                </div>
            </div>
        </div>

</code>```

When i load the Page i get an error;

```<code>Alpine Expression Error: func(...).catch is not a function

Expression: "{ tab:'main' }"
</code>```

Has anybody an idea what im doing wrong, or anybody an sample how to include alpine.js with webpack. And where and how to include the script, i cannot load it via cdn because its not allowed by the wordpress plugin directory. I know its a bit overdoing to use alpine in the wp backend because it comes with jquery out of the box but for frontend files i get the same error.

答: I had a similar problem after upgrading from AlpineJS 3.2.3 (which worked) to AlpineJS 3.8 (which didn't).  Eventually I found THIS.  It seems at some point in time AlpineJS started using async/await which is ECMAScript 2017.  My build had been targeting "es2015".  Changed it to "es2017" and it worked.  My build is via the esbuild embedded in Hugo so I changed js.Build's "target" option to "es2017".  I don't know where to change it in webpack (that hurts my brain).</p>

Body:
H there,
im trying to get Alpine with webpack to run but allways get an error and dont know how to go about.

My Webpack config:

const path                 = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const isProduction         = 'production' === process.env.NODE_ENV;
const { VueLoaderPlugin } = require('vue-loader')
const webpack = require('webpack');

// Set the build prefix.
let prefix = isProduction ? '.min' : '';

const config = {
    entry: {
        main: './source/js/main.js',
        admin: './source/js/admin.js',
        admin_head: './source/js/admin_head.js',
        classic: './source/js/classic.js',
    },
    output: {
        filename: `[name]${prefix}.js`,
        path: path.resolve(__dirname, 'dist')
    },
    mode: process.env.NODE_ENV,
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: 'vue-loader'
            },
            {
                test: /\.js$/,
                loader: 'babel-loader',
                options: {
                    presets: [
                        [
                            "@babel/preset-env"
                        ]
                    ]
                }
            },
            {
                test: /\.s[ac]ss$/i,
                use: [
                    'vue-style-loader',
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                    'sass-loader',
                    {
                        loader: 'postcss-loader',
                        options: {
                            postcssOptions: {
                                plugins: [
                                    require('postcss-import'),
                                    require('tailwindcss')('tailwind.js'),
                                    require('postcss-nested'),
                                    require('autoprefixer'),
                                ]
                            }
                        }
                    }
                ],
            },
        ]
    },
    plugins: [
        new VueLoaderPlugin(),
        new MiniCssExtractPlugin(),
        new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
    ],
    resolve: {
        alias: {
            vue: process.env.NODE_ENV == 'production' ? 'vue/dist/vue.min.js' : 'vue/dist/vue.js'
        }
    }
}
module.exports = config

My Script File:

    $(function (){
        $('.color-picker').wpColorPicker();
    })
})(jQuery)

import Alpine from 'alpinejs'
Alpine.start();

The script is loaded in the footer with defer:

And in a php file ive:

                        <img src="<?php echo RTC_URL ?>dist/images/logo-full.svg" class="border-none w-full h-auto"/>

                                <?php _e( 'Main settings', 'real-time-comments' ) ?>

                                <?php _e( 'Pusher API settings', 'real-time-comments' ) ?>

                                <?php _e( 'Layout settings', 'real-time-comments' ) ?>

                        <form method="post" action="options.php">

                                        <?php settings_fields( 'rtc_main_settings_section' ); ?>
                                        <?php do_settings_sections( 'rtc_main_settings_page' ); ?>

                                        <?php settings_fields( 'rtc_pusher_settings_section' ); ?>
                                        <?php do_settings_sections( 'rtc_pusher_settings_page' ); ?>

                                        <?php settings_fields( 'rtc_layout_settings_section' ); ?>
                                        <?php do_settings_sections( 'rtc_layout_settings_page' ); ?>

                            <input type="submit" name="submit" id="submit"
                                   class="block w-full text-center bg-plugin py-3 text-center text-white my-10 shadow-lg hover:shadow cursor-pointer"
                                   value="<?php echo __( 'save', 'real-time-comments' ) ?>">
                        </form>

When i load the Page i get an error;

Alpine Expression Error: func(...).catch is not a function

Expression: "{ tab:'main' }"

Has anybody an idea what im doing wrong, or anybody an sample how to include alpine.js with webpack. And where and how to include the script, i cannot load it via cdn because its not allowed by the wordpress plugin directory. I know its a bit overdoing to use alpine in the wp backend because it comes with jquery out of the box but for frontend files i get the same error.


问:
Git: copy all files in a directory from another branch
How do I copy all files in a directory from another branch? I can list all of the files in that directory by doing

```<code>git ls-tree master:dirname
</code>```

I can then copy all of the files individually by doing

```<code>git checkout master -- dirname/filename
</code>```

However, using wildcards has so far been a total fail.  This does nothing:

```<code>git checkout master -- dirname/*.png
</code>```

Though I guess I can use a bash script to do that, there has to be an easier way, right?

答:
In my case this simplest solution to get files from the origin branch directory was:

origin - remote repository alias(origin by default)  sourceBranchName

branch with required files in directory

sourceBranchDirPath - relative/absolute path to the required directory with

files

```<code>git checkout origin/sourceBranchName -- sourceBranchDirPath
</code>```

Example:

```<code>git checkout origin/validation_fix -- src/test/java/validation/
</code>```

Result was all files from origin/validation_fix branch by
src/test/java/validation/ relative path in the draft
mode(uncommited)

Body:
How do I copy all files in a directory from another branch? I can list all of the files in that directory by doing

git ls-tree master:dirname

I can then copy all of the files individually by doing

git checkout master -- dirname/filename

However, using wildcards has so far been a total fail.  This does nothing:

git checkout master -- dirname/*.png

Though I guess I can use a bash script to do that, there has to be an easier way, right?

Body:
In my case this simplest solution to get files from the origin branch directory was:

origin - remote repository alias(origin by default)  sourceBranchName

branch with required files in directory

sourceBranchDirPath - relative/absolute path to the required directory with

files

git checkout origin/sourceBranchName -- sourceBranchDirPath

Example:

git checkout origin/validation_fix -- src/test/java/validation/

Result was all files from origin/validation_fix branch by
src/test/java/validation/ relative path in the draft
mode(uncommited)


问:
Perl backticks using bash
In Perl, the default shell to execute backticks is sh. I'd like to switch to use bash for its richer syntax. So far I found that the suggested solution is

```<code>`bash -c \"echo a b\"`
</code>```

The apparent drawback is that the escaped double quotes, which means I will have difficulty to use double quotes in my bash args. For example, if I wanted to run commands requiring double quotes in bash

```<code>echo "a'b"
</code>```

The above method will be very awkward.

Perl's system() call has a solution for this problem: to use ARRAY args,

```<code>system("bash", "-c", qq(echo "a'b"));
</code>```

This keeps my original bash command unmodified, and almost always.

I'd like to use ARRAY args in backticks too. Is it possible?

答:
For one, one can submit a list to qx; it gets interpolated into a string and then passed to either execvp or a shell (see qx, and the second part of this post and comments). And if you need a shell then presumably that string contains shell metacharacters so it goes via shell.

```<code>my @cmd = qw(ls -l "dir with spaces");
#my @cmd = qw(ls -l "dir with spaces" > outfile);
my @out = qx(@cmd);
print for @out;
</code>```

I make a "dir with spaces" directory with a file in it to test.  (For a command with quotes in it a shell does get used.)

Next, I would in principle recommend a module to compose those shell commands, instead of going through a nail-biter to correctly escape and pass it all, like String::ShellQuote

```<code>use String::ShellQuote qw(shell_quote);

my @cmd = ('ls', '-l', q(dir with spaces));

my $quoted = shell_quote(@cmd);;
my @out = qx($quoted);
#my @out = qx($quoted > outfile);
print for @out;
</code>```

I use the q(...) operator form of single quotes to demonstrate another way (also useful for including single quotes); it is not necessary for this simple example. One still need be careful with details; that's in the nature of using complex external commands and cannot be fully avoided by any approach or tool.

As for running bash, note that normally sh delegates to a default-of-sorts shell on your system, and on many systems it is bash that is used. But if it isn't on yours, one way to use bash -c in the command would be to first prepare the command and then add that to the qx string

```<code>my @cmd = ('ls', '-l', q(dir with spaces));
my $quoted = shell_quote(@cmd);
my @out = qx(bash -c "$quoted");
#my @out = qx(bash -c "$quoted" > outfile);
print for @out;
</code>```

A couple more notes I'd like to offer:

That qx is an ancient demon. How about using modern tools/modules for running external commands?  There may be a little more to do in order to prepare your involved bash strings but then everything else will be better.  Options abound. For example

IPC::System::Simple with its few utility functions

Use Capture::Tiny to wrap a system call with syntax you prefer

The IPC::Run can do any and all of this and then way way more

Why use external commands, with Perl's (far) superior richness?  It's a whole, very complete, programming language, vs. the command-interpreter with some programming capabilities.  If you need shell's capabilities why not run just those things via the shell and do all else in Perl?

Title: Perl backticks using bash

Body:
In Perl, the default shell to execute backticks is sh. I'd like to switch to use bash for its richer syntax. So far I found that the suggested solution is

`bash -c \"echo a b\"`

The apparent drawback is that the escaped double quotes, which means I will have difficulty to use double quotes in my bash args. For example, if I wanted to run commands requiring double quotes in bash

echo "a'b"

The above method will be very awkward.

Perl's system() call has a solution for this problem: to use ARRAY args,

system("bash", "-c", qq(echo "a'b"));

This keeps my original bash command unmodified, and almost always.

I'd like to use ARRAY args in backticks too. Is it possible?

Body:
For one, one can submit a list to qx; it gets interpolated into a string and then passed to either execvp or a shell (see qx, and the second part of this post and comments). And if you need a shell then presumably that string contains shell metacharacters so it goes via shell.

my @cmd = qw(ls -l "dir with spaces");
#my @cmd = qw(ls -l "dir with spaces" > outfile);
my @out = qx(@cmd);
print for @out;

I make a "dir with spaces" directory with a file in it to test.  (For a command with quotes in it a shell does get used.)

Next, I would in principle recommend a module to compose those shell commands, instead of going through a nail-biter to correctly escape and pass it all, like String::ShellQuote

use String::ShellQuote qw(shell_quote);

my @cmd = ('ls', '-l', q(dir with spaces));

my $quoted = shell_quote(@cmd);;
my @out = qx($quoted);
#my @out = qx($quoted > outfile);
print for @out;

I use the q(...) operator form of single quotes to demonstrate another way (also useful for including single quotes); it is not necessary for this simple example. One still need be careful with details; that's in the nature of using complex external commands and cannot be fully avoided by any approach or tool.

As for running bash, note that normally sh delegates to a default-of-sorts shell on your system, and on many systems it is bash that is used. But if it isn't on yours, one way to use bash -c in the command would be to first prepare the command and then add that to the qx string

my @cmd = ('ls', '-l', q(dir with spaces));
my $quoted = shell_quote(@cmd);
my @out = qx(bash -c "$quoted");
#my @out = qx(bash -c "$quoted" > outfile);
print for @out;

A couple more notes I'd like to offer:

That qx is an ancient demon. How about using modern tools/modules for running external commands?  There may be a little more to do in order to prepare your involved bash strings but then everything else will be better.  Options abound. For example

IPC::System::Simple with its few utility functions

Use Capture::Tiny to wrap a system call with syntax you prefer

The IPC::Run can do any and all of this and then way way more

Why use external commands, with Perl's (far) superior richness?  It's a whole, very complete, programming language, vs. the command-interpreter with some programming capabilities.  If you need shell's capabilities why not run just those things via the shell and do all else in Perl?


问:
What is causing the '403 Forbidden error' in my Apache2 server? And how can I fix it? The available fixes on the web are not working for me
A little bit of context to my problem... I'm trying to deploy my django application following a tutorial (https://www.youtube.com/watch?v=Sa_kQheCnds) which uses linode to setup a linux apache server, and after following the steps, it always results in the same error, 403 Forbidden: You don't have permission to access this resource. I've followed the steps in this guide roughly 6 times now and I've determined that I'm definitely not doing anything the guy didn't do.

Something worth mentioning is that in the tutorial, Ubuntu 18.10 is being used, however I don't have Ubuntu 18.10 available, so I've tried it using Ubuntu 18.04, 20.04 and 21.10.

In my sixth and latest attempt, I am using Ubuntu 21.10

I've also tried running the server with DEBUG=True to see if I can get a little more insight on the error, but it just displays the following:

The tutorial is very long so I've broken down every single step in this post.

The steps I had to follow are:

(everything done in the Windows Linux Bash shell)

Creating Linode and analizing Ip Address and SSH Credentials I got

Root Connection to the Server

ssh into the server for the first time

Installing Software Updates

Running the command sudo apt-get update && apt-get upgrade

Setting Host Name

hostnamectl set-hostname SERVER_NAME

Then checking if it was rightfully executed with hostname

Setting Host File

nano /etc/hosts and then adding the IP address and server name to the file.

Adding Limited User

The guy in the video said it's not good practice to use root user because it's easy to mess things up like that so we created a limited user with adduser USER_NAME and then gave it sudo permissions with adduser USER_NAME sudo

Setting Up SSH Key Based Authentication

In my local machine's bash shell:
ssh keygen -b 4096
And deposit that file into my home folder, after that I copy that file over to my server with
scp ~/.ssh/id_rsa.pub user@serverip:~/.ssh/authorized_keys
then lasty confirming it was done correcty in the server with
ls .ssh

Setting Permissions for SSH Directory

Attach certain permision like
sudo chmod 700 ~/.ssh/
and
sudo chmod 600 ~/.ssh/*

Forbiding Root Login & Password Authentication

sudo nano /etc/ssh/sshh_config
to forbit #PermitRootLogin and #PasswordAuthentification
and then restart with
sudo systemctl restart sshd

Setting Up a Firewall

First, I install Uncomplicated Firewall with
sudo apt-get install ufw
and then I do the following commands:
sudo ufw default allow outgoing , sudo ufw default deny incoming , sudo ufw allow ssh and sudo ufw allow 8000.
After that, I enable the firewall with sudo ufw enable

Generating requirements.txt File

Here I actually did it a bit different that in the video. I open my VSCODE environment for the project in question, and then I run a pip freeze in the terminal to see if the dependencies are correct, if they are I write the requirements with pip freeze > requirements.txt

Copying Django Application on to the Webserver

This step is pretty straightforward. Just scp -r /folder/ user@serverip:~/ and that way the folder project is copied into the web server.

Creating Virtual Environment on the Server

First run a sudo apt-get install python3-pip and then pip install sudo apt-get install python3-venv. Once that's done, to create my virtual environment I do python3 -m venv django_project/venv and lastly I activate it by cding into the project's folder and then source venv/bin/activate.

Installing Dependencies

With my virtual environment running I run a pip install -r requirements.txt

Changing Django Settings for Testing the Application on Django Server

Inside the project's folder: sudo nano django_project/settings.py and add my server's IP to the allowed hosts list, and add a STATIC_ROOT directory.

Collecting Static Files

python manage.py collectstatic
Which could collect about 120 static files, but my project is a somewhat different from the on in the video because I added way more features so it collects about 137 files (in case these details are needed)

Testing Application

python manage.py runserver 0.0.0.0:8000 and then test to see if there is any problems, there are not (minus some variables I forgot to add because they were in my PC's environment variables) so I move on to the next step.

Installing Apache & ModWSGI

sudo apt-get install apache2, sudo apt-get install libapache2-mod-wsgi-py3.

Configuring Apache Webserver

Then move into the apache configuration folder cd /etc/apache2/sites-available/ and create a new configuration file based off the default one with sudo cp 000-default.conf django_project.conf, and then I edit with sudo nano django_project.conf it and add the following things to it: https://github.com/CoreyMSchafer/code_snippets/blob/master/Django_Blog/snippets/django_project.conf

Enabling Site Through Apache

Run the following commands:
sudo a2ensite django_project , sudo a2dissite 000-default.conf

Setting Up File Permissions

Run the following commands:
sudo chown :www-date django_project/db.sqlite3 , sudo chmod 664 django_project/db.sqlite3 and sudo chown :www-data django_project/. Then sudo chown -R :www-data django_project/media/andsudo chmod -R django_project/media```

Creating Configuration File for Hiding Sensitive Information

I won't detail this process, I just make a .json file with some secret information like the SECRET_KEY and the email and password.

Updating Project Settings File

I delete the sentitive information from the settings.py of the project, and instead add those with the .json file (like if it were an environment variable).

Allowing http Traffic

Run the following commands:
sudo ufw delete allow 8000, and sudo ufw allow http/tcp.

Restarting the Server & Running the Site

sudo service apache2 restart

Please, I'd appreciate any kind of help. I have to fix this error for a school project and I can't find solutions that actually fix it. I've read in some forums that I just needed to change certain permissions again, I did that and still the same error. It's really driving me crazy.

答:
you have not done

```<code>sudo chown :www-data django_project/django_project
</code>```

which is the folder of the wsgi.py script

Body:
you have not done

sudo chown :www-data django_project/django_project

which is the folder of the wsgi.py script


问:
Javascript: I need to find the average, min max sum and product of three variable
I am currently working on a project on finding the Min, Max, sum, product, and average of three numbers inputted by the user on the website and I just can't figure out how to get it to work and I have been working on it for the last two days and just can't seem to understand how to get it to work.

<!DOCTYPE html>

        <title>Homework Number Two Part Two</title>
        <meta charset="utf-8">
        <meta name="description" content= "My Homework Website">

        <form name="myform">
        First Number: <input type="text" id="num1" size="10">

        Second Number: <input type="text" id="num2" size="10">

        Third Number: <input type="text" id="num3" size="10">

        Results: <textarea rows="4" cols="40" id="result"></textarea>

        <input type="button" onclick="process()" value="SUBMIT">
        <input type="reset" value="RESET">```

答: You have to move the  tags to the end of the file before  to make sure that the DOM is fully loaded. Also because you are using a form, each time you click the button submit the page will reload, to prevent that behavior you have to add event.preventDefault() onSubmit event.

Body: You have to move the <script>...</script> tags to the end of the file before </body> to make sure that the DOM is fully loaded. Also because you are using a form, each time you click the button submit the page will reload, to prevent that behavior you have to add event.preventDefault() onSubmit event.


问:
Properly (independent of 32bit/64bit) saving a float to binary ofstream
So apparently on my machine, float, double and long double each have different sizes each. There also doesn't seem to be a strict standard enforcing how many bytes each of those types would have to be.

How would one, then, save a floating point value into a binary file, and then have it read properly on a different system if the sizes differ? e.g my machine has 8 byte doubles, whereas joe's have 12 byte doubles.

Without having to export it in text form (e.g "0.3232"), that is. Seems a lot less compact than the binary representation.

答:
You could store them in a format that is machine-independent. For that you first have to convert it from your representation to the other.

A simple kind of conversion is to analyze the number into a triple (sign, exponent, significand), and save these as whole numbers. That way you can keep the full precision.


问:
Using Azure VPN Gateway to access an external Database through a whitelisted public IP
I'm fairly new the Networking side of Azure, so thanks for taking you time to respond.

My use case is the following:

We have an external Database resource that requires us to provide one(or more) public IPs for whitelisting whilst they provide us with an IP to access the database (plus login data).

For this, our thought was to create a Virtual Network with a VPN Gateway to allow us to provide a single Public IP address which should allow everyone connected to the VPN (with internal private addresses) to access this resource.

My questions are the following:

Is this a valid use case?
If so, would providing the public IP of the VPN Gateway for whitelisting be enough to allow us to connect to that resource or is there anything else we need to do to achieve this(like a tunnel)?

Thanks in advance

答:
If I have understood your question correctly, you have a Database on Azure and you are trying to connect to it using an Azure Site-Site VPN for your onprem users. If this is scenario, then this is a valid use case, but I think you will need to provision a private endpoint connectivity to your Database in order to establish connectivity. Following will be the high level steps required.

Procure a Site-Site or Point-Site VPN

Establish Private endpoint
connectivity for your database.

Create a DNS configuration for
you Azure Private Endpoint


问:
What does "set to root of installation" mean?
I'm still new to these kinds of computer terminologies. Can you help clarify something for me.

If I'm installing a piece of software from github and it says "set the environment variable... to the root of the installation"
Does that just mean that I should set the environment variable to the folder where I downloaded the software from?

ex:  If I install something to /home/user/workspace
Would I then just set the environment variable to " = /home/user/workspace "

Please and Thank you.

答: You answered the question yourself! The root serves as a directory in this case</p>


问:
Sending data from html form to python api then send that data to html
So i just started working witih python since it was necessary for this project (because the API im using). So i've struggled with this a bit. I'm trying to send html data from a form to python to then get data from the API and then send it back to another html page so i can see it on my website. I've trying to use flask for this but i can't really get it to work.

```<code><!DOCTYPE html>
<html lang="sv">
<head>
    <meta charset="utf-8" />
    <title>Gymnasie arbete</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
</head>
<body>
    <div id="background">
        <div id="top">
            <div id="tab1">
                <button class="button" onclick="location.href='Main.html'">Player search</button>
            </div>
            <div id="tab2">
                <button class="button" onclick="location.href='Champ.html'">Champions</button>
            </div>
            <div id="tab3">
                <button class="button" onclick="location.href='Leaderboard.html'">Leaderboard</button>
            </div>
        </div>
        <div id="bot"></div>
        <div id="enter">
            <form method="post" action="{{ url_for('summoner') }}" enctype="multipart/form-data">
            <input type="text" id="Username" name="Username" size="60" autofocus placeholder="Username">
            <select name="region">
            <option>EUW</option>
            <option>EUNE</option>
            <option>NA</option>
            <option>KR</option>
            <option>BR</option>
            <option>JP</option>
            <option>RU</option>
            <option>LAS</option>
            <option>LAN</option>
            <option>OCE</option>
            <option>TR</option>
            </select>
            <input type="submit" name="hello" value="Sök">
            </form>
        </div>
    </div>
    <script src="Main.py"></script>
</body>
</html>
</code>```

```<code>from riotwatcher import LolWatcher, ApiError
import pandas as pd
from bs4 import BeautifulSoup
import urllib.request
from flask import Flask, request, render_template

#user1 =  0;
#region1 = 0;

#app = Flask(__name__)

#@app.route('/summoner')
#def Main():
#    return render_template('Main.html')

#@app.route('summoner', methods =['POST'])
#def summoner():
#    user1 = request.form.get['Username']
#    region1 = request.form.get['region']

#user =  user1;
#region = region1;

user = "TSP";
region = "EUW";

if region == 'NA':
    region = 'NA1';
elif region == 'BR':
    region = 'BR1';
elif region == 'LAN':
    region = 'LA1';
elif region == 'LAS':
    region = 'LA2';
elif region == 'OCE':
    region = 'OC1';
elif region == 'KR':
    region = 'KR';
elif region == 'JP':
    region = 'JP1';
elif region == 'EUNE':
    region = 'EUN1';
elif region == 'EUW':
    region = 'EUW1';
elif region == 'RU':
    region = 'RU';
elif region == 'TR':
    region = 'TR1';

# global variables
api_key = 'RGAPI-7c42efa5-4720-42cb-82c0-78974b3f57cd'
watcher = LolWatcher(api_key)
my_region = 'EUW1'

if region == 'NA1':
    my_region1 = 'AMERICAS';
elif region == 'BR1':
    my_region1 = 'AMERICAS';
elif region == 'LA1':
    my_region1 = 'AMERICAS';
elif region == 'LA2':
    my_region1 = 'AMERICAS';
elif region == 'OC1':
    my_region1 = 'AMERICAS';
elif region == 'KR':
    my_region1 = 'ASIA';
elif region == 'JP1':
    my_region1 = 'ASIA';
elif region == 'EUN1':
    my_region1 = 'EUROPE';
elif region == 'EUW1':
    my_region1 = 'EUROPE';
elif region == 'RU':
    my_region1 = 'EUROPE';
else:
    my_region1 = 'EUROPE';

me = watcher.summoner.by_name(my_region, 'TSP')
print(me)

# Return the rank status for Doublelift
my_ranked_stats = watcher.league.by_summoner(my_region, me['id'])
print(my_ranked_stats)

my_matches = watcher.match.matchlist_by_puuid(my_region1, me['puuid'])
#print(my_matches)

m1 = my_matches[0]
#print(m1)

# fetch last match detail
#last_match = my_matches['matches'][0]
match_detail = watcher.match.by_id(my_region1, m1)

participants = []
for row in match_detail['info']['participants']:
    participants_row = {}
    participants_row['summonerName'] = row['summonerName']
    participants_row['individualPosition'] = row['individualPosition']
    participants_row['championName'] = row['championName']
    participants_row['champLevel'] = row['champLevel']
    participants_row['kills'] = row['kills']
    participants_row['deaths'] = row['deaths']
    participants_row['assists'] = row['assists']
    participants_row['visionScore'] = row['visionScore']
    participants_row['goldEarned'] = row['goldEarned']
    participants_row['item0'] = row['item0']
    participants_row['item1'] = row['item1']
    participants_row['item2'] = row['item2']
    participants_row['item3'] = row['item3']
    participants_row['item4'] = row['item4']
    participants_row['item5'] = row['item5']
    participants_row['item6'] = row['item6']
    participants.append(participants_row)
df = pd.DataFrame(participants)
df
print(participants)

#p1 = participants[8]
#print(p1)
</code>```

Heres the my code if that helps.

答:
There are many ways to reach your goal.

An integration of python files as a script, as you are trying to do, is not easily possible. Furthermore, I am surprised that you are trying to forward the user via javascript. Please use an HTML anchor for this. You can later determine the appearance using a style sheet. Libraries like Bootstrap can help you with this.

My example shows a form for entering all required data. By submitting, the user's entries are sent to the server and stored within the session cookie. The user is redirected to another address. The statistics for the games played are obtained here and then displayed on the page.

Flask (app.py)

```<code>from flask import Flask
from flask import (
    redirect,
    render_template,
    request,
    session,
    url_for
)
from riotwatcher import LolWatcher

API_KEY = 'Your api-key here!' # <- !!!
COUNTRIES = ('AMERICAS', 'ASIA', 'EUROPE')
REGIONS = ('BR1', 'EUN1', 'EUW1', 'JP1', 'KR', 'LA1', 'LA2', 'NA1', 'OC1', 'RU')

app = Flask(__name__)
app.secret_key = b'your secret here' # <-- !!!

@app.route('/', methods=['GET', 'POST'])
def index():
    keys = ('region', 'name', 'country')
    if request.method == 'POST' and all(k in request.form for k in keys):
        for k in keys:
            session[k] = request.form[k]
        return redirect(url_for('info'))
    return render_template('index.html', regions=REGIONS, countries=COUNTRIES)

def get_match_data(region, name, country):
    watcher = LolWatcher(API_KEY)
    user = watcher.summoner.by_name(region, name)
    matches = watcher.match.matchlist_by_puuid(country, user['puuid'])
    matches = { match:watcher.match.by_id(country, match) for match in matches }
    return matches

@app.route('/info')
def info():
    keys = ('region', 'name', 'country')
    if not all(k in session for k in keys):
        return redirect(url_for('index'))
    match_data = get_match_data(*[session[k] for k in keys])
    return render_template('info.html', **locals())
</code>```

HTML (templates/index.html)

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Index</title>
  </head>
  <body>
    <form method="post">
      <div>
        <label for="region">Region</label>
        <select name="region" id="region">
          {% for r in regions -%}
          <option value="{{r}}">{{r}}</option>
          {% endfor -%}
        </select>
      </div>
      <div>
        <label for="name">Name</label>
        <input type="text" name="name" id="name" />
      </div>
      <div>
        <label for="country">Country</label>
        <select name="country" id="country">
          {% for c in countries -%}
          <option value="{{c}}">{{c}}</option>
          {% endfor -%}
        </select>
      </div>
      <input type="submit" />
    </form>
  </body>
</html>
</code>```

HTML (templates/info.html)

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Stats Info</title>
  </head>
  <body>
    <a href="{{ url_for('index') }}">Back</a>
    {% for match, data in match_data.items() -%}
    <h3>{{match}}</h3>
    <table style="width: 100%;">
      <thead><!-- ... --></thead>
      <tbody>
        {% for row in data['info']['participants'] -%}
        <tr>
          <td>{{ row['summonerName'] }}</td>
          <td>{{ row['individualPosition'] }}</td>
          <td>{{ row['championName'] }}</td>
          <td>{{ row['champLevel'] }}</td>
          <td>{{ row['kills'] }}</td>
          <td>{{ row['deaths'] }}</td>
          <td>{{ row['assists'] }}</td>
          <td>{{ row['visionScore'] }}</td>
          <td>{{ row['goldEarned'] }}</td>
          <td>{{ row['item0'] }}</td>
          <td>{{ row['item1'] }}</td>
          <td>{{ row['item2'] }}</td>
          <td>{{ row['item3'] }}</td>
          <td>{{ row['item4'] }}</td>
          <td>{{ row['item5'] }}</td>
          <td>{{ row['item6'] }}</td>
        </tr>
        {% endfor -%}
      </tbody>
    </table>
    {% endfor -%}
  </body>
</html>
</code>```

It is not absolutely necessary to store the user data in the session cookie. You can also implement the query and display of game statistics within a single endpoint. I chose this variant to show you the processing of form data with a clearer structure.

To get to know Flask better, I recommend this tutorial.

Body:
So i just started working witih python since it was necessary for this project (because the API im using). So i've struggled with this a bit. I'm trying to send html data from a form to python to then get data from the API and then send it back to another html page so i can see it on my website. I've trying to use flask for this but i can't really get it to work.

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Gymnasie arbete</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />

                <button class="button" onclick="location.href='Main.html'">Player search</button>

                <button class="button" onclick="location.href='Champ.html'">Champions</button>

                <button class="button" onclick="location.href='Leaderboard.html'">Leaderboard</button>

            <form method="post" action="{{ url_for('summoner') }}" enctype="multipart/form-data">
            <input type="text" id="Username" name="Username" size="60" autofocus placeholder="Username">
            <select name="region">
            <option>EUW</option>
            <option>EUNE</option>
            <option>NA</option>
            <option>KR</option>
            <option>BR</option>
            <option>JP</option>
            <option>RU</option>
            <option>LAS</option>
            <option>LAN</option>
            <option>OCE</option>
            <option>TR</option>
            </select>
            <input type="submit" name="hello" value="Sök">
            </form>

from riotwatcher import LolWatcher, ApiError
import pandas as pd
from bs4 import BeautifulSoup
import urllib.request
from flask import Flask, request, render_template

#user1 =  0;
#region1 = 0;

#app = Flask(__name__)

#@app.route('/summoner')
#def Main():
#    return render_template('Main.html')

#@app.route('summoner', methods =['POST'])
#def summoner():
#    user1 = request.form.get['Username']
#    region1 = request.form.get['region']

#user =  user1;
#region = region1;

user = "TSP";
region = "EUW";

if region == 'NA':
    region = 'NA1';
elif region == 'BR':
    region = 'BR1';
elif region == 'LAN':
    region = 'LA1';
elif region == 'LAS':
    region = 'LA2';
elif region == 'OCE':
    region = 'OC1';
elif region == 'KR':
    region = 'KR';
elif region == 'JP':
    region = 'JP1';
elif region == 'EUNE':
    region = 'EUN1';
elif region == 'EUW':
    region = 'EUW1';
elif region == 'RU':
    region = 'RU';
elif region == 'TR':
    region = 'TR1';

# global variables
api_key = 'RGAPI-7c42efa5-4720-42cb-82c0-78974b3f57cd'
watcher = LolWatcher(api_key)
my_region = 'EUW1'

if region == 'NA1':
    my_region1 = 'AMERICAS';
elif region == 'BR1':
    my_region1 = 'AMERICAS';
elif region == 'LA1':
    my_region1 = 'AMERICAS';
elif region == 'LA2':
    my_region1 = 'AMERICAS';
elif region == 'OC1':
    my_region1 = 'AMERICAS';
elif region == 'KR':
    my_region1 = 'ASIA';
elif region == 'JP1':
    my_region1 = 'ASIA';
elif region == 'EUN1':
    my_region1 = 'EUROPE';
elif region == 'EUW1':
    my_region1 = 'EUROPE';
elif region == 'RU':
    my_region1 = 'EUROPE';
else:
    my_region1 = 'EUROPE';

me = watcher.summoner.by_name(my_region, 'TSP')
print(me)

# Return the rank status for Doublelift
my_ranked_stats = watcher.league.by_summoner(my_region, me['id'])
print(my_ranked_stats)

my_matches = watcher.match.matchlist_by_puuid(my_region1, me['puuid'])
#print(my_matches)

m1 = my_matches[0]
#print(m1)

# fetch last match detail
#last_match = my_matches['matches'][0]
match_detail = watcher.match.by_id(my_region1, m1)

participants = []
for row in match_detail['info']['participants']:
    participants_row = {}
    participants_row['summonerName'] = row['summonerName']
    participants_row['individualPosition'] = row['individualPosition']
    participants_row['championName'] = row['championName']
    participants_row['champLevel'] = row['champLevel']
    participants_row['kills'] = row['kills']
    participants_row['deaths'] = row['deaths']
    participants_row['assists'] = row['assists']
    participants_row['visionScore'] = row['visionScore']
    participants_row['goldEarned'] = row['goldEarned']
    participants_row['item0'] = row['item0']
    participants_row['item1'] = row['item1']
    participants_row['item2'] = row['item2']
    participants_row['item3'] = row['item3']
    participants_row['item4'] = row['item4']
    participants_row['item5'] = row['item5']
    participants_row['item6'] = row['item6']
    participants.append(participants_row)
df = pd.DataFrame(participants)
df
print(participants)

#p1 = participants[8]
#print(p1)

Heres the my code if that helps.

Body:
There are many ways to reach your goal.

An integration of python files as a script, as you are trying to do, is not easily possible. Furthermore, I am surprised that you are trying to forward the user via javascript. Please use an HTML anchor for this. You can later determine the appearance using a style sheet. Libraries like Bootstrap can help you with this.

My example shows a form for entering all required data. By submitting, the user's entries are sent to the server and stored within the session cookie. The user is redirected to another address. The statistics for the games played are obtained here and then displayed on the page.

Flask (app.py)

from flask import Flask
from flask import (
    redirect,
    render_template,
    request,
    session,
    url_for
)
from riotwatcher import LolWatcher

API_KEY = 'Your api-key here!' # <- !!!
COUNTRIES = ('AMERICAS', 'ASIA', 'EUROPE')
REGIONS = ('BR1', 'EUN1', 'EUW1', 'JP1', 'KR', 'LA1', 'LA2', 'NA1', 'OC1', 'RU')

app = Flask(__name__)
app.secret_key = b'your secret here' # <-- !!!

@app.route('/', methods=['GET', 'POST'])
def index():
    keys = ('region', 'name', 'country')
    if request.method == 'POST' and all(k in request.form for k in keys):
        for k in keys:
            session[k] = request.form[k]
        return redirect(url_for('info'))
    return render_template('index.html', regions=REGIONS, countries=COUNTRIES)

def get_match_data(region, name, country):
    watcher = LolWatcher(API_KEY)
    user = watcher.summoner.by_name(region, name)
    matches = watcher.match.matchlist_by_puuid(country, user['puuid'])
    matches = { match:watcher.match.by_id(country, match) for match in matches }
    return matches

@app.route('/info')
def info():
    keys = ('region', 'name', 'country')
    if not all(k in session for k in keys):
        return redirect(url_for('index'))
    match_data = get_match_data(*[session[k] for k in keys])
    return render_template('info.html', **locals())

HTML (templates/index.html)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Index</title>
  </head>
  <body>
    <form method="post">
      <div>
        <label for="region">Region</label>
        <select name="region" id="region">
          {% for r in regions -%}
          <option value="{{r}}">{{r}}</option>
          {% endfor -%}
        </select>
      </div>
      <div>
        <label for="name">Name</label>
        <input type="text" name="name" id="name" />
      </div>
      <div>
        <label for="country">Country</label>
        <select name="country" id="country">
          {% for c in countries -%}
          <option value="{{c}}">{{c}}</option>
          {% endfor -%}
        </select>
      </div>
      <input type="submit" />
    </form>
  </body>
</html>

HTML (templates/info.html)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Stats Info</title>
  </head>
  <body>
    <a href="{{ url_for('index') }}">Back</a>
    {% for match, data in match_data.items() -%}
    <h3>{{match}}</h3>
    <table style="width: 100%;">
      <thead><!-- ... --></thead>
      <tbody>
        {% for row in data['info']['participants'] -%}
        <tr>
          <td>{{ row['summonerName'] }}</td>
          <td>{{ row['individualPosition'] }}</td>
          <td>{{ row['championName'] }}</td>
          <td>{{ row['champLevel'] }}</td>
          <td>{{ row['kills'] }}</td>
          <td>{{ row['deaths'] }}</td>
          <td>{{ row['assists'] }}</td>
          <td>{{ row['visionScore'] }}</td>
          <td>{{ row['goldEarned'] }}</td>
          <td>{{ row['item0'] }}</td>
          <td>{{ row['item1'] }}</td>
          <td>{{ row['item2'] }}</td>
          <td>{{ row['item3'] }}</td>
          <td>{{ row['item4'] }}</td>
          <td>{{ row['item5'] }}</td>
          <td>{{ row['item6'] }}</td>
        </tr>
        {% endfor -%}
      </tbody>
    </table>
    {% endfor -%}
  </body>
</html>

It is not absolutely necessary to store the user data in the session cookie. You can also implement the query and display of game statistics within a single endpoint. I chose this variant to show you the processing of form data with a clearer structure.

To get to know Flask better, I recommend this tutorial.