问:
Why does ScriptManager.RegisterStartupScript skip a single script but continues with adjoining scripts
Good day,

This is actually my first question on the site, I actually made an account for this problem alone.
I struggling a lot with this and can't seem to figure out what the cause is.

I'm playing around with dynamically creating html controls and populating them with data from a SQL Database.

As a test application I have been using the concept of a video store rental shop that has an admin site to modify (Insert, Update, Delete) movies, receive reports and statistics about the movies and so on.

So as a control to display the movies I use a html table with my own custom style sheet, with the Movie's detail in a header row, and when you click on the header row the table expands to show the stock of that movie (As a movie can have multiple physical "discs" within the shop that have different stock codes and statuses).

Thus the reason I'm trying to create the table dynamically as the number of movies and the number of "discs" these movies can have can change. I have created a working "Proof of Concept", but a problem occurs on the eleventh movie where the header row (Showing Main Title, Sub Title, Age Restriction, Main Category, Secondary Category, and Rental Amount) isn't created but the data that is shown when you click on the header and it expands is created, but is appended to the tenth movie's expanded data.

The scripts are appended using ScriptManager.RegisterStartupScript. When I check the compiled code in a browser (Chrome's Inspect Tool), the scripts in the Manager are all appended except for the the eleventh movie's header and first data row.

I used breakpoints to check the codebehind (OnPage_Load Event) and the script runs and it isn't a problem with the ScriptManager.RegisterStartupScript's key parameter, as it is created with a loop and I made sure that the controls created dynamically have unique ID tags to call on in the script itself and for later.

I've been stuck on this problem the whole day and can't figure out why all the rows and there expanded data rows are created and works except for the last one and its first data row.

Why is this happening? Is it a problem in the script? (But why are all the other rows created without a problem?)

So far I believe it's a problem in the codebehind of program but still can't figure out why the problem happens.

Here is the C# from the codebehind

```<code>namespace WebApplication4
{
    public partial class _Default : Page
    {
        private static String connectionString = @"Data Source=BOARDROOM-PC\SQLEXPRESS;Initial Catalog=Express_Video;Integrated Security=True";
        private static SqlConnection connection;
        private SqlDataAdapter da1 = null;
        private SqlDataAdapter da2 = null;
        private SqlCommand command1 = null;
        private SqlCommand command2 = null;
        private DataSet ds1 = null;
        private DataSet ds2 = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            connection = new SqlConnection(connectionString);
            connection.Open();

            da1 = new SqlDataAdapter();
            da2 = new SqlDataAdapter();

            command1 = new SqlCommand("sp_EV_AllMoviesForStock", connection);
            command1.CommandType = CommandType.StoredProcedure;

            ds1 = new DataSet();

            da1.SelectCommand = command1;
            da1.Fill(ds1, "Movies");

            string MovieID;
            string MainTitle;
            string SecTitle;
            string Age_R;
            string Cat_M;
            string Cat_S;
            double Rent_Amount;

            string StockCode;
            string Status;
            string StatusInfo;
            string DateCreated;

            string script1;
            string script2;
            string key1;
            string key2;

            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "CreatePageConnector();", true);

            for (int Outer = 1; Outer <= ds1.Tables["Movies"].Rows.Count; Outer++)
            {

                MovieID     = ds1.Tables["Movies"].Rows[Outer - 1][0].ToString();
                MainTitle   = ds1.Tables["Movies"].Rows[Outer - 1][1].ToString();
                SecTitle    = ds1.Tables["Movies"].Rows[Outer - 1][2].ToString();
                Age_R       = ds1.Tables["Movies"].Rows[Outer - 1][3].ToString();
                Cat_M       = ds1.Tables["Movies"].Rows[Outer - 1][4].ToString();
                Cat_S       = ds1.Tables["Movies"].Rows[Outer - 1][5].ToString();
                Rent_Amount = Convert.ToDouble(ds1.Tables["Movies"].Rows[Outer - 1][6].ToString());

                script1 = "'" + Outer + "','" + MainTitle + "','" + SecTitle + "','" + Age_R + "','" + Cat_M + "','" + Cat_S + "','" + Rent_Amount + "'";
                key1 = "text" + Outer.ToString();

                if (Outer % 2 == 0)
                {
                    ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), key1, "CreateTableRowEven(" + script1 + ");", true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), key1, "CreateTableRowOdd(" + script1 + ");", true);
                }

                command2 = new SqlCommand("sp_EV_StockByMovie", connection);
                command2.CommandType = CommandType.StoredProcedure;
                command2.Parameters.AddWithValue("@MovieID", MovieID);

                ds2 = new DataSet();

                da2.SelectCommand = command2;
                da2.Fill(ds2, "Stock");

                for (int Inner = 1; Inner <= ds2.Tables["Stock"].Rows.Count; Inner++)
                {
                    key2 = "text" + Outer.ToString() + Inner.ToString();

                    StockCode   = ds2.Tables["Stock"].Rows[Inner - 1][0].ToString();
                    Status      = ds2.Tables["Stock"].Rows[Inner - 1][1].ToString();
                    StatusInfo  = ds2.Tables["Stock"].Rows[Inner - 1][2].ToString();
                    DateCreated = ds2.Tables["Stock"].Rows[Inner - 1][3].ToString();

                    script2 = "'" + StockCode + "','" + Status + "','" + StatusInfo + "','" + DateCreated + "'";

                    ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), key2, "CreateInnerData('" + Outer + "','" + Inner + "'," + script2 + ");", true);
                }
            }
        }
    }
}
</code>```

Here is the Page html (.aspx file)

```<code><%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication4._Default" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">

    <div class="container" id="containTable">
        <%--Table is Created Here--%>
    </div>

</asp:Content>

</code>```

Here is CreateTable.js

Note: the Odd and Even functions are to change the row's color (I feel it done this why is repetitive and unnecessary but its good enough for now, as a proof of concept)

```<code>function CreatePageConnector() {
    var TableHolder = document.createElement("table");

    TableHolder.setAttribute("class", "table");
    TableHolder.setAttribute("id", "TableHolder");

    document.getElementById("containTable").appendChild(TableHolder);
}

function CreateTableRowOdd(ID, MainTitle, SubTitle, Age_Restr, Cat_1, Cat_2, Rent_Amount) {
    var HeaderRow = document.createElement("tr");

    HeaderRow.setAttribute("class", "header");
    HeaderRow.setAttribute("id", "HeaderRow_A_" + ID);

    document.getElementById("TableHolder").appendChild(HeaderRow);

    var InfoHeader = document.createElement("td");

    InfoHeader.setAttribute("class", "InfoHeader");
    InfoHeader.setAttribute("colspan", "4");
    InfoHeader.setAttribute("id", "InfoHeaderData_A_" + ID);

    document.getElementById("HeaderRow_A_" + ID).appendChild(InfoHeader);

    var contHolder = document.createElement("div");

    contHolder.setAttribute("class", "container contHolder");
    contHolder.setAttribute("id", "contHolder_A_" + ID);

    document.getElementById("InfoHeaderData_A_" + ID).appendChild(contHolder);

    var innerTable = document.createElement("table");

    innerTable.setAttribute("class", "table innerTable");
    innerTable.setAttribute("id", "innerTable_A_" + ID);

    document.getElementById("contHolder_A_" + ID).appendChild(innerTable);

    var DataHeader = document.createElement("tr");

    DataHeader.setAttribute("class", "DataHeaderOdd");
    DataHeader.setAttribute("id", "DataHeaderOdd_A_" + ID);

    document.getElementById("innerTable_A_" + ID).appendChild(DataHeader);

    var DataHolder1 = document.createElement("td");

    DataHolder1.setAttribute("id", "DataHolder_A_A_" + ID);
    DataHolder1.innerHTML = MainTitle;

    var DataHolder2 = document.createElement("td");

    DataHolder2.setAttribute("id", "DataHolder_A_B_" + ID);
    DataHolder2.innerHTML = SubTitle;

    var DataHolder3 = document.createElement("td");

    DataHolder3.setAttribute("id", "DataHolder_A_C_" + ID);
    DataHolder3.innerHTML = Age_Restr;

    var DataHolder4 = document.createElement("td");

    DataHolder4.setAttribute("id", "DataHolder_A_D_" + ID);
    DataHolder4.innerHTML = Cat_1 + " " + Cat_2;

    var DataHolder5 = document.createElement("td");

    DataHolder5.setAttribute("id", "DataHolder_A_E_" + ID);
    DataHolder5.innerHTML = "R " + Rent_Amount;

    document.getElementById("DataHeaderOdd_A_" + ID).appendChild(DataHolder1);
    document.getElementById("DataHeaderOdd_A_" + ID).appendChild(DataHolder2);
    document.getElementById("DataHeaderOdd_A_" + ID).appendChild(DataHolder3);
    document.getElementById("DataHeaderOdd_A_" + ID).appendChild(DataHolder4);
    document.getElementById("DataHeaderOdd_A_" + ID).appendChild(DataHolder5);

    var InnerHeaderRow = document.createElement("tr");

    InnerHeaderRow.setAttribute("class", "innerDataHeader");
    InnerHeaderRow.setAttribute("id", "InnerHeaderRow_B_" + ID);

    document.getElementById("TableHolder").appendChild(InnerHeaderRow);

    var HeaderHolder1 = document.createElement("td");

    HeaderHolder1.setAttribute("id", "HeaderHolder_B_A" + ID);
    HeaderHolder1.innerHTML = "Stock Code";

    var HeaderHolder2 = document.createElement("td");

    HeaderHolder2.setAttribute("id", "HeaderHolder_B_B" + ID);
    HeaderHolder2.innerHTML = "Status";

    var HeaderHolder3 = document.createElement("td");

    HeaderHolder3.setAttribute("id", "HeaderHolder_B_C" + ID);
    HeaderHolder3.innerHTML = "Status Information";

    var HeaderHolder4 = document.createElement("td");

    HeaderHolder4.setAttribute("id", "HeaderHolder_B_D" + ID);
    HeaderHolder4.innerHTML = "Status Change Date";

    document.getElementById("InnerHeaderRow_B_" + ID).appendChild(HeaderHolder1);
    document.getElementById("InnerHeaderRow_B_" + ID).appendChild(HeaderHolder2);
    document.getElementById("InnerHeaderRow_B_" + ID).appendChild(HeaderHolder3);
    document.getElementById("InnerHeaderRow_B_" + ID).appendChild(HeaderHolder4);
}

function CreateTableRowEven(ID, MainTitle, SubTitle, Age_Restr, Cat_1, Cat_2, Rent_Amount) {
    var HeaderRow = document.createElement("tr");

    HeaderRow.setAttribute("class", "header");
    HeaderRow.setAttribute("id", "HeaderRow_A_" + ID);

    document.getElementById("TableHolder").appendChild(HeaderRow);

    var InfoHeader = document.createElement("td");

    InfoHeader.setAttribute("class", "InfoHeader");
    InfoHeader.setAttribute("colspan", "4");
    InfoHeader.setAttribute("id", "InfoHeaderData_A_" + ID);

    document.getElementById("HeaderRow_A_" + ID).appendChild(InfoHeader);

    var contHolder = document.createElement("div");

    contHolder.setAttribute("class", "container contHolder");
    contHolder.setAttribute("id", "contHolder_A_" + ID);

    document.getElementById("InfoHeaderData_A_" + ID).appendChild(contHolder);

    var innerTable = document.createElement("table");

    innerTable.setAttribute("class", "table innerTable");
    innerTable.setAttribute("id", "innerTable_A_" + ID);

    document.getElementById("contHolder_A_" + ID).appendChild(innerTable);

    var DataHeader = document.createElement("tr");

    DataHeader.setAttribute("class", "DataHeaderEven");
    DataHeader.setAttribute("id", "DataHeaderEven_A_" + ID);

    document.getElementById("innerTable_A_" + ID).appendChild(DataHeader);

    var DataHolder1 = document.createElement("td");

    DataHolder1.setAttribute("id", "DataHolder_A_A_" + ID);
    DataHolder1.innerHTML = MainTitle;

    var DataHolder2 = document.createElement("td");

    DataHolder2.setAttribute("id", "DataHolder_A_B_" + ID);
    DataHolder2.innerHTML = SubTitle;

    var DataHolder3 = document.createElement("td");

    DataHolder3.setAttribute("id", "DataHolder_A_C_" + ID);
    DataHolder3.innerHTML = Age_Restr;

    var DataHolder4 = document.createElement("td");

    DataHolder4.setAttribute("id", "DataHolder_A_D_" + ID);
    DataHolder4.innerHTML = Cat_1 + " " + Cat_2;

    var DataHolder5 = document.createElement("td");

    DataHolder5.setAttribute("id", "DataHolder_A_E_" + ID);
    DataHolder5.innerHTML = "R " + Rent_Amount;

    document.getElementById("DataHeaderEven_A_" + ID).appendChild(DataHolder1);
    document.getElementById("DataHeaderEven_A_" + ID).appendChild(DataHolder2);
    document.getElementById("DataHeaderEven_A_" + ID).appendChild(DataHolder3);
    document.getElementById("DataHeaderEven_A_" + ID).appendChild(DataHolder4);
    document.getElementById("DataHeaderEven_A_" + ID).appendChild(DataHolder5);

    var InnerHeaderRow = document.createElement("tr");

    InnerHeaderRow.setAttribute("class", "innerDataHeader");
    InnerHeaderRow.setAttribute("id", "InnerHeaderRow_B_" + ID);

    document.getElementById("TableHolder").appendChild(InnerHeaderRow);

    var HeaderHolder1 = document.createElement("td");

    HeaderHolder1.setAttribute("id", "HeaderHolder_B_A_" + ID);
    HeaderHolder1.innerHTML = "Stock Code";

    var HeaderHolder2 = document.createElement("td");

    HeaderHolder2.setAttribute("id", "HeaderHolder_B_B_" + ID);
    HeaderHolder2.innerHTML = "Status";

    var HeaderHolder3 = document.createElement("td");

    HeaderHolder3.setAttribute("id", "HeaderHolder_B_C_" + ID);
    HeaderHolder3.innerHTML = "Status Information";

    var HeaderHolder4 = document.createElement("td");

    HeaderHolder4.setAttribute("id", "HeaderHolder_B_D_" + ID);
    HeaderHolder4.innerHTML = "Status Change Date";

    document.getElementById("InnerHeaderRow_B_" + ID).appendChild(HeaderHolder1);
    document.getElementById("InnerHeaderRow_B_" + ID).appendChild(HeaderHolder2);
    document.getElementById("InnerHeaderRow_B_" + ID).appendChild(HeaderHolder3);
    document.getElementById("InnerHeaderRow_B_" + ID).appendChild(HeaderHolder4);
}

function CreateInnerData(ID1, ID2, StockCode, Status, StatusInfo, DateChanged) {
    var InnerData = document.createElement("tr");

    InnerData.setAttribute("class", "innerData");
    InnerData.setAttribute("id", "InnerData_C_" + ID1 + "_" + ID2);

    document.getElementById("TableHolder").appendChild(InnerData);

    var innerDataHolder1 = document.createElement("td");

    innerDataHolder1.setAttribute("id", "HeaderHolder_C_A_" + ID1 + "_" + ID2);
    innerDataHolder1.innerHTML = StockCode;

    var innerDataHolder2 = document.createElement("td");

    innerDataHolder2.setAttribute("id", "HeaderHolder_C_B_" + ID1 + "_" + ID2);
    innerDataHolder2.innerHTML = Status;

    var innerDataHolder3 = document.createElement("td");

    innerDataHolder3.setAttribute("id", "HeaderHolder_C_C_" + ID1 + "_" + ID2);
    innerDataHolder3.innerHTML = StatusInfo;

    var innerDataHolder4 = document.createElement("td");

    innerDataHolder4.setAttribute("id", "HeaderHolder_C_D_" + ID1 + "_" + ID2);
    innerDataHolder4.innerHTML = DateChanged;

    document.getElementById("InnerData_C_" + ID1 + "_" + ID2).appendChild(innerDataHolder1);
    document.getElementById("InnerData_C_" + ID1 + "_" + ID2).appendChild(innerDataHolder2);
    document.getElementById("InnerData_C_" + ID1 + "_" + ID2).appendChild(innerDataHolder3);
    document.getElementById("InnerData_C_" + ID1 + "_" + ID2).appendChild(innerDataHolder4);
}
</code>```

Here is the Javascript for the row dropdown of the table

```<code>$(document).ready(function () {
    var ua = navigator.userAgent,
        event = (ua.match(/iPad/i)) ? "touchstart" : "click";
    if ($('.table').length > 0) {
        $('.table .header').on(event, function () {
            $(this).toggleClass("active", "").nextUntil('.header').css('display', function (i, v) {
                return this.style.display === 'table-row' ? 'none' : 'table-row';
            });
        });
    }
})
</code>```

Here is the Style Sheet

```<code>@import url('https://fonts.googleapis.com/css?family=Titillium+Web&display=swap');

body {
    color: #6a6c6f;
    background-color: #f1f3f6;
    margin-top: 30px;
    font-family: 'Titillium Web', sans-serif;
}

.container {
    max-width: 960px;
}

.contHolder {
    height: 100%;
    padding: 0;
}

.table {
    color: white;
    text-align: center;
}

.table tr.header {
    font-weight: bold;
    cursor: pointer;
    -webkit-user-select: none;
    /* Chrome all / Safari all */
    -moz-user-select: none;
    /* Firefox all */
    -ms-user-select: none;
    /* IE 10+ */
    user-select: none;
    /* Likely future */
}

.table tr:not(.header) {
    display: none;
}

.table tr:nth-child(odd) {
    background: #eee;
}

    .table .header td:after {
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        transition: transform .25s linear;
        -webkit-transition: -webkit-transform .25s linear;
    }

.table .innerTable {
    margin: 0;
}

.table .InfoHeader {
    padding: 0;
    border-top: none;
}

    .table tr.DataHeaderOdd {
        background-color: #414141;
        display: table-row;
    }

    .table tr.DataHeaderEven {
        background-color: #5b5656;
        display: table-row;
    }

    .table tr.DataHeaderOdd td {
        width: 20%;
        border: none;
        line-height: 30px;
    }

    .table tr.DataHeaderEven td {
        width: 20%;
        border: none;
        line-height: 30px;
    }

.table .innerDataHeader td {
    width: 25%;
    border: none;
    font-size: 14px;
    line-height: 25px;
    color: white;
    background-color: #6c7b95;
}

.table .innerData td {
    color: #393e46;
    font-size: 10px;
    line-height: 20px;
}
</code>```

Here is a screenshot:

答:
Good day,

I figured out that there are keys that are duplicated and recreated. In the beginning the eleventh data row of the first movie (Avengers Infinity War), the key is "text111", meaning the key of the first row, eleventh datarow. Later at the eleventh row (which should be Zombieland: Double Tap), the key there is "text111", the eleventh row, first datarow. I solved just by adding an underscore between the key's row and datarow identifiers e.g. "text1_11" and "text11_1", it solved the problem and the table is created with all movie items from the database.

Body:
Good day,

This is actually my first question on the site, I actually made an account for this problem alone.
I struggling a lot with this and can't seem to figure out what the cause is.

I'm playing around with dynamically creating html controls and populating them with data from a SQL Database.

As a test application I have been using the concept of a video store rental shop that has an admin site to modify (Insert, Update, Delete) movies, receive reports and statistics about the movies and so on.

So as a control to display the movies I use a html table with my own custom style sheet, with the Movie's detail in a header row, and when you click on the header row the table expands to show the stock of that movie (As a movie can have multiple physical "discs" within the shop that have different stock codes and statuses).

Thus the reason I'm trying to create the table dynamically as the number of movies and the number of "discs" these movies can have can change. I have created a working "Proof of Concept", but a problem occurs on the eleventh movie where the header row (Showing Main Title, Sub Title, Age Restriction, Main Category, Secondary Category, and Rental Amount) isn't created but the data that is shown when you click on the header and it expands is created, but is appended to the tenth movie's expanded data.

The scripts are appended using ScriptManager.RegisterStartupScript. When I check the compiled code in a browser (Chrome's Inspect Tool), the scripts in the Manager are all appended except for the the eleventh movie's header and first data row.

I used breakpoints to check the codebehind (OnPage_Load Event) and the script runs and it isn't a problem with the ScriptManager.RegisterStartupScript's key parameter, as it is created with a loop and I made sure that the controls created dynamically have unique ID tags to call on in the script itself and for later.

I've been stuck on this problem the whole day and can't figure out why all the rows and there expanded data rows are created and works except for the last one and its first data row.

Why is this happening? Is it a problem in the script? (But why are all the other rows created without a problem?)

So far I believe it's a problem in the codebehind of program but still can't figure out why the problem happens.

Here is the C# from the codebehind

namespace WebApplication4
{
    public partial class _Default : Page
    {
        private static String connectionString = @"Data Source=BOARDROOM-PC\SQLEXPRESS;Initial Catalog=Express_Video;Integrated Security=True";
        private static SqlConnection connection;
        private SqlDataAdapter da1 = null;
        private SqlDataAdapter da2 = null;
        private SqlCommand command1 = null;
        private SqlCommand command2 = null;
        private DataSet ds1 = null;
        private DataSet ds2 = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            connection = new SqlConnection(connectionString);
            connection.Open();

            da1 = new SqlDataAdapter();
            da2 = new SqlDataAdapter();

            command1 = new SqlCommand("sp_EV_AllMoviesForStock", connection);
            command1.CommandType = CommandType.StoredProcedure;

            ds1 = new DataSet();

            da1.SelectCommand = command1;
            da1.Fill(ds1, "Movies");

            string MovieID;
            string MainTitle;
            string SecTitle;
            string Age_R;
            string Cat_M;
            string Cat_S;
            double Rent_Amount;

            string StockCode;
            string Status;
            string StatusInfo;
            string DateCreated;

            string script1;
            string script2;
            string key1;
            string key2;

            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "CreatePageConnector();", true);

            for (int Outer = 1; Outer <= ds1.Tables["Movies"].Rows.Count; Outer++)
            {

                MovieID     = ds1.Tables["Movies"].Rows[Outer - 1][0].ToString();
                MainTitle   = ds1.Tables["Movies"].Rows[Outer - 1][1].ToString();
                SecTitle    = ds1.Tables["Movies"].Rows[Outer - 1][2].ToString();
                Age_R       = ds1.Tables["Movies"].Rows[Outer - 1][3].ToString();
                Cat_M       = ds1.Tables["Movies"].Rows[Outer - 1][4].ToString();
                Cat_S       = ds1.Tables["Movies"].Rows[Outer - 1][5].ToString();
                Rent_Amount = Convert.ToDouble(ds1.Tables["Movies"].Rows[Outer - 1][6].ToString());

                script1 = "'" + Outer + "','" + MainTitle + "','" + SecTitle + "','" + Age_R + "','" + Cat_M + "','" + Cat_S + "','" + Rent_Amount + "'";
                key1 = "text" + Outer.ToString();

                if (Outer % 2 == 0)
                {
                    ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), key1, "CreateTableRowEven(" + script1 + ");", true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), key1, "CreateTableRowOdd(" + script1 + ");", true);
                }

                command2 = new SqlCommand("sp_EV_StockByMovie", connection);
                command2.CommandType = CommandType.StoredProcedure;
                command2.Parameters.AddWithValue("@MovieID", MovieID);

                ds2 = new DataSet();

                da2.SelectCommand = command2;
                da2.Fill(ds2, "Stock");

                for (int Inner = 1; Inner <= ds2.Tables["Stock"].Rows.Count; Inner++)
                {
                    key2 = "text" + Outer.ToString() + Inner.ToString();

                    StockCode   = ds2.Tables["Stock"].Rows[Inner - 1][0].ToString();
                    Status      = ds2.Tables["Stock"].Rows[Inner - 1][1].ToString();
                    StatusInfo  = ds2.Tables["Stock"].Rows[Inner - 1][2].ToString();
                    DateCreated = ds2.Tables["Stock"].Rows[Inner - 1][3].ToString();

                    script2 = "'" + StockCode + "','" + Status + "','" + StatusInfo + "','" + DateCreated + "'";

                    ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), key2, "CreateInnerData('" + Outer + "','" + Inner + "'," + script2 + ");", true);
                }
            }
        }
    }
}

Here is the Page html (.aspx file)

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication4._Default" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">

        <%--Table is Created Here--%>

</asp:Content>

Here is CreateTable.js

Note: the Odd and Even functions are to change the row's color (I feel it done this why is repetitive and unnecessary but its good enough for now, as a proof of concept)

function CreatePageConnector() {
    var TableHolder = document.createElement("table");

    TableHolder.setAttribute("class", "table");
    TableHolder.setAttribute("id", "TableHolder");

    document.getElementById("containTable").appendChild(TableHolder);
}

function CreateTableRowOdd(ID, MainTitle, SubTitle, Age_Restr, Cat_1, Cat_2, Rent_Amount) {
    var HeaderRow = document.createElement("tr");

    HeaderRow.setAttribute("class", "header");
    HeaderRow.setAttribute("id", "HeaderRow_A_" + ID);

    document.getElementById("TableHolder").appendChild(HeaderRow);

    var InfoHeader = document.createElement("td");

    InfoHeader.setAttribute("class", "InfoHeader");
    InfoHeader.setAttribute("colspan", "4");
    InfoHeader.setAttribute("id", "InfoHeaderData_A_" + ID);

    document.getElementById("HeaderRow_A_" + ID).appendChild(InfoHeader);

    var contHolder = document.createElement("div");

    contHolder.setAttribute("class", "container contHolder");
    contHolder.setAttribute("id", "contHolder_A_" + ID);

    document.getElementById("InfoHeaderData_A_" + ID).appendChild(contHolder);

    var innerTable = document.createElement("table");

    innerTable.setAttribute("class", "table innerTable");
    innerTable.setAttribute("id", "innerTable_A_" + ID);

    document.getElementById("contHolder_A_" + ID).appendChild(innerTable);

    var DataHeader = document.createElement("tr");

    DataHeader.setAttribute("class", "DataHeaderOdd");
    DataHeader.setAttribute("id", "DataHeaderOdd_A_" + ID);

    document.getElementById("innerTable_A_" + ID).appendChild(DataHeader);

    var DataHolder1 = document.createElement("td");

    DataHolder1.setAttribute("id", "DataHolder_A_A_" + ID);
    DataHolder1.innerHTML = MainTitle;

    var DataHolder2 = document.createElement("td");

    DataHolder2.setAttribute("id", "DataHolder_A_B_" + ID);
    DataHolder2.innerHTML = SubTitle;

    var DataHolder3 = document.createElement("td");

    DataHolder3.setAttribute("id", "DataHolder_A_C_" + ID);
    DataHolder3.innerHTML = Age_Restr;

    var DataHolder4 = document.createElement("td");

    DataHolder4.setAttribute("id", "DataHolder_A_D_" + ID);
    DataHolder4.innerHTML = Cat_1 + " " + Cat_2;

    var DataHolder5 = document.createElement("td");

    DataHolder5.setAttribute("id", "DataHolder_A_E_" + ID);
    DataHolder5.innerHTML = "R " + Rent_Amount;

    document.getElementById("DataHeaderOdd_A_" + ID).appendChild(DataHolder1);
    document.getElementById("DataHeaderOdd_A_" + ID).appendChild(DataHolder2);
    document.getElementById("DataHeaderOdd_A_" + ID).appendChild(DataHolder3);
    document.getElementById("DataHeaderOdd_A_" + ID).appendChild(DataHolder4);
    document.getElementById("DataHeaderOdd_A_" + ID).appendChild(DataHolder5);

    var InnerHeaderRow = document.createElement("tr");

    InnerHeaderRow.setAttribute("class", "innerDataHeader");
    InnerHeaderRow.setAttribute("id", "InnerHeaderRow_B_" + ID);

    document.getElementById("TableHolder").appendChild(InnerHeaderRow);

    var HeaderHolder1 = document.createElement("td");

    HeaderHolder1.setAttribute("id", "HeaderHolder_B_A" + ID);
    HeaderHolder1.innerHTML = "Stock Code";

    var HeaderHolder2 = document.createElement("td");

    HeaderHolder2.setAttribute("id", "HeaderHolder_B_B" + ID);
    HeaderHolder2.innerHTML = "Status";

    var HeaderHolder3 = document.createElement("td");

    HeaderHolder3.setAttribute("id", "HeaderHolder_B_C" + ID);
    HeaderHolder3.innerHTML = "Status Information";

    var HeaderHolder4 = document.createElement("td");

    HeaderHolder4.setAttribute("id", "HeaderHolder_B_D" + ID);
    HeaderHolder4.innerHTML = "Status Change Date";

    document.getElementById("InnerHeaderRow_B_" + ID).appendChild(HeaderHolder1);
    document.getElementById("InnerHeaderRow_B_" + ID).appendChild(HeaderHolder2);
    document.getElementById("InnerHeaderRow_B_" + ID).appendChild(HeaderHolder3);
    document.getElementById("InnerHeaderRow_B_" + ID).appendChild(HeaderHolder4);
}

function CreateTableRowEven(ID, MainTitle, SubTitle, Age_Restr, Cat_1, Cat_2, Rent_Amount) {
    var HeaderRow = document.createElement("tr");

    HeaderRow.setAttribute("class", "header");
    HeaderRow.setAttribute("id", "HeaderRow_A_" + ID);

    document.getElementById("TableHolder").appendChild(HeaderRow);

    var InfoHeader = document.createElement("td");

    InfoHeader.setAttribute("class", "InfoHeader");
    InfoHeader.setAttribute("colspan", "4");
    InfoHeader.setAttribute("id", "InfoHeaderData_A_" + ID);

    document.getElementById("HeaderRow_A_" + ID).appendChild(InfoHeader);

    var contHolder = document.createElement("div");

    contHolder.setAttribute("class", "container contHolder");
    contHolder.setAttribute("id", "contHolder_A_" + ID);

    document.getElementById("InfoHeaderData_A_" + ID).appendChild(contHolder);

    var innerTable = document.createElement("table");

    innerTable.setAttribute("class", "table innerTable");
    innerTable.setAttribute("id", "innerTable_A_" + ID);

    document.getElementById("contHolder_A_" + ID).appendChild(innerTable);

    var DataHeader = document.createElement("tr");

    DataHeader.setAttribute("class", "DataHeaderEven");
    DataHeader.setAttribute("id", "DataHeaderEven_A_" + ID);

    document.getElementById("innerTable_A_" + ID).appendChild(DataHeader);

    var DataHolder1 = document.createElement("td");

    DataHolder1.setAttribute("id", "DataHolder_A_A_" + ID);
    DataHolder1.innerHTML = MainTitle;

    var DataHolder2 = document.createElement("td");

    DataHolder2.setAttribute("id", "DataHolder_A_B_" + ID);
    DataHolder2.innerHTML = SubTitle;

    var DataHolder3 = document.createElement("td");

    DataHolder3.setAttribute("id", "DataHolder_A_C_" + ID);
    DataHolder3.innerHTML = Age_Restr;

    var DataHolder4 = document.createElement("td");

    DataHolder4.setAttribute("id", "DataHolder_A_D_" + ID);
    DataHolder4.innerHTML = Cat_1 + " " + Cat_2;

    var DataHolder5 = document.createElement("td");

    DataHolder5.setAttribute("id", "DataHolder_A_E_" + ID);
    DataHolder5.innerHTML = "R " + Rent_Amount;

    document.getElementById("DataHeaderEven_A_" + ID).appendChild(DataHolder1);
    document.getElementById("DataHeaderEven_A_" + ID).appendChild(DataHolder2);
    document.getElementById("DataHeaderEven_A_" + ID).appendChild(DataHolder3);
    document.getElementById("DataHeaderEven_A_" + ID).appendChild(DataHolder4);
    document.getElementById("DataHeaderEven_A_" + ID).appendChild(DataHolder5);

    var InnerHeaderRow = document.createElement("tr");

    InnerHeaderRow.setAttribute("class", "innerDataHeader");
    InnerHeaderRow.setAttribute("id", "InnerHeaderRow_B_" + ID);

    document.getElementById("TableHolder").appendChild(InnerHeaderRow);

    var HeaderHolder1 = document.createElement("td");

    HeaderHolder1.setAttribute("id", "HeaderHolder_B_A_" + ID);
    HeaderHolder1.innerHTML = "Stock Code";

    var HeaderHolder2 = document.createElement("td");

    HeaderHolder2.setAttribute("id", "HeaderHolder_B_B_" + ID);
    HeaderHolder2.innerHTML = "Status";

    var HeaderHolder3 = document.createElement("td");

    HeaderHolder3.setAttribute("id", "HeaderHolder_B_C_" + ID);
    HeaderHolder3.innerHTML = "Status Information";

    var HeaderHolder4 = document.createElement("td");

    HeaderHolder4.setAttribute("id", "HeaderHolder_B_D_" + ID);
    HeaderHolder4.innerHTML = "Status Change Date";

    document.getElementById("InnerHeaderRow_B_" + ID).appendChild(HeaderHolder1);
    document.getElementById("InnerHeaderRow_B_" + ID).appendChild(HeaderHolder2);
    document.getElementById("InnerHeaderRow_B_" + ID).appendChild(HeaderHolder3);
    document.getElementById("InnerHeaderRow_B_" + ID).appendChild(HeaderHolder4);
}

function CreateInnerData(ID1, ID2, StockCode, Status, StatusInfo, DateChanged) {
    var InnerData = document.createElement("tr");

    InnerData.setAttribute("class", "innerData");
    InnerData.setAttribute("id", "InnerData_C_" + ID1 + "_" + ID2);

    document.getElementById("TableHolder").appendChild(InnerData);

    var innerDataHolder1 = document.createElement("td");

    innerDataHolder1.setAttribute("id", "HeaderHolder_C_A_" + ID1 + "_" + ID2);
    innerDataHolder1.innerHTML = StockCode;

    var innerDataHolder2 = document.createElement("td");

    innerDataHolder2.setAttribute("id", "HeaderHolder_C_B_" + ID1 + "_" + ID2);
    innerDataHolder2.innerHTML = Status;

    var innerDataHolder3 = document.createElement("td");

    innerDataHolder3.setAttribute("id", "HeaderHolder_C_C_" + ID1 + "_" + ID2);
    innerDataHolder3.innerHTML = StatusInfo;

    var innerDataHolder4 = document.createElement("td");

    innerDataHolder4.setAttribute("id", "HeaderHolder_C_D_" + ID1 + "_" + ID2);
    innerDataHolder4.innerHTML = DateChanged;

    document.getElementById("InnerData_C_" + ID1 + "_" + ID2).appendChild(innerDataHolder1);
    document.getElementById("InnerData_C_" + ID1 + "_" + ID2).appendChild(innerDataHolder2);
    document.getElementById("InnerData_C_" + ID1 + "_" + ID2).appendChild(innerDataHolder3);
    document.getElementById("InnerData_C_" + ID1 + "_" + ID2).appendChild(innerDataHolder4);
}

Here is the Javascript for the row dropdown of the table

$(document).ready(function () {
    var ua = navigator.userAgent,
        event = (ua.match(/iPad/i)) ? "touchstart" : "click";
    if ($('.table').length > 0) {
        $('.table .header').on(event, function () {
            $(this).toggleClass("active", "").nextUntil('.header').css('display', function (i, v) {
                return this.style.display === 'table-row' ? 'none' : 'table-row';
            });
        });
    }
})

Here is the Style Sheet

@import url('https://fonts.googleapis.com/css?family=Titillium+Web&display=swap');

body {
    color: #6a6c6f;
    background-color: #f1f3f6;
    margin-top: 30px;
    font-family: 'Titillium Web', sans-serif;
}

.container {
    max-width: 960px;
}

.contHolder {
    height: 100%;
    padding: 0;
}

.table {
    color: white;
    text-align: center;
}

.table tr.header {
    font-weight: bold;
    cursor: pointer;
    -webkit-user-select: none;
    /* Chrome all / Safari all */
    -moz-user-select: none;
    /* Firefox all */
    -ms-user-select: none;
    /* IE 10+ */
    user-select: none;
    /* Likely future */
}

.table tr:not(.header) {
    display: none;
}

.table tr:nth-child(odd) {
    background: #eee;
}

    .table .header td:after {
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        transition: transform .25s linear;
        -webkit-transition: -webkit-transform .25s linear;
    }

.table .innerTable {
    margin: 0;
}

.table .InfoHeader {
    padding: 0;
    border-top: none;
}

    .table tr.DataHeaderOdd {
        background-color: #414141;
        display: table-row;
    }

    .table tr.DataHeaderEven {
        background-color: #5b5656;
        display: table-row;
    }

    .table tr.DataHeaderOdd td {
        width: 20%;
        border: none;
        line-height: 30px;
    }

    .table tr.DataHeaderEven td {
        width: 20%;
        border: none;
        line-height: 30px;
    }

.table .innerDataHeader td {
    width: 25%;
    border: none;
    font-size: 14px;
    line-height: 25px;
    color: white;
    background-color: #6c7b95;
}

.table .innerData td {
    color: #393e46;
    font-size: 10px;
    line-height: 20px;
}

Here is a screenshot:


来源: stackexchange

问:
Why is npm start (after create-react-app) failing to run?
After I create a sample react app using create-react-app, npm start fails.

I have tried this using node 11.4 and 10.4 (npm 6.4.1)

```<code>npm install create-react-app -g
create-react-app t2
cd t2
npm start
</code>```

Expected

To be able to start simple react server to hit in browser at localhost:3000

Actual

Server did not start, got this in my terminal:

```<code>$ npm start

> t2@0.1.0 start /Users/samr/dev/githubs/react/t2
> react-scripts start

/Users/samr/dev/githubs/react/t2/node_modules/ajv/lib/keyword.js:65
      throw new Error('custom keyword definition is invalid: '  + this.errorsText(validateDefinition.errors));
      ^

Error: custom keyword definition is invalid: data.errors should be boolean
    at Ajv.addKeyword (/Users/samr/dev/githubs/react/t2/node_modules/ajv/lib/keyword.js:65:13)
    at module.exports (/Users/samr/dev/githubs/react/t2/node_modules/ajv-errors/index.js:10:7)
    at Object.<anonymous> (/Users/samr/dev/githubs/react/t2/node_modules/schema-utils/src/validateOptions.js:22:1)
    at Module._compile (internal/modules/cjs/loader.js:723:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:734:10)
    at Module.load (internal/modules/cjs/loader.js:620:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
    at Function.Module._load (internal/modules/cjs/loader.js:552:3)
    at Module.require (internal/modules/cjs/loader.js:659:17)
    at require (internal/modules/cjs/helpers.js:22:18)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! t2@0.1.0 start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the t2@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/samr/.npm/_logs/2019-02-09T23_19_40_848Z-debug.log
</code>```

答:
The accepted answer didn't work for me. Instead i did this:

deleted node_modules folder.

cd to project parent directory.

npm install

npm start

This worked like a charm.

ContentLicense: CC BY-SA 4.0

Body:
After I create a sample react app using create-react-app, npm start fails.

I have tried this using node 11.4 and 10.4 (npm 6.4.1)

npm install create-react-app -g
create-react-app t2
cd t2
npm start

Expected

To be able to start simple react server to hit in browser at localhost:3000

Actual

Server did not start, got this in my terminal:

$ npm start

> t2@0.1.0 start /Users/samr/dev/githubs/react/t2
> react-scripts start

/Users/samr/dev/githubs/react/t2/node_modules/ajv/lib/keyword.js:65
      throw new Error('custom keyword definition is invalid: '  + this.errorsText(validateDefinition.errors));
      ^

Error: custom keyword definition is invalid: data.errors should be boolean
    at Ajv.addKeyword (/Users/samr/dev/githubs/react/t2/node_modules/ajv/lib/keyword.js:65:13)
    at module.exports (/Users/samr/dev/githubs/react/t2/node_modules/ajv-errors/index.js:10:7)
    at Object.<anonymous> (/Users/samr/dev/githubs/react/t2/node_modules/schema-utils/src/validateOptions.js:22:1)
    at Module._compile (internal/modules/cjs/loader.js:723:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:734:10)
    at Module.load (internal/modules/cjs/loader.js:620:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
    at Function.Module._load (internal/modules/cjs/loader.js:552:3)
    at Module.require (internal/modules/cjs/loader.js:659:17)
    at require (internal/modules/cjs/helpers.js:22:18)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! t2@0.1.0 start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the t2@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/samr/.npm/_logs/2019-02-09T23_19_40_848Z-debug.log


问:
Technical design problem: should it be in DAL, Business, or ViewModel layer?
I'm developing a simple expense tracker app, organized by categories, in C# and entity framework.

My entities are:

Category: Id, Name

Expense: Id,Name, Date, CategoryId

I am using MVVM, and separating concerns: I have a business layer, a data access layer, and a view/view model layer.

I want to display on my first page a list of categories with the total amount spent on every category for a specific month.

Where should I integrate the calculation of these amounts for every category?

Q1 : On my business layer my category object has a "SummedExpensesAmount" field, so I thought I would call from my business layer the DAL so I would fill this field for every category and for a specific month.
Is it ok to do this operation on the Business layer? Can it actually be considered business related or should I migrate that to the DAL and design my Database differently?

Second approach: Should I have similar object on DAL on Business, and do all the sorting on the ViewModel layer, meaning having business methods returning total amount for specific categories and period, calling it in a loop and filling a custom Category view model.

What are the pros/cons of each approach?

答:
In my opinion, any approach is OK based on your use-case.

If you are calculating totals in SQL query itself, best way is to put it in DAL.

If you are taking raw data from database and applying some business logic, BLL is better place.

If you are not applying any business logic and its just a presentation logic to add up the numbers and your UI framework is better handling this, UI layer (ViewModel may be) is also fine.

I will personally discard point 3 above. I will take the decision based on whether I am calculating totals in SQL Query or not. Based on that, I will choose 1 or 2 from above.


问:
jQuery File Upload plugin with webpack $(...).fileupload is not a function
I am using Rails 6, and I need to use jquery file upload plugin, I would like to add manually instead of using yarn, so I downloaded this file here: https://cdnjs.cloudflare.com/ajax/libs/blueimp-file-upload/9.31.0/js/jquery.fileupload.js  and put it into app/javascript folder

then in app/javascript/packs/application.js I added the line

```<code>require("jquery.fileupload")
</code>```

In my app/javascript/main.js :

```<code>$('#file-input').fileupload()
</code>```

I get the error :

```<code>TypeError: $(...).fileupload is not a function
</code>```

If I put $('#file-input').fileupload() in javascript/packs/application.js like this :

```<code>require("jquery.fileupload")
$('#file-input').fileupload()
</code>```

The error disappear ! so the issue seems to be that the plugin can only be accessed in application.js and not in other files, how I can solve that ?

答:
I lost 2 or 3 hours trying use webpack without success.

Then simple download *.js files directly from blueimp repository to app/javascript/packs/vendor and import it in application.js.

Body:
I am using Rails 6, and I need to use jquery file upload plugin, I would like to add manually instead of using yarn, so I downloaded this file here: https://cdnjs.cloudflare.com/ajax/libs/blueimp-file-upload/9.31.0/js/jquery.fileupload.js  and put it into app/javascript folder

then in app/javascript/packs/application.js I added the line

require("jquery.fileupload")

In my app/javascript/main.js :

$('#file-input').fileupload()

I get the error :

TypeError: $(...).fileupload is not a function

If I put $('#file-input').fileupload() in javascript/packs/application.js like this :

require("jquery.fileupload")
$('#file-input').fileupload()

The error disappear ! so the issue seems to be that the plugin can only be accessed in application.js and not in other files, how I can solve that ?


问:
stub.getQueryResult(queryString) How to get more then 100 result
```<code>let resultsIterator = await ctx.stub.getQueryResult(JSON.stringify(queryString));
</code>```

This function is in stub only return 100 result. I want more than 100. how to archive this?

答:
As per my understanding, You can check your query limit in config/core.yaml in a fabric-sample folder. If you want more data then you have to use the CouchDB pagination concept. And change the query limit in core.yaml file. All chaincode queries are bound by totalQueryLimit (default 100000) from core.yaml.

Here I recommend these links.

https://hyperledger-fabric.readthedocs.io/en/latest/couchdb_as_state_database.html

https://docs.google.com/document/d/1AzcVjVbuvZGRozfNe3ksIpK-cBMlhhbGOUZhg2bzPW8/edit

Hope it will help you :)

Body:
let resultsIterator = await ctx.stub.getQueryResult(JSON.stringify(queryString));

This function is in stub only return 100 result. I want more than 100. how to archive this?


问:
PostgreSQL-12.1 :: Streaming Replication Error
I have set up streaming replication on PostgreSQL 12.1

The master and slave are configured as below and WAL files are accumulating on the master.

However, something is wrong as I get complaints that the WAL files are missing after a pg_restore on MASTER

MASTER

```<code>postgres@srvm:~$ 2019-12-20 16:35:07.910 CET [1334] replicator@[unknown] ERROR:  requested WAL segment 000000010000000100000076 has already been removed
2019-12-20 16:35:12.920 CET [1338] replicator@[unknown] ERROR:  requested WAL segment 000000010000000100000076 has already been removed
2019-12-20 16:35:17.925 CET [1340] replicator@[unknown] ERROR:  requested WAL segment 000000010000000100000076 has already been removed
2019-12-20 16:35:22.932 CET [1362] replicator@[unknown] ERROR:  requested WAL segment 000000010000000100000076 has already been removed
2019-12-20 16:35:27.935 CET [1364] replicator@[unknown] ERROR:  requested WAL segment 000000010000000100000076 has already been removed
2019-12-20 16:35:32.942 CET [1365] replicator@[unknown] ERROR:  requested WAL segment 000000010000000100000076 has already been removed
2019-12-20 16:35:37.948 CET [1366] replicator@[unknown] ERROR:  requested WAL segment 000000010000000100000076 has already been removed
2019-12-20 16:35:42.954 CET [1367] replicator@[unknown] ERROR:  requested WAL segment 000000010000000100000076 has already been removed
</code>```

SLAVE

```<code>postgres@srvs:~$ 2019-12-20 16:36:53.027 CET [21978] LOG:  started streaming WAL from primary at 1/76000000 on timeline 1
2019-12-20 16:36:53.027 CET [21978] FATAL:  could not receive data from WAL stream: ERROR:  requested WAL segment 000000010000000100000076 has already been removed
2019-12-20 16:36:58.029 CET [21979] LOG:  started streaming WAL from primary at 1/76000000 on timeline 1
2019-12-20 16:36:58.029 CET [21979] FATAL:  could not receive data from WAL stream: ERROR:  requested WAL segment 000000010000000100000076 has already been removed
2019-12-20 16:37:03.040 CET [21980] LOG:  started streaming WAL from primary at 1/76000000 on timeline 1
2019-12-20 16:37:03.040 CET [21980] FATAL:  could not receive data from WAL stream: ERROR:  requested WAL segment 000000010000000100000076 has already been removed
2019-12-20 16:37:08.042 CET [21981] LOG:  started streaming WAL from primary at 1/76000000 on timeline 1
2019-12-20 16:37:08.042 CET [21981] FATAL:  could not receive data from WAL stream: ERROR:  requested WAL segment 000000010000000100000076 has already been removed
</code>```

Then the pg_basebackup is run and the slave started.

The slave has all the data as of the time of the backup, but no new data from the WAL files, and the error above.

```<code>max_wal_senders = 10
wal_keep_segments = 120
</code>```

What have I mis-configured? Do we need to enabled archive_mode = on for streaming replication?

答:
Here is my configuration for streaming replication:

Master config

```<code>listen_addresses = 'localhost,[IP_ADDRESS_OF_PRIMARY_ON_LAN]'              # what IP address(es) to listen on;
wal_level = 'replica'
archive_mode = on
archive_command = 'cd .'
max_wal_senders = 5
primary_conninfo = 'host=[REPLICA_IP] port=5432 user=replication password=[REPLICATION PASSWORD]'
hot_standby = on

max_wal_senders = 10
wal_keep_segments = 48

</code>```

Slave config:

```<code>listen_addresses = 'localhost,[IP_ADDRESS_OF_REPLIACA_ON_LAN]'              # what IP address(es) to listen on;
max_connections = 100 # Ensure that this value is the same as the primary's
wal_level = 'replica'
archive_mode = on
archive_command = 'cd .'
max_wal_senders = 5
primary_conninfo = 'host=[PRIMARY_IP] port=5432 user=replication password=[REPLICATION PASSWORD]'
hot_standby = on

max_wal_senders = 10
wal_keep_segments = 48

</code>```

I set up my server using the following resource: https://www.gab.lc/articles/postgresql-12-replication/

Body:
I have set up streaming replication on PostgreSQL 12.1

The master and slave are configured as below and WAL files are accumulating on the master.

However, something is wrong as I get complaints that the WAL files are missing after a pg_restore on MASTER

MASTER

postgres@srvm:~$ 2019-12-20 16:35:07.910 CET [1334] replicator@[unknown] ERROR:  requested WAL segment 000000010000000100000076 has already been removed
2019-12-20 16:35:12.920 CET [1338] replicator@[unknown] ERROR:  requested WAL segment 000000010000000100000076 has already been removed
2019-12-20 16:35:17.925 CET [1340] replicator@[unknown] ERROR:  requested WAL segment 000000010000000100000076 has already been removed
2019-12-20 16:35:22.932 CET [1362] replicator@[unknown] ERROR:  requested WAL segment 000000010000000100000076 has already been removed
2019-12-20 16:35:27.935 CET [1364] replicator@[unknown] ERROR:  requested WAL segment 000000010000000100000076 has already been removed
2019-12-20 16:35:32.942 CET [1365] replicator@[unknown] ERROR:  requested WAL segment 000000010000000100000076 has already been removed
2019-12-20 16:35:37.948 CET [1366] replicator@[unknown] ERROR:  requested WAL segment 000000010000000100000076 has already been removed
2019-12-20 16:35:42.954 CET [1367] replicator@[unknown] ERROR:  requested WAL segment 000000010000000100000076 has already been removed

SLAVE

postgres@srvs:~$ 2019-12-20 16:36:53.027 CET [21978] LOG:  started streaming WAL from primary at 1/76000000 on timeline 1
2019-12-20 16:36:53.027 CET [21978] FATAL:  could not receive data from WAL stream: ERROR:  requested WAL segment 000000010000000100000076 has already been removed
2019-12-20 16:36:58.029 CET [21979] LOG:  started streaming WAL from primary at 1/76000000 on timeline 1
2019-12-20 16:36:58.029 CET [21979] FATAL:  could not receive data from WAL stream: ERROR:  requested WAL segment 000000010000000100000076 has already been removed
2019-12-20 16:37:03.040 CET [21980] LOG:  started streaming WAL from primary at 1/76000000 on timeline 1
2019-12-20 16:37:03.040 CET [21980] FATAL:  could not receive data from WAL stream: ERROR:  requested WAL segment 000000010000000100000076 has already been removed
2019-12-20 16:37:08.042 CET [21981] LOG:  started streaming WAL from primary at 1/76000000 on timeline 1
2019-12-20 16:37:08.042 CET [21981] FATAL:  could not receive data from WAL stream: ERROR:  requested WAL segment 000000010000000100000076 has already been removed

Then the pg_basebackup is run and the slave started.

The slave has all the data as of the time of the backup, but no new data from the WAL files, and the error above.

max_wal_senders = 10
wal_keep_segments = 120

What have I mis-configured? Do we need to enabled archive_mode = on for streaming replication?

Body:
Here is my configuration for streaming replication:

Master config

listen_addresses = 'localhost,[IP_ADDRESS_OF_PRIMARY_ON_LAN]'              # what IP address(es) to listen on;
wal_level = 'replica'
archive_mode = on
archive_command = 'cd .'
max_wal_senders = 5
primary_conninfo = 'host=[REPLICA_IP] port=5432 user=replication password=[REPLICATION PASSWORD]'
hot_standby = on

max_wal_senders = 10
wal_keep_segments = 48

Slave config:

listen_addresses = 'localhost,[IP_ADDRESS_OF_REPLIACA_ON_LAN]'              # what IP address(es) to listen on;
max_connections = 100 # Ensure that this value is the same as the primary's
wal_level = 'replica'
archive_mode = on
archive_command = 'cd .'
max_wal_senders = 5
primary_conninfo = 'host=[PRIMARY_IP] port=5432 user=replication password=[REPLICATION PASSWORD]'
hot_standby = on

max_wal_senders = 10
wal_keep_segments = 48

I set up my server using the following resource: https://www.gab.lc/articles/postgresql-12-replication/


问:
Rpi3 BMP180 Barometer Sensor Interface Problem
im currently working on a Barometer sensor on my Raspberry Pi 3.
Unfortunately its not really working. My BMP180 Sensor is wired up as following:

```<code>VIN -> 3V3 (1)
GND -> GND (9)
SCL -> GPIO3 (5)
SDA -> GPIO2 (3)
</code>```

The cables and connections were double checked and replaced a few times so those are not the problem. I also enabled I2C in raspi-config. If I type in i2cdetect -y 1 i get something like this, so no connections are detected:

```<code>     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --
</code>```

If I let an example/test code from Adafruit run when everything is connected properly and checked (~/BMP180Code/Adafruit_Python_BMP/examplessimpletest.py) I get an output like that:

```<code>Traceback (most recent call last):
    File "simpletest.py", line 37, in <module>
        sensor = BMP085.BMP085()
    File "build/bdist.linux-armv7l/egg/Adafruit_BMP/BMP085.py", line 69, in __init__
    File "build/bdist.linux-armv7l/egg/Adafruit_BMP/BMP085.py", line 72, in _load_calibration
    File "build/bdist.linux-armv7l/egg/Adafruit_GPIO/I2C.py", line 202, in readS16BE
    File "build/bdist.linux-armv7l/egg/Adafruit_GPIO/I2C.py", line 179, in readS16
    File "build/bdist.linux-armv7l/egg/Adafruit_GPIO/I2C.py", line 166, in readU16
    File "build/bdist.linux-armv7l/egg/Adafruit_PureIO/smbus.py", line 187, in read_word_data
IOError: [Errno 110] Connection timed out
</code>```

I looked up a few solutions online, but nothing helped.
I would be happy if someone of you has a solution for that.
Thanks and have a good day, Leo

答:
First, if you are using Raspberrian with GUI you need to enable i2c interface on raspberry:  Pi Start Menu > Preferences > Raspberry Pi Configuration and in Interface tab turn on I2C. Or if you are using terminal just:
sudo raspi-config -> Interfacing Options -> I2C

My second suggestion is to check wiring once again. I2C uses open drain connection on SDL and SCL pins. As far as I know sparkfun  BMP180 sensors has build in pullup resistors to hold voltage on lines. Check if you model has pull up resistors. If not you have to put in circuit some resistors.

Body:
im currently working on a Barometer sensor on my Raspberry Pi 3.
Unfortunately its not really working. My BMP180 Sensor is wired up as following:

VIN -> 3V3 (1)
GND -> GND (9)
SCL -> GPIO3 (5)
SDA -> GPIO2 (3)

The cables and connections were double checked and replaced a few times so those are not the problem. I also enabled I2C in raspi-config. If I type in i2cdetect -y 1 i get something like this, so no connections are detected:

     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --

If I let an example/test code from Adafruit run when everything is connected properly and checked (~/BMP180Code/Adafruit_Python_BMP/examplessimpletest.py) I get an output like that:

Traceback (most recent call last):
    File "simpletest.py", line 37, in <module>
        sensor = BMP085.BMP085()
    File "build/bdist.linux-armv7l/egg/Adafruit_BMP/BMP085.py", line 69, in __init__
    File "build/bdist.linux-armv7l/egg/Adafruit_BMP/BMP085.py", line 72, in _load_calibration
    File "build/bdist.linux-armv7l/egg/Adafruit_GPIO/I2C.py", line 202, in readS16BE
    File "build/bdist.linux-armv7l/egg/Adafruit_GPIO/I2C.py", line 179, in readS16
    File "build/bdist.linux-armv7l/egg/Adafruit_GPIO/I2C.py", line 166, in readU16
    File "build/bdist.linux-armv7l/egg/Adafruit_PureIO/smbus.py", line 187, in read_word_data
IOError: [Errno 110] Connection timed out

I looked up a few solutions online, but nothing helped.
I would be happy if someone of you has a solution for that.
Thanks and have a good day, Leo


问:
Bounds checking is not supported for CUDA
I am trying to use Numba and access the GPU in order to accelerate the code, but I get the following error:

```<code>in jit raise NotImplementedError("bounds checking is not supported for CUDA")
NotImplementedError: bounds checking is not supported for CUDA
</code>```

I saw that another question was raised, but not completely specified nor answered here.
I implemented the 2-for loops when I saw that the vectorized code (y = corr*x + np.sqrt(1.-corr**2)*z) did not work (same error). I also tried to play around with the option boundscheck, but this did not change the outcome.
The error did not appear when not specifying the target, since it goes on the CPU automatically (I guess).

```<code>import numpy as np
from numba import jit

N = int(1e8)
@jit(nopython=True, target='cuda', boundscheck=False)
def Brownian_motions(T, N, corr):
    x = np.random.normal(0, 1, size=(T,N))
    z = np.random.normal(0, 1, size=(T,N))
    y = np.zeros(shape=(T,N))
    for i in range(T):
        for j in range(N):
            y[i,j] = corr*x[i,j] + np.sqrt(1.-corr**2)*z[i,j]
    return(x,y)

x, y = Brownian_motions(T = 500, N = N, corr = -0.45)
</code>```

Could you please help me? Python is 3.7.6 and Numba is 0.48.0.

答:
Replace @jit(nopython=True, target='cuda', boundscheck=False) with @jit</p>

```<code>import numpy as np
from numba import jit

N = int(1e8)
@jit
def Brownian_motions(T, N, corr):
    x = np.random.normal(0, 1, size=(T,N))
    z = np.random.normal(0, 1, size=(T,N))
    y = np.zeros(shape=(T,N))
    for i in range(T):
        for j in range(N):
            y[i,j] = corr*x[i,j] + np.sqrt(1.-corr**2)*z[i,j]
    return(x,y)

x, y = Brownian_motions(T = 500, N = N, corr = -0.45)
</code>```

Body:
I am trying to use Numba and access the GPU in order to accelerate the code, but I get the following error:

in jit raise NotImplementedError("bounds checking is not supported for CUDA")
NotImplementedError: bounds checking is not supported for CUDA

I saw that another question was raised, but not completely specified nor answered here.
I implemented the 2-for loops when I saw that the vectorized code (y = corr*x + np.sqrt(1.-corr**2)*z) did not work (same error). I also tried to play around with the option boundscheck, but this did not change the outcome.
The error did not appear when not specifying the target, since it goes on the CPU automatically (I guess).

import numpy as np
from numba import jit

N = int(1e8)
@jit(nopython=True, target='cuda', boundscheck=False)
def Brownian_motions(T, N, corr):
    x = np.random.normal(0, 1, size=(T,N))
    z = np.random.normal(0, 1, size=(T,N))
    y = np.zeros(shape=(T,N))
    for i in range(T):
        for j in range(N):
            y[i,j] = corr*x[i,j] + np.sqrt(1.-corr**2)*z[i,j]
    return(x,y)

x, y = Brownian_motions(T = 500, N = N, corr = -0.45)

Could you please help me? Python is 3.7.6 and Numba is 0.48.0.

Body:
Replace @jit(nopython=True, target='cuda', boundscheck=False) with @jit

import numpy as np
from numba import jit

N = int(1e8)
@jit
def Brownian_motions(T, N, corr):
    x = np.random.normal(0, 1, size=(T,N))
    z = np.random.normal(0, 1, size=(T,N))
    y = np.zeros(shape=(T,N))
    for i in range(T):
        for j in range(N):
            y[i,j] = corr*x[i,j] + np.sqrt(1.-corr**2)*z[i,j]
    return(x,y)

x, y = Brownian_motions(T = 500, N = N, corr = -0.45)


问:
Inheriting and overriding ostream operator in C++
I've been trying to find an answer to this, but no one seems to have exactly the same problem as I do.

I am working with several derived classes. The ostream operator << for each of these should print out some things common to each, and some things specific to each.  Later on, I would like to further derive from these derived classes, and again the new derived classes need to print out some things that are in the "generations" above them.

For example:

The Base class .h file

```<code>class Base

{

 int FirstClassNumber;

//The declaration I'm currently working with, that a friend gave me
//I'm pretty sure my problem lies here.

public:

friend ostream& operator << (ostream& os, const Base &base)
{
    base << os ;

    return os;
}

virtual void operator << (ostream& os) const = 0;

};
</code>```

The Base.cpp file includes these lines:

```<code>void Base::operator << (ostream& os)
{
  os << FirstClassNumber;
}
</code>```

Then I derive: (FirstDerived.h)

```<code>class FirstDerived : Public Base

{

int SecondClassNumber;

};
</code>```

FirstDerived.cpp:

```<code>FirstDerived::operator << (ostream& os)
{
  os <<

  "The first Number is:

 //This is the line that isn't working - someone else gave me this syntax

  << Base::operator<<

  << "The second number is"

  << SecondClassNumber;
}
</code>```

Then I want to derive:

```<code>class SecondDerived: Public FirstDerived
{

int ThirdClassNumber;

};
</code>```

Second.cpp:

```<code>FirstDerived::operator << (ostream& os)
{
  os <<

 FirstDerived::operator<<

 << "The third number is "

 << ThirdClassNumber;

 }
</code>```

I think the problem is most likely either the declaration in the very start of the program, or the lines like Base::operator<<.

Another possibility is that I'm not redeclaring it in the .h file of every inherited class.  Should I be, and if so what syntax should I use?

It was suggested to me to use the static_cast method, but my professor (the one who wrote the assignment, and therefore won't give us too much help with it) said that there's a better way to do it.  Any suggestions?

答:
Aside from what @Neil says, it would probably be better to implement a virtual DoStream method, so you don't need the upcasting:

```<code>class Base{
private:
  virtual void DoStream(ostream& os){
    // general stuff
  }
public:
  friend ostream& operator<<(ostream& os, Base& b){
    b.DoStream(os);
    return os;
  }
};

class Derived : public Base{
private:
  void DoStream(ostream& os){
    Base::DoStream(os);
    // derived specific stuff
  }
};
</code>```

So you only need to implement the operator once. You could also make the operator<< non-friend and the DoStream public, but that is probably personal preference.

ContentLicense: CC BY-SA 3.0

Body:
I've been trying to find an answer to this, but no one seems to have exactly the same problem as I do.

I am working with several derived classes. The ostream operator << for each of these should print out some things common to each, and some things specific to each.  Later on, I would like to further derive from these derived classes, and again the new derived classes need to print out some things that are in the "generations" above them.

For example:

The Base class .h file

class Base

{

 int FirstClassNumber;

//The declaration I'm currently working with, that a friend gave me
//I'm pretty sure my problem lies here.

public:

friend ostream& operator << (ostream& os, const Base &base)
{
    base << os ;

    return os;
}

virtual void operator << (ostream& os) const = 0;

};

The Base.cpp file includes these lines:

void Base::operator << (ostream& os)
{
  os << FirstClassNumber;
}

Then I derive: (FirstDerived.h)

class FirstDerived : Public Base

{

int SecondClassNumber;

};

FirstDerived.cpp:

FirstDerived::operator << (ostream& os)
{
  os <<

  "The first Number is:

 //This is the line that isn't working - someone else gave me this syntax

  << Base::operator<<

  << "The second number is"

  << SecondClassNumber;
}

Then I want to derive:

class SecondDerived: Public FirstDerived
{

int ThirdClassNumber;

};

Second.cpp:

FirstDerived::operator << (ostream& os)
{
  os <<

 FirstDerived::operator<<

 << "The third number is "

 << ThirdClassNumber;

 }

I think the problem is most likely either the declaration in the very start of the program, or the lines like Base::operator<<.

Another possibility is that I'm not redeclaring it in the .h file of every inherited class.  Should I be, and if so what syntax should I use?

It was suggested to me to use the static_cast method, but my professor (the one who wrote the assignment, and therefore won't give us too much help with it) said that there's a better way to do it.  Any suggestions?

Body:
Aside from what @Neil says, it would probably be better to implement a virtual DoStream method, so you don't need the upcasting:

class Base{
private:
  virtual void DoStream(ostream& os){
    // general stuff
  }
public:
  friend ostream& operator<<(ostream& os, Base& b){
    b.DoStream(os);
    return os;
  }
};

class Derived : public Base{
private:
  void DoStream(ostream& os){
    Base::DoStream(os);
    // derived specific stuff
  }
};

So you only need to implement the operator once. You could also make the operator<< non-friend and the DoStream public, but that is probably personal preference.


问:
Json parsing with dotted path in python
Is there any python library (PyPI) available from which I can parse json with :

```<code>1.  dot separated path
2.  order independant in case of array
</code>```

Data :

```<code>  "attr1": [
    {
      "attr2": "val2"
    },
    {
      "attr3": {
        "attr4": "val4"
      }
    }
  ]
}
</code>```

Here, I am having path such as 'attr1.attr3.attr4'. From which I need to get value 'val4'.
With the use of dotty dict library, I must provide position in case of array: 'attr1.1.attr3.attr4'. But position can vary. It may possible that 'attr3' comes first in 'attr1'.

So, is there any library available which can provide

```<code>1.  'val4' when I pass 'attr1.attr3.attr4' path  (Not 'attr1.1.attr3.attr4')
2.  'val2' when I pass 'attr1.attr2' (Not 'attr1.0.attr2')
</code>```

答:
you can recursively check for whether its a list or dict. And generate key depending upon whether its a dict or list.

This is hacky solution and I dont know whether this will work for your case. But here is my best try.

d = {
    "attr1": [
    {
      "attr2": "val2"
    },
    {
      "attr3": {
        "attr4": "val4"
      }
    }
  ]
}

l = dict()
def foo(x, z):
    if isinstance(x, list):
        for val in x:
            foo(val, z)
    elif isinstance(x, dict):
        for k,v in x.items():
            foo(v, z+"."+k)
    else:
        l[z[1:]] = x

foo(d, "")

print(l['attr1.attr2'])
print(l['attr1.attr3.attr4'])
```

output

val2

  val4

Title: Json parsing with dotted path in python

Body:
Is there any python library (PyPI) available from which I can parse json with :

1.  dot separated path
2.  order independant in case of array

Data :

  "attr1": [
    {
      "attr2": "val2"
    },
    {
      "attr3": {
        "attr4": "val4"
      }
    }
  ]
}

Here, I am having path such as 'attr1.attr3.attr4'. From which I need to get value 'val4'.
With the use of dotty dict library, I must provide position in case of array: 'attr1.1.attr3.attr4'. But position can vary. It may possible that 'attr3' comes first in 'attr1'.

So, is there any library available which can provide

1.  'val4' when I pass 'attr1.attr3.attr4' path  (Not 'attr1.1.attr3.attr4')
2.  'val2' when I pass 'attr1.attr2' (Not 'attr1.0.attr2')

Body:
you can recursively check for whether its a list or dict. And generate key depending upon whether its a dict or list.

This is hacky solution and I dont know whether this will work for your case. But here is my best try.

d = {
    "attr1": [
    {
      "attr2": "val2"
    },
    {
      "attr3": {
        "attr4": "val4"
      }
    }
  ]
}

l = dict()
def foo(x, z):
    if isinstance(x, list):
        for val in x:
            foo(val, z)
    elif isinstance(x, dict):
        for k,v in x.items():
            foo(v, z+"."+k)
    else:
        l[z[1:]] = x

foo(d, "")

print(l['attr1.attr2'])
print(l['attr1.attr3.attr4'])

output

val2

  val4


问:
I am trying to run an if else function when two variables equal each other
I am trying to make a program where it asks for 2 names, and if they are the same they run an if function. However I can't make this work. I have this so far:

Vote = input("Judge 1 vote: ")
Vote_1 = input("Judge 2 vote: ")

if Vote == Vote_1
    print("Announce the winner.")
else
    print("Ask for a third judge.")
```

if Vote == Vote_1 is my problem area. I can't get it to work. Please help me.

答:
Syntax errror on line that if vote == vote_1. Please try the following.

```<code>vote = input("Judge 1 vote: ");
vote_1 = input("Judge 2 vote: ");

if vote == vote_1:
    print("Announce the winner")
else:
    print("Ask for a third judge")
</code>```

Body:
I am trying to make a program where it asks for 2 names, and if they are the same they run an if function. However I can't make this work. I have this so far:

Vote = input("Judge 1 vote: ")
Vote_1 = input("Judge 2 vote: ")

if Vote == Vote_1
    print("Announce the winner.")
else
    print("Ask for a third judge.")

if Vote == Vote_1 is my problem area. I can't get it to work. Please help me.

Body:
Syntax errror on line that if vote == vote_1. Please try the following.

vote = input("Judge 1 vote: ");
vote_1 = input("Judge 2 vote: ");

if vote == vote_1:
    print("Announce the winner")
else:
    print("Ask for a third judge")


问:
ag-Grid header styles not changing with CSS on component
I'm using ag-Grid on my application and I have it ruining fine with the default theme (ag-theme-balham).

On one specific component I want to change the header background color, but when I add the CSS on my component.scss file nothing happens.

I added the ag-Grid css on my angular-cli.json file

```<code>  "styles": [
    "../node_modules/font-awesome/scss/font-awesome.scss",
    "../node_modules/ag-grid/dist/styles/ag-grid.css",
    "../node_modules/ag-grid/dist/styles/ag-theme-balham.css",
    "styles.scss"
  ],
</code>```

On component.scss file I have the following CSS

```<code>.ag-theme-balham .ag-header {
    background-color: #e0e0e0;
}
</code>```

But nothing happens, and the color does not get applied to the header.

答:
Override background-color with !important.

That is:

```<code>:host {
    ::ng-deep { background-color: }
</code>```

Body:
I'm using ag-Grid on my application and I have it ruining fine with the default theme (ag-theme-balham).

On one specific component I want to change the header background color, but when I add the CSS on my component.scss file nothing happens.

I added the ag-Grid css on my angular-cli.json file

  "styles": [
    "../node_modules/font-awesome/scss/font-awesome.scss",
    "../node_modules/ag-grid/dist/styles/ag-grid.css",
    "../node_modules/ag-grid/dist/styles/ag-theme-balham.css",
    "styles.scss"
  ],

On component.scss file I have the following CSS

.ag-theme-balham .ag-header {
    background-color: #e0e0e0;
}

But nothing happens, and the color does not get applied to the header.

Body:
Override background-color with !important.

That is:

:host {
    ::ng-deep { background-color: }


问:
How can I add required validation on filepond vue?
I read on this docs : https://github.com/pqina/vue-filepond

I try to add like this  :

```<code><FilePond
    allowMultiple="true"
    accepted-file-types="image/jpg, image/jpeg, application/pdf"
    maxFileSize="2MB"
    required="true"/>
</code>```

multiple, validation file type, max file works

But, required does not works

How can I solve this problem guys?

答:
Using the v-bind:required prop works:

```<code><form method="post" action="">
    <file-pond v-bind:required="true"/>
    <button type="submit">submit</button>
</form>
</code>```

Related GitHub issue: https://github.com/pqina/vue-filepond/issues/138

Body:
I read on this docs : https://github.com/pqina/vue-filepond

I try to add like this  :

<FilePond
    allowMultiple="true"
    accepted-file-types="image/jpg, image/jpeg, application/pdf"
    maxFileSize="2MB"
    required="true"/>

multiple, validation file type, max file works

But, required does not works

How can I solve this problem guys?

Body:
Using the v-bind:required prop works:

<form method="post" action="">
    <file-pond v-bind:required="true"/>
    <button type="submit">submit</button>
</form>

Related GitHub issue: https://github.com/pqina/vue-filepond/issues/138


问:
java.lang.NullPointerException on spring boot
i have created a simple java class in spring boot application. calling a method  ns.mesage(); from two different methods but one is executed and another one throw an null pointer exception.</p>

```<code>package TestPackage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/*
import TestPackage.MorningService;
import TestPackage.NightService;*/

@RestController
public class GenerateMessage {

    @Autowired
    public MorningService ms;

    @Autowired
    public NightService ns;

    @RequestMapping(path = "/test")
    public String starter(){
        GenerateMessage gm=new GenerateMessage();
        ns.mesage(); // this call working fine

        gm.mes();
        return "Mail scheduled.";
    }

public void mes(){
    try{
    System.out.println("starts2..............");
    ns.mesage(); // throwing an exception
    }catch(Exception e){
        e.printStackTrace();
    }
}
}
</code>```

答:
Once you're using the new keyword, you're breaking all the injections used with @Autowired(it means that the MorningService and NightService will not be initialized) , that is why you're getting a NPE.

If you really want to test your mes() method from your controller, implement in your @SpringBootApplication class the CommandLineRunner interface.

Then you can inject a GenerateMessage bean with @Autowired and test your method.

Here is an example:

```<code>@SpringBootApplication
public class MainApplication implements CommandLineRunner {

 @Autowired
 private GenerateMessage generateMessage;

 public static void main(String[] args) {
    SpringApplication.run(MainApplication.class, args);
 }

 @Override
 public void run(String... args) throws Exception {
    generateMessage.mes();
 }
}
</code>```

Body:
i have created a simple java class in spring boot application. calling a method  ns.mesage(); from two different methods but one is executed and another one throw an null pointer exception.

package TestPackage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/*
import TestPackage.MorningService;
import TestPackage.NightService;*/

@RestController
public class GenerateMessage {

    @Autowired
    public MorningService ms;

    @Autowired
    public NightService ns;

    @RequestMapping(path = "/test")
    public String starter(){
        GenerateMessage gm=new GenerateMessage();
        ns.mesage(); // this call working fine

        gm.mes();
        return "Mail scheduled.";
    }

public void mes(){
    try{
    System.out.println("starts2..............");
    ns.mesage(); // throwing an exception
    }catch(Exception e){
        e.printStackTrace();
    }
}
}

Body:
Once you're using the new keyword, you're breaking all the injections used with @Autowired(it means that the MorningService and NightService will not be initialized) , that is why you're getting a NPE.

If you really want to test your mes() method from your controller, implement in your @SpringBootApplication class the CommandLineRunner interface.

Then you can inject a GenerateMessage bean with @Autowired and test your method.

Here is an example:

@SpringBootApplication
public class MainApplication implements CommandLineRunner {

 @Autowired
 private GenerateMessage generateMessage;

 public static void main(String[] args) {
    SpringApplication.run(MainApplication.class, args);
 }

 @Override
 public void run(String... args) throws Exception {
    generateMessage.mes();
 }
}


答:
First of all you have take an input and give it to a variable like this:

```<code>1st_person = input("judge 1 vote")
2nd_person = input("Judge 2 vote")
</code>```

Now you can run any statement on both these variable for example:

```<code>if 1st_person == 2nd_person:
   print("Third judge is required!")
else:
   print("Announce the winner!")
</code>```

I dont knwo what you are trying to achieve with this program, because it doesn't make any sense to caompare two names and then announce a winner but still i made it for you, but in case if your question is not clear ask me a question

Title: I am trying to run an if else function when two variables equal each other

Body:
First of all you have take an input and give it to a variable like this:

1st_person = input("judge 1 vote")
2nd_person = input("Judge 2 vote")

Now you can run any statement on both these variable for example:

if 1st_person == 2nd_person:
   print("Third judge is required!")
else:
   print("Announce the winner!")

I dont knwo what you are trying to achieve with this program, because it doesn't make any sense to caompare two names and then announce a winner but still i made it for you, but in case if your question is not clear ask me a question


问:
How to grab an attachment url from a specific channel?
I've got the following code and right now it's grabbing all attachments from any channel and sending it in the channel "luv" as an embed. I want it to only grab attachments from the "luv" channel and post the embed in "luv" also. Any help?</p>

```<code>  client.on("message", async (message) => {
    const channel = message.guild.channels.find(channel => channel.name === "luv");
    if (!channel) return;
    message.attachments.forEach(attachment => { // do something with the attachment // changes all attachements into embed #luv
      if (message.deletable) {
        message.delete(1000)
        const url = attachment.url;
        const aesEmbed = new RichEmbed()
        .setImage(attachment.url)

        client.channels.get("678987398838747166").send(aesEmbed);
        console.log(attachment.url);
        }
      })
    });
</code>```

答:
You can check message channel ID or name for that.

client.on("message", async (message) => {
    if (message.channel.id !== 'PLACE CHANNEL ID HERE') return //Stop function if channel ID !== 'luv' channeld.id
    const channel = message.guild.channels.find(channel => channel.name === "luv");
    if (!channel) return;
    message.attachments.forEach(attachment => { // do something with the attachment // changes all attachements into embed #luv
        if (message.deletable) {
            message.delete(1000)
            const url = attachment.url;
            const aesEmbed = new RichEmbed()
                .setImage(attachment.url)
            client.channels.get("678987398838747166")
                .send(aesEmbed);
            console.log(attachment.url);
        }
    })
});
```

<p>And realy better dont use <code>find by name</code> method to get channel.</p>

<p>Replace </p>

```const channel = message.guild.channels.find(channel => channel.name === "luv");
```

<p>To</p>

<pre class="lang-js prettyprint-override"><code>const channel = message.guild.channels.get('CHANNEL ID')
</code>```

Body:
I've got the following code and right now it's grabbing all attachments from any channel and sending it in the channel "luv" as an embed. I want it to only grab attachments from the "luv" channel and post the embed in "luv" also. Any help?

  client.on("message", async (message) => {
    const channel = message.guild.channels.find(channel => channel.name === "luv");
    if (!channel) return;
    message.attachments.forEach(attachment => { // do something with the attachment // changes all attachements into embed #luv
      if (message.deletable) {
        message.delete(1000)
        const url = attachment.url;
        const aesEmbed = new RichEmbed()
        .setImage(attachment.url)

        client.channels.get("678987398838747166").send(aesEmbed);
        console.log(attachment.url);
        }
      })
    });

Body:
You can check message channel ID or name for that.

client.on("message", async (message) => {
    if (message.channel.id !== 'PLACE CHANNEL ID HERE') return //Stop function if channel ID !== 'luv' channeld.id
    const channel = message.guild.channels.find(channel => channel.name === "luv");
    if (!channel) return;
    message.attachments.forEach(attachment => { // do something with the attachment // changes all attachements into embed #luv
        if (message.deletable) {
            message.delete(1000)
            const url = attachment.url;
            const aesEmbed = new RichEmbed()
                .setImage(attachment.url)
            client.channels.get("678987398838747166")
                .send(aesEmbed);
            console.log(attachment.url);
        }
    })
});

And realy better dont use find by name method to get channel.

Replace

const channel = message.guild.channels.find(channel => channel.name === "luv");

To

const channel = message.guild.channels.get('CHANNEL ID')


问:
Running a stored procedure with NodeJS and MSSQL package error
Im trying to get the MSSQL nodejs package to return the results of a stored procedure from Microsoft SQL server using the code below. However the error I get is...

```<code>[TypeError: Cannot read property 'type' of undefined]
</code>```

I'm not sure I have done the inputs correctly as I couldn't find an example with more than one input anywhere online.

Any ideas?

```<code>exports.executeSqlStoredProd = function (callback) {
    var conn = new sqlDb.Connection(settings.dbConfig)
    conn.connect().then(function () {
        var req = new sqlDb.Request(conn);
        req.input('ProductEntryID', req.Int, 3299);
        req.input('LoginEntryID', req.Int, 4);
        req.input('TempLoginEntryId', req.Int, -1);
        req.input('AddToWishList', req.Bit, 0);
        req.input('WebPortalId', req.Int, 0);
        req.execute('J_ViewAProduct').then(function(err, recordsets) {
        console.log(recordsets);
        callback(recordsets)
    })}).catch(function(err){
        console.log(err);
        callback(null, err);
    });
}
</code>```

I did the request sucessfully using the package "Seriate" but would prefer to use mssql. The code that worked for "Seriate" is below.

```<code>exports.getVAP = function(req, resp, pid) {
    sql.execute({
        procedure: "J_ViewAProduct",
        params: {
            ProductEntryID: {
                type: sql.INT,
                val: pid
            },
            LoginEntryID: {
                type: sql.Int,
                val: 4
            },
            TempLoginEntryId: {
                type: sql.Int,
                val: -1
            },
            AddToWishList: {
                type: sql.Bit,
                val: 0
            },
            WebPortalId: {
                type: sql.Int,
                val: 0
            }
        }
    }).then(function(results){
        console.log(results)
        httpMsgs.sendJSON(req, resp, results)
        //httpMsgs.sendJSON(req, resp, results[0])
        resp.end();
    }), function(err){
        httpMsgs.show500(req, resp, err)
    }

};
</code>```

答:
I don't know if this would be helpful or not but this is how I did

let executeQuery = async (value, country) => {
    try {
        let pool = await sql.connect(dbConfig);
        let results = await pool.request()
            .input('input_parameter', sql.Int, value)
            .input('Country', sql.VarChar(50), country)
            // .output('output_parameter', sql.VarChar(50))
            .execute('procedure_name')

        console.dir(results);

    } catch (err) {
        res.json({
            "error": true,
            "message": "Error executing query"
        })
    }
}

executeQuery(value, country);
```

I've used async and await method to make it more readable.

Body:
Im trying to get the MSSQL nodejs package to return the results of a stored procedure from Microsoft SQL server using the code below. However the error I get is...

[TypeError: Cannot read property 'type' of undefined]

I'm not sure I have done the inputs correctly as I couldn't find an example with more than one input anywhere online.

Any ideas?

exports.executeSqlStoredProd = function (callback) {
    var conn = new sqlDb.Connection(settings.dbConfig)
    conn.connect().then(function () {
        var req = new sqlDb.Request(conn);
        req.input('ProductEntryID', req.Int, 3299);
        req.input('LoginEntryID', req.Int, 4);
        req.input('TempLoginEntryId', req.Int, -1);
        req.input('AddToWishList', req.Bit, 0);
        req.input('WebPortalId', req.Int, 0);
        req.execute('J_ViewAProduct').then(function(err, recordsets) {
        console.log(recordsets);
        callback(recordsets)
    })}).catch(function(err){
        console.log(err);
        callback(null, err);
    });
}

I did the request sucessfully using the package "Seriate" but would prefer to use mssql. The code that worked for "Seriate" is below.

exports.getVAP = function(req, resp, pid) {
    sql.execute({
        procedure: "J_ViewAProduct",
        params: {
            ProductEntryID: {
                type: sql.INT,
                val: pid
            },
            LoginEntryID: {
                type: sql.Int,
                val: 4
            },
            TempLoginEntryId: {
                type: sql.Int,
                val: -1
            },
            AddToWishList: {
                type: sql.Bit,
                val: 0
            },
            WebPortalId: {
                type: sql.Int,
                val: 0
            }
        }
    }).then(function(results){
        console.log(results)
        httpMsgs.sendJSON(req, resp, results)
        //httpMsgs.sendJSON(req, resp, results[0])
        resp.end();
    }), function(err){
        httpMsgs.show500(req, resp, err)
    }

};

Body:
I don't know if this would be helpful or not but this is how I did

let executeQuery = async (value, country) => {
    try {
        let pool = await sql.connect(dbConfig);
        let results = await pool.request()
            .input('input_parameter', sql.Int, value)
            .input('Country', sql.VarChar(50), country)
            // .output('output_parameter', sql.VarChar(50))
            .execute('procedure_name')

        console.dir(results);

    } catch (err) {
        res.json({
            "error": true,
            "message": "Error executing query"
        })
    }
}

executeQuery(value, country);

I've used async and await method to make it more readable.


问:
Is it possible to extract prefix from router in express.js?
I was wondering if it is possible to extract prefix from Router in express.js.

Here is my index.js file:

```<code>const express = require("express");
const router = express.Router();

const admin = require("./admin");
const home = require("./home");

router.use("/admin", admin);
router.use("/", home);

// Catch All Other Pages
router.get("*", (req, res) => {
  res.render("404", { title: "404 Not Found" });
});

module.exports = router;

</code>```

Here is my admin routes file:

```<code>const express = require("express");
const router = express.Router();

router.get("/", function(req, res) {
  res.render("admin", { title: "Admin Menu" });
});

router.get("/settings", function(req, res) {
  res.render("admin/settings", { title: "Admin Menu | Settings" });
});

router.get("/logout", function(req, res) {
  //handle logout logic
  res.redirect("/");
});

module.exports = router;

</code>```

In the index.js file I have set prefix to be '/admin';

Can I know extract this prefix in the admin.js file?
Like for example:

```<code>const express = require("express");
const router = express.Router();

// Require prefix
const prefix = router.getPrexix()?

router.get("/", function(req, res) {
  res.render("admin", { title: "Admin Menu", prefix });
});

router.get("/settings", function(req, res) {
  res.render("admin/settings", { title: "Admin Menu | Settings", prefix });
});

router.get("/logout", function(req, res) {
  //handle logout logic
  res.redirect("/");
});

module.exports = router;

</code>```

Would it be possible to do this?
I could reuse '/admin' in the pug templates.

答:
In Express, req.baseUrl is the URL that the router was mounted on which would be "/admin" in your case.

And, you have req.path which is what the route matched.

And, you have req.originalUrl is the original URL so you can always use this in combination with either of the above to see the whole picture.

Here's a little example to illustrate:

```<code>const express = require('express');
const app = express();

const router = express.Router();

router.get("/new", (req, res) => {
    console.log("baseUrl", req.baseUrl);                // "/admin"
    console.log("path", req.path)                       // "/new"
    console.log("originalUrl", req.originalUrl);        // "/admin/new"
    res.send("new");
});

app.use("/admin", router);

app.listen(80);
</code>```

Body:
I was wondering if it is possible to extract prefix from Router in express.js.

Here is my index.js file:

const express = require("express");
const router = express.Router();

const admin = require("./admin");
const home = require("./home");

router.use("/admin", admin);
router.use("/", home);

// Catch All Other Pages
router.get("*", (req, res) => {
  res.render("404", { title: "404 Not Found" });
});

module.exports = router;

Here is my admin routes file:

const express = require("express");
const router = express.Router();

router.get("/", function(req, res) {
  res.render("admin", { title: "Admin Menu" });
});

router.get("/settings", function(req, res) {
  res.render("admin/settings", { title: "Admin Menu | Settings" });
});

router.get("/logout", function(req, res) {
  //handle logout logic
  res.redirect("/");
});

module.exports = router;

In the index.js file I have set prefix to be '/admin';

Can I know extract this prefix in the admin.js file?
Like for example:

const express = require("express");
const router = express.Router();

// Require prefix
const prefix = router.getPrexix()?

router.get("/", function(req, res) {
  res.render("admin", { title: "Admin Menu", prefix });
});

router.get("/settings", function(req, res) {
  res.render("admin/settings", { title: "Admin Menu | Settings", prefix });
});

router.get("/logout", function(req, res) {
  //handle logout logic
  res.redirect("/");
});

module.exports = router;

Would it be possible to do this?
I could reuse '/admin' in the pug templates.

Body:
In Express, req.baseUrl is the URL that the router was mounted on which would be "/admin" in your case.

And, you have req.path which is what the route matched.

And, you have req.originalUrl is the original URL so you can always use this in combination with either of the above to see the whole picture.

Here's a little example to illustrate:

const express = require('express');
const app = express();

const router = express.Router();

router.get("/new", (req, res) => {
    console.log("baseUrl", req.baseUrl);                // "/admin"
    console.log("path", req.path)                       // "/new"
    console.log("originalUrl", req.originalUrl);        // "/admin/new"
    res.send("new");
});

app.use("/admin", router);

app.listen(80);


问:
Regex for ESI Number
I need a regex in C# for below mentioned number

```<code>31–00–123456–000–0001
</code>```

I am having a problem putting the dash in the regex. The number validation is pretty fine.

Title: Regex for ESI Number

Body:
I need a regex in C# for below mentioned number

31–00–123456–000–0001

I am having a problem putting the dash in the regex. The number validation is pretty fine.

Body:
Is this what you need?

(\d{2})[\–\-](\d{2})[\–\-](\d{6})[\–\-](\d{3})[\–\-](\d{4})

So, if you already have code extracted to string variable code and want to check that it  matches then use ^ and $ like here:

^(\d{2})[\–\-](\d{2})[\–\-](\d{6})[\–\-](\d{3})[\–\-](\d{4})$

According to comments, its better to use [0-9] to reduce other types of degets.

^([0-9]{2})[\–\-]([0-9]{2})[\–\-]([0-9]{6})[\–\-]([0-9]{3})[\–\-]([0-9]{4})$


答:
You are missing the colons : in the if and else lines.

vote_1 = input("Judge 1 vote: ")
vote_2 = input("Judge 2 vote: ")

if vote_1 == vote_2:
    print("Announce the winner.")
else:
    print("Ask for a third judge.")
```

TIPS

Variable names (and function names) in Python follow the snake_case, CamelCase is reserved for class names.

input reads the data from the console as a string, if you want to compare it properly you should probably cast them to integers or floats.

Variable names should be descriptive, if you have two votes, vote for the first and vote_1 for the second is confusing.

Body:
I am trying to make a program where it asks for 2 names, and if they are the same they run an if function. However I can't make this work. I have this so far:

Vote = input("Judge 1 vote: ")
Vote_1 = input("Judge 2 vote: ")

if Vote == Vote_1
    print("Announce the winner.")
else
    print("Ask for a third judge.")

if Vote == Vote_1 is my problem area. I can't get it to work. Please help me.

Body:
You are missing the colons : in the if and else lines.

vote_1 = input("Judge 1 vote: ")
vote_2 = input("Judge 2 vote: ")

if vote_1 == vote_2:
    print("Announce the winner.")
else:
    print("Ask for a third judge.")

TIPS

Variable names (and function names) in Python follow the snake_case, CamelCase is reserved for class names.

input reads the data from the console as a string, if you want to compare it properly you should probably cast them to integers or floats.

Variable names should be descriptive, if you have two votes, vote for the first and vote_1 for the second is confusing.


问:
How to substring one by one in one button in php?
How to substring one by one in one button in php ?
Example:
$myvar="abc";
i need one button when click 1 time=display a, click 2time display b, and click 3time
display c. click how many time ?depend on string of $myvar.

Best regards

答:
Oh, i made a mistake.
the semicolon at the end of "n = (n + 1) % 3" is not correct!(i carelessly used a chinese semicolon instead...)

```<code>var str = 'abc';
var n = 0;
var btn = document.getElementById('Btn');

btn.onclick = function() {
    alert(str.substring(n, n + 1));
    n = (n + 1) % 3;
};
</code>```

this piece might be OK.

Body:
Oh, i made a mistake.
the semicolon at the end of "n = (n + 1) % 3" is not correct!(i carelessly used a chinese semicolon instead...)

var str = 'abc';
var n = 0;
var btn = document.getElementById('Btn');

btn.onclick = function() {
    alert(str.substring(n, n + 1));
    n = (n + 1) % 3;
};

this piece might be OK.


问:
Splitting of an RGB image to R G B using OpenCv Python
When i am splitting my image I am not getting the frames in colors of Red,Green,Blue. The frames I got in output are three Gray color images.</p>

```<code>import numpy as np
import cv2
img=cv2.imread("C:\\Users\\Pavan\\Desktop\\bird.jpg")
#display an image
cv2.imshow('image',img)
b,g,r=cv2.split(img)
cv2.imshow('b',b)
cv2.imshow('g',g)
cv2.imshow('r',r)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

答:
Try writing your output and calling that particular variable as the example given;

Blue = cv2.imwrite('blue_channel.jpg', b)

cv2.imshow('Blue Channel, Blue)

Body:
When i am splitting my image I am not getting the frames in colors of Red,Green,Blue. The frames I got in output are three Gray color images.

import numpy as np
import cv2
img=cv2.imread("C:\\Users\\Pavan\\Desktop\\bird.jpg")
#display an image
cv2.imshow('image',img)
b,g,r=cv2.split(img)
cv2.imshow('b',b)
cv2.imshow('g',g)
cv2.imshow('r',r)
cv2.waitKey(0)
cv2.destroyAllWindows()