问:
ARM-v8 NEON: is there an instruction to split a single normal register across multiple lanes of a NEON register?
I'm new to ARM-v8 (AArch64) and only did a little bit of NEON coding in ARM-v7 (but I'm very comfortable with A32 and ok(*) with normal A64).

Ultimately what I'm trying to do is count the frequency of each set bit [31:0] in a bunch (up to 15) of 32-bit values. I.e in these 15 values, how many times is bit 0 set, how many times is bit 1 set, etc.

So, what I'd like to do is split the 32 bits over 32 nibbles in a 128 bit NEON register and then accumulate the NEON register, like this:

```<code>// args(x0: ptr to array of 16 32-bit words) ret(v0: sum of set bits as 32 nibbles)

   mov     w2, 16                     // w2: loop counter
   mov     v0, 0                      // v0: accumulate count
1:
   ldr     w1, [x0], 4
   split   v1, w1                     // here some magic occurs
   add     v0.16b, v0.16b, v1.16b
   subs    w2, w2, 1
   bne     1b
</code>```

I'm not having much luck with the ARM documentation. The ARMv8-ARM just has an alphabetical listing of the 354 NEON instructions, (800 pages of pseudocode). The ARMv8-A Programmer's guide only has 14 pages of introduction and the enticing statement "New lane insert and extract instructions have been added to support the new register packing scheme." And the NEON Programmer's Guide is about ARM-v7.

Assuming there isn't a single instruction to do that, what would be the most efficient way of doing it? -- Not looking for a complete solution, but can NEON help at all? There wouldn't be much point if I have to load each lane separately...

(*) Can't say I like A64 though. :-(

答:
Combining the above answers, and modifying my requirements ;-) I came up with:

```<code>tst:
    ldr     x0, =test_data
    ldr     x1, =mask
    ld1     {v2.2d}, [x1]                       // ld1.2d       v2, [x1]        // load 2 * 64 = 128 bits
    movi    v0.16b, 0
    mov     w2, 8
1:
    ld1r    {v1.8h}, [x0], 2                    // ld1r.8h      v1, [x0], 2     // repeat one 16-bit word across eight 16-bit lanes
    cmtst   v1.16b, v1.16b, v2.16b              // cmtst.16b    v1, v1, v2      // sets -1 in each 8bit word of 16 8-bit lanes if input matches mask
    sub     v0.16b, v0.16b, v1.16b              // sub.16b      v0, v0, v1      // sub -1 = add +1
    subs    w2, w2, 1
    bne     1b

    // v0 contains 16 bytes, mildly shuffled.
</code>```

If one wants them unshuffled:

```<code>    mov     v1.d[0], v0.d[1]
    uzp1    v2.8b, v0.8b, v1.8b
    uzp2    v3.8b, v0.8b, v1.8b
    mov     v2.d[1], v3.d[0]

    // v2 contains 16 bytes, in order.

</code>```

The following counts up to fifteen samples with 32 bits (accumulating in 32 nibbles):

```<code>tst2:
    ldr     x0, =test_data2
    ldr     x1, =mask2
    ld1     {v2.4s, v3.4s, v4.4s, v5.4s}, [x1]  // ld1.4s       {v2, v3, v4, v5}, [x1]
    movi    v0.16b, 0
    mov     w2, 8
1:
    ld1r    {v1.4s}, [x0], 4                    // ld1r.4s      v1, [x0], 4     // repeat one 32-bit word across four 32-bit lanes
    cmtst   v6.16b, v1.16b, v2.16b              // cmtst.16b    v6, v1, v2      // upper nibbles
    cmtst   v1.16b, v1.16b, v3.16b              // cmtst.16b    v1, v1, v3      // lower nibbles
    and     v6.16b, v6.16b, v4.16b              // and.16b      v6, v6, v4      // upper inc        0001.0000 x 16
    and     v1.16b, v1.16b, v5.16b              // and.16b      v1, v1, v5      // lower inc        0000.0001 x 16
    orr     v1.16b, v1.16b, v6.16b              // orr.16b      v1, v1, v6
    add     v0.16b, v0.16b, v1.16b              // add.16b      v0, v0, v1      // accumulate
    subs    w2, w2, 1
    bne     1b

    // v0 contains 32 nibbles -- somewhat shuffled, but that's ok.

// fedcba98.76543210.fedcba98.76543210.fedcba98.76543210.fedcba98.76543210 fedcba98.76543210.fedcba98.76543210.fedcba98.76543210.fedcba98.76543210
// 10000000.10000000.01000000.01000000.00100000.00100000.00010000.00010000 00001000.00001000.00000100.00000100.00000010.00000010.00000001.00000001
// f        7         e        6         d        5         c        4         b        3         a        2         9        1         8        0

mask:
    .quad   0x0808040402020101
    .quad   0x8080404020201010

test_data:
    .hword 0x0103
    .hword 0x0302
    .hword 0x0506
    .hword 0x080A
    .hword 0x1010
    .hword 0x2020
    .hword 0xc040
    .hword 0x8080

// FEDCBA98.76543210.fedcba⁹⁸.⁷⁶⁵⁴³²¹⁰.FEDCBA98.76543210.fedcba⁹⁸.⁷⁶⁵⁴³²¹⁰.FEDCBA98.76543210.fedcba⁹⁸.⁷⁶⁵⁴³²¹⁰.FEDCBA98.76543210.fedcba⁹⁸.⁷⁶⁵⁴³²¹⁰
// 10001000 10001000 10001000 10001000 01000100 01000100 01000100 01000100 00100010 00100010 00100010 00100010 00010001 00010001 00010001 00010001
// F   B    7   3    f   b    ⁷   ³     E   A    6   2    e   a    ⁶   ²     D   9    5   1    d   ⁹    ⁵   ¹     C   8    4   0    c   ⁸    ⁴   ⁰

mask2:
    .quad   0x8080808040404040  // v2
    .quad   0x2020202010101010
    .quad   0x0808080804040404  // v3
    .quad   0x0202020201010101
    .quad   0x1010101010101010  // v4
    .quad   0x1010101010101010
    .quad   0x0101010101010101  // v5
    .quad   0x0101010101010101

test_data2:
    .word 0xff000103
    .word 0xff000302
    .word 0xff000506
    .word 0xff00080A
    .word 0xff001010
    .word 0xff002020
    .word 0xff00c040
    .word 0xff008080
</code>```

Body:
I'm new to ARM-v8 (AArch64) and only did a little bit of NEON coding in ARM-v7 (but I'm very comfortable with A32 and ok(*) with normal A64).

Ultimately what I'm trying to do is count the frequency of each set bit [31:0] in a bunch (up to 15) of 32-bit values. I.e in these 15 values, how many times is bit 0 set, how many times is bit 1 set, etc.

So, what I'd like to do is split the 32 bits over 32 nibbles in a 128 bit NEON register and then accumulate the NEON register, like this:

// args(x0: ptr to array of 16 32-bit words) ret(v0: sum of set bits as 32 nibbles)

   mov     w2, 16                     // w2: loop counter
   mov     v0, 0                      // v0: accumulate count
1:
   ldr     w1, [x0], 4
   split   v1, w1                     // here some magic occurs
   add     v0.16b, v0.16b, v1.16b
   subs    w2, w2, 1
   bne     1b

I'm not having much luck with the ARM documentation. The ARMv8-ARM just has an alphabetical listing of the 354 NEON instructions, (800 pages of pseudocode). The ARMv8-A Programmer's guide only has 14 pages of introduction and the enticing statement "New lane insert and extract instructions have been added to support the new register packing scheme." And the NEON Programmer's Guide is about ARM-v7.

Assuming there isn't a single instruction to do that, what would be the most efficient way of doing it? -- Not looking for a complete solution, but can NEON help at all? There wouldn't be much point if I have to load each lane separately...

(*) Can't say I like A64 though. :-(

Body:
Combining the above answers, and modifying my requirements ;-) I came up with:

tst:
    ldr     x0, =test_data
    ldr     x1, =mask
    ld1     {v2.2d}, [x1]                       // ld1.2d       v2, [x1]        // load 2 * 64 = 128 bits
    movi    v0.16b, 0
    mov     w2, 8
1:
    ld1r    {v1.8h}, [x0], 2                    // ld1r.8h      v1, [x0], 2     // repeat one 16-bit word across eight 16-bit lanes
    cmtst   v1.16b, v1.16b, v2.16b              // cmtst.16b    v1, v1, v2      // sets -1 in each 8bit word of 16 8-bit lanes if input matches mask
    sub     v0.16b, v0.16b, v1.16b              // sub.16b      v0, v0, v1      // sub -1 = add +1
    subs    w2, w2, 1
    bne     1b

    // v0 contains 16 bytes, mildly shuffled.

If one wants them unshuffled:

    mov     v1.d[0], v0.d[1]
    uzp1    v2.8b, v0.8b, v1.8b
    uzp2    v3.8b, v0.8b, v1.8b
    mov     v2.d[1], v3.d[0]

    // v2 contains 16 bytes, in order.

The following counts up to fifteen samples with 32 bits (accumulating in 32 nibbles):

tst2:
    ldr     x0, =test_data2
    ldr     x1, =mask2
    ld1     {v2.4s, v3.4s, v4.4s, v5.4s}, [x1]  // ld1.4s       {v2, v3, v4, v5}, [x1]
    movi    v0.16b, 0
    mov     w2, 8
1:
    ld1r    {v1.4s}, [x0], 4                    // ld1r.4s      v1, [x0], 4     // repeat one 32-bit word across four 32-bit lanes
    cmtst   v6.16b, v1.16b, v2.16b              // cmtst.16b    v6, v1, v2      // upper nibbles
    cmtst   v1.16b, v1.16b, v3.16b              // cmtst.16b    v1, v1, v3      // lower nibbles
    and     v6.16b, v6.16b, v4.16b              // and.16b      v6, v6, v4      // upper inc        0001.0000 x 16
    and     v1.16b, v1.16b, v5.16b              // and.16b      v1, v1, v5      // lower inc        0000.0001 x 16
    orr     v1.16b, v1.16b, v6.16b              // orr.16b      v1, v1, v6
    add     v0.16b, v0.16b, v1.16b              // add.16b      v0, v0, v1      // accumulate
    subs    w2, w2, 1
    bne     1b

    // v0 contains 32 nibbles -- somewhat shuffled, but that's ok.

// fedcba98.76543210.fedcba98.76543210.fedcba98.76543210.fedcba98.76543210 fedcba98.76543210.fedcba98.76543210.fedcba98.76543210.fedcba98.76543210
// 10000000.10000000.01000000.01000000.00100000.00100000.00010000.00010000 00001000.00001000.00000100.00000100.00000010.00000010.00000001.00000001
// f        7         e        6         d        5         c        4         b        3         a        2         9        1         8        0

mask:
    .quad   0x0808040402020101
    .quad   0x8080404020201010

test_data:
    .hword 0x0103
    .hword 0x0302
    .hword 0x0506
    .hword 0x080A
    .hword 0x1010
    .hword 0x2020
    .hword 0xc040
    .hword 0x8080

// FEDCBA98.76543210.fedcba⁹⁸.⁷⁶⁵⁴³²¹⁰.FEDCBA98.76543210.fedcba⁹⁸.⁷⁶⁵⁴³²¹⁰.FEDCBA98.76543210.fedcba⁹⁸.⁷⁶⁵⁴³²¹⁰.FEDCBA98.76543210.fedcba⁹⁸.⁷⁶⁵⁴³²¹⁰
// 10001000 10001000 10001000 10001000 01000100 01000100 01000100 01000100 00100010 00100010 00100010 00100010 00010001 00010001 00010001 00010001
// F   B    7   3    f   b    ⁷   ³     E   A    6   2    e   a    ⁶   ²     D   9    5   1    d   ⁹    ⁵   ¹     C   8    4   0    c   ⁸    ⁴   ⁰

mask2:
    .quad   0x8080808040404040  // v2
    .quad   0x2020202010101010
    .quad   0x0808080804040404  // v3
    .quad   0x0202020201010101
    .quad   0x1010101010101010  // v4
    .quad   0x1010101010101010
    .quad   0x0101010101010101  // v5
    .quad   0x0101010101010101

test_data2:
    .word 0xff000103
    .word 0xff000302
    .word 0xff000506
    .word 0xff00080A
    .word 0xff001010
    .word 0xff002020
    .word 0xff00c040
    .word 0xff008080


来源: stackexchange

问:
Problem with extracting data from AS400 using SQL
I am writing an SQL request to export data from AS400 using different relations.
I want to write it like that to reduce the time and increase the performance of my ETL (I have at least 29 million row to use it in my ETL).

SQL:

```<code>SELECT  A.x1, A.x2, A.x3, A.x4, A.x5,
        (SELECT B.y1, B.y2, B.y3, C.w1 as w
        FROM TEST1 AS B inner join TEST2 AS C ON ((C.w2=B.y4) and (C.w3=B.y5))
        where (B.y6 = 2)),
        E.q1

FROM TEST3 AS A
LEFT OUTER JOIN TEST1 AS B ON (A.x6 = B.y7)
LEFT OUTER JOIN TEST4 AS E ON ((A.x6 = E.q2) AND (A.x7 = E.q3))
</code>```

I really need help for this error

I got this exception:

TITRE : Microsoft Visual Studio

  Exception de HRESULT : 0xC0202009
  Erreur sur Traitement [Source [2]] : Code d'erreur SSIS DTS_E_OLEDBERROR. Une erreur OLE DB s'est produite. Code d'erreur : 0x80004005.
  Un enregistrement OLE DB est disponible. Source : « IBMDA400 Command » Hresult : 0x80004005 Description : « SQL0412 : Sous-requête non admise, car plus d'une colonne résultat
  Cause . . . . . : La sous-requête d'un prédicat doit avoir uniquement une colonne résultat correspondante lorsque l'autre opérande du prédicat est une expression simple.  En effet, la sous-requête peut extraire zéro, une ou plusieurs valeurs constituant une liste mais apparaissant dans une seule colonne résultat. Que faire . . . : Modifiez le nombre d'éléments renvoyés par la sous-requête pour qu'il n'y ait qu'une seule colonne résultat ou remplacez l'autre opérande du prédicat pour obtenir une liste d'expressions. ».

答:
The reason for your error is that the subquery is returning more than one column. AlwaysLearning already said that.

But the next issue is going to be that your subquery is returning multiple rows.

Unless

```<code>SELECT B.y1, B.y2, B.y3, C.w1 as w
FROM TEST1 AS B inner join TEST2 AS C ON ((C.w2=B.y4) and (C.w3=B.y5))
where (B.y6 = 2)
</code>```

only returns a single row. Notice that the subquery has no conditions that correlate to the outer select. Using the alias B in the subquery does not correlate it to the outer select because it is redefined in the inner select at FROM TEST1 AS B. This makes the alias local to the subquery, and hides the use of B in the outer select from the subquery. If that is not what you intended, and even if it was, you should always follow a simple rule in SQL, do not re-use alises.

ContentLicense: CC BY-SA 4.0

Body:
I am writing an SQL request to export data from AS400 using different relations.
I want to write it like that to reduce the time and increase the performance of my ETL (I have at least 29 million row to use it in my ETL).

SQL:

SELECT  A.x1, A.x2, A.x3, A.x4, A.x5,
        (SELECT B.y1, B.y2, B.y3, C.w1 as w
        FROM TEST1 AS B inner join TEST2 AS C ON ((C.w2=B.y4) and (C.w3=B.y5))
        where (B.y6 = 2)),
        E.q1

FROM TEST3 AS A
LEFT OUTER JOIN TEST1 AS B ON (A.x6 = B.y7)
LEFT OUTER JOIN TEST4 AS E ON ((A.x6 = E.q2) AND (A.x7 = E.q3))

I really need help for this error

I got this exception:

TITRE : Microsoft Visual Studio

  Exception de HRESULT : 0xC0202009
  Erreur sur Traitement [Source [2]] : Code d'erreur SSIS DTS_E_OLEDBERROR. Une erreur OLE DB s'est produite. Code d'erreur : 0x80004005.
  Un enregistrement OLE DB est disponible. Source : « IBMDA400 Command » Hresult : 0x80004005 Description : « SQL0412 : Sous-requête non admise, car plus d'une colonne résultat
  Cause . . . . . : La sous-requête d'un prédicat doit avoir uniquement une colonne résultat correspondante lorsque l'autre opérande du prédicat est une expression simple.  En effet, la sous-requête peut extraire zéro, une ou plusieurs valeurs constituant une liste mais apparaissant dans une seule colonne résultat. Que faire . . . : Modifiez le nombre d'éléments renvoyés par la sous-requête pour qu'il n'y ait qu'une seule colonne résultat ou remplacez l'autre opérande du prédicat pour obtenir une liste d'expressions. ».

Body:
The reason for your error is that the subquery is returning more than one column. AlwaysLearning already said that.

But the next issue is going to be that your subquery is returning multiple rows.

Unless

SELECT B.y1, B.y2, B.y3, C.w1 as w
FROM TEST1 AS B inner join TEST2 AS C ON ((C.w2=B.y4) and (C.w3=B.y5))
where (B.y6 = 2)

only returns a single row. Notice that the subquery has no conditions that correlate to the outer select. Using the alias B in the subquery does not correlate it to the outer select because it is redefined in the inner select at FROM TEST1 AS B. This makes the alias local to the subquery, and hides the use of B in the outer select from the subquery. If that is not what you intended, and even if it was, you should always follow a simple rule in SQL, do not re-use alises.


问:
How do I call the following?
```<code>    public class MyReportRenderer
    {

        private rs2005.ReportingService2005 rs;
        private rs2005Execution.ReportExecutionService rsExec;
        //string casenumberKey;

        public void RenderTest()
        {
            string HistoryID = null;
            string deviceInfo = null;
            string encoding = String.Empty;
            string mimeType = String.Empty;
            string extension = String.Empty;
            rs2005Execution.Warning[] warnings = null;
            string[] streamIDs = null;

            rs = new rs2005.ReportingService2005();
            rsExec = new rs2005Execution.ReportExecutionService();
            rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
            rsExec.Credentials = System.Net.CredentialCache.DefaultCredentials;
            rs.Url = "http://216.40.232.82/ReportServer_DEVELOPMENT/ReportService2005.asmx";
            rsExec.Url = "http://216.40.232.82/ReportServer_DEVELOPMENT/ReportExecution2005.asmx";

            //// pass parameters

            try
            {
                // Get if any parameters needed.

                // Load the selected report.

                rsExec.LoadReport("/LawDept/LawDeptTIC", HistoryID);

                // Prepare report parameter.

                // Set the parameters for the report needed.

                rs2005Execution.ParameterValue[] parameters = new rs2005Execution.ParameterValue[3];
                parameters[0] = new rs2005Execution.ParameterValue();
                parameters[0].Name = "CaseNumberKey";
                parameters[0].Value = "000002";
                //parameters[1] = new rs2005Execution.ParameterValue();
                //parameters[1].Name = "ReportMonth";
                //parameters[1].Value = "6"; // June
                //parameters[2] = new rs2005Execution.ParameterValue();
                //parameters[2].Name = "ReportYear";
                //parameters[2].Value = "2004";
                rsExec.SetExecutionParameters(parameters, "en-us");

                // get pdf of report
                Byte[] results = rsExec.Render("PDF", deviceInfo,
                out extension, out encoding,
                out mimeType, out warnings, out streamIDs);

                MailMessage message = new MailMessage("george.greiner@gmail.com", "george.greiner@gmail.com", "Hello", "This is a test");
                SmtpClient emailClient = new SmtpClient("localhost");
                message.Attachments.Add(new Attachment(new MemoryStream(results), String.Format("{0}_DocumentSavingsReport.pdf", "ReportName")));
                emailClient.Send(message);
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }
        }
    }
</code>```

<p>I would I call this when I need it to be executed?? </p>

答:
I call it "a class named MyReportRenderer". If you mean "invoking a method", I think you need</p>

```<code>var renderer = new MyrReportRenderer();
renderer.RenderTest();
</code>```

ContentLicense: CC BY-SA 3.0

Title: How do I call the following?

Body:
    public class MyReportRenderer
    {

        private rs2005.ReportingService2005 rs;
        private rs2005Execution.ReportExecutionService rsExec;
        //string casenumberKey;

        public void RenderTest()
        {
            string HistoryID = null;
            string deviceInfo = null;
            string encoding = String.Empty;
            string mimeType = String.Empty;
            string extension = String.Empty;
            rs2005Execution.Warning[] warnings = null;
            string[] streamIDs = null;

            rs = new rs2005.ReportingService2005();
            rsExec = new rs2005Execution.ReportExecutionService();
            rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
            rsExec.Credentials = System.Net.CredentialCache.DefaultCredentials;
            rs.Url = "http://216.40.232.82/ReportServer_DEVELOPMENT/ReportService2005.asmx";
            rsExec.Url = "http://216.40.232.82/ReportServer_DEVELOPMENT/ReportExecution2005.asmx";

            //// pass parameters

            try
            {
                // Get if any parameters needed.

                // Load the selected report.

                rsExec.LoadReport("/LawDept/LawDeptTIC", HistoryID);

                // Prepare report parameter.

                // Set the parameters for the report needed.

                rs2005Execution.ParameterValue[] parameters = new rs2005Execution.ParameterValue[3];
                parameters[0] = new rs2005Execution.ParameterValue();
                parameters[0].Name = "CaseNumberKey";
                parameters[0].Value = "000002";
                //parameters[1] = new rs2005Execution.ParameterValue();
                //parameters[1].Name = "ReportMonth";
                //parameters[1].Value = "6"; // June
                //parameters[2] = new rs2005Execution.ParameterValue();
                //parameters[2].Name = "ReportYear";
                //parameters[2].Value = "2004";
                rsExec.SetExecutionParameters(parameters, "en-us");

                // get pdf of report
                Byte[] results = rsExec.Render("PDF", deviceInfo,
                out extension, out encoding,
                out mimeType, out warnings, out streamIDs);

                MailMessage message = new MailMessage("george.greiner@gmail.com", "george.greiner@gmail.com", "Hello", "This is a test");
                SmtpClient emailClient = new SmtpClient("localhost");
                message.Attachments.Add(new Attachment(new MemoryStream(results), String.Format("{0}_DocumentSavingsReport.pdf", "ReportName")));
                emailClient.Send(message);
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }
        }
    }

I would I call this when I need it to be executed??

Body:
I call it "a class named MyReportRenderer". If you mean "invoking a method", I think you need

var renderer = new MyrReportRenderer();
renderer.RenderTest();


问:
Argument must be a string or number [ Label Encoding ]
I am trying to append my data frame to new data frame but I am getting a 'Argument must be a string or number '  error.

```<code># The encoders
le = LabelEncoder()
ohc = OneHotEncoder()
for col in num_ohc_cols.index:

   # Integer encode the string categories
   dat = le.fit_transform(df_ohc[col]).astype(np.int)
   # Remove the original column from the dataframe
    df_ohc = df_ohc.drop(col,axis=1)
   # One hot encode the data--this returns a sparse array
   new_dat = ohc.fit_transform(dat.reshape(-1,1))
   # Create unique column names

   n_cols = new_dat.shape[1]

   col_names = ['_'.join([col,str(x)]) for x in range(n_cols)]
   print(col_names)
   # Create the new dataframe
</code>```

I'm getting the error here, in creating new dataframe:

```<code>new_df=pd.DataFrame(
 new_dat.toarray(),index=df_ohc.index,columns=col_names)
</code>```

答:
I solved by appending changing my append method as :

df_ohc = pd.concat([df_ohc, new_df], axis=1)

Body:
I am trying to append my data frame to new data frame but I am getting a 'Argument must be a string or number '  error.

# The encoders
le = LabelEncoder()
ohc = OneHotEncoder()
for col in num_ohc_cols.index:

   # Integer encode the string categories
   dat = le.fit_transform(df_ohc[col]).astype(np.int)
   # Remove the original column from the dataframe
    df_ohc = df_ohc.drop(col,axis=1)
   # One hot encode the data--this returns a sparse array
   new_dat = ohc.fit_transform(dat.reshape(-1,1))
   # Create unique column names

   n_cols = new_dat.shape[1]

   col_names = ['_'.join([col,str(x)]) for x in range(n_cols)]
   print(col_names)
   # Create the new dataframe

I'm getting the error here, in creating new dataframe:

new_df=pd.DataFrame(
 new_dat.toarray(),index=df_ohc.index,columns=col_names)


问:
Correct use of multimapping in Dapper
I'm trying to use the multimapping feature of Dapper to return a list of ProductItems and associated Customers.

[Table("Product")]
public class ProductItem
{
    public decimal ProductID { get; set; }
    public string ProductName { get; set; }
    public string AccountOpened { get; set; }
    public Customer Customer { get; set; }
}

public class Customer
{
    public decimal CustomerId { get; set; }
    public string CustomerName { get; set; }
}
```
<p>My Dapper code:</p>
<pre class="lang-cs prettyprint-override"><code>var sql = @"select * from Product p
            inner join Customer c on p.CustomerId = c.CustomerId
            order by p.ProductName";

var data = con.Query<ProductItem, Customer, ProductItem>(
    sql,
    (productItem, customer) => {
        productItem.Customer = customer;
        return productItem;
    },
    splitOn: "CustomerId,CustomerName"
);
</code>```

This works fine, but I seem to have to add the complete column list to the "splitOn" parameter to return all the customers' properties.  If I don't add "CustomerName", it returns null.  Am I misunderstanding the core functionality of the multimapping feature? I don't want to have to add a complete list of column names each time.

答:
If you need to map a large entity write each field must be a hard task.

I tried @BlackjacketMack answer, but one of my tables has an Id Column other ones not (I know it's a DB design problem, but ...) then this insert an extra split on dapper, that's why

```<code>select
p.*,

c.CustomerID AS Id,
c.*,

address.AddressID AS Id,
address.*,

country.CountryID AS Id,
country.*
</code>```

Doesn't work for me. Then I ended with a little change to this, just insert an split point with a name that doesn't match with any field on tables, In may case changed as Id by as _SplitPoint_, the final sql script looks like this:

```<code>select
p.*,

c.CustomerID AS _SplitPoint_,
c.*,

address.AddressID AS _SplitPoint_,
address.*,

country.CountryID AS _SplitPoint_,
country.*
</code>```

Then in dapper add just one splitOn as this

```<code>cmd =
    "SELECT Materials.*, " +
    "   Product.ItemtId as _SplitPoint_," +
    "   Product.*, " +
    "   MeasureUnit.IntIdUM as _SplitPoint_, " +
    "   MeasureUnit.* " +
    "FROM   Materials INNER JOIN " +
    "   Product ON Materials.ItemtId = Product.ItemtId INNER JOIN " +
    "   MeasureUnit ON Materials.IntIdUM = MeasureUnit.IntIdUM " +
List < Materials> fTecnica3 = (await dpCx.QueryAsync<Materials>(
        cmd,
        new[] { typeof(Materials), typeof(Product), typeof(MeasureUnit) },
        (objects) =>
        {
            Materials mat = (Materials)objects[0];
            mat.Product = (Product)objects[1];
            mat.MeasureUnit = (MeasureUnit)objects[2];
            return mat;
        },
        splitOn: "_SplitPoint_"
    )).ToList();
</code>```

Title: Correct use of multimapping in Dapper

Body:
I'm trying to use the multimapping feature of Dapper to return a list of ProductItems and associated Customers.

[Table("Product")]
public class ProductItem
{
    public decimal ProductID { get; set; }
    public string ProductName { get; set; }
    public string AccountOpened { get; set; }
    public Customer Customer { get; set; }
}

public class Customer
{
    public decimal CustomerId { get; set; }
    public string CustomerName { get; set; }
}

My Dapper code:

var sql = @"select * from Product p
            inner join Customer c on p.CustomerId = c.CustomerId
            order by p.ProductName";

var data = con.Query<ProductItem, Customer, ProductItem>(
    sql,
    (productItem, customer) => {
        productItem.Customer = customer;
        return productItem;
    },
    splitOn: "CustomerId,CustomerName"
);

This works fine, but I seem to have to add the complete column list to the "splitOn" parameter to return all the customers' properties.  If I don't add "CustomerName", it returns null.  Am I misunderstanding the core functionality of the multimapping feature? I don't want to have to add a complete list of column names each time.

Body:
If you need to map a large entity write each field must be a hard task.

I tried @BlackjacketMack answer, but one of my tables has an Id Column other ones not (I know it's a DB design problem, but ...) then this insert an extra split on dapper, that's why

select
p.*,

c.CustomerID AS Id,
c.*,

address.AddressID AS Id,
address.*,

country.CountryID AS Id,
country.*

Doesn't work for me. Then I ended with a little change to this, just insert an split point with a name that doesn't match with any field on tables, In may case changed as Id by as _SplitPoint_, the final sql script looks like this:

select
p.*,

c.CustomerID AS _SplitPoint_,
c.*,

address.AddressID AS _SplitPoint_,
address.*,

country.CountryID AS _SplitPoint_,
country.*

Then in dapper add just one splitOn as this

cmd =
    "SELECT Materials.*, " +
    "   Product.ItemtId as _SplitPoint_," +
    "   Product.*, " +
    "   MeasureUnit.IntIdUM as _SplitPoint_, " +
    "   MeasureUnit.* " +
    "FROM   Materials INNER JOIN " +
    "   Product ON Materials.ItemtId = Product.ItemtId INNER JOIN " +
    "   MeasureUnit ON Materials.IntIdUM = MeasureUnit.IntIdUM " +
List < Materials> fTecnica3 = (await dpCx.QueryAsync<Materials>(
        cmd,
        new[] { typeof(Materials), typeof(Product), typeof(MeasureUnit) },
        (objects) =>
        {
            Materials mat = (Materials)objects[0];
            mat.Product = (Product)objects[1];
            mat.MeasureUnit = (MeasureUnit)objects[2];
            return mat;
        },
        splitOn: "_SplitPoint_"
    )).ToList();


问:
Get all Childrens of a JSON in C# using NewtonSoftJson
com User!

My Json:

I want to giveout all name -> username1 and username.

I used C# and newtonsoft.json

I hope somebody can help me.
I tried it like this but it didnt work:

```<code>"kind":"UserList",
"data":{
   "children":[
      {
         "name":"test1",
         "author_flair_text":null,
         "mod_permissions":[
            "all"
         ],
         "date":1506648472.0,
         "rel_id":"rb_r8mbbr",
         "id":"t2_x6piz",
         "author_flair_css_class":null
      },
      {
         "name":"username2",
         "author_flair_text":null,
         "mod_permissions":[
            "all"
         ],
         "date":1553842373.0,
         "rel_id":"rb_18jmxnv",
         "id":"t2_a64nduq",
         "author_flair_css_class":null
      }
   ]
}
}

dynamic obj = JsonConvert.DeserializeObject<dynamic>(source);
             var mods = obj["data"]["children"].Children();
             foreach (var mod in mods)
             {
                 string modss = obj["data"]["children"][mods]["name"].ToString();
                 Console.WriteLine(modss);
             }
</code>```

答:
You already have got a ‘mod’ as an object. All you need to do is access the “name” property of the ‘mod’.

```<code>dynamic obj = JsonConvert.DeserializeObject<dynamic>(source);
             var mods = obj["data"]["children"].Children();
             foreach (var mod in mods)
             {
                 string modss = mod["name"].ToString();
                 Console.WriteLine(modss);
             }
</code>```

Note: The json you’ve pasted in the question is missing a starting ‘{‘ and without that it’s not valid.

Body:
com User!

My Json:

I want to giveout all name -> username1 and username.

I used C# and newtonsoft.json

I hope somebody can help me.
I tried it like this but it didnt work:

"kind":"UserList",
"data":{
   "children":[
      {
         "name":"test1",
         "author_flair_text":null,
         "mod_permissions":[
            "all"
         ],
         "date":1506648472.0,
         "rel_id":"rb_r8mbbr",
         "id":"t2_x6piz",
         "author_flair_css_class":null
      },
      {
         "name":"username2",
         "author_flair_text":null,
         "mod_permissions":[
            "all"
         ],
         "date":1553842373.0,
         "rel_id":"rb_18jmxnv",
         "id":"t2_a64nduq",
         "author_flair_css_class":null
      }
   ]
}
}

dynamic obj = JsonConvert.DeserializeObject<dynamic>(source);
             var mods = obj["data"]["children"].Children();
             foreach (var mod in mods)
             {
                 string modss = obj["data"]["children"][mods]["name"].ToString();
                 Console.WriteLine(modss);
             }

Body:
You already have got a ‘mod’ as an object. All you need to do is access the “name” property of the ‘mod’.

dynamic obj = JsonConvert.DeserializeObject<dynamic>(source);
             var mods = obj["data"]["children"].Children();
             foreach (var mod in mods)
             {
                 string modss = mod["name"].ToString();
                 Console.WriteLine(modss);
             }

Note: The json you’ve pasted in the question is missing a starting ‘{‘ and without that it’s not valid.


问:
Searching NTFS directory .NET
I would like to write a web page where users can search a directory on NTFS for certain criteria and display the results.

Does the directory have to be indexed?

Is there a .NET accessible windows search API that I can use to query the directory?

答:
All you get is System.IO.DirectoryInfo, and it doesn't even have built in searching.

Most people end up writing a recursive method that calls getDirectories and getFiles on each DirectoryInfo.

ContentLicense: CC BY-SA 2.5

Title: Searching NTFS directory .NET

OwnerDisplayName: FlySwat


问:
Set Height of separator between Tab widget and FrameLayout
I'm using TabHost in my app and i want to increase the thickness of the strip between tab widget and framelayout.

```<code> <TabHost android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:id="@android:id/tabhost">
 <LinearLayout android:orientation="vertical"
 android:layout_width="fill_parent" android:layout_height="fill_parent">

 <TabWidget android:id="@android:id/tabs"
 android:layout_height="wrap_content" android:layout_width="fill_parent">
 </TabWidget>
 <FrameLayout android:id="@android:id/tabcontent"
 android:layout_height="wrap_content" android:layout_width="fill_parent"                         android:background="#FF0000">
<LinearLayout android:orientation="vertical" android:layout_height="wrap_content"    android:layout_width="wrap_content">
<TextView android:text="TravelApplication1" android:layout_height="70dip"   android:layout_width="fill_parent"></TextView>
<TextView android:text="TravelApplication2" android:layout_height="70dip"       android:layout_width="fill_parent"></TextView>
<TextView android:text="TravelApplication3" android:layout_height="70dip"   android:layout_width="fill_parent"></TextView>
<TextView android:text="TravelApplication4" android:layout_height="70dip"   android:layout_width="fill_parent"></TextView>
</LinearLayout>
</FrameLayout>
</LinearLayout>
</code>```

Kindly suggest me to increse the thickness between tabWidget and FrameLayout.

Regards
Deepak Goel

答:
Add margin property to your FrameLayout element will increase space between Tab widget and FrameLayout :

```<code> <TabWidget android:id="@android:id/tabs"
 android:layout_height="wrap_content" android:layout_width="fill_parent">
 </TabWidget>
 <FrameLayout android:id="@android:id/tabcontent" android:layout_marginTop="10dip"
 android:layout_height="wrap_content" android:layout_width="fill_parent"   android:background="#FF0000">

.......

</FrameLayout>
</LinearLayout>
</code>```

EDIT: The line in tab widget is default, you have to make a custom tab widget by a layout if you want to custom it.

Body:
I'm using TabHost in my app and i want to increase the thickness of the strip between tab widget and framelayout.

 <TabHost android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:id="@android:id/tabhost">
 <LinearLayout android:orientation="vertical"
 android:layout_width="fill_parent" android:layout_height="fill_parent">

 <TabWidget android:id="@android:id/tabs"
 android:layout_height="wrap_content" android:layout_width="fill_parent">
 </TabWidget>
 <FrameLayout android:id="@android:id/tabcontent"
 android:layout_height="wrap_content" android:layout_width="fill_parent"                         android:background="#FF0000">
<LinearLayout android:orientation="vertical" android:layout_height="wrap_content"    android:layout_width="wrap_content">
<TextView android:text="TravelApplication1" android:layout_height="70dip"   android:layout_width="fill_parent"></TextView>
<TextView android:text="TravelApplication2" android:layout_height="70dip"       android:layout_width="fill_parent"></TextView>
<TextView android:text="TravelApplication3" android:layout_height="70dip"   android:layout_width="fill_parent"></TextView>
<TextView android:text="TravelApplication4" android:layout_height="70dip"   android:layout_width="fill_parent"></TextView>
</LinearLayout>
</FrameLayout>
</LinearLayout>

Kindly suggest me to increse the thickness between tabWidget and FrameLayout.

Regards
Deepak Goel

Body:
Add margin property to your FrameLayout element will increase space between Tab widget and FrameLayout :

 <TabWidget android:id="@android:id/tabs"
 android:layout_height="wrap_content" android:layout_width="fill_parent">
 </TabWidget>
 <FrameLayout android:id="@android:id/tabcontent" android:layout_marginTop="10dip"
 android:layout_height="wrap_content" android:layout_width="fill_parent"   android:background="#FF0000">

.......

</FrameLayout>
</LinearLayout>

EDIT: The line in tab widget is default, you have to make a custom tab widget by a layout if you want to custom it.


问:
Does std thread constructor take variadic thread function?
I am trying to pass a variable count of callback functions (all of the same signature) to a thread function. I came up with the following code

```<code>using namespace std;

void callback(int i)
{
    cout<<"thread "<<i<<" running"<<endl;
}

template<typename ...CallbackType>
void threadProc(int id, CallbackType ...callbackPack)
{
    auto callbacks = {callbackPack...};
    for(auto callback : callbacks)
    {
        callback(id);
    }
}

int main()
{
    thread t(threadProc<void(int)>, 1, callback);
    t.join();
    return 0;
}
</code>```

This code fails to compile with

```<code>error: no matching function for call to ‘std::thread::thread(, int, void (&)(int))’
 thread t(threadProc<void(int)>, 1, callback);
</code>```

Things would work fine if threadProc() is not using any parameter pack. Is there a correct way to launch a thread with variadic thread function?

答:
your first argument is a function pointer, hence use

```<code>thread t{threadProc<void(*)(int)>, 1, callback};
</code>```

Here https://godbolt.org/z/Hzp9EP

Body:
I am trying to pass a variable count of callback functions (all of the same signature) to a thread function. I came up with the following code

using namespace std;

void callback(int i)
{
    cout<<"thread "<<i<<" running"<<endl;
}

template<typename ...CallbackType>
void threadProc(int id, CallbackType ...callbackPack)
{
    auto callbacks = {callbackPack...};
    for(auto callback : callbacks)
    {
        callback(id);
    }
}

int main()
{
    thread t(threadProc<void(int)>, 1, callback);
    t.join();
    return 0;
}

This code fails to compile with

error: no matching function for call to ‘std::thread::thread(, int, void (&)(int))’
 thread t(threadProc<void(int)>, 1, callback);

Things would work fine if threadProc() is not using any parameter pack. Is there a correct way to launch a thread with variadic thread function?

Body:
your first argument is a function pointer, hence use

thread t{threadProc<void(*)(int)>, 1, callback};

Here https://godbolt.org/z/Hzp9EP


问:
Load image from local machine and render using react js
i am trying to load an image from the local machine and then display it, the problem is that when I load the image, instead of giving me the absolute path of the file, it gives a fake path as shown below:

```<code>C:\fakepath\image0.jpg
</code>```

The problem is that this path does not exist so it makes an error, how can I get the absolute path and then render the image when the image is uploaded?
This is the code that I have:

class MyApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isImage: false,
      val: "",
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleChange(e) {
    this.setState({
      mySrc: e.target.value,
      isImage: true,
    });
  }
  render() {
    const { isImage, val } = this.state;
    return (

        <form onSubmit={this.handleSubmit}>
          <input
            type="file"
            id="imgInp"
            value={val}
            onChange={this.handleChange}
          />

        </form>
        {isImage ? (

        ) : (

 Please select an image

        )}

    );
  }
}

export default MyApp;
```

答:
The file is stored in event.target.files[0] not event.target.value, then you need to create an URL for that file using URL.createObjectURL()

So in your case should be

mySrc: URL.createObjectURL(event.target.files[0])
```

Body:
i am trying to load an image from the local machine and then display it, the problem is that when I load the image, instead of giving me the absolute path of the file, it gives a fake path as shown below:

C:\fakepath\image0.jpg

The problem is that this path does not exist so it makes an error, how can I get the absolute path and then render the image when the image is uploaded?
This is the code that I have:

class MyApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isImage: false,
      val: "",
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleChange(e) {
    this.setState({
      mySrc: e.target.value,
      isImage: true,
    });
  }
  render() {
    const { isImage, val } = this.state;
    return (

        <form onSubmit={this.handleSubmit}>
          <input
            type="file"
            id="imgInp"
            value={val}
            onChange={this.handleChange}
          />

        </form>
        {isImage ? (

        ) : (

 Please select an image

        )}

    );
  }
}

export default MyApp;


问:
React select elements value is setting state to the previous selected options value?
On my select element in React, the first couple of selects aren't changing the value, but then they start changing the value to the previous selected option, like if I select the option FRITOS, the value is undefined, then when I select the option COFFEE, the value is FRITOS, and then when I select FRITOS again, the value goes to COFFEE. Really confused what's going on haha.

My function that's setting the state

```<code>  changeGroup = (event) => {
    this.setState({ [event.target.name]: event.target.value });
    console.log(this.state.groupSelected);
    const bugQuery = {
      GroupID: this.state.groupSelected,
    };
    console.log(bugQuery);
    console.log(this.props.bugs);
    if (this.state.groupSelected !== undefined) {
      this.props.getBugs(bugQuery);
    }
  };
</code>```

My select element

```<code>     <select
                style={{ border: "1px solid white", fontSize: "2.7vh" }}
                name="groupSelected"
                value={this.state.groupSelected}
                onChange={this.changeGroup}
              >
                <option value="FRITOS">FRITOS</option>
                <option value="5AFSA">5AFSA</option>
                <option selected>Groups</option>
    </select>

</code>```

答:
[Previous answer was dumb, let's edit !]

You can trigger a re-render by putting your select in a component :

```<code>import React, { Component } from "react";
import { render } from "react-dom";
import Hello from "./Hello";
import "./style.css";

class App extends Component {
  constructor() {
    super();

    this.options = ["FRITOS", "SAFSA"];

    this.state = {
      name: "React",
      groupSelected:''
    };
  }

  changeGroup = event => {
    this.setState({[event.target.name]: event.target.value }, () => console.log(this.state.groupSelected));

  };

  render() {
    return (
      <div>
        <Hello name={this.state.name} />

        <MySelect
          options={this.options}
          selectedOption={this.state.groupSelected}
          onSelectChange={this.changeGroup} />

        <div>groupSelected = {this.state.groupSelected}</div>
      </div>
    );
  }
}

class MySelect extends Component {
  constructor(props) {
    super(props);

    this.options = ["FRITOS", "SAFSA"];
  }

  buildSelectOptions = () => {
    return this.props.options.map(option => (
      <option key={option} value={option}>
        {option}
      </option>
    ));
  };

  render() {
    return (
      <>
        <select
          style={{ border: "1px solid white", fontSize: "2.7vh" }}
          name="groupSelected"
          value={this.props.groupSelected}
          onChange={this.props.onSelectChange}
        >
          {this.buildSelectOptions()}
          <option selected>Groups</option>
        </select>
      </>
    );
  }
}

render(<App />, document.getElementById("root"));

</code>```

Here is the repro on Stackblitz

I kept it the old way since you are using this.setState, but if you can, move to an up to date version of react and use functional components and hooks, this won't be a problem anymore.

Body:
On my select element in React, the first couple of selects aren't changing the value, but then they start changing the value to the previous selected option, like if I select the option FRITOS, the value is undefined, then when I select the option COFFEE, the value is FRITOS, and then when I select FRITOS again, the value goes to COFFEE. Really confused what's going on haha.

My function that's setting the state

  changeGroup = (event) => {
    this.setState({ [event.target.name]: event.target.value });
    console.log(this.state.groupSelected);
    const bugQuery = {
      GroupID: this.state.groupSelected,
    };
    console.log(bugQuery);
    console.log(this.props.bugs);
    if (this.state.groupSelected !== undefined) {
      this.props.getBugs(bugQuery);
    }
  };

My select element

     <select
                style={{ border: "1px solid white", fontSize: "2.7vh" }}
                name="groupSelected"
                value={this.state.groupSelected}
                onChange={this.changeGroup}
              >
                <option value="FRITOS">FRITOS</option>
                <option value="5AFSA">5AFSA</option>
                <option selected>Groups</option>
    </select>

Body:
[Previous answer was dumb, let's edit !]

You can trigger a re-render by putting your select in a component :

import React, { Component } from "react";
import { render } from "react-dom";
import Hello from "./Hello";
import "./style.css";

class App extends Component {
  constructor() {
    super();

    this.options = ["FRITOS", "SAFSA"];

    this.state = {
      name: "React",
      groupSelected:''
    };
  }

  changeGroup = event => {
    this.setState({[event.target.name]: event.target.value }, () => console.log(this.state.groupSelected));

  };

  render() {
    return (
      <div>
        <Hello name={this.state.name} />

        <MySelect
          options={this.options}
          selectedOption={this.state.groupSelected}
          onSelectChange={this.changeGroup} />

        <div>groupSelected = {this.state.groupSelected}</div>
      </div>
    );
  }
}

class MySelect extends Component {
  constructor(props) {
    super(props);

    this.options = ["FRITOS", "SAFSA"];
  }

  buildSelectOptions = () => {
    return this.props.options.map(option => (
      <option key={option} value={option}>
        {option}
      </option>
    ));
  };

  render() {
    return (
      <>
        <select
          style={{ border: "1px solid white", fontSize: "2.7vh" }}
          name="groupSelected"
          value={this.props.groupSelected}
          onChange={this.props.onSelectChange}
        >
          {this.buildSelectOptions()}
          <option selected>Groups</option>
        </select>
      </>
    );
  }
}

render(<App />, document.getElementById("root"));

Here is the repro on Stackblitz

I kept it the old way since you are using this.setState, but if you can, move to an up to date version of react and use functional components and hooks, this won't be a problem anymore.


问:
android app crashes when uploading to google play
My application worked well when I run it through Android Studio but it crashes when I download it from Google Play store.
It used to work well but suddenly this happened without changing anything
this is the google play crash log:

```<code>      java.lang.NoClassDefFoundError:
      at net.sourceforge.jtds.jdbc.Support.calculateNamedPipeBufferSize (Support.java)
      at net.sourceforge.jtds.jdbc.Support.class$ (Support.java)
      at net.sourceforge.jtds.jdbc.Support.convert (Support.java)
      at net.sourceforge.jtds.jdbc.Support.convertLOB (Support.java)
      at net.sourceforge.jtds.jdbc.Support.convertLOBType (Support.java)
      at net.sourceforge.jtds.jdbc.Support.encodeString (Support.java)
      at net.sourceforge.jtds.jdbc.Support.getJdbcType (Support.java)
      at net.sourceforge.jtds.jdbc.Support.getParameterDefinitions (Support.java)
      at net.sourceforge.jtds.jdbc.Support.getStatementKey (Support.java)
      at net.sourceforge.jtds.jdbc.Support.isWindowsOS (Support.java)
      at net.sourceforge.jtds.jdbc.Support.linkException (Support.java)
      at net.sourceforge.jtds.jdbc.Support.normalizeBigDecimal (Support.java)
      at net.sourceforge.jtds.jdbc.Support.substituteParamMarkers (Support.java)
      at net.sourceforge.jtds.jdbc.Support.timeFromZone (Support.java)
      at net.sourceforge.jtds.jdbc.Support.toHex (Support.java)
      at net.sourceforge.jtds.jdbc.Support.<clinit> (Support.java)
      at net.sourceforge.jtds.jdbc.Support.calculateNamedPipeBufferSize (Support.java)
      at net.sourceforge.jtds.jdbc.Support.class$ (Support.java)
      at net.sourceforge.jtds.jdbc.Support.convert (Support.java)
      at net.sourceforge.jtds.jdbc.Support.convertLOB (Support.java)
      at net.sourceforge.jtds.jdbc.Support.convertLOBType (Support.java)
      at net.sourceforge.jtds.jdbc.Support.encodeString (Support.java)
      at net.sourceforge.jtds.jdbc.Support.getJdbcType (Support.java)
      at net.sourceforge.jtds.jdbc.Support.getParameterDefinitions (Support.java)
      at net.sourceforge.jtds.jdbc.Support.getStatementKey (Support.java)
      at net.sourceforge.jtds.jdbc.Support.isWindowsOS (Support.java)
      at net.sourceforge.jtds.jdbc.Support.linkException (Support.java)
      at net.sourceforge.jtds.jdbc.Support.normalizeBigDecimal (Support.java)
      at net.sourceforge.jtds.jdbc.Support.substituteParamMarkers (Support.java)
      at net.sourceforge.jtds.jdbc.Support.timeFromZone (Support.java)
      at net.sourceforge.jtds.jdbc.Support.toHex (Support.java)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.addStatement (ConnectionJDBC2.java)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.checkLocal (ConnectionJDBC2.java)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.checkOpen (ConnectionJDBC2.java)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.getSybaseInfo (ConnectionJDBC2.java)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.parseBooleanProperty (ConnectionJDBC2.java)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.setCollation (ConnectionJDBC2.java)
      at net.sourceforge.jtds.jdbc.TdsCore.z (TdsCore.java)
      at net.sourceforge.jtds.jdbc.TdsCore.nextToken (TdsCore.java:4)
      at net.sourceforge.jtds.jdbc.TdsCore.login (TdsCore.java:43)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.<init> (ConnectionJDBC2.java:16)
      at net.sourceforge.jtds.jdbc.Driver.connect (Driver.java:2)
      at java.sql.DriverManager.getConnection (DriverManager.java:569)
      at java.sql.DriverManager.getConnection (DriverManager.java:219)
      at info.xyz.yourapplication2.ConnectSQL.Run (ConnectSQL.java)
      at info.xyz.yourapplication2.ConnectSQL.connectionclass (ConnectSQL.java)
      at info.xyz.yourapplication2.getproducttype.a (getproducttype.java)
      at info.xyz.yourapplication2.MainActivity.onCreate (MainActivity.java:5)
      at android.app.Activity.performCreate (Activity.java:6942)
      at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1126)
      at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2880)
      at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2988)
      at android.app.ActivityThread.-wrap14 (ActivityThread.java)
      at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1631)
      at android.os.Handler.dispatchMessage (Handler.java:102)
      at android.os.Looper.loop (Looper.java:154)
      at android.app.ActivityThread.main (ActivityThread.java:6682)
      at java.lang.reflect.Method.invoke (Method.java)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1520)
      at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1410)
</code>```

Any idea what may have caused that?

Here is my proguard-rules.pro.

```<code># Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
#   http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
#   public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
</code>```

Thank you in advance

答:
There must be a problem at your release while using pro guard.
Try to change your gradle.App property of </p>

```<code>   buildTypes {
        release {
//try it without proguard
        }
}
</code>```

Body:
My application worked well when I run it through Android Studio but it crashes when I download it from Google Play store.
It used to work well but suddenly this happened without changing anything
this is the google play crash log:

      java.lang.NoClassDefFoundError:
      at net.sourceforge.jtds.jdbc.Support.calculateNamedPipeBufferSize (Support.java)
      at net.sourceforge.jtds.jdbc.Support.class$ (Support.java)
      at net.sourceforge.jtds.jdbc.Support.convert (Support.java)
      at net.sourceforge.jtds.jdbc.Support.convertLOB (Support.java)
      at net.sourceforge.jtds.jdbc.Support.convertLOBType (Support.java)
      at net.sourceforge.jtds.jdbc.Support.encodeString (Support.java)
      at net.sourceforge.jtds.jdbc.Support.getJdbcType (Support.java)
      at net.sourceforge.jtds.jdbc.Support.getParameterDefinitions (Support.java)
      at net.sourceforge.jtds.jdbc.Support.getStatementKey (Support.java)
      at net.sourceforge.jtds.jdbc.Support.isWindowsOS (Support.java)
      at net.sourceforge.jtds.jdbc.Support.linkException (Support.java)
      at net.sourceforge.jtds.jdbc.Support.normalizeBigDecimal (Support.java)
      at net.sourceforge.jtds.jdbc.Support.substituteParamMarkers (Support.java)
      at net.sourceforge.jtds.jdbc.Support.timeFromZone (Support.java)
      at net.sourceforge.jtds.jdbc.Support.toHex (Support.java)
      at net.sourceforge.jtds.jdbc.Support.<clinit> (Support.java)
      at net.sourceforge.jtds.jdbc.Support.calculateNamedPipeBufferSize (Support.java)
      at net.sourceforge.jtds.jdbc.Support.class$ (Support.java)
      at net.sourceforge.jtds.jdbc.Support.convert (Support.java)
      at net.sourceforge.jtds.jdbc.Support.convertLOB (Support.java)
      at net.sourceforge.jtds.jdbc.Support.convertLOBType (Support.java)
      at net.sourceforge.jtds.jdbc.Support.encodeString (Support.java)
      at net.sourceforge.jtds.jdbc.Support.getJdbcType (Support.java)
      at net.sourceforge.jtds.jdbc.Support.getParameterDefinitions (Support.java)
      at net.sourceforge.jtds.jdbc.Support.getStatementKey (Support.java)
      at net.sourceforge.jtds.jdbc.Support.isWindowsOS (Support.java)
      at net.sourceforge.jtds.jdbc.Support.linkException (Support.java)
      at net.sourceforge.jtds.jdbc.Support.normalizeBigDecimal (Support.java)
      at net.sourceforge.jtds.jdbc.Support.substituteParamMarkers (Support.java)
      at net.sourceforge.jtds.jdbc.Support.timeFromZone (Support.java)
      at net.sourceforge.jtds.jdbc.Support.toHex (Support.java)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.addStatement (ConnectionJDBC2.java)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.checkLocal (ConnectionJDBC2.java)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.checkOpen (ConnectionJDBC2.java)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.getSybaseInfo (ConnectionJDBC2.java)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.parseBooleanProperty (ConnectionJDBC2.java)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.setCollation (ConnectionJDBC2.java)
      at net.sourceforge.jtds.jdbc.TdsCore.z (TdsCore.java)
      at net.sourceforge.jtds.jdbc.TdsCore.nextToken (TdsCore.java:4)
      at net.sourceforge.jtds.jdbc.TdsCore.login (TdsCore.java:43)
      at net.sourceforge.jtds.jdbc.ConnectionJDBC2.<init> (ConnectionJDBC2.java:16)
      at net.sourceforge.jtds.jdbc.Driver.connect (Driver.java:2)
      at java.sql.DriverManager.getConnection (DriverManager.java:569)
      at java.sql.DriverManager.getConnection (DriverManager.java:219)
      at info.xyz.yourapplication2.ConnectSQL.Run (ConnectSQL.java)
      at info.xyz.yourapplication2.ConnectSQL.connectionclass (ConnectSQL.java)
      at info.xyz.yourapplication2.getproducttype.a (getproducttype.java)
      at info.xyz.yourapplication2.MainActivity.onCreate (MainActivity.java:5)
      at android.app.Activity.performCreate (Activity.java:6942)
      at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1126)
      at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2880)
      at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2988)
      at android.app.ActivityThread.-wrap14 (ActivityThread.java)
      at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1631)
      at android.os.Handler.dispatchMessage (Handler.java:102)
      at android.os.Looper.loop (Looper.java:154)
      at android.app.ActivityThread.main (ActivityThread.java:6682)
      at java.lang.reflect.Method.invoke (Method.java)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1520)
      at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1410)

Any idea what may have caused that?

Here is my proguard-rules.pro.

# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
#   http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
#   public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

Thank you in advance

Body:
There must be a problem at your release while using pro guard.
Try to change your gradle.App property of

   buildTypes {
        release {
//try it without proguard
        }
}


问:
what is the scope of this variable in c++?
If i define a function like this

```<code>std::string& returnstring(std::istringstream &ist)
{
    std::string temp;
    std::getline(ist,temp);
    return temp;
}
</code>```

and if i use this temp which is passed by reference to another function like this

```<code>void displaystring(std::string &temp)
{
    std::cout<<temp;
}
</code>```

would the string temp still be in scope when i pass it by reference to displaystring function?

答:
The scope of a variable is the scope where it is declared. std::string temp; is declared within the body of the function returnstring, therefore that function body is the scope of the variable. It is an automatic variable, and therefore its lifetime ends at the end of its scope and it is automatically destroyed.

The returned reference will be invalid (i.e. it is a dangling reference). If you attempt to access the non-existing object through the invalid reference, then the behaviour of the program will be undefined.

To fix the function, a simple solution is to return a value instead.

Body:
If i define a function like this

std::string& returnstring(std::istringstream &ist)
{
    std::string temp;
    std::getline(ist,temp);
    return temp;
}

and if i use this temp which is passed by reference to another function like this

void displaystring(std::string &temp)
{
    std::cout<<temp;
}

would the string temp still be in scope when i pass it by reference to displaystring function?


问:
Passing Variable to sed
I'm having trouble passing the variable $APN to sed, tried lots of combinations of ' " \ \

First column of .csv files is a number, this code works:

```<code>cat *.csv > "$APN".csv              #combine

sort -u "$APN".csv -o "$APN".csv    #sort, remove duplicate APNs

sed -i '/^715/!d' combined2.csv     #remove not 715
</code>```

This code third line does nothing:

```<code>cat *.csv > "$APN".csv             #combine

sort -u "$APN".csv -o "$APN".csv    #sort, remove duplicate APNs

sed -i '/^$APN/!d'                  #remove not $APN
</code>```

答:
The variables inside single quotes are not expanded, you need double quotes.

```<code>sed -i "/^$APN/!d" "${APN}.csv"
</code>```

Learn how to quote properly in shell, it's very important :

"Double quote" every literal that contains spaces/metacharacters and every expansion: "$var", "$(command "$var")", "${array[@]}", "a & b". Use 'single quotes' for code or literal $'s: 'Costs $5 US', ssh host 'echo "$HOSTNAME"'. See

  http://mywiki.wooledge.org/Quotes

  http://mywiki.wooledge.org/Arguments

  http://wiki.bash-hackers.org/syntax/words

Title: Passing Variable to sed

Body:
I'm having trouble passing the variable $APN to sed, tried lots of combinations of ' " \ \

First column of .csv files is a number, this code works:

cat *.csv > "$APN".csv              #combine

sort -u "$APN".csv -o "$APN".csv    #sort, remove duplicate APNs

sed -i '/^715/!d' combined2.csv     #remove not 715

This code third line does nothing:

cat *.csv > "$APN".csv             #combine

sort -u "$APN".csv -o "$APN".csv    #sort, remove duplicate APNs

sed -i '/^$APN/!d'                  #remove not $APN

Body:
The variables inside single quotes are not expanded, you need double quotes.

sed -i "/^$APN/!d" "${APN}.csv"

Learn how to quote properly in shell, it's very important :

"Double quote" every literal that contains spaces/metacharacters and every expansion: "$var", "$(command "$var")", "${array[@]}", "a & b". Use 'single quotes' for code or literal $'s: 'Costs $5 US', ssh host 'echo "$HOSTNAME"'. See

  http://mywiki.wooledge.org/Quotes

  http://mywiki.wooledge.org/Arguments

  http://wiki.bash-hackers.org/syntax/words


问:
Number of ways to change a coin
I am doing this question https://leetcode.com/problems/coin-change-2/. I need to find number of ways to change a coin given the amount and denominations.

I came up with the solution to try every possibility of denominations for an amount and caching it if its already seen before.

```<code>class Solution(object):
    def change(self, amount, coins):
        """
        :type amount: int
        :type coins: List[int]
        :rtype: int
        """
        dp = [[-1]*len(coins)]*(amount+1)
        def changeHelper(amount, coins, index):
            if amount == 0:
                return 1

            if index<0:
                return 0

            if dp[amount][index]!=-1:
                return dp[amount][index]

            total_ways = 0
            if amount>=coins[index]:
                total_ways = changeHelper(amount-coins[index], coins, index)

            total_ways += changeHelper(amount, coins, index-1)

            dp[amount][index] = total_ways
            return dp[amount][index]

        return changeHelper(amount, coins, len(coins)-1)
</code>```

I am getting wrong answer and have spent hours figuring out the bug.

```<code>Test case
500
[1,2,5]
expected answer 12701
my output 301
</code>```

答:
Your code is fine, the issue is in the dp list. When you do [[-1]*len(coins)]*(amount+1) in your example, first a list of [-1, -1, -1] is created then it is copied (by reference) 501 times. When you change any item in any of the lists all the other lists will get updated too which will lead to incorrect result.

To fix that, either create the list using list comprehension:

dp = [[-1 for _ in range(len(coins))] for _ in range(amount+2)]

or make use of the fact that dict lookup is O(1) in Python and use a dict for memoization to avoid such error in the future, for example:

```<code>dp = {}
def changeHelper(amount, coins, index):
    if amount == 0:
        return 1

    if index<0:
        return 0

    if (amount, index) in dp:
        return dp[(amount, index)]

    total_ways = 0
    if amount>=coins[index]:
        total_ways = changeHelper(amount-coins[index], coins, index)

    total_ways += changeHelper(amount, coins, index-1)

    dp[(amount, index)] = total_ways
    return dp[(amount, index)]
</code>```

EDIT:

Here is more explanation to why that happened

```<code>>>> dp = [[-1] * 3] * 4
>>> dp
[[-1, -1, -1], [-1, -1, -1], [-1, -1, -1], [-1, -1, -1]]
>>> dp[0][0] = 5
>>> dp
[[5, -1, -1], [5, -1, -1], [5, -1, -1], [5, -1, -1]]
</code>```

Think of it like, the inner statement creates:

```<code>tmp = [-1, -1, -1]
</code>```

then the outer one:

```<code>dp = [tmp, tmp, tmp, tmp]
</code>```

Title: Number of ways to change a coin

Body:
I am doing this question https://leetcode.com/problems/coin-change-2/. I need to find number of ways to change a coin given the amount and denominations.

I came up with the solution to try every possibility of denominations for an amount and caching it if its already seen before.

class Solution(object):
    def change(self, amount, coins):
        """
        :type amount: int
        :type coins: List[int]
        :rtype: int
        """
        dp = [[-1]*len(coins)]*(amount+1)
        def changeHelper(amount, coins, index):
            if amount == 0:
                return 1

            if index<0:
                return 0

            if dp[amount][index]!=-1:
                return dp[amount][index]

            total_ways = 0
            if amount>=coins[index]:
                total_ways = changeHelper(amount-coins[index], coins, index)

            total_ways += changeHelper(amount, coins, index-1)

            dp[amount][index] = total_ways
            return dp[amount][index]

        return changeHelper(amount, coins, len(coins)-1)

I am getting wrong answer and have spent hours figuring out the bug.

Test case
500
[1,2,5]
expected answer 12701
my output 301

Body:
Your code is fine, the issue is in the dp list. When you do [[-1]*len(coins)]*(amount+1) in your example, first a list of [-1, -1, -1] is created then it is copied (by reference) 501 times. When you change any item in any of the lists all the other lists will get updated too which will lead to incorrect result.

To fix that, either create the list using list comprehension:

dp = [[-1 for _ in range(len(coins))] for _ in range(amount+2)]

or make use of the fact that dict lookup is O(1) in Python and use a dict for memoization to avoid such error in the future, for example:

dp = {}
def changeHelper(amount, coins, index):
    if amount == 0:
        return 1

    if index<0:
        return 0

    if (amount, index) in dp:
        return dp[(amount, index)]

    total_ways = 0
    if amount>=coins[index]:
        total_ways = changeHelper(amount-coins[index], coins, index)

    total_ways += changeHelper(amount, coins, index-1)

    dp[(amount, index)] = total_ways
    return dp[(amount, index)]

EDIT:

Here is more explanation to why that happened

>>> dp = [[-1] * 3] * 4
>>> dp
[[-1, -1, -1], [-1, -1, -1], [-1, -1, -1], [-1, -1, -1]]
>>> dp[0][0] = 5
>>> dp
[[5, -1, -1], [5, -1, -1], [5, -1, -1], [5, -1, -1]]

Think of it like, the inner statement creates:

tmp = [-1, -1, -1]

then the outer one:

dp = [tmp, tmp, tmp, tmp]


问:
favicon.ico results in 404 error in flask app
I found a lot of entries in my logfile, which indicate that somebody tried to load /favicon.ico and similar files

```<code>GET - /favicon.ico
GET - /apple-touch-icon.png
GET - /apple-touch-icon-precomposed.png
</code>```

I read a lot about this issue online, but I can't get rid of it. Here is what I trued. First I added the following to my head tag

```<code><link rel="shortcut icon" href="/static/favicon/favicon.ico" type="image/x-icon">
</code>```

However, even though I provide this information in my header, there seem to be browsers out there which don't care about it and still call /favicon.ico?
So I thought just putting the ico file at root and be done with it, but it does not seem to work? If I call

```<code>http://localhost:5000/static/favicon/favicon.ico
</code>```

I get to the icon, but

```<code>http://localhost:5000/favicon.ico
</code>```

Does not work (gives 404)? I cleared my cache and tried it with Chrome and Safari, but I get 404 in both cases? I am really at a loss here. If I move the image in the static folder and call

```<code>http://localhost:5000/static/favicon.ico
</code>```

it works, but the root folder doesn't? What am I missing here?

答:
I ran into a very similar problem. I do not have the necessary points to add a comment to the answer yet. So I'll do it using "Your answer". For those who need a much more specific answer on how to use url_for () here is one way to do it.

```<code><!-- Adding a favicon icon to Flask app -->
<!-- SEE: https://favicon.io/favicon-converter/-->

<link rel="shortcut icon"
      href="{{ url_for('static', filename='favicon.ico') }}">

<link rel="apple-touch-icon"
      sizes="180x180"
      href="{{ url_for('static', filename='apple-touch-icon.png') }}">

<link rel="icon"
      type="image/png"
      sizes="180x180"
      href="{{ url_for('static', filename='favicon-32x32.png') }}">

<link rel="icon"
      type="image/png"
      sizes="16x16"
      href="{{ url_for('static', filename='favicon-16x16.png') }}">

<link rel="manifest"
      href="site.webmanifest">
</code>```

To generate the necessary files use the following link: https://favicon.io/favicon-converter/ All files were copied into the /static directory.

Body:
I found a lot of entries in my logfile, which indicate that somebody tried to load /favicon.ico and similar files

GET - /favicon.ico
GET - /apple-touch-icon.png
GET - /apple-touch-icon-precomposed.png

I read a lot about this issue online, but I can't get rid of it. Here is what I trued. First I added the following to my head tag

<link rel="shortcut icon" href="/static/favicon/favicon.ico" type="image/x-icon">

However, even though I provide this information in my header, there seem to be browsers out there which don't care about it and still call /favicon.ico?
So I thought just putting the ico file at root and be done with it, but it does not seem to work? If I call

http://localhost:5000/static/favicon/favicon.ico

I get to the icon, but

http://localhost:5000/favicon.ico

Does not work (gives 404)? I cleared my cache and tried it with Chrome and Safari, but I get 404 in both cases? I am really at a loss here. If I move the image in the static folder and call

http://localhost:5000/static/favicon.ico

it works, but the root folder doesn't? What am I missing here?

Body:
I ran into a very similar problem. I do not have the necessary points to add a comment to the answer yet. So I'll do it using "Your answer". For those who need a much more specific answer on how to use url_for () here is one way to do it.

<!-- Adding a favicon icon to Flask app -->
<!-- SEE: https://favicon.io/favicon-converter/-->

<link rel="shortcut icon"
      href="{{ url_for('static', filename='favicon.ico') }}">

<link rel="apple-touch-icon"
      sizes="180x180"
      href="{{ url_for('static', filename='apple-touch-icon.png') }}">

<link rel="icon"
      type="image/png"
      sizes="180x180"
      href="{{ url_for('static', filename='favicon-32x32.png') }}">

<link rel="icon"
      type="image/png"
      sizes="16x16"
      href="{{ url_for('static', filename='favicon-16x16.png') }}">

<link rel="manifest"
      href="site.webmanifest">

To generate the necessary files use the following link: https://favicon.io/favicon-converter/ All files were copied into the /static directory.


答:
There is nothing wrong with your code. This seems to just be a bug in GCC, which has nothing to do with threads. A minimal test case that reproduces the bug is:

```<code>template <typename... T>
void foo(T...) {}

int main()
{
    auto* pfoo = foo<void(int)>;

    return 0;
}
</code>```

It seems that GCC does not like the fact that foo has a parameter of type void(int). Yet the rules of the language are clear: this is allowed, and the function type is adjusted to the corresponding function pointer type when it appears as a parameter type.

Other compilers seem to have no issue with it. See https://godbolt.org/z/tgaV7B

As a workaround, you can write:

```<code>thread t(threadProc<void(*)(int)>, 1, callback);
</code>```

Or:

```<code>thread t(threadProc<decltype(&callback)>, 1, callback);
</code>```

Title: Does std thread constructor take variadic thread function?

Body:
There is nothing wrong with your code. This seems to just be a bug in GCC, which has nothing to do with threads. A minimal test case that reproduces the bug is:

template <typename... T>
void foo(T...) {}

int main()
{
    auto* pfoo = foo<void(int)>;

    return 0;
}

It seems that GCC does not like the fact that foo has a parameter of type void(int). Yet the rules of the language are clear: this is allowed, and the function type is adjusted to the corresponding function pointer type when it appears as a parameter type.

Other compilers seem to have no issue with it. See https://godbolt.org/z/tgaV7B

As a workaround, you can write:

thread t(threadProc<void(*)(int)>, 1, callback);

Or:

thread t(threadProc<decltype(&callback)>, 1, callback);


问:
How do you use tensorflow ctc_batch_cost function with keras?
I have been trying to implement a CTC loss function in keras for several days now.

Unfortunately, I have yet to find a simple way to do this that fits well with keras. I found tensorflow's tf.keras.backend.ctc_batch_cost function but there is not much documentation on it. I am confused about a few things. First, what are the input_length and label_length parameters? I am trying to make a handwriting recognition model and my images are 32x128, my RNN has 32 time steps, and my character list has a length of 80. I have tried to use 32 for both parameters and this gives me the error below.

Shouldn't the function already know the input_length and label_length from the shape of the first two parameters (y_true and y_pred)?

Secondly, do I need to encode my training data? Is this all done automatically?

I know tensorflow also has a function called tf.keras.backend.ctc_decode. Is this only used when making predictions?

```<code>def ctc_cost(y_true, y_pred):
    return tf.keras.backend.ctc_batch_cost(
        y_true, y_pred, 32, 32)

model = tf.keras.Sequential([
    layers.Conv2D(32, 5, padding="SAME", input_shape=(32, 128, 1)),
    layers.BatchNormalization(),
    layers.Activation("relu"),
    layers.MaxPool2D(2, 2),
    layers.Conv2D(64, 5, padding="SAME"),
    layers.BatchNormalization(),
    layers.Activation("relu"),
    layers.MaxPool2D(2, 2),
    layers.Conv2D(128, 3, padding="SAME"),
    layers.BatchNormalization(),
    layers.Activation("relu"),
    layers.MaxPool2D((1, 2), (1, 2)),
    layers.Conv2D(128, 3, padding="SAME"),
    layers.BatchNormalization(),
    layers.Activation("relu"),
    layers.MaxPool2D((1, 2), (1, 2)),
    layers.Conv2D(256, 3, padding="SAME"),
    layers.BatchNormalization(),
    layers.Activation("relu"),
    layers.MaxPool2D((1, 2), (1, 2)),
    layers.Reshape((32, 256)),
    layers.Bidirectional(layers.LSTM(256, return_sequences=True)),
    layers.Bidirectional(layers.LSTM(256, return_sequences=True)),
    layers.Reshape((-1, 32, 512)),
    layers.Conv2D(80, 1, padding="SAME"),
    layers.Softmax(-1)
])

print(model.summary())

model.compile(tf.optimizers.RMSprop(0.001), ctc_cost)
</code>```

Error:

tensorflow.python.framework.errors_impl.InvalidArgumentError: squeeze_dims[0] not in [0,0). for 'loss/softmax_loss/Squeeze' (op: 'Squeeze') with input shapes: []

Model:

```<code>Layer (type)                 Output Shape              Param #
=================================================================
conv2d (Conv2D)              (None, 32, 128, 32)       832
batch_normalization (BatchNo (None, 32, 128, 32)       128
activation (Activation)      (None, 32, 128, 32)       0
max_pooling2d (MaxPooling2D) (None, 16, 64, 32)        0
conv2d_1 (Conv2D)            (None, 16, 64, 64)        51264
batch_normalization_1 (Batch (None, 16, 64, 64)        256
activation_1 (Activation)    (None, 16, 64, 64)        0
max_pooling2d_1 (MaxPooling2 (None, 8, 32, 64)         0
conv2d_2 (Conv2D)            (None, 8, 32, 128)        73856
batch_normalization_2 (Batch (None, 8, 32, 128)        512
activation_2 (Activation)    (None, 8, 32, 128)        0
max_pooling2d_2 (MaxPooling2 (None, 8, 16, 128)        0
conv2d_3 (Conv2D)            (None, 8, 16, 128)        147584
batch_normalization_3 (Batch (None, 8, 16, 128)        512
activation_3 (Activation)    (None, 8, 16, 128)        0
max_pooling2d_3 (MaxPooling2 (None, 8, 8, 128)         0
conv2d_4 (Conv2D)            (None, 8, 8, 256)         295168
batch_normalization_4 (Batch (None, 8, 8, 256)         1024
activation_4 (Activation)    (None, 8, 8, 256)         0
max_pooling2d_4 (MaxPooling2 (None, 8, 4, 256)         0
reshape (Reshape)            (None, 32, 256)           0
bidirectional (Bidirectional (None, 32, 512)           1050624
bidirectional_1 (Bidirection (None, 32, 512)           1574912
reshape_1 (Reshape)          (None, None, 32, 512)     0
conv2d_5 (Conv2D)            (None, None, 32, 80)      41040
softmax (Softmax)            (None, None, 32, 80)      0
</code>```

Here is the tensorflow documentation I was referencing:

https://www.tensorflow.org/api_docs/python/tf/keras/backend/ctc_batch_cost

答:
First, what are the input_length and label_length parameters?

input_length is the length of the input sequence in time steps. label_length is the length of the text label.

For example, if you are trying to recognize:

and you are doing it in 32 time steps, then your input_length is 32 and your label_length is 12 (len("John Hancock")).

Shouldn't the function already know the input_length and label_length from the shape of the first two parameters (y_true and y_pred)?

You usually process input data in batches, which have to be padded to the largest element in the batch, so this information is lost. In your case the input_length is always the same, but the label_length varies.

When dealing with speech recognition, for example, input_length can vary as well.

Secondly, do I need to encode my training data? Is this all done automatically?

Not sure I understand what you are asking, but here is a good example written in Keras:

https://keras.io/examples/image_ocr/

I know tensorflow also has a function called tf.keras.backend.ctc_decode. Is this only used when making predictions?

In general, yes. You can also try to use it make you breakfast in the morning, but it's not very good at it ;)

Body:
I have been trying to implement a CTC loss function in keras for several days now.

Unfortunately, I have yet to find a simple way to do this that fits well with keras. I found tensorflow's tf.keras.backend.ctc_batch_cost function but there is not much documentation on it. I am confused about a few things. First, what are the input_length and label_length parameters? I am trying to make a handwriting recognition model and my images are 32x128, my RNN has 32 time steps, and my character list has a length of 80. I have tried to use 32 for both parameters and this gives me the error below.

Shouldn't the function already know the input_length and label_length from the shape of the first two parameters (y_true and y_pred)?

Secondly, do I need to encode my training data? Is this all done automatically?

I know tensorflow also has a function called tf.keras.backend.ctc_decode. Is this only used when making predictions?

def ctc_cost(y_true, y_pred):
    return tf.keras.backend.ctc_batch_cost(
        y_true, y_pred, 32, 32)

model = tf.keras.Sequential([
    layers.Conv2D(32, 5, padding="SAME", input_shape=(32, 128, 1)),
    layers.BatchNormalization(),
    layers.Activation("relu"),
    layers.MaxPool2D(2, 2),
    layers.Conv2D(64, 5, padding="SAME"),
    layers.BatchNormalization(),
    layers.Activation("relu"),
    layers.MaxPool2D(2, 2),
    layers.Conv2D(128, 3, padding="SAME"),
    layers.BatchNormalization(),
    layers.Activation("relu"),
    layers.MaxPool2D((1, 2), (1, 2)),
    layers.Conv2D(128, 3, padding="SAME"),
    layers.BatchNormalization(),
    layers.Activation("relu"),
    layers.MaxPool2D((1, 2), (1, 2)),
    layers.Conv2D(256, 3, padding="SAME"),
    layers.BatchNormalization(),
    layers.Activation("relu"),
    layers.MaxPool2D((1, 2), (1, 2)),
    layers.Reshape((32, 256)),
    layers.Bidirectional(layers.LSTM(256, return_sequences=True)),
    layers.Bidirectional(layers.LSTM(256, return_sequences=True)),
    layers.Reshape((-1, 32, 512)),
    layers.Conv2D(80, 1, padding="SAME"),
    layers.Softmax(-1)
])

print(model.summary())

model.compile(tf.optimizers.RMSprop(0.001), ctc_cost)

Error:

tensorflow.python.framework.errors_impl.InvalidArgumentError: squeeze_dims[0] not in [0,0). for 'loss/softmax_loss/Squeeze' (op: 'Squeeze') with input shapes: []

Model:

Layer (type)                 Output Shape              Param #
=================================================================
conv2d (Conv2D)              (None, 32, 128, 32)       832
batch_normalization (BatchNo (None, 32, 128, 32)       128
activation (Activation)      (None, 32, 128, 32)       0
max_pooling2d (MaxPooling2D) (None, 16, 64, 32)        0
conv2d_1 (Conv2D)            (None, 16, 64, 64)        51264
batch_normalization_1 (Batch (None, 16, 64, 64)        256
activation_1 (Activation)    (None, 16, 64, 64)        0
max_pooling2d_1 (MaxPooling2 (None, 8, 32, 64)         0
conv2d_2 (Conv2D)            (None, 8, 32, 128)        73856
batch_normalization_2 (Batch (None, 8, 32, 128)        512
activation_2 (Activation)    (None, 8, 32, 128)        0
max_pooling2d_2 (MaxPooling2 (None, 8, 16, 128)        0
conv2d_3 (Conv2D)            (None, 8, 16, 128)        147584
batch_normalization_3 (Batch (None, 8, 16, 128)        512
activation_3 (Activation)    (None, 8, 16, 128)        0
max_pooling2d_3 (MaxPooling2 (None, 8, 8, 128)         0
conv2d_4 (Conv2D)            (None, 8, 8, 256)         295168
batch_normalization_4 (Batch (None, 8, 8, 256)         1024
activation_4 (Activation)    (None, 8, 8, 256)         0
max_pooling2d_4 (MaxPooling2 (None, 8, 4, 256)         0
reshape (Reshape)            (None, 32, 256)           0
bidirectional (Bidirectional (None, 32, 512)           1050624
bidirectional_1 (Bidirection (None, 32, 512)           1574912
reshape_1 (Reshape)          (None, None, 32, 512)     0
conv2d_5 (Conv2D)            (None, None, 32, 80)      41040
softmax (Softmax)            (None, None, 32, 80)      0

Here is the tensorflow documentation I was referencing:

https://www.tensorflow.org/api_docs/python/tf/keras/backend/ctc_batch_cost


问:
How to generate random numbers and compare them with token inputs?
So i'm trying to make a function def number_guess(num): in order to generate some random integers and compare them with certain inputs() and print some statements.

For ex if i input:

```<code>32 45 48 80
</code>```

My target output is

```<code>32 is too low. Random number was 80.
45 is too high. Random number was 30.
48 is correct!
80 is too low. Random number was 97.
</code>```

We are also using the seed value 900, which will cause the computer to choose the same random number every time the program runs.

So far my code is:

```<code># TODO: Import the random module
import random

def number_guess(num):
    # TODO: Get a random number between 1-100

    random.randint(1,100)

    # TODO: Read numbers and compare to random number

    for token in tokens:
        if token < randint:
            print('{} is too low. Random number was {}.'.format(user_input[0], randint))
        elif token > randint:
            print('{} is too high. Random number was {}.'.format(user_input[1], randint))
        elif token == randint:
            print('{} is correct!'.format(randint))

if __name__ == "__main__":
    # Use the seed 900 to get the same pseudo random numbers every time
    random.seed(900)

    # Convert the string tokens into integers
    user_input = input()
    tokens = user_input.split()
    for token in tokens:
        num = int(token)
        number_guess(num)
</code>```

I tried:
def number_guess(num):
        # TODO: Get a random number between 1-100

```<code>    randint = ['']
    random.randint(1,100)

    # TODO: Read numbers and compare to random number

    for num in tokens:
        if token < randint:
            print('{} is too low. Random number was {}.'.format(num[0], randint))
        elif token > randint:
            print('{} is too high. Random number was {}.'.format(num[1], randint))
        elif token == randint:
            print('{} is correct!'.format(randint))
</code>```

But i'm not really understanding the format and how the functions for this should work. Any help is appreciated!

答:
There were several issues with your code, the chief of which was that you did not do anything with the random number you generated, and tried accessing it through the name randint, which would cause an "undefined name" exception.

A somewhat simplified version of you code, that will also work, would look like this:

```<code>import random

tokens = [32, 45, 48, 80]

def number_guess():
    secret = random.randint(1,100)
    for token in tokens:
        if token < secret:
            print('{} is too low. Random number was {}.'.format(token, secret))
        elif token > secret:
            print('{} is too high. Random number was {}.'.format(token, secret))
        elif token == secret:
            print('{} is correct!'.format(secret))

if __name__ == "__main__":
    # Use the seed 900 to get the same pseudo random numbers every time
    random.seed(900)
    number_guess()
</code>```

I removed the user input part, irrelevant parameters, and an extraneous loop, and now you get feedback on all the tested tokens:

```<code>32 is too low. Random number was 80.
45 is too low. Random number was 80.
48 is too low. Random number was 80.
80 is correct!
</code>```

Body:
So i'm trying to make a function def number_guess(num): in order to generate some random integers and compare them with certain inputs() and print some statements.

For ex if i input:

32 45 48 80

My target output is

32 is too low. Random number was 80.
45 is too high. Random number was 30.
48 is correct!
80 is too low. Random number was 97.

We are also using the seed value 900, which will cause the computer to choose the same random number every time the program runs.

So far my code is:

# TODO: Import the random module
import random

def number_guess(num):
    # TODO: Get a random number between 1-100

    random.randint(1,100)

    # TODO: Read numbers and compare to random number

    for token in tokens:
        if token < randint:
            print('{} is too low. Random number was {}.'.format(user_input[0], randint))
        elif token > randint:
            print('{} is too high. Random number was {}.'.format(user_input[1], randint))
        elif token == randint:
            print('{} is correct!'.format(randint))

if __name__ == "__main__":
    # Use the seed 900 to get the same pseudo random numbers every time
    random.seed(900)

    # Convert the string tokens into integers
    user_input = input()
    tokens = user_input.split()
    for token in tokens:
        num = int(token)
        number_guess(num)

I tried:
def number_guess(num):
        # TODO: Get a random number between 1-100

    randint = ['']
    random.randint(1,100)

    # TODO: Read numbers and compare to random number

    for num in tokens:
        if token < randint:
            print('{} is too low. Random number was {}.'.format(num[0], randint))
        elif token > randint:
            print('{} is too high. Random number was {}.'.format(num[1], randint))
        elif token == randint:
            print('{} is correct!'.format(randint))

But i'm not really understanding the format and how the functions for this should work. Any help is appreciated!

Body:
There were several issues with your code, the chief of which was that you did not do anything with the random number you generated, and tried accessing it through the name randint, which would cause an "undefined name" exception.

A somewhat simplified version of you code, that will also work, would look like this:

import random

tokens = [32, 45, 48, 80]

def number_guess():
    secret = random.randint(1,100)
    for token in tokens:
        if token < secret:
            print('{} is too low. Random number was {}.'.format(token, secret))
        elif token > secret:
            print('{} is too high. Random number was {}.'.format(token, secret))
        elif token == secret:
            print('{} is correct!'.format(secret))

if __name__ == "__main__":
    # Use the seed 900 to get the same pseudo random numbers every time
    random.seed(900)
    number_guess()

I removed the user input part, irrelevant parameters, and an extraneous loop, and now you get feedback on all the tested tokens:

32 is too low. Random number was 80.
45 is too low. Random number was 80.
48 is too low. Random number was 80.
80 is correct!


问:
accessing the return value of function that was bound to an event (tkinter)
Basically, what I've done is bound a click event to a function.  For example:

```<code>self.button1.bind("<Button-1>",self.chooseDice)
</code>```

What I want now is to access the result of chooseDice() in another function.  What is the best way to go about doing that?

```<code>class GraphicsInterface:

    #we want to initialize the game board here, set up the dice and buttons
    def __init__(self):
        self.window = Tk()
        self.window.geometry("720x500")

        #buttons under each die
        self.clicked=[] #empty list to collect all the buttons that were clicked (see chooseDice function)
        self.button1 = Button(self.window, text="Dice 1", width=13) #create the button object
        self.button1.place(x=60, y=160)
        #bind button click event to a function (chooseDice())
        self.button1.bind("<Button-1>",self.chooseDice)

        self.button2 = Button(self.window, text="Dice 2", width=13)
        self.button2.place(x=185, y=160)
        self.button2.bind("<Button-1>",self.chooseDice)

    #using the event as an argument, append the text to the clicked list
    def chooseDice(self, event):
        self.clicked.append(event.widget.cget('text'))
        self.diceList=[] #create a new empty list
        for i in range(len(self.clicked)):
            self.diceList.append(int(self.clicked[i][5])) #get just the int value of the last character (i.e. the dice number)
        self.deactivate(event.widget)  #deactivate the button
        return self.diceList
</code>```

答: just add a self.result attribute to your class and set it at chooseDice()

Body:
Basically, what I've done is bound a click event to a function.  For example:

self.button1.bind("<Button-1>",self.chooseDice)

What I want now is to access the result of chooseDice() in another function.  What is the best way to go about doing that?

class GraphicsInterface:

    #we want to initialize the game board here, set up the dice and buttons
    def __init__(self):
        self.window = Tk()
        self.window.geometry("720x500")

        #buttons under each die
        self.clicked=[] #empty list to collect all the buttons that were clicked (see chooseDice function)
        self.button1 = Button(self.window, text="Dice 1", width=13) #create the button object
        self.button1.place(x=60, y=160)
        #bind button click event to a function (chooseDice())
        self.button1.bind("<Button-1>",self.chooseDice)

        self.button2 = Button(self.window, text="Dice 2", width=13)
        self.button2.place(x=185, y=160)
        self.button2.bind("<Button-1>",self.chooseDice)

    #using the event as an argument, append the text to the clicked list
    def chooseDice(self, event):
        self.clicked.append(event.widget.cget('text'))
        self.diceList=[] #create a new empty list
        for i in range(len(self.clicked)):
            self.diceList.append(int(self.clicked[i][5])) #get just the int value of the last character (i.e. the dice number)
        self.deactivate(event.widget)  #deactivate the button
        return self.diceList


问:
I can't display the KML
I am taking my first steps in openlayers, I find it quite interesting, but based on a simple example to show OSM it has been impossible for me to add a layer with a KML file and show it together.

I understand that I am close to achieving it and that is why I go to you, thanks in advance for any help.

My code is the following:

```<code>import 'ol/ol.css';
import { Map, View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import VectorLayer from 'ol/layer/Vector';
import OSM from 'ol/source/OSM';
import KML from 'ol/format/KML';
import VectorSource from 'ol/source/Vector';

var openstreet = new TileLayer({
    source: new OSM()
})

var geomapa = new VectorLayer({
    source: new VectorSource({
        url: 'maps/kml/doc.kml',
        format: new KML()
    })
});

const map = new Map({
    target: 'map',
    layers: [openstreet, geomapa],
    view: new View({
        center: [0, 0],
        zoom: 0
    })
});
</code>```

答:
Hurra! debugging parcel i found the following error

```<code>    Access to XMLHttpRequest at 'https://geo.anantara.cl/maps/kml/2012-02-10.kml'
from origin 'http://localhost:1234' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.

[http://localhost:1234/]
Failed to load resource: net::ERR_FAILED [https://geo.anantara.cl/maps/kml/2012-02-10.kml]
</code>```

So working in express server..

Title: I can't display the KML

Body:
I am taking my first steps in openlayers, I find it quite interesting, but based on a simple example to show OSM it has been impossible for me to add a layer with a KML file and show it together.

I understand that I am close to achieving it and that is why I go to you, thanks in advance for any help.

My code is the following:

import 'ol/ol.css';
import { Map, View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import VectorLayer from 'ol/layer/Vector';
import OSM from 'ol/source/OSM';
import KML from 'ol/format/KML';
import VectorSource from 'ol/source/Vector';

var openstreet = new TileLayer({
    source: new OSM()
})

var geomapa = new VectorLayer({
    source: new VectorSource({
        url: 'maps/kml/doc.kml',
        format: new KML()
    })
});

const map = new Map({
    target: 'map',
    layers: [openstreet, geomapa],
    view: new View({
        center: [0, 0],
        zoom: 0
    })
});

Body:
Hurra! debugging parcel i found the following error

    Access to XMLHttpRequest at 'https://geo.anantara.cl/maps/kml/2012-02-10.kml'
from origin 'http://localhost:1234' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.

[http://localhost:1234/]
Failed to load resource: net::ERR_FAILED [https://geo.anantara.cl/maps/kml/2012-02-10.kml]

So working in express server..


问:
Eclipse 2020 language server for JS is showing error on thymeleaf to javascript variables
After upgrade from Eclipse 2019 to Eclipse 2020-03 I'm getting Markers: 'Language Server Error' on codes of thymeleaf to javascript variables. I still can run the code but the problem is these annoying messages.

I've tried to disable Eclipse language server preferences but nothing change.

For example, in a thymeleaf HTML file:

```<code><script th:inline="javascript">
  // thymeleaf to javascript variables
  var txSiglaUsina = [[${usina.txSigla}]];
  var idUsina = [[${usina.id}]];
  var cfgsVazaoSanitariaRef = [[${vazaoSanitariaRef}]];
  var contextPath = [[@{/}]];
  var blHoraCheia = false;
</script>
</code>```

I got this Eclipse Markers errors:

Thanks ;)

答:
The answer is disabling Eclipse Language Server on: Windows > Preferences > Language Server.

As I wrote above I've tried that but nothing change, only after editing and saving the file the erros Markers finally disapear.

Body:
After upgrade from Eclipse 2019 to Eclipse 2020-03 I'm getting Markers: 'Language Server Error' on codes of thymeleaf to javascript variables. I still can run the code but the problem is these annoying messages.

I've tried to disable Eclipse language server preferences but nothing change.

For example, in a thymeleaf HTML file:

I got this Eclipse Markers errors:

Thanks ;)


答:
You should replace this:

```<code>randint = ['']
random.randint(1,100)
</code>```

with this:

```<code>randint = random.randint(1,100)
</code>```

Title: How to generate random numbers and compare them with token inputs?

Body:
You should replace this:

randint = ['']
random.randint(1,100)

with this:

randint = random.randint(1,100)