问:
How to Update my Access Database from textboxes
i created a screen where i can edit the details in the database. but as soon as i click on the update button, it says no value given for one or more required parameters. i have attached my code....

Update BUtton...

```<code>Private Sub SimpleButton5_Click(sender As Object, e As EventArgs) Handles SimpleButton5.Click

    Try

        Access.AddParam("@UId", TextBox1.Text)
        Access.AddParam("@ImagePic", PictureBox1.Image)
        Access.AddParam("@Barcod", TextBox2.Text)
        Access.AddParam("@BrandName", TextBox3.Text)
        Access.AddParam("@StockName", TextBox4.Text)
        Access.AddParam("@Category", TextBox5.Text)
        Access.AddParam("@SubCat", TextBox6.Text)
        Access.AddParam("@Subcat2", TextBox7.Text)
        Access.AddParam("@Discrip", TextBox8.Text)
        Access.AddParam("@StockLvl", TextBox9.Text)
        Access.AddParam("@CustomAmount", TextBox10.Text)
        Access.AddParam("@CostPrice", TextBox11.Text)
        Access.AddParam("@Markup", TextBox12.Text)
        Access.AddParam("@TaxAmount", TextBox13.Text)
        Access.AddParam("@SellingPrice", TextBox14.Text)
        Access.AddParam("@BeforTax", TextBox15.Text)
        Access.AddParam("@AfterTax", TextBox16.Text)
        Access.AddParam("@TaxPer", TextBox17.Text)
        Access.AddParam("@MarkupPer", TextBox18.Text)
        Access.AddParam("@LastDate", TextBox19.Text)
        Access.AddParam("@LastUser", TextBox20.Text)

        Access.ExecQuery("UPDATE Inventory " &
                         "SET [Image]=PictureBox1.image, BarCode=Textbox2.text, " &
                         "BrandName=@BrandName, StockName=@StockName, Category=@Category, SubCategory=@SubCat, " &
                         "SubCategory2=@SubCat2, Description=@Discrip, StockLevels=@StockLvl, CustomAmount=@Customamount, " &
                         "CostPrice=@CostPrice, MarkupAmount=@Markup, SellingPrice=@SellingPrice, ProfirBefore=@BeforeTax, " &
                         "ProfitAfter=@AfterTax, TaxAmount=@TaxAmount, taxPer=@TaxPer, MarkupPer=@MarkupPer, LastDateupdated=@LAstDate, " &
                         "UpserUpdated=@LastUser WHERE ID=@UId")

        If NoErrors(True) = False Then Exit Sub

        RefreshData()

    Catch ex As Exception
        MsgBox(ex.Message)
    Finally

    End Try

End Sub
</code>```

My Access.ExecQuery --- (Class...)

```<code>Imports System.Data.OleDb

Public Class DBControl
    Private DBCon As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database1.accdb;")
    Private DBCmd As OleDbCommand
    Public DBDA As OleDbDataAdapter
    Public DBDT As DataTable
    Public Params As New List(Of OleDbParameter)
    Public RecordCount As Integer
    Public Exception As String

    Public Sub ExecQuery(Query As String)
        RecordCount = 0
        Exception = ""

        Try
            DBCon.Open()
            DBCmd = New OleDbCommand(Query, DBCon)

            Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))

            Params.Clear()

            DBDT = New DataTable
            DBDA = New OleDbDataAdapter(DBCmd)
            RecordCount = DBDA.Fill(DBDT)
        Catch ex As Exception
            Exception = ex.Message
        End Try

        If DBCon.State = ConnectionState.Open Then DBCon.Close()
    End Sub

    ' INCLUDE QUERY & COMMAND PARAMETERS
    Public Sub AddParam(Name As String, Value As Object)
        Dim NewParam As New OleDbParameter(Name, Value)
        Params.Add(NewParam)
    End Sub
End Class
</code>```

I have played around with this for 2 days now, but somewhere i am missing something or overlooking something

thx

Jaco

答:
I created a simple class for your Inventory object so I could avoid passing all of Properties as parameters. I can just pass the Inventory object to the UpdateDatabase method.

```<code>Public Class Inventory
    Public Property Picture As Byte()
    Public Property BarCode As String
    Public Property BrandName As String
    Public Property StockName As String
    Public Property Category As String
    Public Property SubCategory As String
    Public Property SubCategory2 As String
    Public Property Description As String
    Public Property StockLevels As Integer
    Public Property CustomAmount As Decimal
    Public Property CostPrice As Decimal
    Public Property MarkupAmount As Decimal
    Public Property SellingPrice As Decimal
    Public Property ProfitBefore As Decimal
    Public Property ProfitAfter As Decimal
    Public Property TaxAmount As Decimal
    Public Property taxPer As Decimal
    Public Property MarkupPer As Decimal
    Public Property LastDateupdated As Date
    Public Property UpserUpdated As String
    Public Property ID As Integer
End Class
</code>```

To get your picture box image in the proper format for storage I have a small function that takes an Image as a parameter and returns a Byte array.

```<code>'This Function requires Imports System.Drawing
Private Function GetByteArrayFromImage(img As Image) As Byte()
    Dim convert As New ImageConverter
    Dim arr = DirectCast(convert.ConvertTo(img, GetType(Byte())), Byte())
    Return arr
End Function
</code>```

Each property of the Inventory object is set. You can see that giving your controls meaningful names would help here. CInt, CDec, and CDate text boxes need to be validated before this code is reached.

I put the Try...Catch here so you could show a message to the user.

```<code>Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim img As Image = PictureBox1.Image
    Dim imgArray = GetByteArrayFromImage(img)
    Dim inv As New Inventory With
    {
        .Picture = imgArray,
        .BarCode = TextBox2.Text,
        .BrandName = TextBox3.Text,
        .StockName = TextBox4.Text,
        .Category = TextBox5.Text,
        .SubCategory = TextBox6.Text,
        .SubCategory2 = TextBox7.Text,
        .Description = TextBox8.Text,
        .StockLevels = CInt(TextBox9.Text),
        .CustomAmount = CDec(TextBox10.Text),
        .CostPrice = CDec(TextBox11.Text),
        .MarkupAmount = CDec(TextBox12.Text),
        .SellingPrice = CDec(TextBox14.Text),
        .ProfitBefore = CDec(TextBox15.Text),
        .ProfitAfter = CDec(TextBox16.Text),
        .TaxAmount = CDec(TextBox13.Text),
        .taxPer = CDec(TextBox17.Text),
        .MarkupPer = CDec(TextBox18.Text),
        .LastDateupdated = CDate(TextBox19.Text),
        .UpserUpdated = TextBox20.Text,
        .ID = CInt(TextBox1.Text)
    }
    Try
        UpdateDatabase(inv)
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub
</code>```

In Access the order that the parameters appear in the sql statement must match the order that they are added to the parameters collection.

I thought it was odd that all your field names are capitalized except taxPer. Check your database.

Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error.

The .Add method is superior to the method you were using because it includes datatypes and size. I had to guess at the types and sizes so check your database. Where I have guessed wrong, you will have to correct the .Add method, the type of the property in the Inventory class and the conversion of the text boxes .Text property. (3 places to change)

```<code>Private Sub UpdateDatabase(inv As Inventory)
    Dim sql = "UPDATE Inventory SET
                [Image]=@Picture,
                BarCode= @BarCode,
                BrandName=@BrandName,
                StockName=@StockName,
                Category=@Category,
                SubCategory=@SubCat,
                SubCategory2=@SubCat2,
                Description=@Discrip,
                StockLevels=@StockLvl,
                CustomAmount=@Customamount,
                CostPrice=@CostPrice,
                MarkupAmount=@Markup,
                SellingPrice=@SellingPrice,
                ProfirBefore=@BeforeTax,
                ProfitAfter=@AfterTax,
                TaxAmount=@TaxAmount,
                taxPer=@TaxPer,
                MarkupPer=@MarkupPer,
                LastDateupdated=@LAstDate,
                UpserUpdated=@LastUser
                WHERE ID=@UId"
    Using cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database1.accdb;"),
            cmd As New OleDbCommand(sql, cn)
        With cmd.Parameters
            .Add("@Picture", OleDbType.LongVarBinary).Value = inv.Picture
            .Add("@BarCode", OleDbType.VarChar, 100).Value = inv.BarCode
            .Add("@BrandName", OleDbType.VarChar, 100).Value = inv.BrandName
            .Add("@StockName", OleDbType.VarChar, 100).Value = inv.StockName
            .Add("@Category", OleDbType.VarChar, 100).Value = inv.Category
            .Add("@SubCat", OleDbType.VarChar, 100).Value = inv.SubCategory
            .Add("@SubCat2", OleDbType.VarChar, 100).Value = inv.SubCategory2
            .Add("@Discrip", OleDbType.VarChar, 100).Value = inv.Description
            .Add("@StockLvl", OleDbType.Integer).Value = inv.StockLevels
            .Add("@Customamount", OleDbType.Decimal).Value = inv.CustomAmount
            .Add("@CostPrice", OleDbType.Decimal).Value = inv.CostPrice
            .Add("@Markup", OleDbType.Decimal).Value = inv.MarkupAmount
            .Add("@SellingPrice", OleDbType.Decimal).Value = inv.SellingPrice
            .Add("@BeforeTax", OleDbType.Decimal).Value = inv.ProfitBefore
            .Add("@AfterTax", OleDbType.Decimal).Value = inv.ProfitAfter
            .Add("@TaxAmount", OleDbType.Decimal).Value = inv.TaxAmount
            .Add("@TaxPer", OleDbType.Decimal).Value = inv.taxPer
            .Add("@MarkupPer", OleDbType.Decimal).Value = inv.MarkupPer
            .Add("@LAstDate", OleDbType.Date).Value = inv.LastDateupdated
            .Add("@LastUser ", OleDbType.VarChar, 100).Value = inv.UpserUpdated
            .Add("@UId", OleDbType.Integer).Value = inv.ID
        End With
        cn.Open()
        cmd.ExecuteNonQuery()
    End Using
End Sub
</code>```

Body:
i created a screen where i can edit the details in the database. but as soon as i click on the update button, it says no value given for one or more required parameters. i have attached my code....

Update BUtton...

Private Sub SimpleButton5_Click(sender As Object, e As EventArgs) Handles SimpleButton5.Click

    Try

        Access.AddParam("@UId", TextBox1.Text)
        Access.AddParam("@ImagePic", PictureBox1.Image)
        Access.AddParam("@Barcod", TextBox2.Text)
        Access.AddParam("@BrandName", TextBox3.Text)
        Access.AddParam("@StockName", TextBox4.Text)
        Access.AddParam("@Category", TextBox5.Text)
        Access.AddParam("@SubCat", TextBox6.Text)
        Access.AddParam("@Subcat2", TextBox7.Text)
        Access.AddParam("@Discrip", TextBox8.Text)
        Access.AddParam("@StockLvl", TextBox9.Text)
        Access.AddParam("@CustomAmount", TextBox10.Text)
        Access.AddParam("@CostPrice", TextBox11.Text)
        Access.AddParam("@Markup", TextBox12.Text)
        Access.AddParam("@TaxAmount", TextBox13.Text)
        Access.AddParam("@SellingPrice", TextBox14.Text)
        Access.AddParam("@BeforTax", TextBox15.Text)
        Access.AddParam("@AfterTax", TextBox16.Text)
        Access.AddParam("@TaxPer", TextBox17.Text)
        Access.AddParam("@MarkupPer", TextBox18.Text)
        Access.AddParam("@LastDate", TextBox19.Text)
        Access.AddParam("@LastUser", TextBox20.Text)

        Access.ExecQuery("UPDATE Inventory " &
                         "SET [Image]=PictureBox1.image, BarCode=Textbox2.text, " &
                         "BrandName=@BrandName, StockName=@StockName, Category=@Category, SubCategory=@SubCat, " &
                         "SubCategory2=@SubCat2, Description=@Discrip, StockLevels=@StockLvl, CustomAmount=@Customamount, " &
                         "CostPrice=@CostPrice, MarkupAmount=@Markup, SellingPrice=@SellingPrice, ProfirBefore=@BeforeTax, " &
                         "ProfitAfter=@AfterTax, TaxAmount=@TaxAmount, taxPer=@TaxPer, MarkupPer=@MarkupPer, LastDateupdated=@LAstDate, " &
                         "UpserUpdated=@LastUser WHERE ID=@UId")

        If NoErrors(True) = False Then Exit Sub

        RefreshData()

    Catch ex As Exception
        MsgBox(ex.Message)
    Finally

    End Try

End Sub

My Access.ExecQuery --- (Class...)

Imports System.Data.OleDb

Public Class DBControl
    Private DBCon As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database1.accdb;")
    Private DBCmd As OleDbCommand
    Public DBDA As OleDbDataAdapter
    Public DBDT As DataTable
    Public Params As New List(Of OleDbParameter)
    Public RecordCount As Integer
    Public Exception As String

    Public Sub ExecQuery(Query As String)
        RecordCount = 0
        Exception = ""

        Try
            DBCon.Open()
            DBCmd = New OleDbCommand(Query, DBCon)

            Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))

            Params.Clear()

            DBDT = New DataTable
            DBDA = New OleDbDataAdapter(DBCmd)
            RecordCount = DBDA.Fill(DBDT)
        Catch ex As Exception
            Exception = ex.Message
        End Try

        If DBCon.State = ConnectionState.Open Then DBCon.Close()
    End Sub

    ' INCLUDE QUERY & COMMAND PARAMETERS
    Public Sub AddParam(Name As String, Value As Object)
        Dim NewParam As New OleDbParameter(Name, Value)
        Params.Add(NewParam)
    End Sub
End Class

I have played around with this for 2 days now, but somewhere i am missing something or overlooking something

thx

Jaco

Body:
I created a simple class for your Inventory object so I could avoid passing all of Properties as parameters. I can just pass the Inventory object to the UpdateDatabase method.

Public Class Inventory
    Public Property Picture As Byte()
    Public Property BarCode As String
    Public Property BrandName As String
    Public Property StockName As String
    Public Property Category As String
    Public Property SubCategory As String
    Public Property SubCategory2 As String
    Public Property Description As String
    Public Property StockLevels As Integer
    Public Property CustomAmount As Decimal
    Public Property CostPrice As Decimal
    Public Property MarkupAmount As Decimal
    Public Property SellingPrice As Decimal
    Public Property ProfitBefore As Decimal
    Public Property ProfitAfter As Decimal
    Public Property TaxAmount As Decimal
    Public Property taxPer As Decimal
    Public Property MarkupPer As Decimal
    Public Property LastDateupdated As Date
    Public Property UpserUpdated As String
    Public Property ID As Integer
End Class

To get your picture box image in the proper format for storage I have a small function that takes an Image as a parameter and returns a Byte array.

'This Function requires Imports System.Drawing
Private Function GetByteArrayFromImage(img As Image) As Byte()
    Dim convert As New ImageConverter
    Dim arr = DirectCast(convert.ConvertTo(img, GetType(Byte())), Byte())
    Return arr
End Function

Each property of the Inventory object is set. You can see that giving your controls meaningful names would help here. CInt, CDec, and CDate text boxes need to be validated before this code is reached.

I put the Try...Catch here so you could show a message to the user.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim img As Image = PictureBox1.Image
    Dim imgArray = GetByteArrayFromImage(img)
    Dim inv As New Inventory With
    {
        .Picture = imgArray,
        .BarCode = TextBox2.Text,
        .BrandName = TextBox3.Text,
        .StockName = TextBox4.Text,
        .Category = TextBox5.Text,
        .SubCategory = TextBox6.Text,
        .SubCategory2 = TextBox7.Text,
        .Description = TextBox8.Text,
        .StockLevels = CInt(TextBox9.Text),
        .CustomAmount = CDec(TextBox10.Text),
        .CostPrice = CDec(TextBox11.Text),
        .MarkupAmount = CDec(TextBox12.Text),
        .SellingPrice = CDec(TextBox14.Text),
        .ProfitBefore = CDec(TextBox15.Text),
        .ProfitAfter = CDec(TextBox16.Text),
        .TaxAmount = CDec(TextBox13.Text),
        .taxPer = CDec(TextBox17.Text),
        .MarkupPer = CDec(TextBox18.Text),
        .LastDateupdated = CDate(TextBox19.Text),
        .UpserUpdated = TextBox20.Text,
        .ID = CInt(TextBox1.Text)
    }
    Try
        UpdateDatabase(inv)
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub

In Access the order that the parameters appear in the sql statement must match the order that they are added to the parameters collection.

I thought it was odd that all your field names are capitalized except taxPer. Check your database.

Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error.

The .Add method is superior to the method you were using because it includes datatypes and size. I had to guess at the types and sizes so check your database. Where I have guessed wrong, you will have to correct the .Add method, the type of the property in the Inventory class and the conversion of the text boxes .Text property. (3 places to change)

Private Sub UpdateDatabase(inv As Inventory)
    Dim sql = "UPDATE Inventory SET
                [Image]=@Picture,
                BarCode= @BarCode,
                BrandName=@BrandName,
                StockName=@StockName,
                Category=@Category,
                SubCategory=@SubCat,
                SubCategory2=@SubCat2,
                Description=@Discrip,
                StockLevels=@StockLvl,
                CustomAmount=@Customamount,
                CostPrice=@CostPrice,
                MarkupAmount=@Markup,
                SellingPrice=@SellingPrice,
                ProfirBefore=@BeforeTax,
                ProfitAfter=@AfterTax,
                TaxAmount=@TaxAmount,
                taxPer=@TaxPer,
                MarkupPer=@MarkupPer,
                LastDateupdated=@LAstDate,
                UpserUpdated=@LastUser
                WHERE ID=@UId"
    Using cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database1.accdb;"),
            cmd As New OleDbCommand(sql, cn)
        With cmd.Parameters
            .Add("@Picture", OleDbType.LongVarBinary).Value = inv.Picture
            .Add("@BarCode", OleDbType.VarChar, 100).Value = inv.BarCode
            .Add("@BrandName", OleDbType.VarChar, 100).Value = inv.BrandName
            .Add("@StockName", OleDbType.VarChar, 100).Value = inv.StockName
            .Add("@Category", OleDbType.VarChar, 100).Value = inv.Category
            .Add("@SubCat", OleDbType.VarChar, 100).Value = inv.SubCategory
            .Add("@SubCat2", OleDbType.VarChar, 100).Value = inv.SubCategory2
            .Add("@Discrip", OleDbType.VarChar, 100).Value = inv.Description
            .Add("@StockLvl", OleDbType.Integer).Value = inv.StockLevels
            .Add("@Customamount", OleDbType.Decimal).Value = inv.CustomAmount
            .Add("@CostPrice", OleDbType.Decimal).Value = inv.CostPrice
            .Add("@Markup", OleDbType.Decimal).Value = inv.MarkupAmount
            .Add("@SellingPrice", OleDbType.Decimal).Value = inv.SellingPrice
            .Add("@BeforeTax", OleDbType.Decimal).Value = inv.ProfitBefore
            .Add("@AfterTax", OleDbType.Decimal).Value = inv.ProfitAfter
            .Add("@TaxAmount", OleDbType.Decimal).Value = inv.TaxAmount
            .Add("@TaxPer", OleDbType.Decimal).Value = inv.taxPer
            .Add("@MarkupPer", OleDbType.Decimal).Value = inv.MarkupPer
            .Add("@LAstDate", OleDbType.Date).Value = inv.LastDateupdated
            .Add("@LastUser ", OleDbType.VarChar, 100).Value = inv.UpserUpdated
            .Add("@UId", OleDbType.Integer).Value = inv.ID
        End With
        cn.Open()
        cmd.ExecuteNonQuery()
    End Using
End Sub


来源: stackexchange

问:
How do you get a file in C++?
So the teacher has posed this assignment:

You have been hired by the United Network Command for Law Enforcement, and you have been given files containing null cyphers you have to decrypt.

So for the first file given (as an example), every other letter is correct (ie: 'hielqlpo' is hello (assuming you start with the first letter).  My first question is, how do I read in a file?  The document is on my desktop in a folder and the file is named document01.cry.  I'm not sure the command I need to put that file into the program.

I'm also not overly sure how to grab a letter and skip a letter, but honestly I want to tinker with that before I post that question! So for now...my question is as stated in the title: How do you grab a file for reading in C++?

If it makes a difference (As I'm sure it does), I'm using Visual C++ 2008 Express Edition (because it's free and I like it! I've also attached what I have so far, please keep in mind it's -very- basic...and I added the getchar(); at the end so when it does run properly, the window stays open so I can see it (as Visual Express tends to close the window as soon as it's done running.)

The code so far:

```<code>#include<iostream>

using namespace std;

int main()
{
    while (! cin.eof())
    {
        int c = cin.get() ;
        cout.put(c) ;
    }
    getchar();
}
</code>```

PS: I realize that this code grabs and puts out every character. For now that's fine, once I can read in the file I think I can tinker with it from there.  I'm also poking at a book or two I have on C++ to see it anything pops up and screams "Pick me!" Thanks again!

EDIT:: Also curious, is there a way to input the file you want?
(I.e.:

```<code>char filename;
cout << "Please make sure the document is in the same file as the program, thank you!" << endl << "Please input document name: " ;
cin >> filename;
cout << endl;
ifstream infile(filename, ios::in);
</code>```

This code doesn't work. It shoots back an error saying the char can't be converted to a const char *.  How can this problem be fixed?

EDIT 2:
Never mind about said part 2, I found it out! Thanks again for the assistance!

答:
[EDIT]  include support for command line arguments
[EDIT]  Fixed possible memory leak
[EDIT]  Fixed a missing reference

```<code>#include <fstream>
#include <iostream>

using namespace std;

int main(int argc, char *argv){
    ifstream infh;  // our file stream
    char *buffer;

    for(int c = 1; c < argc; c++){
        infh.open(argv[c]);

        //Error out if the file is not open
        if(!infh){
            cerr << "Could not open file: "<< argv[c] << endl;
            continue;
        }

        //Get the length of the file
        infh.seekg(0, ios::end);
        int length = infh.tellg();

        //reset the file pointer to the beginning
        is.seekg(0, ios::beg);

        //Create our buffer
        buffer = new char[length];

        // Read the entire file into the buffer
        infd.read(buffer, length);

        //Cycle through the buffer, outputting every other char
        for(int i=0; i < length; i+= 2){
            cout << buffer[i];
        }
        infh.close();
    }
    //Clean up
    delete[] buffer;
    return 0;
}
</code>```

Should do the trick. If the file is extremely large, you probably shouldn't load the entire file into the buffer.

OwnerDisplayName: Jeff

ContentLicense: CC BY-SA 2.5

Title: How do you get a file in C++?

Body:
So the teacher has posed this assignment:

You have been hired by the United Network Command for Law Enforcement, and you have been given files containing null cyphers you have to decrypt.

So for the first file given (as an example), every other letter is correct (ie: 'hielqlpo' is hello (assuming you start with the first letter).  My first question is, how do I read in a file?  The document is on my desktop in a folder and the file is named document01.cry.  I'm not sure the command I need to put that file into the program.

I'm also not overly sure how to grab a letter and skip a letter, but honestly I want to tinker with that before I post that question! So for now...my question is as stated in the title: How do you grab a file for reading in C++?

If it makes a difference (As I'm sure it does), I'm using Visual C++ 2008 Express Edition (because it's free and I like it! I've also attached what I have so far, please keep in mind it's -very- basic...and I added the getchar(); at the end so when it does run properly, the window stays open so I can see it (as Visual Express tends to close the window as soon as it's done running.)

The code so far:

#include<iostream>

using namespace std;

int main()
{
    while (! cin.eof())
    {
        int c = cin.get() ;
        cout.put(c) ;
    }
    getchar();
}

PS: I realize that this code grabs and puts out every character. For now that's fine, once I can read in the file I think I can tinker with it from there.  I'm also poking at a book or two I have on C++ to see it anything pops up and screams "Pick me!" Thanks again!

EDIT:: Also curious, is there a way to input the file you want?
(I.e.:

char filename;
cout << "Please make sure the document is in the same file as the program, thank you!" << endl << "Please input document name: " ;
cin >> filename;
cout << endl;
ifstream infile(filename, ios::in);

This code doesn't work. It shoots back an error saying the char can't be converted to a const char *.  How can this problem be fixed?

EDIT 2:
Never mind about said part 2, I found it out! Thanks again for the assistance!

LastEditorDisplayName: EvilTeach

Body:
[EDIT]  include support for command line arguments
[EDIT]  Fixed possible memory leak
[EDIT]  Fixed a missing reference

#include <fstream>
#include <iostream>

using namespace std;

int main(int argc, char *argv){
    ifstream infh;  // our file stream
    char *buffer;

    for(int c = 1; c < argc; c++){
        infh.open(argv[c]);

        //Error out if the file is not open
        if(!infh){
            cerr << "Could not open file: "<< argv[c] << endl;
            continue;
        }

        //Get the length of the file
        infh.seekg(0, ios::end);
        int length = infh.tellg();

        //reset the file pointer to the beginning
        is.seekg(0, ios::beg);

        //Create our buffer
        buffer = new char[length];

        // Read the entire file into the buffer
        infd.read(buffer, length);

        //Cycle through the buffer, outputting every other char
        for(int i=0; i < length; i+= 2){
            cout << buffer[i];
        }
        infh.close();
    }
    //Clean up
    delete[] buffer;
    return 0;
}

Should do the trick. If the file is extremely large, you probably shouldn't load the entire file into the buffer.

OwnerDisplayName: Scott

LastEditorDisplayName: Scott


问:
Mismatch in batch size
**My complete code is here: I am following github code for accomplishing my task. I am getting dimensions mismatch error. The code is giving me dimension mismatch error. I am receiving the following error: ValueError: Expected input batch_size (1) to match target batch_size (64).I am confused, i don't know what should i change in this code. Please help me in resolving this issue. **

```<code>def windowz(data, size):
   start = 0
   while start < len(data):
       yield start, start + size
      start += (size // 2)

 def segment_pa2(x_train,y_train,window_size):
segments = np.zeros(((len(x_train)//(window_size//2))-1,window_size,52))
labels = np.zeros(((len(y_train)//(window_size//2))-1))
i_segment = 0
i_label = 0
for (start,end) in windowz(x_train,window_size):
    if(len(x_train[start:end]) == window_size):
        m = stats.mode(y_train[start:end])
        segments[i_segment] = x_train[start:end]
        labels[i_label] = m[0]
        i_label+=1
        i_segment+=1

  return segments, labels
  print ('starting...')
 start_time = time.time()

dataset = sys.argv[1]
 path = '/Users/tehreem/Desktop/PAMAP2/PAMAP2_Dataset/pamap2.h5'

f = h5py.File(path, 'r')
print(f)

   x_train = f.get('train').get('inputs')[()]
   y_train = f.get('train').get('targets')[()]

  x_test = f.get('test').get('inputs')[()]
  y_test = f.get('test').get('targets')[()]

 print ("x_train shape =",x_train.shape)
 print ("y_train shape =",y_train.shape)
 print ("x_test shape =" ,x_test.shape)
 print ("y_test shape =",y_test.shape)

x_train = x_train[::3,:]
y_train = y_train[::3]
x_test = x_test[::3,:]
y_test = y_test[::3]
print ("x_train shape(downsampled) = ", x_train.shape)
print ("y_train shape(downsampled) =",y_train.shape)
print ("x_test shape(downsampled) =" ,x_test.shape)
print ("y_test shape(downsampled) =",y_test.shape)

 print (np.unique(y_train))
 print (np.unique(y_test))
unq = np.unique(y_test)

input_width = 52
print("segmenting signal...")
train_x, train_y = segment_pa2(x_train,y_train,input_width)
test_x, test_y = segment_pa2(x_test,y_test,input_width)
print ("signal segmented.")

train = pd.get_dummies(train_y)
test = pd.get_dummies(test_y)
train, test = train.align(test, join='inner', axis=1)

train_y = np.asarray(train)
test_y = np.asarray(test)

input_height = 1
input_width = input_width
num_labels = 11
num_channels = 52

   batch_size = 64
   stride_size = 2
   kernel_size_1 = 7
  kernel_size_2 = 3
  kernel_size_3 = 1
  depth_1 = 128
 depth_2 = 128
depth_3 = 128
num_hidden = 512

 dropout_1 = 0.1 #0.1
 dropout_2 = 0.25 #0.25
 dropout_3 = 0.5 #0.5

learning_rate = 0.0005
training_epochs = 50
total_batches = train_x.shape[0] // batch_size

  train_x = train_x.reshape(len(train_x),1,input_width,num_channels)
  test_x = test_x.reshape(len(test_x),1,input_width,num_channels)
 print ("test_x_reshaped = " , test_x.shape)
 print ("train_x shape =",train_x.shape)
 print ("train_y shape =",train_y.shape)
 print ("test_x shape =",test_x.shape)
 print ("test_y shape =",test_y.shape)

 train_x = train_x.reshape(-1,input_width,num_channels)
 test_x = test_x.reshape(-1,input_width,num_channels)

 def init_weights(m):
if type(m) == nn.LSTM:
    for name, param in m.named_parameters():
        if 'weight_ih' in name:
            torch.nn.init.orthogonal_(param.data)
        elif 'weight_hh' in name:
            torch.nn.init.orthogonal_(param.data)
        elif 'bias' in name:
            param.data.fill_(0)
  elif type(m) == nn.Conv1d or type(m) == nn.Linear:
    torch.nn.init.orthogonal_(m.weight)
    m.bias.data.fill_(0)
 model.apply(init_weights)

 import torch
 import torch.nn as nn
import torch.nn.functional as F

  class  CharCNN(nn.Module):
     def __init__(self):
     super(CharCNN, self).__init__()

    self.conv1 = nn.Sequential(
        nn.Conv1d(num_channels, depth_1, kernel_size=kernel_size_1, stride=stride_size),
        nn.ReLU(),
        nn.MaxPool1d(kernel_size=kernel_size_1, stride=stride_size),
        nn.Dropout(0.1),
    )

    self.conv2 = nn.Sequential(
        nn.Conv1d(depth_1, depth_2, kernel_size=kernel_size_2, stride=stride_size),
        nn.ReLU(),
        nn.MaxPool1d(kernel_size=kernel_size_2, stride=stride_size),
        nn.Dropout(0.25)
    )

    self.fc1 = nn.Sequential(
        nn.Linear(128*64, num_hidden),
        nn.ReLU(),
        nn.Dropout(0.5)
    )

    self.fc2 = nn.Sequential(
        nn.Linear(num_hidden, 11),
        nn.ReLU(),
        nn.Dropout(0.5)
    )

def forward(self, x):
    out = self.conv1(x)
    out = self.conv2(out)

    # collapse
    out = out.reshape(-1,128*64)
    #out = out.view(out.size(0), -1)
    # linear layer
    out = self.fc1(out)
    # output layer
    out = self.fc2(out)
    #out = self.log_softmax(x,dim=1)

    return out

 model =  CharCNN()
 print(model)

def iterate_minibatches(inputs, targets, batch_size, shuffle=True):
assert len(inputs) == len(targets)
if shuffle:
    indices = np.arange(len(inputs))
    np.random.shuffle(indices)
for start_idx in range(0, len(inputs) - batch_size + 1, batch_size):
    if shuffle:
        excerpt = indices[start_idx:start_idx + batch_size]
    else:
        excerpt = slice(start_idx, start_idx + batch_size)
    yield inputs[excerpt], targets[excerpt]

 criterion = nn.CrossEntropyLoss()
opt = torch.optim.Adam(model.parameters(),lr=learning_rate)

for e in range(training_epochs):
   if(train_on_gpu):
     net.cuda()
   train_losses = []

for batch in iterate_minibatches(train_x, train_y, batch_size):
    x, y = batch
    inputs, targets = torch.from_numpy(x), torch.from_numpy(y)
    if(train_on_gpu):
        inputs, targets = inputs.cuda(), targets.cuda()
        #inputs= inputs.view(batch_size,  128*64)
        #targets = targets.view(batch_size)
    opt.zero_grad()
    output = model(inputs)

    loss = criterion(output, targets.long())
    train_losses.append(loss.item())
    loss.backward()
    opt.step()
val_losses = []
accuracy=0
f1score=0
print("Epoch: {}/{}...".format(e+1, training_epochs),
              "Train Loss: {:.4f}...".format(np.mean(train_losses)))
</code>```

I received the following error:

```<code><ipython-input-468-7a508893b28d> in <module>
     21         output = model(inputs)
     22
---> 23         loss = criterion(output, targets.long())
     24         train_losses.append(loss.item())
     25         loss.backward()

~\AppData\Local\Continuum\anaconda3\lib\site-packages\torch\nn\modules\module.py in __call__(self, *input, **kwargs)
    530             result = self._slow_forward(*input, **kwargs)
    531         else:
--> 532             result = self.forward(*input, **kwargs)
    533         for hook in self._forward_hooks.values():
    534             hook_result = hook(self, input, result)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\torch\nn\modules\loss.py in forward(self, input, target)
    914     def forward(self, input, target):
    915         return F.cross_entropy(input, target, weight=self.weight,
--> 916                                ignore_index=self.ignore_index, reduction=self.reduction)
    917
    918

~\AppData\Local\Continuum\anaconda3\lib\site-packages\torch\nn\functional.py in cross_entropy(input, target, weight, size_average, ignore_index, reduce, reduction)
   2019     if size_average is not None or reduce is not None:
   2020         reduction = _Reduction.legacy_get_string(size_average, reduce)
-> 2021     return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)
   2022
   2023

~\AppData\Local\Continuum\anaconda3\lib\site-packages\torch\nn\functional.py in nll_loss(input, target, weight, size_average, ignore_index, reduce, reduction)
   1834     if input.size(0) != target.size(0):
   1835         raise ValueError('Expected input batch_size ({}) to match target batch_size ({}).'
-> 1836                          .format(input.size(0), target.size(0)))
   1837     if dim == 2:
   1838         ret = torch._C._nn.nll_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)

ValueError: Expected input batch_size (1) to match target batch_size (64).```

```

答:
The code you have posted hasn't been pasted correctly with proper indentations (it's different in every part of the code), so it's hard to go through the code.

But from what I understand from your error message, the problem lies with the size of your 'output' tensor. For a batch size of 64, the 'output' tensor should have the dimension (64, num_classes). But the first dimension of your 'output' tensor is 1 according to the error message. I suspect that there is an extra dimension getting added to your tensor somehow.

I would suggest printing out the size of your 'output' tensor using output.size() and that should give you an idea where the bug lies. If my intuition is correct and if it is indeed (1, 64, num_classes), then a simple output = output.squeeze(0) should do the trick.

ContentLicense: CC BY-SA 4.0

Title: Mismatch in batch size

Body:
**My complete code is here: I am following github code for accomplishing my task. I am getting dimensions mismatch error. The code is giving me dimension mismatch error. I am receiving the following error: ValueError: Expected input batch_size (1) to match target batch_size (64).I am confused, i don't know what should i change in this code. Please help me in resolving this issue. **

def windowz(data, size):
   start = 0
   while start < len(data):
       yield start, start + size
      start += (size // 2)

 def segment_pa2(x_train,y_train,window_size):
segments = np.zeros(((len(x_train)//(window_size//2))-1,window_size,52))
labels = np.zeros(((len(y_train)//(window_size//2))-1))
i_segment = 0
i_label = 0
for (start,end) in windowz(x_train,window_size):
    if(len(x_train[start:end]) == window_size):
        m = stats.mode(y_train[start:end])
        segments[i_segment] = x_train[start:end]
        labels[i_label] = m[0]
        i_label+=1
        i_segment+=1

  return segments, labels
  print ('starting...')
 start_time = time.time()

dataset = sys.argv[1]
 path = '/Users/tehreem/Desktop/PAMAP2/PAMAP2_Dataset/pamap2.h5'

f = h5py.File(path, 'r')
print(f)

   x_train = f.get('train').get('inputs')[()]
   y_train = f.get('train').get('targets')[()]

  x_test = f.get('test').get('inputs')[()]
  y_test = f.get('test').get('targets')[()]

 print ("x_train shape =",x_train.shape)
 print ("y_train shape =",y_train.shape)
 print ("x_test shape =" ,x_test.shape)
 print ("y_test shape =",y_test.shape)

x_train = x_train[::3,:]
y_train = y_train[::3]
x_test = x_test[::3,:]
y_test = y_test[::3]
print ("x_train shape(downsampled) = ", x_train.shape)
print ("y_train shape(downsampled) =",y_train.shape)
print ("x_test shape(downsampled) =" ,x_test.shape)
print ("y_test shape(downsampled) =",y_test.shape)

 print (np.unique(y_train))
 print (np.unique(y_test))
unq = np.unique(y_test)

input_width = 52
print("segmenting signal...")
train_x, train_y = segment_pa2(x_train,y_train,input_width)
test_x, test_y = segment_pa2(x_test,y_test,input_width)
print ("signal segmented.")

train = pd.get_dummies(train_y)
test = pd.get_dummies(test_y)
train, test = train.align(test, join='inner', axis=1)

train_y = np.asarray(train)
test_y = np.asarray(test)

input_height = 1
input_width = input_width
num_labels = 11
num_channels = 52

   batch_size = 64
   stride_size = 2
   kernel_size_1 = 7
  kernel_size_2 = 3
  kernel_size_3 = 1
  depth_1 = 128
 depth_2 = 128
depth_3 = 128
num_hidden = 512

 dropout_1 = 0.1 #0.1
 dropout_2 = 0.25 #0.25
 dropout_3 = 0.5 #0.5

learning_rate = 0.0005
training_epochs = 50
total_batches = train_x.shape[0] // batch_size

  train_x = train_x.reshape(len(train_x),1,input_width,num_channels)
  test_x = test_x.reshape(len(test_x),1,input_width,num_channels)
 print ("test_x_reshaped = " , test_x.shape)
 print ("train_x shape =",train_x.shape)
 print ("train_y shape =",train_y.shape)
 print ("test_x shape =",test_x.shape)
 print ("test_y shape =",test_y.shape)

 train_x = train_x.reshape(-1,input_width,num_channels)
 test_x = test_x.reshape(-1,input_width,num_channels)

 def init_weights(m):
if type(m) == nn.LSTM:
    for name, param in m.named_parameters():
        if 'weight_ih' in name:
            torch.nn.init.orthogonal_(param.data)
        elif 'weight_hh' in name:
            torch.nn.init.orthogonal_(param.data)
        elif 'bias' in name:
            param.data.fill_(0)
  elif type(m) == nn.Conv1d or type(m) == nn.Linear:
    torch.nn.init.orthogonal_(m.weight)
    m.bias.data.fill_(0)
 model.apply(init_weights)

 import torch
 import torch.nn as nn
import torch.nn.functional as F

  class  CharCNN(nn.Module):
     def __init__(self):
     super(CharCNN, self).__init__()

    self.conv1 = nn.Sequential(
        nn.Conv1d(num_channels, depth_1, kernel_size=kernel_size_1, stride=stride_size),
        nn.ReLU(),
        nn.MaxPool1d(kernel_size=kernel_size_1, stride=stride_size),
        nn.Dropout(0.1),
    )

    self.conv2 = nn.Sequential(
        nn.Conv1d(depth_1, depth_2, kernel_size=kernel_size_2, stride=stride_size),
        nn.ReLU(),
        nn.MaxPool1d(kernel_size=kernel_size_2, stride=stride_size),
        nn.Dropout(0.25)
    )

    self.fc1 = nn.Sequential(
        nn.Linear(128*64, num_hidden),
        nn.ReLU(),
        nn.Dropout(0.5)
    )

    self.fc2 = nn.Sequential(
        nn.Linear(num_hidden, 11),
        nn.ReLU(),
        nn.Dropout(0.5)
    )

def forward(self, x):
    out = self.conv1(x)
    out = self.conv2(out)

    # collapse
    out = out.reshape(-1,128*64)
    #out = out.view(out.size(0), -1)
    # linear layer
    out = self.fc1(out)
    # output layer
    out = self.fc2(out)
    #out = self.log_softmax(x,dim=1)

    return out

 model =  CharCNN()
 print(model)

def iterate_minibatches(inputs, targets, batch_size, shuffle=True):
assert len(inputs) == len(targets)
if shuffle:
    indices = np.arange(len(inputs))
    np.random.shuffle(indices)
for start_idx in range(0, len(inputs) - batch_size + 1, batch_size):
    if shuffle:
        excerpt = indices[start_idx:start_idx + batch_size]
    else:
        excerpt = slice(start_idx, start_idx + batch_size)
    yield inputs[excerpt], targets[excerpt]

 criterion = nn.CrossEntropyLoss()
opt = torch.optim.Adam(model.parameters(),lr=learning_rate)

for e in range(training_epochs):
   if(train_on_gpu):
     net.cuda()
   train_losses = []

for batch in iterate_minibatches(train_x, train_y, batch_size):
    x, y = batch
    inputs, targets = torch.from_numpy(x), torch.from_numpy(y)
    if(train_on_gpu):
        inputs, targets = inputs.cuda(), targets.cuda()
        #inputs= inputs.view(batch_size,  128*64)
        #targets = targets.view(batch_size)
    opt.zero_grad()
    output = model(inputs)

    loss = criterion(output, targets.long())
    train_losses.append(loss.item())
    loss.backward()
    opt.step()
val_losses = []
accuracy=0
f1score=0
print("Epoch: {}/{}...".format(e+1, training_epochs),
              "Train Loss: {:.4f}...".format(np.mean(train_losses)))

I received the following error:

<ipython-input-468-7a508893b28d> in <module>
     21         output = model(inputs)
     22
---> 23         loss = criterion(output, targets.long())
     24         train_losses.append(loss.item())
     25         loss.backward()

~\AppData\Local\Continuum\anaconda3\lib\site-packages\torch\nn\modules\module.py in __call__(self, *input, **kwargs)
    530             result = self._slow_forward(*input, **kwargs)
    531         else:
--> 532             result = self.forward(*input, **kwargs)
    533         for hook in self._forward_hooks.values():
    534             hook_result = hook(self, input, result)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\torch\nn\modules\loss.py in forward(self, input, target)
    914     def forward(self, input, target):
    915         return F.cross_entropy(input, target, weight=self.weight,
--> 916                                ignore_index=self.ignore_index, reduction=self.reduction)
    917
    918

~\AppData\Local\Continuum\anaconda3\lib\site-packages\torch\nn\functional.py in cross_entropy(input, target, weight, size_average, ignore_index, reduce, reduction)
   2019     if size_average is not None or reduce is not None:
   2020         reduction = _Reduction.legacy_get_string(size_average, reduce)
-> 2021     return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)
   2022
   2023

~\AppData\Local\Continuum\anaconda3\lib\site-packages\torch\nn\functional.py in nll_loss(input, target, weight, size_average, ignore_index, reduce, reduction)
   1834     if input.size(0) != target.size(0):
   1835         raise ValueError('Expected input batch_size ({}) to match target batch_size ({}).'
-> 1836                          .format(input.size(0), target.size(0)))
   1837     if dim == 2:
   1838         ret = torch._C._nn.nll_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)

ValueError: Expected input batch_size (1) to match target batch_size (64).```


问:
Can any one please tell me proper way to Develop Separate Undefined component in ReactJs
ReactJs

I am trying to create separate reusable Undefined Component to handle undefined properties but initially its comes with undefined so passed children throwing "Cant read property error"
here is the component

Final Aim = how to show children  only if the passed property  not undefined

```<code> <CanUndefined property={schedules.review} message="Yet you dont have any reviews">
      <span>{schedules.review.message}</span>
 </CanUndefined>
</code>```

bellow component is ParentComponent

```<code>const CanUndefined = props => props.property ?
                             (props.children) :
                             (<span>
                                 {props.message}
                              </span>)
</code>```

thanks in advance

答:
You can wrap your component around condition,

e.g.

you want to display div tag if message is there than

```<code>
const {message} = source of your property;
if(message){
   <span>{message}</span>
}

or even short format

{message && (
   <span>{message}</span>
)}

</code>```

Body:
ReactJs

I am trying to create separate reusable Undefined Component to handle undefined properties but initially its comes with undefined so passed children throwing "Cant read property error"
here is the component

Final Aim = how to show children  only if the passed property  not undefined

 <CanUndefined property={schedules.review} message="Yet you dont have any reviews">
      {schedules.review.message}
 </CanUndefined>

bellow component is ParentComponent

const CanUndefined = props => props.property ?
                             (props.children) :
                             (
                                 {props.message}
                              )

thanks in advance

Body:
You can wrap your component around condition,

e.g.

you want to display div tag if message is there than

const {message} = source of your property;
if(message){
   <span>{message}</span>
}

or even short format

{message && (
   <span>{message}</span>
)}


问:
How to fix this "Invisible" syntax error in MySql query? (Using UPDATE inside TRIGGER)
I have the following MySQL query to create a trigger:

CREATE TRIGGER `updateParentLastInteractionOnInsert`
AFTER INSERT
ON `Post` FOR EACH ROW
BEGIN
    UPDATE `Post` SET `lastInteraction` = CURRENT_TIMESTAMP WHERE `id` = new.`parentPostId`;
END;
```

<p>When I execute the query, I get the following error message:</p>

<p><code>#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 5</code></p>

<p>Since this means literally nothing, I've done my own research:</p>

<p>When I remove everything in the trigger's body (the statements between "BEGIN" and "END"), the query is processed successfully and an empty trigger is created.</p>

<p>So I've tested the inner statement by running the following query with a similar syntax:</p>

<pre class="lang-sql prettyprint-override"><code>UPDATE `Post` SET `lastInteraction` = CURRENT_TIMESTAMP WHERE `Post`.`id` = 1
</code>```

which was also successfully executed.

I don't know what's wrong here. If both the trigger and the inner statements are syntactically & logically correct, how can the top query be syntactically incorrect? Maybe update statements aren't compatible with triggers? I've looked into MySql's documentation and around the web and I couldn't find any relevant information.

What's wrong in my query?

答:
@BillKarwin 's comment has the answer.

This works:

DELIMITER //
CREATE TRIGGER `updateParentLastInteractionOnInsert`
AFTER INSERT
ON `Post` FOR EACH ROW
BEGIN
    UPDATE `Post` SET `lastInteraction` = CURRENT_TIMESTAMP WHERE `id` = new.`parentPostId`;
END //
```

Body:
I have the following MySQL query to create a trigger:

CREATE TRIGGER `updateParentLastInteractionOnInsert`
AFTER INSERT
ON `Post` FOR EACH ROW
BEGIN
    UPDATE `Post` SET `lastInteraction` = CURRENT_TIMESTAMP WHERE `id` = new.`parentPostId`;
END;

When I execute the query, I get the following error message:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 5

Since this means literally nothing, I've done my own research:

When I remove everything in the trigger's body (the statements between "BEGIN" and "END"), the query is processed successfully and an empty trigger is created.

So I've tested the inner statement by running the following query with a similar syntax:

UPDATE `Post` SET `lastInteraction` = CURRENT_TIMESTAMP WHERE `Post`.`id` = 1

which was also successfully executed.

I don't know what's wrong here. If both the trigger and the inner statements are syntactically & logically correct, how can the top query be syntactically incorrect? Maybe update statements aren't compatible with triggers? I've looked into MySql's documentation and around the web and I couldn't find any relevant information.

What's wrong in my query?


问:
Find the count of IDs that have the same value
I'd like to get a count of all of the Ids that have have the same value (Drops) as other Ids. For instance, the illustration below shows you that ID 1 and 3 have A drops so the query would count them. Similarly, ID 7 & 18 have B drops so that's another two IDs that the query would count totalling in 4 Ids that share the same values so that's what my query would return.

```<code>+------+-------+
| ID   | Drops |
+------+-------+
|  1   |   A   |
|  2   |   C   |
|  3   |   A   |
|  7   |   B   |
| 18   |   B   |
+------+-------+
</code>```

I've tried the several approaches but the following query was my last attempt.

```<code>With cte1 (Id1, D1) as
(
    select Id, Drops
    from Posts
),
cte2 (Id2, D2) as
(
    select Id, Drops
    from Posts
)
Select count(distinct c1.Id1) newcnt, c1.D1
from cte1 c1
left outer join cte2 c2 on c1.D1 = c2.D2
group by c1.D1
</code>```

The result if written out in full would be a single value output but the records that the query should be choosing should look as follows:

```<code>    +------+-------+
    | ID   | Drops |
    +------+-------+
    |  1   |   A   |
    |  3   |   A   |
    |  7   |   B   |
    | 18   |   B   |
    +------+-------+
</code>```

Any advice would be great. Thanks

答:
You can use a CTE to generate a list of Drops values that have more than one corresponding ID value, and then JOIN that to Posts to find all rows which have a Drops value that has more than one Post:

```<code>WITH CTE AS (
  SELECT Drops
  FROM Posts
  GROUP BY Drops
  HAVING COUNT(*) > 1
)
SELECT P.*
FROM Posts P
JOIN CTE ON P.Drops = CTE.Drops
</code>```

Output:

```<code>ID  Drops
1   A
3   A
7   B
18  B
</code>```

If desired you can then count those posts in total (or grouped by Drops value):

```<code>WITH CTE AS (
  SELECT Drops
  FROM Posts
  GROUP BY Drops
  HAVING COUNT(*) > 1
)
SELECT COUNT(*) AS newcnt
FROM Posts P
JOIN CTE ON P.Drops = CTE.Drops
</code>```

Output

```<code>newcnt
4
</code>```

Demo on SQLFiddle

Body:
I'd like to get a count of all of the Ids that have have the same value (Drops) as other Ids. For instance, the illustration below shows you that ID 1 and 3 have A drops so the query would count them. Similarly, ID 7 & 18 have B drops so that's another two IDs that the query would count totalling in 4 Ids that share the same values so that's what my query would return.

+------+-------+
| ID   | Drops |
+------+-------+
|  1   |   A   |
|  2   |   C   |
|  3   |   A   |
|  7   |   B   |
| 18   |   B   |
+------+-------+

I've tried the several approaches but the following query was my last attempt.

With cte1 (Id1, D1) as
(
    select Id, Drops
    from Posts
),
cte2 (Id2, D2) as
(
    select Id, Drops
    from Posts
)
Select count(distinct c1.Id1) newcnt, c1.D1
from cte1 c1
left outer join cte2 c2 on c1.D1 = c2.D2
group by c1.D1

The result if written out in full would be a single value output but the records that the query should be choosing should look as follows:

    +------+-------+
    | ID   | Drops |
    +------+-------+
    |  1   |   A   |
    |  3   |   A   |
    |  7   |   B   |
    | 18   |   B   |
    +------+-------+

Any advice would be great. Thanks

Body:
You can use a CTE to generate a list of Drops values that have more than one corresponding ID value, and then JOIN that to Posts to find all rows which have a Drops value that has more than one Post:

WITH CTE AS (
  SELECT Drops
  FROM Posts
  GROUP BY Drops
  HAVING COUNT(*) > 1
)
SELECT P.*
FROM Posts P
JOIN CTE ON P.Drops = CTE.Drops

Output:

ID  Drops
1   A
3   A
7   B
18  B

If desired you can then count those posts in total (or grouped by Drops value):

WITH CTE AS (
  SELECT Drops
  FROM Posts
  GROUP BY Drops
  HAVING COUNT(*) > 1
)
SELECT COUNT(*) AS newcnt
FROM Posts P
JOIN CTE ON P.Drops = CTE.Drops

Output

newcnt
4

Demo on SQLFiddle


问:
Acquiring a regular reference from a weakref proxy in python
Is there a way to get a proper reference for an object for which I get a weakref proxy?

I've gone through the weakref module's documentation and coulnd't get an answer there, or through poking a weakproxy object manually.

答:
Although there's nothing exposed directly on the proxy object itself, it is possible to obtain a reference by abusing the __self__ attribute of bound methods:

```<code>obj_ref = proxy.__repr__.__self__
</code>```

Using __repr__ here is just a random choice, although if you want a generic method it'd be better to use a method that all objects should have.

ContentLicense: CC BY-SA 3.0

Body:
Although there's nothing exposed directly on the proxy object itself, it is possible to obtain a reference by abusing the __self__ attribute of bound methods:

obj_ref = proxy.__repr__.__self__

Using __repr__ here is just a random choice, although if you want a generic method it'd be better to use a method that all objects should have.


问:
How to create sub associative array?
I am learning associative arrays. This is what I am doing:

```<code>array_push( $classe ,array(
  'year'=>$annoClasse,
  'section'=>$sezione,
  'student'=>$member->first_name." ".$member->last_name)
);
</code>```

That creates:

```<code>array (
  0 =>
  array (
    'year' => 'Secondo',
    'section' => 'd',
    'student' => 'Stephany Johnson',
  ),
  1 =>
  array (
    'year' => 'Secondo',
    'section' => 'd',
    'student' => 'Sandra White',
  ),
)
</code>```

How would I create something like this? Basically to have each separate property for the student.

```<code>array (
  0 =>
  array (
    'year' => 'Second',
    'section' => 'd',
    'student' (
      'name' => 'Stephany',
      'surname' => 'Johnson'
    )
  ),
  1 =>
  array (
    'year' => 'Second',
    'section' => 'd',
    'student' (
      'name' => 'Sandra',
      'surname' => 'White'
     ),
   )
 )
</code>```

And how would I then echo the student only?

答:
This can be accomplished with the following code:

```<code>array_push( $classe ,array(
                   'year'=>$annoClasse,
                   'section'=>$sezione,
                   'student'=>array(
                       'name'=>$member->first_name,
                       'surname'=>$member->last_name
                   )
);
</code>```

Then to echo only the student:

```<code>foreach ($classe as $c) {
    echo $c['student']['name'] . " " . $c['student']['surname'] . PHP_EOL;
}
</code>```

Title: How to create sub associative array?

Body:
I am learning associative arrays. This is what I am doing:

array_push( $classe ,array(
  'year'=>$annoClasse,
  'section'=>$sezione,
  'student'=>$member->first_name." ".$member->last_name)
);

That creates:

array (
  0 =>
  array (
    'year' => 'Secondo',
    'section' => 'd',
    'student' => 'Stephany Johnson',
  ),
  1 =>
  array (
    'year' => 'Secondo',
    'section' => 'd',
    'student' => 'Sandra White',
  ),
)

How would I create something like this? Basically to have each separate property for the student.

array (
  0 =>
  array (
    'year' => 'Second',
    'section' => 'd',
    'student' (
      'name' => 'Stephany',
      'surname' => 'Johnson'
    )
  ),
  1 =>
  array (
    'year' => 'Second',
    'section' => 'd',
    'student' (
      'name' => 'Sandra',
      'surname' => 'White'
     ),
   )
 )

And how would I then echo the student only?

Body:
This can be accomplished with the following code:

array_push( $classe ,array(
                   'year'=>$annoClasse,
                   'section'=>$sezione,
                   'student'=>array(
                       'name'=>$member->first_name,
                       'surname'=>$member->last_name
                   )
);

Then to echo only the student:

foreach ($classe as $c) {
    echo $c['student']['name'] . " " . $c['student']['surname'] . PHP_EOL;
}


问:
How should I assert in WebAPI integration test?
I'm writing integration tests for Controller classes in my .NET Core WebAPI, and honestly, I'm not sure if Assert.Equal(HttpStatusCode.OK, response.StatusCode); is enough. I'm using my production Startup class with only database different (using InMemory database).

This is one of my tests, named ShouldAddUpdateAndDeleteUser. It's basically:

Send POST request with specific input.

Assert If POST worked. Because POST sends respond with created object, I can Assert on every property and if the Id is greater then 0.

Change the output a little bit and send Update request

Send GET request and assert if update worked.

Send DELETE request

Send GET request and assert if null.

Basically, I test, ADD,UPDATE,DELETE,GET (when item exists), GET (when item doesn't exists).

I have a few questions:

Is it a good practice to have such tests? It does do a lot, but it's not a unit test after all. If it fails, I can be pretty specific and specify which part didn't work. Worst case scenario I can debug it pretty quickly.

Is it integration tests or functional test or neither?

If this is wrong, how can I test DELETE or UPDATE? I'm kinda forced to call GET request after them (They return NoContent)

(Side note: It's not the only test I have for that controller obviously. I also have tests for GET all as well as BedRequest requests)

答:
Is it a good practice to have such tests? It does do a lot, but it's not a unit test after all. If it fails, I can be pretty specific and specify which part didn't work. Worst case scenario I can debug it pretty quickly.

Testing your endpoints full stack does have value but make sure to keep in mind the testing pyramid. Its valuable to have a small number of full stack integration to validate the most important pathways/use cases in your application. Having too many however, can add a lot of extra time to your test runs which could impact release times if those tests are tied to releasing (which they should be).

Is it integration tests or functional test or neither?

Without seeing more of the code I would guess it's probably a bit of both. Functionally, you want to test the output of the endpoints and it seems as though you're testing some level of component integration if you're mocking out data in memory.

If this is wrong, how can I test DELETE or UPDATE? I'm kinda forced to call GET request after them (They return NoContent)

Like I said earlier, a few full stack tests are fine in my opinion as long as they provide value for major workflows in your application. I would suggest one to two integration tests that make database calls that make sure your application can stand up full stack but not bundle that requirement for your functional testing. In my experience you get way more value from modular component testing and a couple end to end functional tests.

I think the test flow you mentioned makes sense. I've done similar patterns throughout my services at work. Sometimes you can't realistically test one component without testing another like your example about getting after a delete.


答:
you can do it like that :

```<code>array_push( $classe ,array('year'=>$annoClasse, 'section'=>$sezione, 'student' => array('name' => $student_name, 'surname' => $student_surname)));
</code>```

use foreach to loop the array and print the values you want :

```<code>foreach ($classe as $key => $value) {
    echo $value['student']['name']; // or echo $value['student']['surname']; etc..
}
</code>```

Title: How to create sub associative array?

Body:
you can do it like that :

array_push( $classe ,array('year'=>$annoClasse, 'section'=>$sezione, 'student' => array('name' => $student_name, 'surname' => $student_surname)));

use foreach to loop the array and print the values you want :

foreach ($classe as $key => $value) {
    echo $value['student']['name']; // or echo $value['student']['surname']; etc..
}


问:
File Table (SQL Server 2016) FILESTREAM permissions lost in IIS

I am trying to store images in a FileTable that is accessible from a website.
According to my understanding, the FileTable needs "SELECT" granted to the account running ApplicationPool that the website runs in.

Example of what I have:

IIS (6.2)

Application pool user : Domain\Bob.

SQL Server login Domain\Bob

Database has Domain\Bob in db_owner group. I explicitly granted Domain\Bob select on the file table also.

DB.dbo.FileStream_FileTable is \\DEV\FileStream_FileTable\

IIS has SiteA

SiteA has virtual directory Image targeting \\127.0.0.1\DEV\FileStream_FileTable\

If I look at the IIS authentication, IIS errors saying insufficient permission to access web.config - but there is no web.config.

On the server, running Internet Explorer, referencing an image as \\127.0.0.1\DEV\FileStream_FileTable\<...>\Image1.jpg it resolves to the jpg.

On the server, running Internet Explorer, referencing an image as HTTP://127.0.0.1/SiteA/Image/Image1.jpg, IE errors (same error as the authentication error)...

Config Error

  Cannot read configuration file due to insufficient permissions

Config File

  \?\UNC\127.0.0.1\dev\ItemImage\web.config

There IS no config file.

I have tried specifying the Windows user (Domain\Bob) context when accessing the virtual folder "Images" targetting \127.0.0.1\DEV\Filestream_FileTable
and also not specifying the windows credential...

I do not understand why the Image is visible using the UNC path in Internet Explorer (it must authenticate my context as having select on the filestream_filetable table) but not when using the context specifying a Windows context of a user who also has select on the table, in IIS.

NOTE: As an experiment, I modified the user, in IIS, used to access the share to Administrator. Then the IIS site resolved the image.

(Virtual directory targetting the \\servername\sql_instance_filestream_handle\directory\tablename)

The Windows User Domain\Bob has full rights on database - database owner.

There is another user's question, Access to SQL Server FileTable from IIS, that has servername in file share being a potential issue if the IIS and SQL server is on the same host, which I have taken into consideration.

I have added Domain\Bob to IIS_ISURS group...

What is Domain\Bob not a member of that grants access?
I can't very well make all my IIS shares accessing with Administrator accounts!

答:
In some case, IIS will try to create web.config if the UNC path just return access denied error. If IIS failed to create web.config, It will also fail to access web.config with 500.19.

So please ensure your Application pool identity is set to a domain account who have read/write permission to access the folder.

Then please try to set Anonymous authentication->edit..->Application pool identity.


问:
How to get exponent and modulus value of RSA public key from pfx file/pem file in java
I want to extract information about RSA Public Key from the pfx file using java.

I have a pfx file and converted to x509 Pem file. From pem file, Using the below command in terminal:

```<code>openssl x509 -in file.pem -text
</code>```

I am able to view the public key exponent and modulus value

Subject Public Key Info:

```<code>Public Key Algorithm: rsaEncryption
    Public-Key: (2048 bit)
    Modulus:
        00:da:7c:e0:3e:c4:62:8d:ce:29:04:2f:93:78:7c:
        :
         6a:e7:c9:7c:8b:6f:09:5c:75:5f:8c:5e:9c:6a:b9:
        7:32:90: a4:4b
    Exponent: 65537 (0x10001)
</code>```

How to extract the above information in java?

Input: pfxfile and password

Output:public key exponent and modulus value.

I m using the below code to extract the public key exponent and modulus, but i am not getting the value that is extracted using openssl. I doubt whether java.security.cert.Certificate uses some other DER format??

What is the java equivalent of openssl?

Code:

```<code>KeyStore ks = KeyStore.getInstance("pkcs12");
ks.load(new FileInputStream(file), password.toCharArray());
Enumeration enumeration = ks.aliases();
while (enumeration.hasMoreElements()) {
    String alias = (String) enumeration.nextElement();
    java.security.cert.Certificate certificate = ks.getCertificate(alias);
    PublicKey publickey = certificate.getPublicKey();
}
</code>```

答:
It would be helpful to validate the JSON WebToken against the JWKS URL. For Example, the sample JWKS keys would be as follows.

```<code>{
  "keys": [
    {
      "use": "sig",
      "kty": "RSA",
      "kid": "c424b67b-fe28-45d7-b015-f79da50b5b21",
      "alg": "RS256",
      "n": "AKoYq6Q7UN7vOFmPr4fSq2NORXHBMKm8p7h4JnQU-quLRxvYll9cn8OBhIXq9SnCYkbzBVBkqN4ZyMM4vlSWy66wWdwLNYFDtEo1RJ6yZBExIaRVvX_eP6yRnpS1b7m7T2Uc2yPq1DnWzVI-sIGR51s1_ROnQZswkPJHh71PThln",
      "e": "AQAB"
    },
    {
      "use": "sig",
      "kty": "RSA",
      "kid": "9b9d0b47-b9ed-4ba6-9180-52fc5b161a3a",
      "alg": "RS256",
      "n": "AKoYq6Q7UN7vOFmPr4fSq2NORXHBMKm8p7h4JnQU-quLRxvYll9cn8OBhIXq9SnCYkbzBVBkqN4ZyMM4vlSWy66wWdwLNYFDtEo1RJ6yZBExIaRVvX_eP6yRnpS1b7m7T2Uc2yPq1DnWzVI-sIGR51s1_ROnQZswkPJHh71PThln",
      "e": "AQAB"
    }
  ]
}
</code>```

The description of the JWKS is as follows.

```<code>n:    Modulus of the Public Key
alg:  the signing algorithm.
kid:  a unique id for every key in the set.
e:    Exponent part of RSA algorithm
use:  This denotes the Signature Validation
</code>```

Body:
I want to extract information about RSA Public Key from the pfx file using java.

I have a pfx file and converted to x509 Pem file. From pem file, Using the below command in terminal:

openssl x509 -in file.pem -text

I am able to view the public key exponent and modulus value

Subject Public Key Info:

Public Key Algorithm: rsaEncryption
    Public-Key: (2048 bit)
    Modulus:
        00:da:7c:e0:3e:c4:62:8d:ce:29:04:2f:93:78:7c:
        :
         6a:e7:c9:7c:8b:6f:09:5c:75:5f:8c:5e:9c:6a:b9:
        7:32:90: a4:4b
    Exponent: 65537 (0x10001)

How to extract the above information in java?

Input: pfxfile and password

Output:public key exponent and modulus value.

I m using the below code to extract the public key exponent and modulus, but i am not getting the value that is extracted using openssl. I doubt whether java.security.cert.Certificate uses some other DER format??

What is the java equivalent of openssl?

Code:

KeyStore ks = KeyStore.getInstance("pkcs12");
ks.load(new FileInputStream(file), password.toCharArray());
Enumeration enumeration = ks.aliases();
while (enumeration.hasMoreElements()) {
    String alias = (String) enumeration.nextElement();
    java.security.cert.Certificate certificate = ks.getCertificate(alias);
    PublicKey publickey = certificate.getPublicKey();
}

Body:
It would be helpful to validate the JSON WebToken against the JWKS URL. For Example, the sample JWKS keys would be as follows.

{
  "keys": [
    {
      "use": "sig",
      "kty": "RSA",
      "kid": "c424b67b-fe28-45d7-b015-f79da50b5b21",
      "alg": "RS256",
      "n": "AKoYq6Q7UN7vOFmPr4fSq2NORXHBMKm8p7h4JnQU-quLRxvYll9cn8OBhIXq9SnCYkbzBVBkqN4ZyMM4vlSWy66wWdwLNYFDtEo1RJ6yZBExIaRVvX_eP6yRnpS1b7m7T2Uc2yPq1DnWzVI-sIGR51s1_ROnQZswkPJHh71PThln",
      "e": "AQAB"
    },
    {
      "use": "sig",
      "kty": "RSA",
      "kid": "9b9d0b47-b9ed-4ba6-9180-52fc5b161a3a",
      "alg": "RS256",
      "n": "AKoYq6Q7UN7vOFmPr4fSq2NORXHBMKm8p7h4JnQU-quLRxvYll9cn8OBhIXq9SnCYkbzBVBkqN4ZyMM4vlSWy66wWdwLNYFDtEo1RJ6yZBExIaRVvX_eP6yRnpS1b7m7T2Uc2yPq1DnWzVI-sIGR51s1_ROnQZswkPJHh71PThln",
      "e": "AQAB"
    }
  ]
}

The description of the JWKS is as follows.

n:    Modulus of the Public Key
alg:  the signing algorithm.
kid:  a unique id for every key in the set.
e:    Exponent part of RSA algorithm
use:  This denotes the Signature Validation


问:
CSS Print layout is adding an extra page
I've been working on a print page for a client. After playing around for awhile I've found I get an extra blank page. The unusual thing is that if I select "Outline Block Level Elements" in Web Developer for chrome, the extra page disappears. This is all the CSS being used on that page right now:

```<code>@page
    {
        size: auto;   /* auto is the initial value */
        margin: 0mm;  /* this affects the margin in the printer settings */
    }

    body
    {
        background-color:#FFFFFF;
        height: 296mm;
        border: 1px solid black;
        margin: 0px;  /* this affects the margin on the content before sending to printer */
   }

.print_A4 {
margin: 0mm;
padding: 0mm;
height: 270mm; /*A4 Size*/
width: 210mm; /*A4 Size*/
}

.A4_content {
    margin-left: auto;
    margin-right: auto;
    margin-top: 44mm;
    height: 210mm;
    width: 165mm;
 }
</code>```

I've done a lot of googling but I can't see anything related to this. The body border clearly shows the div ending before the end of the first page, however I still get an extra blank page for some reason.

答:
So because 27.9cm turns into something like 1423.03px I suspect it's causing the print renderer to display an additional pixel. Adding this to my page fixed the issue.

.page-a4 {
  width: 21cm;
  height: calc(27.9cm - 1px);
}```

Body:
I've been working on a print page for a client. After playing around for awhile I've found I get an extra blank page. The unusual thing is that if I select "Outline Block Level Elements" in Web Developer for chrome, the extra page disappears. This is all the CSS being used on that page right now:

@page
    {
        size: auto;   /* auto is the initial value */
        margin: 0mm;  /* this affects the margin in the printer settings */
    }

    body
    {
        background-color:#FFFFFF;
        height: 296mm;
        border: 1px solid black;
        margin: 0px;  /* this affects the margin on the content before sending to printer */
   }

.print_A4 {
margin: 0mm;
padding: 0mm;
height: 270mm; /*A4 Size*/
width: 210mm; /*A4 Size*/
}

.A4_content {
    margin-left: auto;
    margin-right: auto;
    margin-top: 44mm;
    height: 210mm;
    width: 165mm;
 }

I've done a lot of googling but I can't see anything related to this. The body border clearly shows the div ending before the end of the first page, however I still get an extra blank page for some reason.


问:
Definining user libraries in Eclipse as part of a project and not a workspace
I saw that in Eclipse I can define User Libraries - to make setting the classpath easier (and probably for other reasons as well).

The problem is, that these libraries are only available in the workspace, and if I want other people using the same project to use them - I need to export my user library and they need to import it.

Is there any functionality like this on the project level? I basically need to have a 'classpath group' - can it be done?

If not, is there an automatic way to auto import the user library to the workspace when importing the project?

I'm using Eclipse 3.6.

答:
JDT has the 2 concepts, user libraries and classpath variables.  In the classpath variable, you can add jars to your project.  Other team members have to fill in the variables in their workspace so their classpath is complete.  This is useful when external jars might be in different locations on each team members local file system.

The USER_LIBRARY is a container for adding a logical group of local jars all at once.  For example, the JRE_LIB container represents a number of local jars.  But as you've seen, it points to a local set of jars meant to be used in multiple projects (as the JRE is added to multiple projects).

Aside from export/import (which you're already doing), I don't believe you can check CLASS_LIBRARIES into a project's SCM.  If there was, the preference page would have a "Configure Project specific settings" link at the top.

Your best bet is to simply add the jars to the project, so they'll be included in the SCM.  If they can be in different locations depending on the rest of your team, then use a classpath variable so it can be set in each workspace.  That's the least amount of hassle as far as team members checking out the project and being ready to go.


问:
I've created a function in C++ to reverse a string recursively, but how can I make the funtion print a endl afterwards?
This is in C++ The original prompt was to create a recursive function that reverses a string. The function works, but I am not sure how to get endl IN the function after it reverses the string so it looks good in console. This works:

```<code>string reverse(string str) {
    if (str.size() == 1) {
        return str;
    }
    string str2 = reverse(str.substr(1));
    return str2 + str[0];
}
</code>```

答:
You can prepend new line character to your string argument before passing it to the reverse() function,

string str {"Hello"};

str = "\n" + str;

cout << reverse(str);
```

<p>If you want to do this in the <code>reverse</code> function definition, you need to keep track of the depth of recursion so you can prepend the new line character in the first level of recursion, </p>

<pre class="lang-c prettyprint-override"><code>string reverse(string str, int depth = 0) {

    if(depth==0) {
        str = "\n" + str;
    }

    depth++;

    if(str.size() == 1) {
        return str;
    }
    string str2 = reverse(str.substr(1), depth);
    return str2 + str[0];
}
</code>```

Body:
This is in C++ The original prompt was to create a recursive function that reverses a string. The function works, but I am not sure how to get endl IN the function after it reverses the string so it looks good in console. This works:

string reverse(string str) {
    if (str.size() == 1) {
        return str;
    }
    string str2 = reverse(str.substr(1));
    return str2 + str[0];
}

Body:
You can prepend new line character to your string argument before passing it to the reverse() function,

string str {"Hello"};

str = "\n" + str;

cout << reverse(str);

If you want to do this in the reverse function definition, you need to keep track of the depth of recursion so you can prepend the new line character in the first level of recursion,

string reverse(string str, int depth = 0) {

    if(depth==0) {
        str = "\n" + str;
    }

    depth++;

    if(str.size() == 1) {
        return str;
    }
    string str2 = reverse(str.substr(1), depth);
    return str2 + str[0];
}


问:
How to implement encrypted sharepreferences
How to implement encrypted sharepreferences in my android java apps using https://developer.android.google.cn/reference/androidx/security/crypto/EncryptedSharedPreferences? I dont  know how to implement it, anyone can help?</p>

答:
As per the documentation example, you can init EncryptedSharedPreferences like this.

```<code>public SharedPreferences getEncryptedSharedPreferences(){
   String masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);
   SharedPreferences sharedPreferences = EncryptedSharedPreferences.create(
       "secret_shared_prefs_file",
       masterKeyAlias,
       context,
       EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
       EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
   );
    return sharedPreferences;
}
</code>```

Save Data

```<code>getEncryptedSharedPreferences().edit()
        .putString("key", value)
        .apply()
</code>```

Get Data

```<code>getEncryptedSharedPreferences().getString("key", "defaultValue");
</code>```

Make sure your app API version is 23+ and you need to add this dependency

```<code>implementation "androidx.security:security-crypto:1.0.0-alpha02" //Use latest version
</code>```

Body:
As per the documentation example, you can init EncryptedSharedPreferences like this.

public SharedPreferences getEncryptedSharedPreferences(){
   String masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC);
   SharedPreferences sharedPreferences = EncryptedSharedPreferences.create(
       "secret_shared_prefs_file",
       masterKeyAlias,
       context,
       EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
       EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
   );
    return sharedPreferences;
}

Save Data

getEncryptedSharedPreferences().edit()
        .putString("key", value)
        .apply()

Get Data

getEncryptedSharedPreferences().getString("key", "defaultValue");

Make sure your app API version is 23+ and you need to add this dependency

implementation "androidx.security:security-crypto:1.0.0-alpha02" //Use latest version


问:
Why does my CSS animation work in every browser except for Safari?
My CSS animation works on every single browser except for Safari. Could someone tell me why this is, or what changes I need to make for it to work universally?</p>

```<code>
    #job-title:before {
        content: '';
        animation-name: animate;
        animation-iteration-count: infinite;
        animation-timing-function: linear;
        animation-duration: 4s;
        animation-delay: 1s;
    }

    @keyframes animate {
        0% {
            content: "Web Developer.";
        }
        50% {
            content: "Web Designer.";
        }
        100% {
            content: "Graphic Designer.";
        }
    }

</code>```

答:
Can you try to include -webkit prefix for the animation?

#job-title:before {
  content: '';
  -webkit-animation-name: animate;
  animation-name: animate;
  -webkit-animation-iteration-count: infinite;
  animation-iteration-count: infinite;
  -webkit-animation-timing-function: linear;
  animation-timing-function: linear;
  -webkit-animation-duration: 4s;
  animation-duration: 4s;
  -webkit-animation-delay: 1s;
  animation-delay: 1s;
}

@-webkit-keyframes animate {
  0% {
    content: "Web Developer.";
  }
  50% {
    content: "Web Designer.";
  }
  100% {
    content: "Graphic Designer.";
  }
}

@keyframes animate {
  0% {
    content: "Web Developer.";
  }
  50% {
    content: "Web Designer.";
  }
  100% {
    content: "Graphic Designer.";
  }
}```

Body:
My CSS animation works on every single browser except for Safari. Could someone tell me why this is, or what changes I need to make for it to work universally?

    #job-title:before {
        content: '';
        animation-name: animate;
        animation-iteration-count: infinite;
        animation-timing-function: linear;
        animation-duration: 4s;
        animation-delay: 1s;
    }

    @keyframes animate {
        0% {
            content: "Web Developer.";
        }
        50% {
            content: "Web Designer.";
        }
        100% {
            content: "Graphic Designer.";
        }
    }


问:
How to convert a NumPy array to PIL image applying matplotlib colormap
I have a simple problem, but I cannot find a good solution to it.

I want to take a NumPy 2D array which represents a grayscale image, and convert it to an RGB PIL image while applying some of the matplotlib colormaps.

I can get a reasonable PNG output by using the pyplot.figure.figimage command:

```<code>dpi = 100.0
w, h = myarray.shape[1]/dpi, myarray.shape[0]/dpi
fig = plt.figure(figsize=(w,h), dpi=dpi)
fig.figimage(sub, cmap=cm.gist_earth)
plt.savefig('out.png')
</code>```

Although I could adapt this to get what I want (probably using StringIO do get the PIL image), I wonder if there is not a simpler way to do that, since it seems to be a very natural problem of image visualization. Let's say, something like this:

```<code>colored_PIL_image = magic_function(array, cmap)
</code>```

答:
input = numpy_image

np.uint8 -> converts to integers

convert('RGB') -> converts to RGB

Image.fromarray -> returns an image object

```<code>  from PIL import Image
  import numpy as np

  PIL_image = Image.fromarray(np.uint8(numpy_image)).convert('RGB')

  PIL_image = Image.fromarray(numpy_image.astype('uint8'), 'RGB')
</code>```

Body:
I have a simple problem, but I cannot find a good solution to it.

I want to take a NumPy 2D array which represents a grayscale image, and convert it to an RGB PIL image while applying some of the matplotlib colormaps.

I can get a reasonable PNG output by using the pyplot.figure.figimage command:

dpi = 100.0
w, h = myarray.shape[1]/dpi, myarray.shape[0]/dpi
fig = plt.figure(figsize=(w,h), dpi=dpi)
fig.figimage(sub, cmap=cm.gist_earth)
plt.savefig('out.png')

Although I could adapt this to get what I want (probably using StringIO do get the PIL image), I wonder if there is not a simpler way to do that, since it seems to be a very natural problem of image visualization. Let's say, something like this:

colored_PIL_image = magic_function(array, cmap)

Body:
input = numpy_image

np.uint8 -> converts to integers

convert('RGB') -> converts to RGB

Image.fromarray -> returns an image object

  from PIL import Image
  import numpy as np

  PIL_image = Image.fromarray(np.uint8(numpy_image)).convert('RGB')

  PIL_image = Image.fromarray(numpy_image.astype('uint8'), 'RGB')


问:
Using Recursion to add to a trie
I have been learning about the Trie structure through python. What is a little bit different about his trie compared to other tries is the fact that we are trying to implement a counter into every node of the trie in order to do an autocomplete (that is the final hope for the project). So far, I decided that having a recursive function to put the letter into a list of dictionaries would be a good idea.

Final Product (Trie):

```<code>Trie = {"value":"*start"
        "count":1
        "children":["value":"t"
                    "count":1
                    "children":["value":"e"
                                "count":1
                                "children":[...]
</code>```

I know that a recursion would be very useful as it is just adding letters to the list, however, I can't figure out how to construct the basic function and how to tell the computer to refer to the last part of the dictionary without writing out

```<code>Trie["children"]["children"]["children"]["children"]
</code>```

a bunch of times. Can you guys please give me some ideas as of how to construct the function?

--Thanks

答: Perhaps you only want to store a counter in the end-of-word node. (I always use a separate node for this!). So given a prefix, you work your way down the Trie, then perform a traversal to find the end-of-word nodes below your prefix, pushing them into a binary tree by their counter value. Once you have all the end-of-word nodes, you perform a post-order traversal to collect the end-of-word nodes with the largest counters - however many you decide. With each of these collected end-of-word nodes, you can obtain a list of candidate words most likely to fit the prefix! From just the end-of-word node, and storing the parent node in each node, you zoom up to the root to re-assemble the word!</p>

Title: Using Recursion to add to a trie

Body:
I have been learning about the Trie structure through python. What is a little bit different about his trie compared to other tries is the fact that we are trying to implement a counter into every node of the trie in order to do an autocomplete (that is the final hope for the project). So far, I decided that having a recursive function to put the letter into a list of dictionaries would be a good idea.

Final Product (Trie):

Trie = {"value":"*start"
        "count":1
        "children":["value":"t"
                    "count":1
                    "children":["value":"e"
                                "count":1
                                "children":[...]

I know that a recursion would be very useful as it is just adding letters to the list, however, I can't figure out how to construct the basic function and how to tell the computer to refer to the last part of the dictionary without writing out

Trie["children"]["children"]["children"]["children"]

a bunch of times. Can you guys please give me some ideas as of how to construct the function?

--Thanks


问:
Which audio format can be recorded and played back by iPhone and Android?
I am designing an app that can record short audio files on iPhone and Android that can be played back on both platforms, as well as hopefully any other smartphone.

Right now I'm using *.caf with the iLBC codec, as I know the iPhone does not encode mp3.

Is there a file format/codec that I should use in this case?

答: Try modifying the file type in your ios version file to be .wav and you should be able to listen to this audio file on an Android phone, as well as a Windows operating system.


问:
How do I check if there are any extra columns in my pandas csv?
Currently I am trying to check a csv file if there are certain columns (whether they exist) and also to find out if there are any extra columns (that should not be there) in a certain csv file.

I have put all the required columns into a list and check the list against the columns in the file.

```<code>list = ['column 1', 'column 2' , 'column 3']
for column in list:
    if column not in list:
        /execute  action
</code>```

However, I am unable to find out if any extra columns already exist .
For example csv file has 4 columns, and 3 of them is checked against the list.

How do I get the last column to be displayed or shown?

Thanks in advance!

答:
Try the following code (pythonic approach): </p>

```<code>import pandas as pd
someList = ['column 1', 'column 2' , 'column 3']

df = pd.read_csv('filename.csv')

differenceCols= list(set(df.columns) - set(someList))
print(differenceCols)

for item in differenceCols:
    # perform some action
</code>```

Body:
Currently I am trying to check a csv file if there are certain columns (whether they exist) and also to find out if there are any extra columns (that should not be there) in a certain csv file.

I have put all the required columns into a list and check the list against the columns in the file.

list = ['column 1', 'column 2' , 'column 3']
for column in list:
    if column not in list:
        /execute  action

However, I am unable to find out if any extra columns already exist .
For example csv file has 4 columns, and 3 of them is checked against the list.

How do I get the last column to be displayed or shown?

Thanks in advance!

Body:
Try the following code (pythonic approach):

import pandas as pd
someList = ['column 1', 'column 2' , 'column 3']

df = pd.read_csv('filename.csv')

differenceCols= list(set(df.columns) - set(someList))
print(differenceCols)

for item in differenceCols:
    # perform some action


问:
StreamString(pipeClient) throws error Type is not defined
I am trying to unlock the machine by passing user id and password in UiPath when scheduled bot trying to run the process in locked system

Below is my code

```<code>    'Create a new pipe client
    Using pipeClient As New System.IO.Pipes.NamedPipeClientStream(
        ".",
        "CredentialProviderPipe",
        PipeDirection.InOut,
        PipeOptions.None,
        System.Security.Principal.TokenImpersonationLevel.Impersonation)

        'Attempt to connect to it
        pipeClient.Connect(10000)
        'Send credentials
        Dim dom As String
         If Domain = "" Then
            dom = Environment.UserDomainName
        Else
            dom = Domain
        End If

        Dim ss As New StreamString(pipeClient)

        ss.WriteString(String.Format("LOGON{0}{1}{0}{2}{0}{3}", vbLf, dom, Username, Password))

        'Wait for reply
        Using pr As New StreamReader(pipeClient, System.Text.Encoding.Unicode)
            Response = pr.ReadLine()
            If Response = "OK" OrElse Response = "UNKNOWN" Then Return

            ErrorCode = pr.ReadLine()
            ErrorMessage = pr.ReadLine()
        End Using
    End Using
Catch ex As TimeoutException
    Response = "ERROR"
    ErrorCode = "0x80131505"
    ErrorMessage = ex.Message
Catch ex As Exception
    Response = "ERROR"
    ErrorCode = ""
    ErrorMessage = ex.Message
End Try
</code>```

I am getting below error that error BC30002: Type StringStream is not defined.

I dont know how to resolve the issue. Please help

答:
It looks like all those uses of StreamString are based on the example here, which includes the definition of that class as below:

' Defines the data protocol for reading and writing strings on our stream
Public Class StreamString
    Private ioStream As Stream
    Private streamEncoding As UnicodeEncoding

    Public Sub New(ioStream As Stream)
        Me.ioStream = ioStream
        streamEncoding = New UnicodeEncoding(False, False)
    End Sub

    Public Function ReadString() As String
        Dim len As Integer = 0
        len = CType(ioStream.ReadByte(), Integer) * 256
        len += CType(ioStream.ReadByte(), Integer)
        Dim inBuffer As Array = Array.CreateInstance(GetType(Byte), len)
        ioStream.Read(inBuffer, 0, len)

        Return streamEncoding.GetString(inBuffer)
    End Function

    Public Function WriteString(outString As String) As Integer
        Dim outBuffer() As Byte = streamEncoding.GetBytes(outString)
        Dim len As Integer = outBuffer.Length
        If len > UInt16.MaxValue Then
            len = CType(UInt16.MaxValue, Integer)
        End If
        ioStream.WriteByte(CType(len \ 256, Byte))
        ioStream.WriteByte(CType(len And 255, Byte))
        ioStream.Write(outBuffer, 0, outBuffer.Length)
        ioStream.Flush()

        Return outBuffer.Length + 2
    End Function
End Class
```

Body:
I am trying to unlock the machine by passing user id and password in UiPath when scheduled bot trying to run the process in locked system

Below is my code

    'Create a new pipe client
    Using pipeClient As New System.IO.Pipes.NamedPipeClientStream(
        ".",
        "CredentialProviderPipe",
        PipeDirection.InOut,
        PipeOptions.None,
        System.Security.Principal.TokenImpersonationLevel.Impersonation)

        'Attempt to connect to it
        pipeClient.Connect(10000)
        'Send credentials
        Dim dom As String
         If Domain = "" Then
            dom = Environment.UserDomainName
        Else
            dom = Domain
        End If

        Dim ss As New StreamString(pipeClient)

        ss.WriteString(String.Format("LOGON{0}{1}{0}{2}{0}{3}", vbLf, dom, Username, Password))

        'Wait for reply
        Using pr As New StreamReader(pipeClient, System.Text.Encoding.Unicode)
            Response = pr.ReadLine()
            If Response = "OK" OrElse Response = "UNKNOWN" Then Return

            ErrorCode = pr.ReadLine()
            ErrorMessage = pr.ReadLine()
        End Using
    End Using
Catch ex As TimeoutException
    Response = "ERROR"
    ErrorCode = "0x80131505"
    ErrorMessage = ex.Message
Catch ex As Exception
    Response = "ERROR"
    ErrorCode = ""
    ErrorMessage = ex.Message
End Try

I am getting below error that error BC30002: Type StringStream is not defined.

I dont know how to resolve the issue. Please help


问:
Borderless Form Dropshadow
So I have the following code:

```<code>#region Dropshadow
[DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
private static extern IntPtr CreateRoundRectRgn
(
    int nLeftRect,
    int nTopRect,
    int nRightRect,
    int nBottomRect,
    int nWidthEllipse,
    int nHeightEllipse
);
[DllImport("dwmapi.dll")]
public static extern int DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS pMarInset);
[DllImport("dwmapi.dll")]
public static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize);
[DllImport("dwmapi.dll")]
public static extern int DwmIsCompositionEnabled(ref int pfEnabled);
private bool m_aeroEnabled;
public struct MARGINS
{
    public int leftWidth;
    public int rightWidth;
    public int topHeight;
    public int bottomHeight;
}
protected override CreateParams CreateParams {
    get {
        m_aeroEnabled = CheckAeroEnabled();
        CreateParams cp = base.CreateParams;
        if (!m_aeroEnabled) {
            cp.ClassStyle |= 0x00020000;
        }

        return cp;
    }
}
private bool CheckAeroEnabled()
{
    if (Environment.OSVersion.Version.Major >= 6) {
        int enabled = 0;
        DwmIsCompositionEnabled(ref enabled);
        return (enabled == 1) ? true : false;
    }
    return false;
}
protected override void WndProc(ref Message m)
{
    switch (m.Msg) {
        case 0x0085:
            if (m_aeroEnabled) {
                int v = 2;
                DwmSetWindowAttribute(Handle, 2, ref v, 4);
                MARGINS margins = new MARGINS() {
                    bottomHeight = 1,
                    leftWidth = 0,
                    rightWidth = 0,
                    topHeight = 0
                };
                DwmExtendFrameIntoClientArea(Handle, ref margins);
            }
            break;
        default:
            break;
    }
    base.WndProc(ref m);
}
#endregion
</code>```

This makes a Dropshadow using GDI.
The only issue however, is I had to make it keep a 1 pixel height border on the top (it can be any edge, just top is hardest to notice on my app).

This makes a line on my app at the top essentially degrading viewing experience.

Is it possible to do this with no border at all?

(The bottomHeight = 1 code is where its all about. If I set it to 0, and topHeight to 1, the line will be on the bottom. Setting all of them to 0, shows no dropshadow at all.)

Turns out, its to do with my padding, I need to leave 1 pixel line empty on atleast 1 edge for the Dropshadow to work. I chose to use Padding to make that 1 pixel line and I set the top padding to 1. This sets the line at the top. The bottomHeight = 1 doesnt matter at all. It's just there as it requires atleast one of them to be non 0.

If I remove the Padding and Top Line etc. And in the CreateParams overide, if I remove the aero enabled check, it shows a dropshadow similar like this:

答:
I set the bottomHeight to 3, and I found that the border height was included in the form size (the form's size didn't change).
So I set a BackgroundImage to this form, and the border was hidden by the image.

Title: Borderless Form Dropshadow

Body:
So I have the following code:

#region Dropshadow
[DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
private static extern IntPtr CreateRoundRectRgn
(
    int nLeftRect,
    int nTopRect,
    int nRightRect,
    int nBottomRect,
    int nWidthEllipse,
    int nHeightEllipse
);
[DllImport("dwmapi.dll")]
public static extern int DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS pMarInset);
[DllImport("dwmapi.dll")]
public static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize);
[DllImport("dwmapi.dll")]
public static extern int DwmIsCompositionEnabled(ref int pfEnabled);
private bool m_aeroEnabled;
public struct MARGINS
{
    public int leftWidth;
    public int rightWidth;
    public int topHeight;
    public int bottomHeight;
}
protected override CreateParams CreateParams {
    get {
        m_aeroEnabled = CheckAeroEnabled();
        CreateParams cp = base.CreateParams;
        if (!m_aeroEnabled) {
            cp.ClassStyle |= 0x00020000;
        }

        return cp;
    }
}
private bool CheckAeroEnabled()
{
    if (Environment.OSVersion.Version.Major >= 6) {
        int enabled = 0;
        DwmIsCompositionEnabled(ref enabled);
        return (enabled == 1) ? true : false;
    }
    return false;
}
protected override void WndProc(ref Message m)
{
    switch (m.Msg) {
        case 0x0085:
            if (m_aeroEnabled) {
                int v = 2;
                DwmSetWindowAttribute(Handle, 2, ref v, 4);
                MARGINS margins = new MARGINS() {
                    bottomHeight = 1,
                    leftWidth = 0,
                    rightWidth = 0,
                    topHeight = 0
                };
                DwmExtendFrameIntoClientArea(Handle, ref margins);
            }
            break;
        default:
            break;
    }
    base.WndProc(ref m);
}
#endregion

This makes a Dropshadow using GDI.
The only issue however, is I had to make it keep a 1 pixel height border on the top (it can be any edge, just top is hardest to notice on my app).

This makes a line on my app at the top essentially degrading viewing experience.

Is it possible to do this with no border at all?

(The bottomHeight = 1 code is where its all about. If I set it to 0, and topHeight to 1, the line will be on the bottom. Setting all of them to 0, shows no dropshadow at all.)

Turns out, its to do with my padding, I need to leave 1 pixel line empty on atleast 1 edge for the Dropshadow to work. I chose to use Padding to make that 1 pixel line and I set the top padding to 1. This sets the line at the top. The bottomHeight = 1 doesnt matter at all. It's just there as it requires atleast one of them to be non 0.

If I remove the Padding and Top Line etc. And in the CreateParams overide, if I remove the aero enabled check, it shows a dropshadow similar like this: