问:
How to get ID dynamic in Jquery?
I am making dynamic input, when the user clicks "Add From Checklist" there will be an input form, and if clicked again "Add From Checklist" then the input form becomes two and so on, for the actual select code there is already data such as
'1-022020-001', now for inputting stations and equipment, the data is where the value '1-022020-001' is in the database, now I'm still confused about how to get results from value '1-022020-001' can be sent to the controller and returned to js to display the input Station and Equipment.

DEMO:

var html = '';
    $('.btnSend').attr('disabled', true);

    $("#inputCode, #inputStasiun, #inputPeralatan").select2({
        placeholder: "Choose one",
        allowClear: true
    });

    var runNumberAdd = 1;
    $("#add-more").click(function() {
        html =
        '
'+
            '
'+
                '
'+
                    '
'+
                        'Tanggal'+
                        '
'+
                            '<input name="inputTgl[]" type="date" id="inputTglClone'+ runNumberAdd +'" class="form-control inputTglClone">'+
                        '
'+
                    '
'+
                    '
'+
                        'Code'+
                        '
'+
                            '<select name="inputCode[]" id="inputCodeClone'+ runNumberAdd +'" class="form-control select2 inputCodeClone">'+
                            '</select>'+
                        '
'+
                    '
'+
                    '
'+
                        'Stasiun'+
                        '
'+
                            '<select name="inputStasiun[]" id="inputStasiunClone'+ runNumberAdd +'" class="form-control select2 inputStasiunClone">'+
                            '</select>'+
                            '<input name="inputStasiunHidden[]" type="text" id="inputStasiunHiddenClone'+ runNumberAdd +'" class="form-control inputStasiunHiddenClone">'+
                        '
'+
                    '
'+
                    '
'+
                        'Peralatan'+
                        '
'+
                            '<select name="inputPeralatan[]" id="inputPeralatanClone'+ runNumberAdd +'" class="form-control select2 inputPeralatanClone">'+
                            '</select>'+
                        '
'+
                    '
'+
                    '
'+
                        'Deskripsi'+
                        '
'+
                            '<textarea name="inputDeskripsi[]" id="inputDeskripsiClone'+ runNumberAdd +'" class="form-control inputDeskripsiClone"></textarea>'+
                        '
'+
                    '
'+
                    '
'+
                        'Resume'+
                        '
'+
                            ''+
                                '<input type="radio" name="inputChecklist[]" id="inputChecklist1Clone'+ runNumberAdd +'" class="inputChecklist1Clone'+ runNumberAdd +'" value="1"> OK'+
                            ''+
                            ''+
                                '<input type="radio" name="inputChecklist[]" id="inputChecklist2Clone'+ runNumberAdd +'" class="inputChecklist2Clone'+ runNumberAdd +'" value="0"> NOK'+
                            ''+
                            '
'+
                                '<button type="button" class="btn btn-danger btn-sm remove_list"> Hapus From Checklist</button>'+
                            '
'+
                        '
'+
                    '
'+
                '
'+
            '
'+
        '
';
        $('.clone-form').append(html);
        $(".inputCodeClone, .inputStasiunClone, .inputPeralatanClone").select2({
            placeholder: "Choose one",
            allowClear: true
        });
        $.ajax({
            url   : 'showDataCode',
            dataType : 'JSON',
            async : true,
            success : function(data) {
                var minrunNumberAdd = runNumberAdd - 1;
                var attrCode = '#inputCodeClone' + minrunNumberAdd;
                $(attrCode).append($("<option selected disabled></option>").attr("value", '').text(''));
                $.each(data, function(key, value) {
                    $(attrCode).append($("<option></option>").attr("value", value.id).text(value.code));
                });
            }
        });
        $('.btnSend').attr('disabled', false);
        $('.inputStasiunClone').attr("disabled", true);
        $('.inputPeralatanClone').attr("disabled", true);
        runNumberAdd++;
    });

    $("body").on("click", ".remove_list",function() {
        var numItems = $('.control-group').length;
        $(this).parents(".control-group").remove();
        if (numItems == 1) {
            $('.btnSend').attr('disabled', true);
        } else {
            $('.btnSend').attr('disabled', false);
        }
    });

    // How to get attribut ID
    // My Xample
    $('input[id^="inputCodeClone"]').on('click', function() {
        alert('A');
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet"/>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

<div class="box-header">
                    <div class="pull-right">
                        <button type="button"  id="add-more" class="btn btn-success btn-sm"> Tambah From Checklist</button>
                    </div>
                </div>
                <form action="<?= base_url('GeneralFormChecklist/submitChecklist'); ?>" method="post" id="formInput">
                    <div class="box-body">
                        <div class="clone-form">
                        </div>
                    </div>
                    <div class="box-footer">
                        <div class="pull-right">
                            <button type="submit" class="btn btn-primary btn-sm btnSend">Kirim Checklist</button>
                        </div>
                    </div>
                </form></code>```

Sample data in a database

The question is:

how to be able to display id_location in the input station and id_equipment_name in the input equipment by selecting code as where in the database later?

NOTE: the code that I have stuck when looking for a dynamic ID

答:
if you want to get the value of current input that you clicked or all the nearest inputs then you can use $(this).
it helps you to point on the currently focused or clicked element.</p>

Title: How to get ID dynamic in Jquery?

Body:
I am making dynamic input, when the user clicks "Add From Checklist" there will be an input form, and if clicked again "Add From Checklist" then the input form becomes two and so on, for the actual select code there is already data such as
'1-022020-001', now for inputting stations and equipment, the data is where the value '1-022020-001' is in the database, now I'm still confused about how to get results from value '1-022020-001' can be sent to the controller and returned to js to display the input Station and Equipment.

DEMO:

var html = '';
    $('.btnSend').attr('disabled', true);

    $("#inputCode, #inputStasiun, #inputPeralatan").select2({
        placeholder: "Choose one",
        allowClear: true
    });

    var runNumberAdd = 1;
    $("#add-more").click(function() {
        html =
        '
'+
            '
'+
                '
'+
                    '
'+
                        'Tanggal'+
                        '
'+
                            '<input name="inputTgl[]" type="date" id="inputTglClone'+ runNumberAdd +'" class="form-control inputTglClone">'+
                        '
'+
                    '
'+
                    '
'+
                        'Code'+
                        '
'+
                            '<select name="inputCode[]" id="inputCodeClone'+ runNumberAdd +'" class="form-control select2 inputCodeClone">'+
                            '</select>'+
                        '
'+
                    '
'+
                    '
'+
                        'Stasiun'+
                        '
'+
                            '<select name="inputStasiun[]" id="inputStasiunClone'+ runNumberAdd +'" class="form-control select2 inputStasiunClone">'+
                            '</select>'+
                            '<input name="inputStasiunHidden[]" type="text" id="inputStasiunHiddenClone'+ runNumberAdd +'" class="form-control inputStasiunHiddenClone">'+
                        '
'+
                    '
'+
                    '
'+
                        'Peralatan'+
                        '
'+
                            '<select name="inputPeralatan[]" id="inputPeralatanClone'+ runNumberAdd +'" class="form-control select2 inputPeralatanClone">'+
                            '</select>'+
                        '
'+
                    '
'+
                    '
'+
                        'Deskripsi'+
                        '
'+
                            '<textarea name="inputDeskripsi[]" id="inputDeskripsiClone'+ runNumberAdd +'" class="form-control inputDeskripsiClone"></textarea>'+
                        '
'+
                    '
'+
                    '
'+
                        'Resume'+
                        '
'+
                            ''+
                                '<input type="radio" name="inputChecklist[]" id="inputChecklist1Clone'+ runNumberAdd +'" class="inputChecklist1Clone'+ runNumberAdd +'" value="1"> OK'+
                            ''+
                            ''+
                                '<input type="radio" name="inputChecklist[]" id="inputChecklist2Clone'+ runNumberAdd +'" class="inputChecklist2Clone'+ runNumberAdd +'" value="0"> NOK'+
                            ''+
                            '
'+
                                '<button type="button" class="btn btn-danger btn-sm remove_list"> Hapus From Checklist</button>'+
                            '
'+
                        '
'+
                    '
'+
                '
'+
            '
'+
        '
';
        $('.clone-form').append(html);
        $(".inputCodeClone, .inputStasiunClone, .inputPeralatanClone").select2({
            placeholder: "Choose one",
            allowClear: true
        });
        $.ajax({
            url   : 'showDataCode',
            dataType : 'JSON',
            async : true,
            success : function(data) {
                var minrunNumberAdd = runNumberAdd - 1;
                var attrCode = '#inputCodeClone' + minrunNumberAdd;
                $(attrCode).append($("<option selected disabled></option>").attr("value", '').text(''));
                $.each(data, function(key, value) {
                    $(attrCode).append($("<option></option>").attr("value", value.id).text(value.code));
                });
            }
        });
        $('.btnSend').attr('disabled', false);
        $('.inputStasiunClone').attr("disabled", true);
        $('.inputPeralatanClone').attr("disabled", true);
        runNumberAdd++;
    });

    $("body").on("click", ".remove_list",function() {
        var numItems = $('.control-group').length;
        $(this).parents(".control-group").remove();
        if (numItems == 1) {
            $('.btnSend').attr('disabled', true);
        } else {
            $('.btnSend').attr('disabled', false);
        }
    });

    // How to get attribut ID
    // My Xample
    $('input[id^="inputCodeClone"]').on('click', function() {
        alert('A');
    });

<link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet"/>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>

                        <button type="button"  id="add-more" class="btn btn-success btn-sm"> Tambah From Checklist</button>

                <form action="<?= base_url('GeneralFormChecklist/submitChecklist'); ?>" method="post" id="formInput">

                            <button type="submit" class="btn btn-primary btn-sm btnSend">Kirim Checklist</button>

                </form>

Sample data in a database

The question is:

how to be able to display id_location in the input station and id_equipment_name in the input equipment by selecting code as where in the database later?

NOTE: the code that I have stuck when looking for a dynamic ID


来源: stackexchange

问:
Function Callbacks Not Working on Multipage Dash/Django Application
I have the application below that uses dash plotly.

If i execute this application in a single file/page application all callbacks works correctly.

But in this case I using dash multipage application with Django.

And my callbacks stop to work, the computed-table and table-backlog.

I not sure why these callbacks not working regarding that there's no error in runtime or code as well.

The objective of callback is perform calculations in dash table once values is changed by user.

Full Project: https://github.com/CaioEuzebio/DjangoDashboard/blob/master/app/as_dash.py

Application:

```import sys
from random import randint
import base64
import io
import datetime

from dash.dependencies import Input, Output, State

import dash

import dash_core_components as dcc
import dash_html_components as dhc

import pandas as pd
import random
import plotly.graph_objects as go
import dash_table
import dash_table_experiments
import dash_table
import dash_bootstrap_components as dbc
import os, time
from os import listdir
import os.path, time
import datetime
import subprocess

from website.views import *

PLOTLY_LOGO = "https://p7.hiclipart.com/preview/243/790/417/doing-business-as-company-logo-name-creative-company-logo.jpg"

def dispatcher(request):
    '''
    Main function
    @param request: Request object
    '''

    app = _create_app()
    params = {
        'data': request.body,
        'method': request.method,
        'content_type': request.content_type
    }
    with app.server.test_request_context(request.path, **params):
        app.server.preprocess_request()
        try:
            response = app.server.full_dispatch_request()
        except Exception as e:
            response = app.server.make_response(app.server.handle_exception(e))
        return response.get_data()

def _create_app():

    ''' Creates dash application '''

    app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
    app.config['suppress_callback_exceptions']=True
    app.layout = dhc.Div(children=[

                dbc.Navbar(
            [
                dhc.A(
                    # Use row and col to control vertical alignment of logo / brand
                    dbc.Row(
                        [
                            dbc.Col(dhc.Img(src=PLOTLY_LOGO, height="30px")),
                            dbc.Col(dcc.Link("Home", className="ml-2", href="/home", refresh=True)),
                        ],
                        align="center",
                        no_gutters=True,

                    ),href="/home"
                ),

                dhc.A(
                    # Use row and col to control vertical alignment of logo / brand
                    dbc.Row(
                        [

                            dbc.Col(dcc.Link("Dashboard", className="ml-2", href="/dash-fig1")),
                        ],
                        align="center",
                        no_gutters=True,
                    ),
                    href="/home",
                ),
                dhc.A(
                    # Use row and col to control vertical alignment of logo / brand
                    dbc.Row(
                        [

                            dbc.Col(dcc.Link("Dashboard S.", className="ml-2", href="/dash-fig2")),
                        ],
                        align="center",
                        no_gutters=True,
                    ),

                ),

                 dhc.A(
                    dbc.Row([
                     dbc.Col(dcc.Link("Load New File", className="ml-2", href="/loadfile", refresh=True)),
                     ],
                        align="center",
                        no_gutters=True,
                    ), href="/loadfile"
                 ),

                dbc.NavbarToggler(id="navbar-toggler"),

            ],
            color="dark",
            dark=True,
        ),

        dcc.Location(id='url', refresh=True),

        dhc.Br(),
        dhc.Br(),
        dhc.Div(id='content'),
    ])

    @app.callback(dash.dependencies.Output('content', 'children'),
                [dash.dependencies.Input('url', 'pathname')],
    )

    def display_page(pathname):

        ''' '''
        if not pathname:
            return ''
        if pathname == '/':
            return dash_index()
        method = pathname[1:].replace('-', '_')
        func = getattr(sys.modules[__name__], method, None)
        if func:
            return func()
        return 'Unknown link'

    @app.callback(
        Output('computed-table', 'data'),
        [Input('computed-table', 'data_timestamp')],
        [State('computed-table', 'data')])
    def update_columns(timestamp, rows):
        for row in rows:
            try:
                if row['Unidades Pendentes'] != 0:
                    row['UPH_BPI_vs_Head'] = float(row['UPH_BPI_vs_Perfil']) * float(row['Head_Disponível'])
                    row['ETA_Geral'] = float(row['Unidades Pendentes']) / float(row['UPH_BPI_vs_Head'])
                    row['Delta_Hora'] = float(row['Horas_Disp']) - float(row['ETA_Geral'])
                    row['Risco_Aging'] = float(row['Delta_Hora']) * float(row['UPH_BPI_vs_Head'])
                else:
                    row['UPH_BPI_vs_Head'] = "Completed"
                    row['ETA_Geral'] = "Completed"
                    row['Delta_Hora'] = "Completed"
                    row['Risco_Aging'] = "Completed"
                    row['UPH_BPI_vs_Perfil'] = "Completed"
                    row['Head_Disponível'] = "Completed"
                    row['Horas_Disp'] = "Completed"
            except:
                row['ETA_Geral'] = 'N/A'

        return rows

    @app.callback(
        Output('table-backlog', 'data'),
        [Input('table-backlog', 'data_timestamp')],
        [State('table-backlog', 'data')])
    def update_columns(timestamp, rows):
        for row in rows:
            try:
                if row['Unidades Pendentes'] != 0:
                    row['Delta Hora'] = float(row['Horas Disp']) - float(row['ETA'])
                    row['Risco Aging'] = float(row['Delta Hora']) * float(row['UPH'])
                else:
                    row['ETA'] = "Completed"

            except:

                row['ETA'] = row['ETA']
        return rows

    return app

def dash_fig1():

    #pandas code

    return  dhc.Div([
            dhc.Div([ dhc.H2(children= 'Nome Do Aqrquivo: ' + filename ),
            dhc.H2(children= "Date created: " + dataa),

            ],style={'textAlign': 'center',
                            'align-items': 'center',
                            'fontSize': 12,
                            'width': '100%',
                            'display': 'block',
                            'align-items': 'center',
                            'justify-content': 'center',
                            'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                            'padding': '30px 20px',
                            'marginBottom': 50} ),
            dhc.Div([
            dhc.Div([

                dhc.H2(children = "Perfil Por Canal",
                    style = {'textAlign' : 'center',}),

                dhc.Br(""),

            dash_table.DataTable(
                    id='table1',
                    columns=[{"name": i, "id": i} for i in dforderbypn.columns],
                    data=dforderbypn.to_dict('records'),
                    style_table={'textAlign': 'center'},
                    style_as_list_view=True,
                    style_cell={'padding': '5px','fontSize': 12, 'textAlign': 'center'},
                    style_header={
                        'backgroundColor': 'Gainsboro',
                        'fontWeight': 'bold',
                        'fontSize': 12},
                    export_format='xlsx',
                    export_headers='display',
                    merge_duplicate_headers=True

                ),

            ]

                    ,style={'textAlign': 'center',
                            'align-items': 'center',
                            'fontSize': 12,
                            'width': '100%',
                            'display': 'block',
                            'align-items': 'center',
                            'justify-content': 'center',
                            'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                            'padding': '30px 20px'}),

                    ],style={'textAlign': 'center' }),

            #Tabela De Perfil Por Canal/>

            #Tabela De Desempenho Por Canal<

            dhc.Div([
            dhc.Div([

                dhc.H2(children = "UPH / ETA  Médio Por Canal",
                    style = {'textAlign' : 'center',}),

                dhc.Br(""),

            dash_table.DataTable(
                    id='table1',
                    columns=[{"name": i, "id": i} for i in dfordertype.columns],
                    data=dfordertype.to_dict('records'),
                    style_table={'textAlign': 'center'},
                    style_as_list_view=True,
                    style_cell={'padding': '5px','fontSize': 12, 'textAlign': 'center'},
                    style_header={
                        'backgroundColor': 'Gainsboro',
                        'fontWeight': 'bold',
                        'fontSize': 12},
                    export_format='xlsx',
                    export_headers='display',
                    merge_duplicate_headers=True

                ),

                    ],style={'textAlign': 'center',
                            'align-items': 'center',
                            'fontSize': 12,
                            'width': '100%',
                            'display': 'block',
                            'align-items': 'center',
                            'justify-content': 'center',
                            'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                            'padding': '30px 20px'}),

                    ],style={'textAlign': 'center', 'marginTop': '15px'}),

            #Tabela De Desempenho Por Canal/>

            #Planejamento Estilizado<
            dhc.Div([
            dhc.Div([

                    dhc.H2(children = "Planner - Suporte",
                    style = {'textAlign' : 'center',}),

                dhc.Br(""),

                dash_table.DataTable(
                    id='computed-table',
                    columns=[{"name": i, "id": i} for i in dfplano.columns ],
                    data=dfordertype.to_dict('records'),
                    editable=True,
                    style_table={'textAlign': 'center'},
                    style_as_list_view=True,
                    style_cell={'padding': '5px','fontSize': 12, 'textAlign': 'center'},
                    style_header={
                        'backgroundColor': 'Gainsboro',
                        'fontWeight': 'bold',
                        'fontSize': 12},
                    export_format='xlsx',
                    export_headers='display',
                    merge_duplicate_headers=True

                ),

                    ],style={'textAlign': 'center',
                            'align-items': 'center',
                            'fontSize': 12,
                            'width': '100%',
                            'display': 'block',
                            'align-items': 'center',
                            'justify-content': 'center',
                            'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                            'padding': '30px 20px'}),

                    ],style={'textAlign': 'center',
                            'marginTop': '15px',
                            'display': 'block'}),
            #Planejamento Estilizado/>

            # Tabela Gerenciamento de Backlog<

            dhc.Div([
            dhc.Div([
                dhc.H2(children = "Status Por Cut Off",
                    style = {'textAlign' : 'center',}),

                dhc.Br(""),

                dash_table.DataTable(
                    id='table-backlog',
                    columns=[{"name": i, "id": i} for i in tabelaback.columns ],
                    data=tabelaback.to_dict('records'),
                    editable=True,
                    style_table={'textAlign': 'center'},
                    style_as_list_view=True,
                    style_cell={'padding': '5px','fontSize': 12, 'textAlign': 'center'},
                    style_header={
                        'backgroundColor': 'Gainsboro',
                        'fontWeight': 'bold',
                        'fontSize': 12},
                    export_format='xlsx',
                    export_headers='display',
                    merge_duplicate_headers=True

                ),

                    ],style={'textAlign': 'center',
                            'align-items': 'center',
                            'fontSize': 12,
                            'width': '100%',
                            'display': 'block',
                            'align-items': 'center',
                            'justify-content': 'center',
                            'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                            'padding': '30px 20px'}),

                    ],style={'textAlign': 'center',
                            'marginTop': '15px',
                            'display': 'block'}),

            # Tabela Gerenciamento de Backlog/>

            #Prod Hora Estaao<

            dhc.Div([
                dhc.Div([

                        dhc.H3(children = "Produção Por Hora (Estação)",
                        style = {'textAlign' : 'center',}),

                        dhc.Br(""),

                        dcc.Graph(id = 'GrapGo2', figure = figure3),
                        ],style={'textAlign': 'center',
                                'align-items': 'center',
                                'fontSize': 12,
                                'width': '100%',
                                'display': 'block',
                                'align-items': 'center',
                                'justify-content': 'center',
                                'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                                'padding': '30px 20px'}),

                        ],style={'textAlign': 'center',
                                'marginTop': '15px',
                                'display': 'block'}),

            #Prod Hora Estacao/>

            #Prod Hora Operador<

            dhc.Div([
                dhc.Div([

                        dhc.H3(children = "Produção Por Hora (Pessoa)",
                        style = {'textAlign' : 'center',}),

                        dhc.Br(""),

                        dcc.Graph( id = 'GrapGo3', figure = figure4),
                        ],style={'textAlign': 'center',
                                'align-items': 'center',
                                'fontSize': 12,
                                'width': '100%',
                                'display': 'block',
                                'align-items': 'center',
                                'justify-content': 'center',
                                'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                                'padding': '30px 20px'}),

                        ],style={'textAlign': 'center',
                                'marginTop': '15px',
                                'display': 'block'}),

            #Prod Hora Operador/>

            #Medias moveis<
            dhc.Div([
                dhc.Div([

                        dhc.H3(children = "Médias Mveis (10, 20 e 30 periodos)",
                        style = {'textAlign' : 'center',}),

                        dhc.Br(""),

                        dcc.Graph(id = 'GrapGo4',figure = figuremm),
                        ],style={'textAlign': 'center',
                                'align-items': 'center',
                                'fontSize': 12,
                                'width': '100%',
                                'display': 'block',
                                'align-items': 'center',
                                'justify-content': 'center',
                                'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                                'padding': '30px 20px'}),

                        ],style={'textAlign': 'center',
                                'marginTop': '15px',
                                'display': 'block'}),

            #Medias moveis/>

            #Media 10 intervalos<
            dhc.Div([
                dhc.Div([

                        dhc.H3(children = "Médias Móveis - 10 Intervalos por canal",
                        style = {'textAlign' : 'center',}),

                        dhc.Br(""),

                        dcc.Graph(id = 'GrapGo4',figure = figure7),
                        ],style={'textAlign': 'center',
                                'align-items': 'center',
                                'fontSize': 12,
                                'width': '100%',
                                'display': 'block',
                                'align-items': 'center',
                                'justify-content': 'center',
                                'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                                'padding': '30px 20px'}),

                        ],style={'textAlign': 'center',
                                'marginTop': '15px',
                                'display': 'block'}),

            #Media 10 intervalos/>

            #Unidades Recebidas Vs Processadas/hora<
            dhc.Div([
                dhc.Div([

                        dhc.H3(children = "Unidades Recebidas Vs Processadas por Hora (Drop)",
                        style = {'textAlign' : 'center',}),

                        dhc.Br(""),

                        dcc.Graph(id = 'GrapGo4',figure = figurefd),
                        ],style={'textAlign': 'center',
                                'align-items': 'center',
                                'fontSize': 12,
                                'width': '100%',
                                'display': 'block',
                                'align-items': 'center',
                                'justify-content': 'center',
                                'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                                'padding': '30px 20px'}),

                        ],style={'textAlign': 'center',
                                'marginTop': '15px',
                                'display': 'block'}),
            #Unidades Recebidas Vs Processadas/hora/>

            #UPPH Chart<
            dhc.Div([
                dhc.Div([

                        dhc.H3(children = "Unidade Produzidas Por Pessoa (Hora)",
                        style = {'textAlign' : 'center',}),

                        dhc.Br(""),

                        dcc.Graph(id = 'GrapGo4',figure = figure52)
                        ],style={'textAlign': 'center',
                                'align-items': 'center',
                                'fontSize': 12,
                                'width': '100%',
                                'display': 'block',
                                'align-items': 'center',
                                'justify-content': 'center',
                                'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                                'padding': '30px 20px'}),

                        ],style={'textAlign': 'center',
                                'marginTop': '15px',
                                'display': 'block'}),
            #UPPH chrta/>

            ], style={'marginBottom': 50,
                        'marginTop': 50,
                        'textAlign': 'center',
                        'padding': '30px 20px',
                        'align-items': 'center' }),

            ], style={'marginLeft': 50,
                        'marginRight': 50,
                        'display':'block',
                        'textAlign': 'center',
                        'align-items': 'center',
                        'padding': '30px 20px'})

def dash_fig2():

    return dhc.Div([
            dhc.Div([
                dhc.Div(children=[dhc.H1('Dash 2')

                                ],style={'textAlign': 'center',
                                'align-items': 'center',
                                'fontSize': 12,
                                'width': '100%',
                                'display': 'block',
                                'align-items': 'center',
                                'justify-content': 'center',
                                'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                                'padding': '30px 20px'}),

            dhc.Div([
            dhc.Div([

                    dhc.H2(children = "Planner - Suporte",
                    style = {'textAlign' : 'center',}),

                dhc.Br(""),

                dash_table.DataTable(
                    id='computed-table',
                    columns=[{"name": i, "id": i} for i in dfplano.columns ],
                    data=dfordertype.to_dict('records'),
                    editable=True,
                    style_table={'textAlign': 'center'},
                    style_as_list_view=True,
                    style_cell={'padding': '5px','fontSize': 12, 'textAlign': 'center'},
                    style_header={
                        'backgroundColor': 'Gainsboro',
                        'fontWeight': 'bold',
                        'fontSize': 12},
                    export_format='xlsx',
                    export_headers='display',
                    merge_duplicate_headers=True

                )

                    ],style={'textAlign': 'center',
                            'align-items': 'center',
                            'fontSize': 12,
                            'width': '100%',
                            'display': 'block',
                            'align-items': 'center',
                            'justify-content': 'center',
                            'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                            'padding': '30px 20px'}),

                    ],style={'textAlign': 'center',
                            'marginTop': '15px',
                            'display': 'block'}),

            ], style={'marginBottom': 50,
            'marginTop': 50,
            'textAlign': 'center',
            'padding': '30px 20px',
            'align-items': 'center' }),

            ], style={'marginLeft': 50,
                        'marginRight': 50,
                        'display':'block',
                        'textAlign': 'center',
                        'align-items': 'center',
                        'padding': '30px 20px'})

def dash_fig3():

    return 'a'

if __name__ == '__main__':
    app = _create_app()
    app.run_server(threaded=True, dev_tools_hot_reload=False)

```

答:
In a multipage application, you can put all your callbacks in a single py file say callbacks.py. If you have split your multipage app as suggested in the documentation of dash, and have an app.py, index.py, you need to have in your callback.py

```<code>from app import app
</code>```

Then in the index.py you need to have

```<code>import callback
</code>```

Try to separate out the code this way and ensure to have the import callback in index.py and it should work.

ContentLicense: CC BY-SA 4.0

Body:
I have the application below that uses dash plotly.

If i execute this application in a single file/page application all callbacks works correctly.

But in this case I using dash multipage application with Django.

And my callbacks stop to work, the computed-table and table-backlog.

I not sure why these callbacks not working regarding that there's no error in runtime or code as well.

The objective of callback is perform calculations in dash table once values is changed by user.

Full Project: https://github.com/CaioEuzebio/DjangoDashboard/blob/master/app/as_dash.py

Application:

import sys
from random import randint
import base64
import io
import datetime

from dash.dependencies import Input, Output, State

import dash

import dash_core_components as dcc
import dash_html_components as dhc

import pandas as pd
import random
import plotly.graph_objects as go
import dash_table
import dash_table_experiments
import dash_table
import dash_bootstrap_components as dbc
import os, time
from os import listdir
import os.path, time
import datetime
import subprocess

from website.views import *

PLOTLY_LOGO = "https://p7.hiclipart.com/preview/243/790/417/doing-business-as-company-logo-name-creative-company-logo.jpg"

def dispatcher(request):
    '''
    Main function
    @param request: Request object
    '''

    app = _create_app()
    params = {
        'data': request.body,
        'method': request.method,
        'content_type': request.content_type
    }
    with app.server.test_request_context(request.path, **params):
        app.server.preprocess_request()
        try:
            response = app.server.full_dispatch_request()
        except Exception as e:
            response = app.server.make_response(app.server.handle_exception(e))
        return response.get_data()

def _create_app():

    ''' Creates dash application '''

    app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
    app.config['suppress_callback_exceptions']=True
    app.layout = dhc.Div(children=[

                dbc.Navbar(
            [
                dhc.A(
                    # Use row and col to control vertical alignment of logo / brand
                    dbc.Row(
                        [
                            dbc.Col(dhc.Img(src=PLOTLY_LOGO, height="30px")),
                            dbc.Col(dcc.Link("Home", className="ml-2", href="/home", refresh=True)),
                        ],
                        align="center",
                        no_gutters=True,

                    ),href="/home"
                ),

                dhc.A(
                    # Use row and col to control vertical alignment of logo / brand
                    dbc.Row(
                        [

                            dbc.Col(dcc.Link("Dashboard", className="ml-2", href="/dash-fig1")),
                        ],
                        align="center",
                        no_gutters=True,
                    ),
                    href="/home",
                ),
                dhc.A(
                    # Use row and col to control vertical alignment of logo / brand
                    dbc.Row(
                        [

                            dbc.Col(dcc.Link("Dashboard S.", className="ml-2", href="/dash-fig2")),
                        ],
                        align="center",
                        no_gutters=True,
                    ),

                ),

                 dhc.A(
                    dbc.Row([
                     dbc.Col(dcc.Link("Load New File", className="ml-2", href="/loadfile", refresh=True)),
                     ],
                        align="center",
                        no_gutters=True,
                    ), href="/loadfile"
                 ),

                dbc.NavbarToggler(id="navbar-toggler"),

            ],
            color="dark",
            dark=True,
        ),

        dcc.Location(id='url', refresh=True),

        dhc.Br(),
        dhc.Br(),
        dhc.Div(id='content'),
    ])

    @app.callback(dash.dependencies.Output('content', 'children'),
                [dash.dependencies.Input('url', 'pathname')],
    )

    def display_page(pathname):

        ''' '''
        if not pathname:
            return ''
        if pathname == '/':
            return dash_index()
        method = pathname[1:].replace('-', '_')
        func = getattr(sys.modules[__name__], method, None)
        if func:
            return func()
        return 'Unknown link'

    @app.callback(
        Output('computed-table', 'data'),
        [Input('computed-table', 'data_timestamp')],
        [State('computed-table', 'data')])
    def update_columns(timestamp, rows):
        for row in rows:
            try:
                if row['Unidades Pendentes'] != 0:
                    row['UPH_BPI_vs_Head'] = float(row['UPH_BPI_vs_Perfil']) * float(row['Head_Disponível'])
                    row['ETA_Geral'] = float(row['Unidades Pendentes']) / float(row['UPH_BPI_vs_Head'])
                    row['Delta_Hora'] = float(row['Horas_Disp']) - float(row['ETA_Geral'])
                    row['Risco_Aging'] = float(row['Delta_Hora']) * float(row['UPH_BPI_vs_Head'])
                else:
                    row['UPH_BPI_vs_Head'] = "Completed"
                    row['ETA_Geral'] = "Completed"
                    row['Delta_Hora'] = "Completed"
                    row['Risco_Aging'] = "Completed"
                    row['UPH_BPI_vs_Perfil'] = "Completed"
                    row['Head_Disponível'] = "Completed"
                    row['Horas_Disp'] = "Completed"
            except:
                row['ETA_Geral'] = 'N/A'

        return rows

    @app.callback(
        Output('table-backlog', 'data'),
        [Input('table-backlog', 'data_timestamp')],
        [State('table-backlog', 'data')])
    def update_columns(timestamp, rows):
        for row in rows:
            try:
                if row['Unidades Pendentes'] != 0:
                    row['Delta Hora'] = float(row['Horas Disp']) - float(row['ETA'])
                    row['Risco Aging'] = float(row['Delta Hora']) * float(row['UPH'])
                else:
                    row['ETA'] = "Completed"

            except:

                row['ETA'] = row['ETA']
        return rows

    return app

def dash_fig1():

    #pandas code

    return  dhc.Div([
            dhc.Div([ dhc.H2(children= 'Nome Do Aqrquivo: ' + filename ),
            dhc.H2(children= "Date created: " + dataa),

            ],style={'textAlign': 'center',
                            'align-items': 'center',
                            'fontSize': 12,
                            'width': '100%',
                            'display': 'block',
                            'align-items': 'center',
                            'justify-content': 'center',
                            'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                            'padding': '30px 20px',
                            'marginBottom': 50} ),
            dhc.Div([
            dhc.Div([

                dhc.H2(children = "Perfil Por Canal",
                    style = {'textAlign' : 'center',}),

                dhc.Br(""),

            dash_table.DataTable(
                    id='table1',
                    columns=[{"name": i, "id": i} for i in dforderbypn.columns],
                    data=dforderbypn.to_dict('records'),
                    style_table={'textAlign': 'center'},
                    style_as_list_view=True,
                    style_cell={'padding': '5px','fontSize': 12, 'textAlign': 'center'},
                    style_header={
                        'backgroundColor': 'Gainsboro',
                        'fontWeight': 'bold',
                        'fontSize': 12},
                    export_format='xlsx',
                    export_headers='display',
                    merge_duplicate_headers=True

                ),

            ]

                    ,style={'textAlign': 'center',
                            'align-items': 'center',
                            'fontSize': 12,
                            'width': '100%',
                            'display': 'block',
                            'align-items': 'center',
                            'justify-content': 'center',
                            'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                            'padding': '30px 20px'}),

                    ],style={'textAlign': 'center' }),

            #Tabela De Perfil Por Canal/>

            #Tabela De Desempenho Por Canal<

            dhc.Div([
            dhc.Div([

                dhc.H2(children = "UPH / ETA  Médio Por Canal",
                    style = {'textAlign' : 'center',}),

                dhc.Br(""),

            dash_table.DataTable(
                    id='table1',
                    columns=[{"name": i, "id": i} for i in dfordertype.columns],
                    data=dfordertype.to_dict('records'),
                    style_table={'textAlign': 'center'},
                    style_as_list_view=True,
                    style_cell={'padding': '5px','fontSize': 12, 'textAlign': 'center'},
                    style_header={
                        'backgroundColor': 'Gainsboro',
                        'fontWeight': 'bold',
                        'fontSize': 12},
                    export_format='xlsx',
                    export_headers='display',
                    merge_duplicate_headers=True

                ),

                    ],style={'textAlign': 'center',
                            'align-items': 'center',
                            'fontSize': 12,
                            'width': '100%',
                            'display': 'block',
                            'align-items': 'center',
                            'justify-content': 'center',
                            'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                            'padding': '30px 20px'}),

                    ],style={'textAlign': 'center', 'marginTop': '15px'}),

            #Tabela De Desempenho Por Canal/>

            #Planejamento Estilizado<
            dhc.Div([
            dhc.Div([

                    dhc.H2(children = "Planner - Suporte",
                    style = {'textAlign' : 'center',}),

                dhc.Br(""),

                dash_table.DataTable(
                    id='computed-table',
                    columns=[{"name": i, "id": i} for i in dfplano.columns ],
                    data=dfordertype.to_dict('records'),
                    editable=True,
                    style_table={'textAlign': 'center'},
                    style_as_list_view=True,
                    style_cell={'padding': '5px','fontSize': 12, 'textAlign': 'center'},
                    style_header={
                        'backgroundColor': 'Gainsboro',
                        'fontWeight': 'bold',
                        'fontSize': 12},
                    export_format='xlsx',
                    export_headers='display',
                    merge_duplicate_headers=True

                ),

                    ],style={'textAlign': 'center',
                            'align-items': 'center',
                            'fontSize': 12,
                            'width': '100%',
                            'display': 'block',
                            'align-items': 'center',
                            'justify-content': 'center',
                            'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                            'padding': '30px 20px'}),

                    ],style={'textAlign': 'center',
                            'marginTop': '15px',
                            'display': 'block'}),
            #Planejamento Estilizado/>

            # Tabela Gerenciamento de Backlog<

            dhc.Div([
            dhc.Div([
                dhc.H2(children = "Status Por Cut Off",
                    style = {'textAlign' : 'center',}),

                dhc.Br(""),

                dash_table.DataTable(
                    id='table-backlog',
                    columns=[{"name": i, "id": i} for i in tabelaback.columns ],
                    data=tabelaback.to_dict('records'),
                    editable=True,
                    style_table={'textAlign': 'center'},
                    style_as_list_view=True,
                    style_cell={'padding': '5px','fontSize': 12, 'textAlign': 'center'},
                    style_header={
                        'backgroundColor': 'Gainsboro',
                        'fontWeight': 'bold',
                        'fontSize': 12},
                    export_format='xlsx',
                    export_headers='display',
                    merge_duplicate_headers=True

                ),

                    ],style={'textAlign': 'center',
                            'align-items': 'center',
                            'fontSize': 12,
                            'width': '100%',
                            'display': 'block',
                            'align-items': 'center',
                            'justify-content': 'center',
                            'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                            'padding': '30px 20px'}),

                    ],style={'textAlign': 'center',
                            'marginTop': '15px',
                            'display': 'block'}),

            # Tabela Gerenciamento de Backlog/>

            #Prod Hora Estaao<

            dhc.Div([
                dhc.Div([

                        dhc.H3(children = "Produção Por Hora (Estação)",
                        style = {'textAlign' : 'center',}),

                        dhc.Br(""),

                        dcc.Graph(id = 'GrapGo2', figure = figure3),
                        ],style={'textAlign': 'center',
                                'align-items': 'center',
                                'fontSize': 12,
                                'width': '100%',
                                'display': 'block',
                                'align-items': 'center',
                                'justify-content': 'center',
                                'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                                'padding': '30px 20px'}),

                        ],style={'textAlign': 'center',
                                'marginTop': '15px',
                                'display': 'block'}),

            #Prod Hora Estacao/>

            #Prod Hora Operador<

            dhc.Div([
                dhc.Div([

                        dhc.H3(children = "Produção Por Hora (Pessoa)",
                        style = {'textAlign' : 'center',}),

                        dhc.Br(""),

                        dcc.Graph( id = 'GrapGo3', figure = figure4),
                        ],style={'textAlign': 'center',
                                'align-items': 'center',
                                'fontSize': 12,
                                'width': '100%',
                                'display': 'block',
                                'align-items': 'center',
                                'justify-content': 'center',
                                'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                                'padding': '30px 20px'}),

                        ],style={'textAlign': 'center',
                                'marginTop': '15px',
                                'display': 'block'}),

            #Prod Hora Operador/>

            #Medias moveis<
            dhc.Div([
                dhc.Div([

                        dhc.H3(children = "Médias Mveis (10, 20 e 30 periodos)",
                        style = {'textAlign' : 'center',}),

                        dhc.Br(""),

                        dcc.Graph(id = 'GrapGo4',figure = figuremm),
                        ],style={'textAlign': 'center',
                                'align-items': 'center',
                                'fontSize': 12,
                                'width': '100%',
                                'display': 'block',
                                'align-items': 'center',
                                'justify-content': 'center',
                                'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                                'padding': '30px 20px'}),

                        ],style={'textAlign': 'center',
                                'marginTop': '15px',
                                'display': 'block'}),

            #Medias moveis/>

            #Media 10 intervalos<
            dhc.Div([
                dhc.Div([

                        dhc.H3(children = "Médias Móveis - 10 Intervalos por canal",
                        style = {'textAlign' : 'center',}),

                        dhc.Br(""),

                        dcc.Graph(id = 'GrapGo4',figure = figure7),
                        ],style={'textAlign': 'center',
                                'align-items': 'center',
                                'fontSize': 12,
                                'width': '100%',
                                'display': 'block',
                                'align-items': 'center',
                                'justify-content': 'center',
                                'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                                'padding': '30px 20px'}),

                        ],style={'textAlign': 'center',
                                'marginTop': '15px',
                                'display': 'block'}),

            #Media 10 intervalos/>

            #Unidades Recebidas Vs Processadas/hora<
            dhc.Div([
                dhc.Div([

                        dhc.H3(children = "Unidades Recebidas Vs Processadas por Hora (Drop)",
                        style = {'textAlign' : 'center',}),

                        dhc.Br(""),

                        dcc.Graph(id = 'GrapGo4',figure = figurefd),
                        ],style={'textAlign': 'center',
                                'align-items': 'center',
                                'fontSize': 12,
                                'width': '100%',
                                'display': 'block',
                                'align-items': 'center',
                                'justify-content': 'center',
                                'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                                'padding': '30px 20px'}),

                        ],style={'textAlign': 'center',
                                'marginTop': '15px',
                                'display': 'block'}),
            #Unidades Recebidas Vs Processadas/hora/>

            #UPPH Chart<
            dhc.Div([
                dhc.Div([

                        dhc.H3(children = "Unidade Produzidas Por Pessoa (Hora)",
                        style = {'textAlign' : 'center',}),

                        dhc.Br(""),

                        dcc.Graph(id = 'GrapGo4',figure = figure52)
                        ],style={'textAlign': 'center',
                                'align-items': 'center',
                                'fontSize': 12,
                                'width': '100%',
                                'display': 'block',
                                'align-items': 'center',
                                'justify-content': 'center',
                                'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                                'padding': '30px 20px'}),

                        ],style={'textAlign': 'center',
                                'marginTop': '15px',
                                'display': 'block'}),
            #UPPH chrta/>

            ], style={'marginBottom': 50,
                        'marginTop': 50,
                        'textAlign': 'center',
                        'padding': '30px 20px',
                        'align-items': 'center' }),

            ], style={'marginLeft': 50,
                        'marginRight': 50,
                        'display':'block',
                        'textAlign': 'center',
                        'align-items': 'center',
                        'padding': '30px 20px'})

def dash_fig2():

    return dhc.Div([
            dhc.Div([
                dhc.Div(children=[dhc.H1('Dash 2')

                                ],style={'textAlign': 'center',
                                'align-items': 'center',
                                'fontSize': 12,
                                'width': '100%',
                                'display': 'block',
                                'align-items': 'center',
                                'justify-content': 'center',
                                'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                                'padding': '30px 20px'}),

            dhc.Div([
            dhc.Div([

                    dhc.H2(children = "Planner - Suporte",
                    style = {'textAlign' : 'center',}),

                dhc.Br(""),

                dash_table.DataTable(
                    id='computed-table',
                    columns=[{"name": i, "id": i} for i in dfplano.columns ],
                    data=dfordertype.to_dict('records'),
                    editable=True,
                    style_table={'textAlign': 'center'},
                    style_as_list_view=True,
                    style_cell={'padding': '5px','fontSize': 12, 'textAlign': 'center'},
                    style_header={
                        'backgroundColor': 'Gainsboro',
                        'fontWeight': 'bold',
                        'fontSize': 12},
                    export_format='xlsx',
                    export_headers='display',
                    merge_duplicate_headers=True

                )

                    ],style={'textAlign': 'center',
                            'align-items': 'center',
                            'fontSize': 12,
                            'width': '100%',
                            'display': 'block',
                            'align-items': 'center',
                            'justify-content': 'center',
                            'boxShadow': '0 0 14px 0 rgba(0, 0, 0, 0.2)',
                            'padding': '30px 20px'}),

                    ],style={'textAlign': 'center',
                            'marginTop': '15px',
                            'display': 'block'}),

            ], style={'marginBottom': 50,
            'marginTop': 50,
            'textAlign': 'center',
            'padding': '30px 20px',
            'align-items': 'center' }),

            ], style={'marginLeft': 50,
                        'marginRight': 50,
                        'display':'block',
                        'textAlign': 'center',
                        'align-items': 'center',
                        'padding': '30px 20px'})

def dash_fig3():

    return 'a'

if __name__ == '__main__':
    app = _create_app()
    app.run_server(threaded=True, dev_tools_hot_reload=False)

Body:
In a multipage application, you can put all your callbacks in a single py file say callbacks.py. If you have split your multipage app as suggested in the documentation of dash, and have an app.py, index.py, you need to have in your callback.py

from app import app

Then in the index.py you need to have

import callback

Try to separate out the code this way and ensure to have the import callback in index.py and it should work.


问:
Why does it return 1?
Goal of program: return 1 if two arrays are identical. if not return 0.
What I did:

```<code>#include <stdio.h>

int identical ( int arr1[], int arr2[], unsigned int len )
{
    for (int i = 0; i < len; i++){
        if (len == 0){
            return 1;
        } else if (arr1[i] != arr2[i]) {
            return 0;
        } else {
            return 1;
        }
    }

}

int main ()
{
    int arr1[3] = {10,15,20};
    int arr2[3] = {10,15,21};
    printf("%d\n", identical(arr1, arr2, 3));

    return 0;
}
</code>```

It always returns 1 and I cannot find the reason why.
What's wrong?

答:
```<code>int identical ( int arr1[], int arr2[], unsigned int len )
{
    for (int i = 0; i < len; i++){
     if (arr1[i] != arr2[i]) {
        return 0;
     }
   }
   return 1;
}
</code>```

This only checks if 2 arrays have 3(len=3) similar values in a row.

Title: Why does it return 1?

Body:
Goal of program: return 1 if two arrays are identical. if not return 0.
What I did:

#include <stdio.h>

int identical ( int arr1[], int arr2[], unsigned int len )
{
    for (int i = 0; i < len; i++){
        if (len == 0){
            return 1;
        } else if (arr1[i] != arr2[i]) {
            return 0;
        } else {
            return 1;
        }
    }

}

int main ()
{
    int arr1[3] = {10,15,20};
    int arr2[3] = {10,15,21};
    printf("%d\n", identical(arr1, arr2, 3));

    return 0;
}

It always returns 1 and I cannot find the reason why.
What's wrong?

Body:
int identical ( int arr1[], int arr2[], unsigned int len )
{
    for (int i = 0; i < len; i++){
     if (arr1[i] != arr2[i]) {
        return 0;
     }
   }
   return 1;
}

This only checks if 2 arrays have 3(len=3) similar values in a row.


问:
Mysql support this kind of "with" sql?
In postgres, I use this kind of sql often.

```<code>with list (id, name) as (
    values
    (1004007, 'aaa'),
    (1002147, 'bbb'),
    (1004493, 'ccc'),
    (1007978, 'ddd'),
    (1005218, 'eee'),
    (1005507, 'fff')
)
select * from list;
</code>```

Dose Mysql support that kind of sql ?

答:
Later 8.0 in mysql , we can use it like bellow</p>

```<code>with
list (a, b, c) as (VALUES
ROW('1',-2,3),
ROW('5',7,9),
ROW('4',6,8)
)
select * from list;
</code>```

Title: Mysql support this kind of "with" sql?

Body:
In postgres, I use this kind of sql often.

with list (id, name) as (
    values
    (1004007, 'aaa'),
    (1002147, 'bbb'),
    (1004493, 'ccc'),
    (1007978, 'ddd'),
    (1005218, 'eee'),
    (1005507, 'fff')
)
select * from list;

Dose Mysql support that kind of sql ?

Body:
Later 8.0 in mysql , we can use it like bellow

with
list (a, b, c) as (VALUES
ROW('1',-2,3),
ROW('5',7,9),
ROW('4',6,8)
)
select * from list;


问:
How to set slate value based on the plain string value(serialized)
I am building a rich text editor with slate js on React and I need to parse URL from the content(for example: www.website.me should be transformed to www.website.me).

I have already implemented the function to parse URL from plain text and then wrap the content inside the correct  tag.

However, the problem is that I need to display the parsed value as soon as the user is typing on the editor(on onChange event). Here is what I have :

onChange = ({ value }) => {
    const { isFocused } = value.selection
    if (isFocused !== this.state.isFocused) {
      this.setState({ isFocused })
    }

    const string = this.state.html.serialize(value)
    const linkifiedString = linkifyHtml(string) || ''
    if (value.document !== this.state.value.document) {
      const { onChange } = this.props
      onChange && onChange(linkifiedString)
    }

    // this won't work and will call the onChange method infinitely
    this.setState({ value: this.state.html.deserialize(linkifiedString) })
}
```

Thanks for your help.

答: Finally, I have found the solution, you have to create your own slate plugin or use this one: https://github.com/enzoferey/slate-instant-replace</p>

Body:
I am building a rich text editor with slate js on React and I need to parse URL from the content(for example: www.website.me should be transformed to www.website.me).

I have already implemented the function to parse URL from plain text and then wrap the content inside the correct  tag.

However, the problem is that I need to display the parsed value as soon as the user is typing on the editor(on onChange event). Here is what I have :

onChange = ({ value }) => {
    const { isFocused } = value.selection
    if (isFocused !== this.state.isFocused) {
      this.setState({ isFocused })
    }

    const string = this.state.html.serialize(value)
    const linkifiedString = linkifyHtml(string) || ''
    if (value.document !== this.state.value.document) {
      const { onChange } = this.props
      onChange && onChange(linkifiedString)
    }

    // this won't work and will call the onChange method infinitely
    this.setState({ value: this.state.html.deserialize(linkifiedString) })
}

Thanks for your help.


问:
The authenticity of host 'gitlab.com (35.231.145.151)' can't be established
Why do I get this message?

The authenticity of host 'gitlab.com (35.231.145.151)' can't be established.

I can't find that IP on https://docs.gitlab.com/ee/user/gitlab_com/

答:
I can't find that IP

The page you mention only includes the IP for GItLab pages.

It does include the SSH host keys fingerprints though.

So do type 'yes', to accept the authenticity of gitlab.com, then fo to your ~/.ssh/known_hosts file, and do check it includes one of the SSH host keys fingerprints listed in the documentation.


问:
inserting the records in the c# form
I am working with C#.

I want to insert record in the table. I m using the MS Access database. I have the following code:

```<code>private void button1_Click(object sender, EventArgs e)
{
    con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;
        Data Source=C:\\Documents and Settings\\mayur patil\\
                       My Documents\\Dairy_db\\tblCompany.mdb";
    con.Open();
    OleDbCommand cmd = new OleDbCommand(
       "INSERT INTO tblCompany (CoCode,CoName_mar)
       VALUES("+textBox1.Text+","+textBox4.Text+")", con);
    cmd.ExecuteNonQuery();
    con.Close();

    this.Hide();
    Form1 f = new Form1();
    f.ShowDialog();
}
</code>```

I am not getting the answer..

答: can you please give providerName="System.Data.OleDb" in the connection string and check whether you can access the db with that connection string</p>

ContentLicense: CC BY-SA 3.0

Title: inserting the records in the c# form

Body:
I am working with C#.

I want to insert record in the table. I m using the MS Access database. I have the following code:

private void button1_Click(object sender, EventArgs e)
{
    con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;
        Data Source=C:\\Documents and Settings\\mayur patil\\
                       My Documents\\Dairy_db\\tblCompany.mdb";
    con.Open();
    OleDbCommand cmd = new OleDbCommand(
       "INSERT INTO tblCompany (CoCode,CoName_mar)
       VALUES("+textBox1.Text+","+textBox4.Text+")", con);
    cmd.ExecuteNonQuery();
    con.Close();

    this.Hide();
    Form1 f = new Form1();
    f.ShowDialog();
}

I am not getting the answer..


问:
Can't select dynamically generated HTML-elements (generated with Handlebars Block helpers)
I am working on a Flask-based chat app and am generating the below HTML using a Handlebars JavaScript-template. In my JavaScript code I would like to select the -Tag ('#delete-message') element and add an onclick functionality to it. The
s that contain the elements are chat messages, so they are generated dynamically. Now when someone clicks "Delete", I want them to delete the message. But no matter what I try, none of the below options even select (return an array/collection of) my "Delete"s:

I tried:

```<code>const dels = document.getElementById('chat_log').getElementsByTagName('a');

const dels = document.getElementsByClassName('delete_message');
</code>```

The following two don't work because I understand querySelectorAll returns a static list and my content is dynamic, but I tried:

```<code>const dels = document.querySelectorAll('.delete_message');

const dels = document.querySelectorAll('#delete_message');
</code>```

HTML snippet is:

```<code>    <script id="chat_log" type="text/template">
      {% raw -%}
        {{#each values}}
        <div class=container>
            <b> {{this.sender}}: </b>
            <p>{{this.text}}</p>
            <p hidden>{{this.id}}</p>
            <span class="time-left">{{this.time}}</span>
            <span class="right-side"><a class="delete_message" id="delete_message" href="">Delete</a></span>
        </div>
        {{/each}}
      {%- endraw %}
    </script>
</code>```

I then want to add the functionality using .forEach, but the array/collection/nodes returned always have a length of 0 (i.e. no elements), no matter how many chat messages there are. Can someone help me out here?

答:
Event delegation to the rescue.

With elements that are added after page load you either need to add the event listener when the object is created, or better still use event delegation. With event delegation to add a listener to a common parent element and add an event listener to that. You then can use event properties to perform the appropriate task.

For the example below I've replaced your handlebar template with a template literal, just because it's easier for a quick example. I've also added a common element which will contain the chat.

const chat = document.getElementById("chat");
//Event delegation
chat.addEventListener("click", function(event) {
  event.preventDefault();
  //Do stuff when delete button clicked
  if (event.target.classList.contains("delete_message")) {
    alert("about to to delete item id: " + event.target.href);
  }
});

const data = [{
    sender: "Bill",
    text: "'sup?",
    id: 1,
    time: "12:11"
  },
  {
    sender: "Ben",
    text: "Hey! How you doin'?",
    id: 2,
    time: "12:12"
  },
  {
    sender: "Bill",
    text: "'Great! And you?",
    id: 1,
    time: "12:13"
  }
];

//DONT ADD CONTENT THIS WAY IT's FOR DEMO ONLY
data.forEach(function(send) {
  let template = `

         ${send.sender}:

${send.text}

${send.id}

        ${send.time}
        Delete

`;
  chat.innerHTML += template;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="chat"></div></code>```

Body:
I am working on a Flask-based chat app and am generating the below HTML using a Handlebars JavaScript-template. In my JavaScript code I would like to select the -Tag ('#delete-message') element and add an onclick functionality to it. The
s that contain the elements are chat messages, so they are generated dynamically. Now when someone clicks "Delete", I want them to delete the message. But no matter what I try, none of the below options even select (return an array/collection of) my "Delete"s:

I tried:

const dels = document.getElementById('chat_log').getElementsByTagName('a');

const dels = document.getElementsByClassName('delete_message');

The following two don't work because I understand querySelectorAll returns a static list and my content is dynamic, but I tried:

const dels = document.querySelectorAll('.delete_message');

const dels = document.querySelectorAll('#delete_message');

HTML snippet is:

I then want to add the functionality using .forEach, but the array/collection/nodes returned always have a length of 0 (i.e. no elements), no matter how many chat messages there are. Can someone help me out here?

Body:
Event delegation to the rescue.

With elements that are added after page load you either need to add the event listener when the object is created, or better still use event delegation. With event delegation to add a listener to a common parent element and add an event listener to that. You then can use event properties to perform the appropriate task.

For the example below I've replaced your handlebar template with a template literal, just because it's easier for a quick example. I've also added a common element which will contain the chat.

const chat = document.getElementById("chat");
//Event delegation
chat.addEventListener("click", function(event) {
  event.preventDefault();
  //Do stuff when delete button clicked
  if (event.target.classList.contains("delete_message")) {
    alert("about to to delete item id: " + event.target.href);
  }
});

const data = [{
    sender: "Bill",
    text: "'sup?",
    id: 1,
    time: "12:11"
  },
  {
    sender: "Ben",
    text: "Hey! How you doin'?",
    id: 2,
    time: "12:12"
  },
  {
    sender: "Bill",
    text: "'Great! And you?",
    id: 1,
    time: "12:13"
  }
];

//DONT ADD CONTENT THIS WAY IT's FOR DEMO ONLY
data.forEach(function(send) {
  let template = `
    <div class=container>
        <b> ${send.sender}: </b>
        <p>${send.text}</p>
        <p hidden>${send.id}</p>
        <span class="time-left">${send.time}</span>
        <span class="right-side"><a class="delete_message" id="delete_message_${send.id}" href="#${send.id}">Delete</a></span>
    </div>`;
  chat.innerHTML += template;
});

<div id="chat"></div>


问:
How do i call a dictionary value from user input
I am new to programming, this is also my first post.

The problem is;

Ask the user how their weight is from a 1 to 4 scale.

```<code>1 = 0.5, 2 = 1.2, 3 = 1.7, 4 = 2.4.
</code>```

I set up my dictionary like this.

So when the user inputs 2

When I execute print, it prints 2 and not 1.2.
how do I update the new value?

答:
If you don't want to store the keys in your dictionary in string type, you will have to convert the user input (string) to integer.

Also, for printing the desired output you need to access the dictionary for value with a key. You can do that simply by : my_dict[key] . This will give you the value for key.

Try this :

```<code>weight_dict = {1 : 0.5, 2 : 1.2, 3 : 1.7, 4 : 2.4}

input = input("enter a weight: ")

input_weight = int(input.strip())

print("Weight on scale is : {0}".format(weight_dict[input_weight]))
</code>```

Body:
I am new to programming, this is also my first post.

The problem is;

Ask the user how their weight is from a 1 to 4 scale.

1 = 0.5, 2 = 1.2, 3 = 1.7, 4 = 2.4.

I set up my dictionary like this.

So when the user inputs 2

When I execute print, it prints 2 and not 1.2.
how do I update the new value?

Body:
If you don't want to store the keys in your dictionary in string type, you will have to convert the user input (string) to integer.

Also, for printing the desired output you need to access the dictionary for value with a key. You can do that simply by : my_dict[key] . This will give you the value for key.

Try this :

weight_dict = {1 : 0.5, 2 : 1.2, 3 : 1.7, 4 : 2.4}

input = input("enter a weight: ")

input_weight = int(input.strip())

print("Weight on scale is : {0}".format(weight_dict[input_weight]))


问:
What is runtime in context of Python? What does it consist of?
In context to this question What is “runtime”? (https://stackoverflow.com/questions/3900549/what-is-runtime/3900561)

I am trying to understand what would a python runtime be made of. My guess is:

The python process that contains all runtime variables.

The GIL

The underlying interpreter code (CPython etc.).

Now if this is right, can we say that multiprocessing in python creates multiple runtimes and a python process is something we can directly relate to the runtime? (I think this is the right option)

Or, every python thread with its own stack which works on the same GIL and memory space as the parent process can be called as having a separate runtime?

Or, doesn't matter how many threads or processes are running, it will all come under a single runtime?

Simply put, what is the definition of runtime in the context of Python?

PS: I understand the difference between threads and processes. GIL: I understand the impacts but I do not grok it.

答:
You are talking about two different (yet similar) concepts in computer science; multiprocess, and multithreading. Here is some compilation of questions/answers that might be useful:

Multiprocessing -- Wikipedia

Multiprocessing is the use of two or more central processing units (CPUs) within a single computer system.The term also refers to the ability of a system to support more than one processor or the ability to allocate tasks between them.

Multithreading -- Wikipedia

In computer architecture, multithreading is the ability of a central processing unit (CPU) (or a single core in a multi-core processor) to provide multiple threads of execution concurrently, supported by the operating system. This approach differs from multiprocessing. In a multithreaded application, the threads share the resources of a single or multiple cores, which include the computing units, the CPU caches, and the translation lookaside buffer (TLB).

What is the difference between a process and a thread? -- StackOverflow

Process

Each process provides the resources needed to execute a program. A process has a virtual address space, executable code, open handles to system objects, a security context, a unique process identifier, environment variables, a priority class, minimum and maximum working set sizes, and at least one thread of execution. Each process is started with a single thread, often called the primary thread, but can create additional threads from any of its threads.

Thread

A thread is an entity within a process that can be scheduled for execution. All threads of a process share its virtual address space and system resources. In addition, each thread maintains exception handlers, a scheduling priority, thread local storage, a unique thread identifier, and a set of structures the system will use to save the thread context until it is scheduled. The thread context includes the thread's set of machine registers, the kernel stack, a thread environment block, and a user stack in the address space of the thread's process. Threads can also have their own security context, which can be used for impersonating clients.

Meaning of “Runtime Environment” and of “Software framework”? -- StackOverflow

A runtime environment basically is a virtual machine that runs on top of a machine - provides machine abstraction. It is generally lower level than a library. A framework can contain a runtime environment, but is generally tied to a library.

Runtime System -- Wikipedia

In computer programming, a runtime system, also called runtime environment, primarily implements portions of an execution model. Most languages have some form of runtime system that provides an environment in which programs run. This environment may address a number of issues including the layout of application memory, how the program accesses variables, mechanisms for passing parameters between procedures, interfacing with the operating system, and otherwise. Typically the runtime system will have some responsibility for setting up and managing the stack and heap, and may include features such as garbage collection, threads or other dynamic features built into the language.

global interpreter lock -- Python Docs

The mechanism used by the CPython interpreter to assure that only one thread executes Python bytecode at a time. This simplifies the CPython implementation by making the object model (including critical built-in types such as dict) implicitly safe against concurrent access. Locking the entire interpreter makes it easier for the interpreter to be multi-threaded, at the expense of much of the parallelism afforded by multi-processor machines.

However, some extension modules, either standard or third-party, are designed so as to release the GIL when doing computationally-intensive tasks such as compression or hashing. Also, the GIL is always released when doing I/O.

Past efforts to create a “free-threaded” interpreter (one which locks shared data at a much finer granularity) have not been successful because performance suffered in the common single-processor case. It is believed that overcoming this performance issue would make the implementation much more complicated and therefore costlier to maintain.

What is the Python Global Interpreter Lock (GIL)?
-- Real Python

Useful source for more info on GIL.

Does python os.fork uses the same python interpreter? -- StackOverflow

Whenever you fork, the entire Python process is duplicated in memory (including the Python interpreter, your code and any libraries, current stack etc.) to create a second process - one reason why forking a process is much more expensive than creating a thread.

This creates a new copy of the python interpreter.

One advantage of having two python interpreters running is that you now have two GIL's (Global Interpreter Locks), and therefore can have true multi-processing on a multi-core system.

Threads in one process share the same GIL, meaning only one runs at a given moment, giving only the illusion of parallelism.

Memory Management -- Python Docs

Memory management in Python involves a private heap containing all Python objects and data structures. The management of this private heap is ensured internally by the Python memory manager. The Python memory manager has different components which deal with various dynamic storage management aspects, like sharing, segmentation, preallocation or caching.

When you spawn a thread via the threading library, you are effectively spawning jobs inside a single Python runtime. This runtime ensures the threads have a shared memory and manages the running sequence of these threads via the global interpreter lock:

Understanding the Python GIL -- dabeaz

When you spawn a process via the multiprocessing library, you are spawning a new process that contains a new Python interpreter (a new runtime) that runs the designated code. If you want to share memory you have to use multiprocessing.shared_memory:

multiprocessing.shared_memory -- Python Docs

This module provides a class, SharedMemory, for the allocation and management of shared memory to be accessed by one or more processes on a multicore or symmetric multiprocessor (SMP) machine. To assist with the life-cycle management of shared memory especially across distinct processes, a BaseManager subclass, SharedMemoryManager, is also provided in the multiprocessing.managers module.

Can we say that multiprocessing in python creates multiple runtimes and a python process is something we can directly relate to the runtime?

Yes. Different GIL, different memory space, different runtime.

Every python thread with its own stack which works on the same GIL and memory space as the parent process can be called as having a separate runtime?

Depends what you mean by "stack". Same GIL, shared memory space, same runtime.

Doesn't matter how many threads and processes are running, it will all come under a single runtime?

Depends if multithreading/multiprocess.

Simply put, what is the definition of runtime in the context of Python?

The runtime environment is literally python.exe or /usr/bin/python. It's the Python executable that will interpret your Python code by transforming it into CPU-readable bytecode. When you multithread, you only have one python running. When you multiprocess you have multiple pythons running.

I hope that a core dev can come in and speak more to this in greater detail. For now the above is simply just a compilation of sources for you to start understanding/seeing the bigger picture.


问:
Simulation of android webview
I'm new to android.....
I have to automate some user actions in webview.
Robotium is not supporting user action in webview..... as far as i know...
Can anyone please shed some light on...</p>

答:
I'm looking for the same thing but didn't find anything yet.

AFAIK, selenium allows you to test web-based apps in Adnroid but don't think it can automate native apps. Check out this lecture

Title: Simulation of android webview


答:
Welcome to SO, Daniel!

If I understand correctly, you have 1, 2, 3, and 4 as keys corresponding to 0.5, 1.2, 1.7, and 2.4, respectively.

Since input is accepted as a string, we must convert it to integer, like so:

```<code>weights_dictionary = {1: 0.5, 2: 1.2, 3: 1.7, 4: 2.4}

user_weight = int(input("Enter weight from 1 to 4:"))

print(weights_dictionary[user_weight])
</code>```

Title: How do i call a dictionary value from user input

Body:
Welcome to SO, Daniel!

If I understand correctly, you have 1, 2, 3, and 4 as keys corresponding to 0.5, 1.2, 1.7, and 2.4, respectively.

Since input is accepted as a string, we must convert it to integer, like so:

weights_dictionary = {1: 0.5, 2: 1.2, 3: 1.7, 4: 2.4}

user_weight = int(input("Enter weight from 1 to 4:"))

print(weights_dictionary[user_weight])


问:
How can I split a string and get just key part with regexp?
I have a string like <code>"A < -5.9 AND B >= 6 OR (C < 3)"</code> I have to get keys part.(A,B,C). So I thought I should split first AND and OR then I should get key part? Could you help me? I wrote just A,B,C but in my real example A can be any string. The important thing is that is value on the right side of
<,>,<=,>=  </p>

答:
If it's just a matter of capturing variable names that appear to the left of a comparison operator:

const s = "A < -5.9 AND B >= 6 OR (C < 3)";

const variables = s.match(/\w+(?=\s*[<>])/g);

console.log(variables);```

Body:
I have a string like "A < -5.9 AND B >= 6 OR (C < 3)" I have to get keys part.(A,B,C). So I thought I should split first AND and OR then I should get key part? Could you help me? I wrote just A,B,C but in my real example A can be any string. The important thing is that is value on the right side of
<,>,<=,>=


问:
Session Id + change password, best practice
on our web-store (Java, Hybris) a user has an opportunity to change a password.
According to the best vulnerability practice should we change SessionId or leave the old one or maybe create a new Session? What is the best solution?</p>

答:
A User want to reset the password when

Suspects account compromise

Routinely changes the password thinking of security practice or force by the system policy

I would suggest to logout all the current user sessions on the password reset. Also, it's a good idea to implement a mechanism to confirm the user's identity like secure code SMS/email, reset password link over email, etc. Which distinguishes between the legitimate user and an attacker.

Yes, it may not be a good user experience.

Read a more detailed answer.


问:
Background color to Navbar links
I have already defined my Navbar and it works perfectly fine, except I want to give a full page background to the Navbar links as well. Currently when I want to open the page on a mobile device, the links background doesn't cover the whole page horizontally, but instead it looks like a highlighted line. For more detail see the screenshots. I would appreciate if someone can help me with this. Thanks!

  <button class="navbar-toggler ml-auto custom-toggler" type="button" data-toggle="collapse" data-target="#collapsingNavbar4">

      </button>

         Portfolio

        About

        Contact

        Resume

        &nbsp&nbsp&nbsp

        &nbsp&nbsp&nbsp

        &nbsp&nbsp&nbsp

[![enter image description here][1]][1]
```

答:
Try adding the below style:

```<code>.navbar.scrolled .navbar-collapse{
    background: #116980;
    margin: -15px;
    padding: 15px;
    z-index: -1;
}
</code>```

The above lines would assign background color to .navbar-collapse when scrolled down. However since .navbar-collapse contains margin, the above code would remove the margin and change it to padding while move .navbar-collapse to back to prevent it from covering .navbar-brand and .navbar-toggler.

Title: Background color to Navbar links

Body:
Try adding the below style:

.navbar.scrolled .navbar-collapse{
    background: #116980;
    margin: -15px;
    padding: 15px;
    z-index: -1;
}

The above lines would assign background color to .navbar-collapse when scrolled down. However since .navbar-collapse contains margin, the above code would remove the margin and change it to padding while move .navbar-collapse to back to prevent it from covering .navbar-brand and .navbar-toggler.


问:
Apache Tomcat - HTTP Status 404 - Not Found
I am facing the exact problem stated Tomcat 404 error and tried all the suggestions but nothing has helped me fix this. Apache Tomcat 9.0 and Eclipse Oxygen is what I'm currently using now and following a tutorial from YouTube.

答:
I'd like to add one suggestion here if Tomcat is on Linux machine,

I have faced same issue. In my case Tomcat is deployed to a Linux system and i am not Admin User. When i am starting Tomcat with my account it was giving same error mentioned above. So once i started tomcat with admin account it stated working.


问:
What is the difference between iPhone Developer Standard Program (99 USD) and Enterprise Program (299 USD)?
Can someone point out what is the difference?

And what for do we actually pay so much money, when supporting the iPhone with our hard work?

Is it right that I have to have the Enterprise Membership (299 USD), when I want to sell Apps for money? Or can I also sell Apps when I "only" have the cheaper Standard Membership (99 USD)?

Is there a fee every time I want to upload a new app to the App Store? Where is the hook in the Standard Membership?

答:
The Enterprise Membership is only for enterprises - no app store distribution, but you can distribute your programs within your enterprise (ad-hoc). With the Standard one, you can put your apps on the app store but can only give out 100 copies of your program using ad-hoc.

There is no fee for submitting apps to the App Store once you have a Standard membership.

OwnerDisplayName: Unknown Individual

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Isaac Waller

LastEditorDisplayName: Isaac Waller


问:
C++ including a ".h" file, function duplication confusion
I'm currently writing a program, and couldn't figure out why I got an error (note: I already fixed it, I'm curious about WHY the error was there and what this implies about including .h files).

Basically, my program was structured as follows:

The current file I'm working with, I'll call Current.cc (which is an implementation of Current.h).

Current.cc included a header file, named CalledByCurrent.h (which has an associated implementation called CalledByCurrent.cc).  CalledByCurrent.h contains a class definition.

There was a non-class function defined in CalledByCurrent.cc called thisFunction().  thisFunction() was not declared in CalledByCurrent.h since it was not actually a member function of the class (just a little helper function).  In Current.cc, I needed to use this function, so I just redefined thisFunction() at the top of Current.cc.  However, when I did this, I got an error saying that the function was duplicated.  Why is this, when myFunction() wasn't even declared in CalledByCurrent.h?

Thus, I just removed the function from Current.cc, now assuming that Current.cc had access to thisFunction() from CalledByCurrent.cc.  However, when I did this, I found that Current.cc did not know what function I was talking about.  What the heck?  I then copied the function definition for thisFunction() to the top of my CalledByCurrent.h file and this resolved the problem.  Could you help me understand this behavior?  Particularly, why would it think there was a duplicate, yet it didn't know how to use the original?

p.s - I apologize for how confusing this post is.  Please let me know if there's anything I can clear up.

答: The header file inclusion mechanism should be tolerant  to duplicate header file inclusions.</p>


问:
How can I use number as key?
I have ids like as numbers 374,242,435

I want to use this as key of hash for the object.

```<code>var json = [];
ids = [374,242,435];
for(let i in ids) {
    var id = ids[i];
    json[id] = []; // it makes 372 array!!!
    json[id]['name'] = name;
    json[id]['color'] = color;
}
</code>```

Can I make object using number as key????

This is my silly mistake

I just changed var json = []; -> var json = {}; it works.

and thank you for your comments.

答:
```<code>var json = {};

var ids = [374,242,435];

for(const i of ids) {
    json[i] : {
     name : 'name',
     color : '#colorcode'
    }
}
</code>```

Title: How can I use number as key?

Body:
I have ids like as numbers 374,242,435

I want to use this as key of hash for the object.

var json = [];
ids = [374,242,435];
for(let i in ids) {
    var id = ids[i];
    json[id] = []; // it makes 372 array!!!
    json[id]['name'] = name;
    json[id]['color'] = color;
}

Can I make object using number as key????

This is my silly mistake

I just changed var json = []; -> var json = {}; it works.

and thank you for your comments.


问:
Can you mutate the properties of a factory function without using this?
I've been reading about the benefits of using factory functions over classes, however, I'm having trouble getting them to work in a similar manner.

For instance, with classes:

```<code>class NumberManager {
    constructor(numbers){
        this.numbers = numbers;
    }

    removeNumber(input){
        this.numbers = this.numbers.filter( number => number != input )
    }
}

n = new NumberManager([1, 2])
n.numbers // --> [1, 2]
n.removeNumber(2)
n.numbers // --> [1]
</code>```

However, with a factory function:

```<code>const NumberFactory = (numbers) => {
  const removeNumber = (input) => {
    numbers = numbers.filter( number => number != input )
  }

  return {
    numbers,
    removeNumber
  }
}

n = NumberFactory([1, 2])
n.numbers // --> [1, 2]
n.removeNumber(2)
n.numbers // --> [1, 2]
</code>```

Is it possible to have a similar level of freedom that classes have (e.g. easily mutating properties), without having to use things like this (which can break across execution contexts) and new (which can break if having to convert a class to a factory)?

答:
Besides @CertainPerformance's solution, you can expose a getter (and maybe a setter as well) for the numbers varible:

const NumberFactory = (numbers) => {
  const removeNumber = (input) => {
    numbers = numbers.filter( number => number != input );
  };
  return {
    get numbers(){ return numbers },
    // And if you want to allow external replacement of numbers:
    // set numbers(value){ numbers = value },
    removeNumber
  };
}

const n = NumberFactory([1, 2]);
console.log(n.numbers); // --> [1, 2]
n.removeNumber(2);
console.log(n.numbers); // --> [1]```
</div>
</div>
</p>

<p>Or just mutate the array (using mutator methods instead of <code>filter</code>):</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const NumberFactory = (numbers) => {
  const removeNumber = (input) => {
    for(let i = 0; i < numbers.length; ){ // <-- Note that we don't increment i here
      if(numbers[i] != input) // <-- Condition goes here
        i++
      else
        numbers.splice(i, 1)
    }
  };
  return {
    numbers,
    removeNumber
  };
}

const n = NumberFactory([1, 2]);
console.log(n.numbers); // --> [1, 2]
n.removeNumber(2);
console.log(n.numbers); // --> [1]</code>```

Body:
I've been reading about the benefits of using factory functions over classes, however, I'm having trouble getting them to work in a similar manner.

For instance, with classes:

class NumberManager {
    constructor(numbers){
        this.numbers = numbers;
    }

    removeNumber(input){
        this.numbers = this.numbers.filter( number => number != input )
    }
}

n = new NumberManager([1, 2])
n.numbers // --> [1, 2]
n.removeNumber(2)
n.numbers // --> [1]

However, with a factory function:

const NumberFactory = (numbers) => {
  const removeNumber = (input) => {
    numbers = numbers.filter( number => number != input )
  }

  return {
    numbers,
    removeNumber
  }
}

n = NumberFactory([1, 2])
n.numbers // --> [1, 2]
n.removeNumber(2)
n.numbers // --> [1, 2]

Is it possible to have a similar level of freedom that classes have (e.g. easily mutating properties), without having to use things like this (which can break across execution contexts) and new (which can break if having to convert a class to a factory)?

Body:
Besides @CertainPerformance's solution, you can expose a getter (and maybe a setter as well) for the numbers varible:

const NumberFactory = (numbers) => {
  const removeNumber = (input) => {
    numbers = numbers.filter( number => number != input );
  };
  return {
    get numbers(){ return numbers },
    // And if you want to allow external replacement of numbers:
    // set numbers(value){ numbers = value },
    removeNumber
  };
}

const n = NumberFactory([1, 2]);
console.log(n.numbers); // --> [1, 2]
n.removeNumber(2);
console.log(n.numbers); // --> [1]

Or just mutate the array (using mutator methods instead of filter):

const NumberFactory = (numbers) => {
  const removeNumber = (input) => {
    for(let i = 0; i < numbers.length; ){ // <-- Note that we don't increment i here
      if(numbers[i] != input) // <-- Condition goes here
        i++
      else
        numbers.splice(i, 1)
    }
  };
  return {
    numbers,
    removeNumber
  };
}

const n = NumberFactory([1, 2]);
console.log(n.numbers); // --> [1, 2]
n.removeNumber(2);
console.log(n.numbers); // --> [1]


问:
SmartGit, unable to push, "remote: HTTP Basic: Access denied"

remote: HTTP Basic: Access denied

remote: You must use a personal access token with 'read_repository' or 'write_repository' scope for Git over HTTP.

remote: You can generate one at https://gitlab.com/profile/personal_access_tokens

I've created Personal Access Tokens with all available scopes included and placed it in Edit -> Preferences -> Hosting Providers for the GitLab account, but I still can't push. The GitLab account has 2FA and I also have this installed if it matters.

Windows 10 x64.

答:
Since you have a credential helper installed, check if it is active:

```<code>cd C:\path\to\repo
git config credential.helper
</code>```

If it returns "manager", open your Windows Credentials Manager and check if credentials are already stored for gitlab.com.

If so, delete it, then push again: Git should ask for your credentials. Do enter your PAT (Personal Access Token) as password.

Body:
Since you have a credential helper installed, check if it is active:

cd C:\path\to\repo
git config credential.helper

If it returns "manager", open your Windows Credentials Manager and check if credentials are already stored for gitlab.com.

If so, delete it, then push again: Git should ask for your credentials. Do enter your PAT (Personal Access Token) as password.