问:
how to sort a list of Object arrays in c#
I'm working on a project that focuses on rearranging user controls in a page, for example, each user control will have like and dislike buttons, and these will decide its spot on the page compared to the other user controls statistics.
To do so, my user control constructor creates an array of info in the following way:

```<code>private Object[] matrControls = new Object[3];
        matrControls[0] = this; ///post
        matrControls[1] = 0; ///precent of votes
        matrControls[2] = 0; /// number of votes
</code>```

then I have another method to return the array to the main code

```<code>public Object[] arrReturn()
        {
            return matrControls;
        }
</code>```

In my code, I manually added 2 user controls to work and the reorganizing method, then "voted" and by that changed the amount and percent of it, and then I put them in a list of Object arrays:

```<code>private List<Object[]> ListPost = new List<Object[]>();
ListPost.Add(NewPost.arrReturn());
</code>```

I want to organize firstly by the percent of votes (for example 6 likes, 4 dislikes = 60%), then if we have the same percent on 2 user controls (6 likes 4 dislikes & 60 likes 40 dislikes) to organize by the number of votes.
Both of these variables should be saved in my list.
My question is the following, How do I organize the list by the second and then the third variables, and then how would I change their spot on the page?
I would appreciate any help, Thanks.

答:
You can simply create class instead of using object[].

```<code>public class matrControls{
public int matrControls1 { get; set; }
public int matrControls2 { get; set; }
public int matrControls3 { get; set; }}

List<matrControls> matControlsList = new List<matrControls>();
matControlsList.Add(new matrControls{matrControls1=value1, matrControls2=value2, matrControls3=value3 });
matControlsList.Add(new matrControls{matrControls1=value1, matrControls2=value2, matrControls3=value3 });

var sortedList = matControlsList.OrderBy(control => control.matrControls1).ThenBy(control => control.matrControls2).ToList();
</code>```

The above code shows how to create class and then how to add it to list and then sorting of the list as you require.

Body:
I'm working on a project that focuses on rearranging user controls in a page, for example, each user control will have like and dislike buttons, and these will decide its spot on the page compared to the other user controls statistics.
To do so, my user control constructor creates an array of info in the following way:

private Object[] matrControls = new Object[3];
        matrControls[0] = this; ///post
        matrControls[1] = 0; ///precent of votes
        matrControls[2] = 0; /// number of votes

then I have another method to return the array to the main code

public Object[] arrReturn()
        {
            return matrControls;
        }

In my code, I manually added 2 user controls to work and the reorganizing method, then "voted" and by that changed the amount and percent of it, and then I put them in a list of Object arrays:

private List<Object[]> ListPost = new List<Object[]>();
ListPost.Add(NewPost.arrReturn());

I want to organize firstly by the percent of votes (for example 6 likes, 4 dislikes = 60%), then if we have the same percent on 2 user controls (6 likes 4 dislikes & 60 likes 40 dislikes) to organize by the number of votes.
Both of these variables should be saved in my list.
My question is the following, How do I organize the list by the second and then the third variables, and then how would I change their spot on the page?
I would appreciate any help, Thanks.

Body:
You can simply create class instead of using object[].

public class matrControls{
public int matrControls1 { get; set; }
public int matrControls2 { get; set; }
public int matrControls3 { get; set; }}

List<matrControls> matControlsList = new List<matrControls>();
matControlsList.Add(new matrControls{matrControls1=value1, matrControls2=value2, matrControls3=value3 });
matControlsList.Add(new matrControls{matrControls1=value1, matrControls2=value2, matrControls3=value3 });

var sortedList = matControlsList.OrderBy(control => control.matrControls1).ThenBy(control => control.matrControls2).ToList();

The above code shows how to create class and then how to add it to list and then sorting of the list as you require.


来源: stackexchange

ContentLicense: CC BY-SA 4.0

Title: create one-hot encoding for values of histogram bins

Body:
Given the tensor below of size torch.Size([22])

tensor([-20.1659, -19.7022, -17.4124, -16.7115, -16.4696, -15.6848, -15.5201, -14.5384, -12.5017, -12.4227, -11.0946, -10.7844, -10.5467,  -9.3933,  -4.2351,  -4.0521,  -3.8844, -3.8668,  -3.7337,  -3.7002,  -3.6242,  -3.5820])

and the below historgram:

hist = torch.histogram(tensor, 5)
hist
torch.return_types.histogram(
hist=tensor([3., 5., 5., 1., 8.]),
bin_edges=tensor([-20.1659, -16.8491, -13.5323, -10.2156,  -6.8988,  -3.5820]))

For each value of the tensor, how to create a one hot encoding that corresponds to its bin number, so that the output is a tensor of size torch.Size([22, 5])

Body:
You can use torch.repeat_interleave

import torch

bins = torch.tensor([3, 5, 5, 1, 8])
one_hots = torch.eye(len(bins))
one_hots = torch.repeat_interleave(one_hots, bins, dim=0)
print(one_hots)

output

tensor([[1., 0., 0., 0., 0.],
        [1., 0., 0., 0., 0.],
        [1., 0., 0., 0., 0.],
        [0., 1., 0., 0., 0.],
        [0., 1., 0., 0., 0.],
        [0., 1., 0., 0., 0.],
        [0., 1., 0., 0., 0.],
        [0., 1., 0., 0., 0.],
        [0., 0., 1., 0., 0.],
        [0., 0., 1., 0., 0.],
        [0., 0., 1., 0., 0.],
        [0., 0., 1., 0., 0.],
        [0., 0., 1., 0., 0.],
        [0., 0., 0., 1., 0.],
        [0., 0., 0., 0., 1.],
        [0., 0., 0., 0., 1.],
        [0., 0., 0., 0., 1.],
        [0., 0., 0., 0., 1.],
        [0., 0., 0., 0., 1.],
        [0., 0., 0., 0., 1.],
        [0., 0., 0., 0., 1.],
        [0., 0., 0., 0., 1.]])


问:
Find, Sum, and Remove Duplicates in 3 different subsets of data in a spreadsheet
I have a spreadsheet that contains truck load data.  The spreadsheet contains each portion of the delivery cycle; Month-Year, Supplier(VDH_Columns) to Vendor Pickup(VPK_Columns) to Receiver(CUST_Columns) and Tons delivered(Tons). If the Vendor Pickup Columns are populated, the cycle goes VPK to CUST.  If the Vendor Pickup Columns are not populated, the cycle goes VDH to CUST.

I want to maintain the spreadsheet exactly how it is and not make a CUST sheet, VPK Sheet, and VDH Sheet.
The ultimate goal is to have 1 Month_Year for each Receiver(CUST) and sum either the VDH or the VPK. Below is a piece of the spreadsheet(What it looks like now) and I manually created what I want it to look like.Spreadsheet Example
I tried a pivot table with a Month_Year filter but the problem is that I can't see once I try to add all the other columns it becomes so busy that I end up quitting.  I've thought about Consolidate but I have no experience with that.  I'm assuming VBA code would be able to accomplish it but I have no experience there either.
Thanks for any help

答:
A Pivot Table is the way to do this.  You need to drag all of your columns to the "Rows" field, and then drag the Tons column to Values.  It should automatically use a SUM summarization:

Then, you would select a Tabular layout from the Design tab.

This will give you the desired output:

You can get rid of the (blank) values by using Conditional Formatting on the Pivot Table.  Use custom number format ;;;


问:
How to create byte array with your own bytes?
I have to create my own byte array e.g:

```<code>byte[] connect = new byte[] { 0x00, 0x21, 0x60, 0x1F, 0xA1, 0x07 };
</code>```

This byte array works fine, but I need to change some hex code. I tried to do a lot of changes but
no one work.

```<code>Int32 hex = 0xA1;

byte[] connect = new byte[] { 0x00, 0x21, 0x60, 0x1F, 0xA1, hex};

string hex = "0xA1";

byte[] connect = new byte[] { 0x00, 0x21, 0x60, 0x1F, 0xA1, hex};

byte[] array = new byte[1];
array[0] = 0xA1;

byte[] connect = new byte[] { 0x00, 0x21, 0x60, 0x1F, 0xA1, array[0]};
</code>```

I don't know what type of variable I must have to use to replace automatic the array values.

答:
On a WinCE5 system I had to pass a char-string from a C# app to a c-dll. To form up the char string in the c# code I had to cast to byte (like @fejesjoco suggested). So to form the string test_ I had           byte[] name_comms_layer = new byte[] {(byte)0x74,(byte) 0x65,(byte)0x73,(byte)0x74,(byte)0x5f,(byte) 0x00} //test_
Painful but it did work.

ContentLicense: CC BY-SA 3.0

Body:
I have to create my own byte array e.g:

byte[] connect = new byte[] { 0x00, 0x21, 0x60, 0x1F, 0xA1, 0x07 };

This byte array works fine, but I need to change some hex code. I tried to do a lot of changes but
no one work.

Int32 hex = 0xA1;

byte[] connect = new byte[] { 0x00, 0x21, 0x60, 0x1F, 0xA1, hex};

string hex = "0xA1";

byte[] connect = new byte[] { 0x00, 0x21, 0x60, 0x1F, 0xA1, hex};

byte[] array = new byte[1];
array[0] = 0xA1;

byte[] connect = new byte[] { 0x00, 0x21, 0x60, 0x1F, 0xA1, array[0]};

I don't know what type of variable I must have to use to replace automatic the array values.


问:
How to count lines in C++ and add new lines with current number
I know that there are many topics about it but i've got a problem.

I have a code like this.

```<code>    void ADDAso()
    {
    fstream file;
    int n, number=0;
    file.open("Asortymenty.txt", ios::in| ios::out| ios::app);
    string line;
    while(getline(file, line)) number++;
    cout<<"Ile Asortymentow chcesz wprowadzic do bazy: ";
    cin>>n;
    DaneAso tab_aso[n];
    if(file.good())
    {
        int i=0;
        do
        {
            cout<<"\nWporwadz Kod Asortymentu "<<i+1<<": ";
            cin>>tab_aso[i].kod;
            cout<<"Wprowadz Nazwe Asortymentu "<<i+1<<": ";
            cin>>tab_aso[i].nazwa;
            cout<<"Wprowadz Jednostke miary "<<i+1<<":";
            cin>>tab_aso[i].jm;
            file <<number++<<";";
            file <<tab_aso[i].kod<<";";
            file <<tab_aso[i].nazwa<<";";
            file <<tab_aso[i].jm<<";"<<endl;
            i++;
        }
        while(i<n);
    }
    else cout<<"\tFILE IS BROKEN!!\n";
    plik.close();
    system("pause");
    }
</code>```

End after I try to use it, it says that file is broken.
Main thing is to read existing file, count it's lines and add new line with current number.

@molbdnilo

Here is my whole code. Please show me what am i supposed to change.

```<code>#include <iostream>
#include <fstream>
#include <windows.h>
#include <conio.h>
#include <vector>

using namespace std;

struct DaneAso
{
    char kod[10];
    char nazwa[50];
    char jm[3];
};
struct Stany
{
    char ilosc[10];
};
void menu()
{
    cout<<"\t\t\tMENU GLOWNE\n\n\n";
    cout<<"\t\t1. Wprowadz Asortyment do systemu\n";
    cout<<"\t\t2. Wyswietl baze Asortymentow\n";
    cout<<"\t\t3. Wstaw Towar na magazyn\n";
    cout<<"\t\t4. Wydaj Towar z magazynu\n";
    cout<<"\t\t5. Obecne stany magazynowe\n";
    cout<<"\t\t6. Wyjdz\n";
}

void DodajAso()
{
    fstream plik;
    int n, numer=0;
    plik.open("Asortymenty.txt", ios::in| ios::out| ios::app);
    cout<<"Ile Asortymentow chcesz wprowadzic do bazy: ";
    cin>>n;
    DaneAso tab_aso[n];
    if(plik.good())
    {
        string linia;
        while(getline(plik, linia)) numer++;
        int i=0;
        do
        {
            cout<<"\nWporwadz Kod Asortymentu "<<i+1<<": ";
            cin>>tab_aso[i].kod;
            cout<<"Wprowadz Nazwe Asortymentu "<<i+1<<": ";
            cin>>tab_aso[i].nazwa;
            cout<<"Wprowadz Jednostke miary "<<i+1<<":";
            cin>>tab_aso[i].jm;
            plik <<numer++<<";";
            plik <<tab_aso[i].kod<<";";
            plik <<tab_aso[i].nazwa<<";";
            plik <<tab_aso[i].jm<<";"<<endl;
            i++;
        }
        while(i<n);
    }
    else cout<<"\tPLIK ZOSTAL USZKODZONY!!\n";
    plik.close();
    system("pause");
}
void WyswietlAso(string Asortymenty)
{
    char linia[50],slowo,litera;
    bool znak=0;
    ifstream otworz;
    cout<<"Numer           Kod             Nazwa           Jednostka Miary"<<endl;
    otworz.open(Asortymenty);
    while(!otworz.eof())
    {
        for(int i=0;i<4;i++)
        {
            for(int j=0;j<23;j++)
            {
                otworz >> litera;
                if(litera!=';')
                    cout << litera;
                else
                    for (int k=j;k<16;k++)
                    {
                        cout << " ";
                        j=24;
                    }
            }
        }
        cout << endl;
    }
    otworz.close();
    cout << endl<<endl;
    system("pause");
}

void DodajStan(string Asortymenty, string stany)
{
    bool znak=0;
    char linia[50],slowo,litera;
    ifstream otworz;
    cout<<"Numer           Kod             Nazwa           Jednostka Miary"<<endl;
    otworz.open(Asortymenty);
    while(!otworz.eof())
    {
        for(int i=0;i<4;i++)
        {
            for(int j=0;j<23;j++)
            {
                otworz >> litera;
                if(litera!=';')
                    cout << litera;
                else
                    for (int k=j;k<16;k++)
                    {
                        cout << " ";
                        j=24;
                    }
            }
        }
        cout << endl;
    }
    otworz.close();
    cout << endl<<endl;
    cout<<"\nWybierz z listy ktory asortyment chcesz wprowadzic na magazyn\n\n";
    fstream plik;
    plik.open("stany.txt", ios::in| ios::out| ios::app);
    if(plik.good())
    {

    }
    plik.close();
    system("pause");
}
void ZdejmijStan()
{

}
void WyswietlStan(string stany)
{
    char linia[50],slowo,litera;
    bool znak=0;
    int index=0;
    ifstream otworz;
    otworz.open("stany.txt");
    while(!otworz.eof())
    {
        for(int i=0;i<4;i++)
        {
            for(int j=0;j<23;j++)
            {
                otworz >> litera;
                if(litera!=';')
                    cout << litera;
                else
                    for (int k=j;k<22;k++)
                    {
                        cout << " ";
                        j=24;
                    }
            }
        }
        cout << endl;
    }
    otworz.close();
    cout << endl<<endl;
    system("pause");
}

int main()
{
    SetConsoleTitleA("Ksiega Inwentarzowa");
    string wybor;
    bool running = true;
    while(running)
    {
        cout<<"Program wspomagajacy zarzadzanie ksiega inwentarzowa\n\n\n";
        menu();
        cout<<"\n\n\tWybierz co chcesz zrobic: ";
        cin>>wybor;
        if(wybor == "6")
        {
            cout<<"\n\n\tDziekuje za korzystanie z programu\n\n";
            system("pause");
            return 0;
        }
        else if(wybor == "1")
        {
            DodajAso();
        }
        else if(wybor == "2")
        {
            WyswietlAso("Asortymenty.txt");
        }
        else if(wybor == "3")
        {
            DodajStan("Asortymenty.txt", "stany.txt");
        }
        else if(wybor == "4")
        {
            ZdejmijStan();
        }
        else if(wybor == "5")
        {
            WyswietlStan("stany.txt");
        }
        else
        {
            cout<<"\tWybrales zla opcje, wcisnij poprawny przycisk\n\n";
            system("pause");
        }
    system("cls");
    }
}
</code>```

答:
I've managed to do it.

All i had to do is use file.clear(); after while function.

Thanks for your help!

Body:
I know that there are many topics about it but i've got a problem.

I have a code like this.

    void ADDAso()
    {
    fstream file;
    int n, number=0;
    file.open("Asortymenty.txt", ios::in| ios::out| ios::app);
    string line;
    while(getline(file, line)) number++;
    cout<<"Ile Asortymentow chcesz wprowadzic do bazy: ";
    cin>>n;
    DaneAso tab_aso[n];
    if(file.good())
    {
        int i=0;
        do
        {
            cout<<"\nWporwadz Kod Asortymentu "<<i+1<<": ";
            cin>>tab_aso[i].kod;
            cout<<"Wprowadz Nazwe Asortymentu "<<i+1<<": ";
            cin>>tab_aso[i].nazwa;
            cout<<"Wprowadz Jednostke miary "<<i+1<<":";
            cin>>tab_aso[i].jm;
            file <<number++<<";";
            file <<tab_aso[i].kod<<";";
            file <<tab_aso[i].nazwa<<";";
            file <<tab_aso[i].jm<<";"<<endl;
            i++;
        }
        while(i<n);
    }
    else cout<<"\tFILE IS BROKEN!!\n";
    plik.close();
    system("pause");
    }

End after I try to use it, it says that file is broken.
Main thing is to read existing file, count it's lines and add new line with current number.

@molbdnilo

Here is my whole code. Please show me what am i supposed to change.

#include <iostream>
#include <fstream>
#include <windows.h>
#include <conio.h>
#include <vector>

using namespace std;

struct DaneAso
{
    char kod[10];
    char nazwa[50];
    char jm[3];
};
struct Stany
{
    char ilosc[10];
};
void menu()
{
    cout<<"\t\t\tMENU GLOWNE\n\n\n";
    cout<<"\t\t1. Wprowadz Asortyment do systemu\n";
    cout<<"\t\t2. Wyswietl baze Asortymentow\n";
    cout<<"\t\t3. Wstaw Towar na magazyn\n";
    cout<<"\t\t4. Wydaj Towar z magazynu\n";
    cout<<"\t\t5. Obecne stany magazynowe\n";
    cout<<"\t\t6. Wyjdz\n";
}

void DodajAso()
{
    fstream plik;
    int n, numer=0;
    plik.open("Asortymenty.txt", ios::in| ios::out| ios::app);
    cout<<"Ile Asortymentow chcesz wprowadzic do bazy: ";
    cin>>n;
    DaneAso tab_aso[n];
    if(plik.good())
    {
        string linia;
        while(getline(plik, linia)) numer++;
        int i=0;
        do
        {
            cout<<"\nWporwadz Kod Asortymentu "<<i+1<<": ";
            cin>>tab_aso[i].kod;
            cout<<"Wprowadz Nazwe Asortymentu "<<i+1<<": ";
            cin>>tab_aso[i].nazwa;
            cout<<"Wprowadz Jednostke miary "<<i+1<<":";
            cin>>tab_aso[i].jm;
            plik <<numer++<<";";
            plik <<tab_aso[i].kod<<";";
            plik <<tab_aso[i].nazwa<<";";
            plik <<tab_aso[i].jm<<";"<<endl;
            i++;
        }
        while(i<n);
    }
    else cout<<"\tPLIK ZOSTAL USZKODZONY!!\n";
    plik.close();
    system("pause");
}
void WyswietlAso(string Asortymenty)
{
    char linia[50],slowo,litera;
    bool znak=0;
    ifstream otworz;
    cout<<"Numer           Kod             Nazwa           Jednostka Miary"<<endl;
    otworz.open(Asortymenty);
    while(!otworz.eof())
    {
        for(int i=0;i<4;i++)
        {
            for(int j=0;j<23;j++)
            {
                otworz >> litera;
                if(litera!=';')
                    cout << litera;
                else
                    for (int k=j;k<16;k++)
                    {
                        cout << " ";
                        j=24;
                    }
            }
        }
        cout << endl;
    }
    otworz.close();
    cout << endl<<endl;
    system("pause");
}

void DodajStan(string Asortymenty, string stany)
{
    bool znak=0;
    char linia[50],slowo,litera;
    ifstream otworz;
    cout<<"Numer           Kod             Nazwa           Jednostka Miary"<<endl;
    otworz.open(Asortymenty);
    while(!otworz.eof())
    {
        for(int i=0;i<4;i++)
        {
            for(int j=0;j<23;j++)
            {
                otworz >> litera;
                if(litera!=';')
                    cout << litera;
                else
                    for (int k=j;k<16;k++)
                    {
                        cout << " ";
                        j=24;
                    }
            }
        }
        cout << endl;
    }
    otworz.close();
    cout << endl<<endl;
    cout<<"\nWybierz z listy ktory asortyment chcesz wprowadzic na magazyn\n\n";
    fstream plik;
    plik.open("stany.txt", ios::in| ios::out| ios::app);
    if(plik.good())
    {

    }
    plik.close();
    system("pause");
}
void ZdejmijStan()
{

}
void WyswietlStan(string stany)
{
    char linia[50],slowo,litera;
    bool znak=0;
    int index=0;
    ifstream otworz;
    otworz.open("stany.txt");
    while(!otworz.eof())
    {
        for(int i=0;i<4;i++)
        {
            for(int j=0;j<23;j++)
            {
                otworz >> litera;
                if(litera!=';')
                    cout << litera;
                else
                    for (int k=j;k<22;k++)
                    {
                        cout << " ";
                        j=24;
                    }
            }
        }
        cout << endl;
    }
    otworz.close();
    cout << endl<<endl;
    system("pause");
}

int main()
{
    SetConsoleTitleA("Ksiega Inwentarzowa");
    string wybor;
    bool running = true;
    while(running)
    {
        cout<<"Program wspomagajacy zarzadzanie ksiega inwentarzowa\n\n\n";
        menu();
        cout<<"\n\n\tWybierz co chcesz zrobic: ";
        cin>>wybor;
        if(wybor == "6")
        {
            cout<<"\n\n\tDziekuje za korzystanie z programu\n\n";
            system("pause");
            return 0;
        }
        else if(wybor == "1")
        {
            DodajAso();
        }
        else if(wybor == "2")
        {
            WyswietlAso("Asortymenty.txt");
        }
        else if(wybor == "3")
        {
            DodajStan("Asortymenty.txt", "stany.txt");
        }
        else if(wybor == "4")
        {
            ZdejmijStan();
        }
        else if(wybor == "5")
        {
            WyswietlStan("stany.txt");
        }
        else
        {
            cout<<"\tWybrales zla opcje, wcisnij poprawny przycisk\n\n";
            system("pause");
        }
    system("cls");
    }
}


问:
How to disable the hours before the start date&time using v-calendar?
I am using v-calendar to have the start date&time and end date&time using mode as dateTime. My requirement is to make the end date&time not go before the start date&time. For this, I am using :min-date prop bounded with start date&time value as shown in the below code.

```<code><v-date-picker :min-date="this.formData.startDate" v-model="formData['endDate']" mode="dateTime" :timezone="timezone" name="End Date" class="dateTimePicker">
    <template v-slot="{ inputValue, inputEvents }">
        <input
           class="px-2 py-1 border rounded focus:outline-none focus:border-blue-300"
           :value="inputValue"
           v-on="inputEvents"
        />
    </template>
</v-date-picker>
</code>```

Now let's say the start date&time selected is Feb 10th, 05:00 AM and while selecting the end date&time, the dates before the 10th will be disabled. But If I select 10th as the date(same date), I could still select 04:00 AM as the time, which is not proper.

So is there a way of disabling the time with respect to the selected date?

答:
As I can see in their documentation you can pass validHours prop that is a function that returns if an hour is valid.

So depending on your implementaton you can do something like this:

<v-date-picker :validHours="isHourValid()" :min-date="this.formData.startDate" v-model="formData['endDate']" mode="dateTime" :timezone="timezone" name="End Date" class="dateTimePicker" >
    <template v-slot="{ inputValue, inputEvents }">
        <input
           class="px-2 py-1 border rounded focus:outline-none focus:border-blue-300"
           :value="inputValue"
           v-on="inputEvents"
        />
    </template>
</v-date-picker>

```

Body:
I am using v-calendar to have the start date&time and end date&time using mode as dateTime. My requirement is to make the end date&time not go before the start date&time. For this, I am using :min-date prop bounded with start date&time value as shown in the below code.

<v-date-picker :min-date="this.formData.startDate" v-model="formData['endDate']" mode="dateTime" :timezone="timezone" name="End Date" class="dateTimePicker">
    <template v-slot="{ inputValue, inputEvents }">
        <input
           class="px-2 py-1 border rounded focus:outline-none focus:border-blue-300"
           :value="inputValue"
           v-on="inputEvents"
        />
    </template>
</v-date-picker>

Now let's say the start date&time selected is Feb 10th, 05:00 AM and while selecting the end date&time, the dates before the 10th will be disabled. But If I select 10th as the date(same date), I could still select 04:00 AM as the time, which is not proper.

So is there a way of disabling the time with respect to the selected date?

Body:
As I can see in their documentation you can pass validHours prop that is a function that returns if an hour is valid.

So depending on your implementaton you can do something like this:

<v-date-picker :validHours="isHourValid()" :min-date="this.formData.startDate" v-model="formData['endDate']" mode="dateTime" :timezone="timezone" name="End Date" class="dateTimePicker" >
    <template v-slot="{ inputValue, inputEvents }">
        <input
           class="px-2 py-1 border rounded focus:outline-none focus:border-blue-300"
           :value="inputValue"
           v-on="inputEvents"
        />
    </template>
</v-date-picker>

<script>
  function isHourValid(hourThatIsSelected){
    let startDateVal = 12 // extract hour from formData['startDate'], eg. 12
    return hourThatIsSelected > startDateVal
  }
</script>


问:
Creating hook in Typescript with useContext and empty context object
I'm trying to create a useAuth custom hook within React 17 and Typescript. The solution that I have is kind of working, but it requires the following when accessing the hook methods:

    const auth = useAuth();
    // Do other stuff
    const result = await auth?.login(data);
```
<p>The issue is that I need to use the <code>?</code> operator when calling the <code>login</code> method, as the <code>auth</code> object can be null.</p>
<p>The reason for this I know is how I have implemented in the context, however I can't figure out how in TypeScript to create the context with a null context object by default (i.e. no currentUser).</p>
<p>This is how I've currently implemented the hook:</p>
<pre class="lang-ts prettyprint-override"><code>    interface AuthProvider {
        children: ReactNode;
    }

    interface ProvideAuthContext {
      currentUser: AppUser | null,
      login: (loginInfo: LoginInfo) => Promise<LoginResponse>,
      register: (registerInfo: RegisterInfo) => Promise<RegisterResponse>
    }

    const authContext = createContext<ProvideAuthContext | null>(null);

    export function ProvideAuth({ children }: AuthProvider) {
      const auth = useProvideAuth();
      return <authContext.Provider value={auth}>{children}</authContext.Provider>
    }

    // Hook for child components to get the auth object and re-render when it changes.
    export const useAuth = () => {
      return useContext(authContext);
    };

    // Provider hook that creates auth object and handles state
    function useProvideAuth() {
      // This is where I implement the ProvideAuthContext interface

      // Return the user object and auth methods
      return {
        currentUser,
        login,
        register
      };

    }
</code>```

Any help with this would be amazing. I'm 99% sure it's got to do with this line:
const authContext = createContext<ProvideAuthContext | null>(null);.

I can't do it this way: const authContext = createContext<ProvideAuthContext | null>({ currentUser: null }); as I get the following error:

Argument of type '{ currentUser: null; }' is not assignable to parameter of type 'ProvideAuthContext'.
Type '{ currentUser: null; }' is missing the following properties from type 'ProvideAuthContext': login, register

I can't change the ProvideAuthContext login and register methods to be login?:... or register?:... as I can't then use them in components that use the useAuth hook.

Thanks, Justin

答:
You can make use of the never type which is inferred from throw new Error:

```<code>
    interface ProvideAuthContext {
      currentUser: AppUser | null,
      login: (loginInfo: LoginInfo) => Promise<LoginResponse>,
      register: (registerInfo: RegisterInfo) => Promise<RegisterResponse>
    }

    const authContext = createContext<ProvideAuthContext>({
      currentUser: null,
      login: () => { throw new Error("context is missing") },
      register: () => { throw new Error("context is missing") }
    });
</code>```

Body:
I'm trying to create a useAuth custom hook within React 17 and Typescript. The solution that I have is kind of working, but it requires the following when accessing the hook methods:

    const auth = useAuth();
    // Do other stuff
    const result = await auth?.login(data);

The issue is that I need to use the ? operator when calling the login method, as the auth object can be null.

The reason for this I know is how I have implemented in the context, however I can't figure out how in TypeScript to create the context with a null context object by default (i.e. no currentUser).

This is how I've currently implemented the hook:

    interface AuthProvider {
        children: ReactNode;
    }

    interface ProvideAuthContext {
      currentUser: AppUser | null,
      login: (loginInfo: LoginInfo) => Promise<LoginResponse>,
      register: (registerInfo: RegisterInfo) => Promise<RegisterResponse>
    }

    const authContext = createContext<ProvideAuthContext | null>(null);

    export function ProvideAuth({ children }: AuthProvider) {
      const auth = useProvideAuth();
      return <authContext.Provider value={auth}>{children}</authContext.Provider>
    }

    // Hook for child components to get the auth object and re-render when it changes.
    export const useAuth = () => {
      return useContext(authContext);
    };

    // Provider hook that creates auth object and handles state
    function useProvideAuth() {
      // This is where I implement the ProvideAuthContext interface

      // Return the user object and auth methods
      return {
        currentUser,
        login,
        register
      };

    }

Any help with this would be amazing. I'm 99% sure it's got to do with this line:
const authContext = createContext<ProvideAuthContext | null>(null);.

I can't do it this way: const authContext = createContext<ProvideAuthContext | null>({ currentUser: null }); as I get the following error:

Argument of type '{ currentUser: null; }' is not assignable to parameter of type 'ProvideAuthContext'.
Type '{ currentUser: null; }' is missing the following properties from type 'ProvideAuthContext': login, register

I can't change the ProvideAuthContext login and register methods to be login?:... or register?:... as I can't then use them in components that use the useAuth hook.

Thanks, Justin

Body:
You can make use of the never type which is inferred from throw new Error:

    interface ProvideAuthContext {
      currentUser: AppUser | null,
      login: (loginInfo: LoginInfo) => Promise<LoginResponse>,
      register: (registerInfo: RegisterInfo) => Promise<RegisterResponse>
    }

    const authContext = createContext<ProvideAuthContext>({
      currentUser: null,
      login: () => { throw new Error("context is missing") },
      register: () => { throw new Error("context is missing") }
    });


问:
Is there a quick lookup for url-to-controller mapping when @RequestMapping is used?
Given a web app that completely uses @RequestMapping to tie urls to a controller, I was wondering if there is a way or plug-in that would produce the web app's complete url-to-controller mappings?

Similar to struts.xml where you have all the urls mapping to an action hence you can see these information in a central place?

Otherwise, what happens is given a url from the screen, I end up doing a java file search each time I want to lookup that url's controller.

答:
Eclipse has plugin Springsource Tool Suite (you can also download it standalone): http://www.springsource.com/developer/sts You must first add Spring project nature to your project, then switch to Java EE perspective and then you will see "Spring Elements" in your project and there you will see all request mappings (and much more).

edit: useful features like this in STS made me switch from NetBeans to Eclipse.


问:
Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired
I installed Laravel 5.7

Added a form to the file \resources\views\welcome.blade.php

```<code><form method="POST" action="/foo" >
    @csrf
    <input type="text" name="name"/><br/>
    <input type="submit" value="Add"/>
</form>
</code>```

Added to file \routes\web.php

```<code>Route::post('/foo', function () {
    echo 1;
    return;
});
</code>```

After sending a POST request:

419 Sorry, your session has expired. Please refresh and try again.

In version 5.6 there was no such a problem.

答: For some, make sure also that your blade file is named with filename.blade.php not filename.php, this would result to 419 too.</p>

Body:
I installed Laravel 5.7

Added a form to the file \resources\views\welcome.blade.php

<form method="POST" action="/foo" >
    @csrf
    <input type="text" name="name"/>

    <input type="submit" value="Add"/>
</form>

Added to file \routes\web.php

Route::post('/foo', function () {
    echo 1;
    return;
});

After sending a POST request:

419 Sorry, your session has expired. Please refresh and try again.

In version 5.6 there was no such a problem.


问:
WatermelonDB [Diagnostic error: Passed undefined to query]
Good night everyone, I have the following problem.
I'm using a sync function from WatermelonDB but it's giving this error when it runs.
I'm sure an object manually to see why it doesn't work.

And that same object works if it's inserted out of sync.
Does anyone know how to fix?

```<code>    await synchronize({
    database,
    pullChanges: async ({ lastPulledAt }) => {
      const { data } = await api.get(`/sync/pull/${1637416552 || 0}`);
      console.log(JSON.stringify(data.changes, null, 2));
      return {
        // changes: data.changes,
        changes: {
          sub_workspaces: {
            created: [
              {
                sub_workspace_id: 57,
                name: "Teiu",
                avatar_url: "-",
                slug: "teiu",
                workspace_id: 19,
              },
            ],
            updated: [],
            deleted: [],
          },
        },
        timestamp: 1637416552,
      };
    },
    pushChanges: async ({ changes }) => {},
  });
</code>```
```<code>    import { tableSchema } from '@nozbe/watermelondb'

    const subWorskapceSchema = tableSchema({
        name: 'sub_workspaces',
        columns: [
            {
                name: 'sub_workspace_id',
                type: 'number',
            },
            {
                name: 'name',
                type: 'string'
            },
            {
                name: 'avatar_url',
                type: 'string'
            },
            {
                name: 'slug',
                type: 'string'
            },
            {
                name: 'workspace_id',
                type: 'number'
            },
        ]
    })
    export { subWorskapceSchema }
</code>```

答:
Good morning, the error is because you are not receiving the 'id' field and watermelon requires it to create, update or delete a record.
the structure of the changes is fine, it is only necessary to add the field 'id' with a value of type string
try with:</p>
```<code>await synchronize({
    database,
    pullChanges: async ({ lastPulledAt }) => {
      const { data } = await api.get(`/sync/pull/${1637416552 || 0}`);
      console.log(JSON.stringify(data.changes, null, 2));
      return {
        // changes: data.changes,
        changes: {
          sub_workspaces: {
            created: [
              {
                id: 'testid'
                sub_workspace_id: 57,
                name: "Teiu",
                avatar_url: "-",
                slug: "teiu",
                workspace_id: 19,
              },
            ],
            updated: [],
            deleted: [],
          },
        },
        timestamp: 1637416552,
      };
    },
    pushChanges: async ({ changes }) => {},
  });
</code>```

Body:
Good night everyone, I have the following problem.
I'm using a sync function from WatermelonDB but it's giving this error when it runs.
I'm sure an object manually to see why it doesn't work.

And that same object works if it's inserted out of sync.
Does anyone know how to fix?

    await synchronize({
    database,
    pullChanges: async ({ lastPulledAt }) => {
      const { data } = await api.get(`/sync/pull/${1637416552 || 0}`);
      console.log(JSON.stringify(data.changes, null, 2));
      return {
        // changes: data.changes,
        changes: {
          sub_workspaces: {
            created: [
              {
                sub_workspace_id: 57,
                name: "Teiu",
                avatar_url: "-",
                slug: "teiu",
                workspace_id: 19,
              },
            ],
            updated: [],
            deleted: [],
          },
        },
        timestamp: 1637416552,
      };
    },
    pushChanges: async ({ changes }) => {},
  });

    import { tableSchema } from '@nozbe/watermelondb'

    const subWorskapceSchema = tableSchema({
        name: 'sub_workspaces',
        columns: [
            {
                name: 'sub_workspace_id',
                type: 'number',
            },
            {
                name: 'name',
                type: 'string'
            },
            {
                name: 'avatar_url',
                type: 'string'
            },
            {
                name: 'slug',
                type: 'string'
            },
            {
                name: 'workspace_id',
                type: 'number'
            },
        ]
    })
    export { subWorskapceSchema }

Body:
Good morning, the error is because you are not receiving the 'id' field and watermelon requires it to create, update or delete a record.
the structure of the changes is fine, it is only necessary to add the field 'id' with a value of type string
try with:

await synchronize({
    database,
    pullChanges: async ({ lastPulledAt }) => {
      const { data } = await api.get(`/sync/pull/${1637416552 || 0}`);
      console.log(JSON.stringify(data.changes, null, 2));
      return {
        // changes: data.changes,
        changes: {
          sub_workspaces: {
            created: [
              {
                id: 'testid'
                sub_workspace_id: 57,
                name: "Teiu",
                avatar_url: "-",
                slug: "teiu",
                workspace_id: 19,
              },
            ],
            updated: [],
            deleted: [],
          },
        },
        timestamp: 1637416552,
      };
    },
    pushChanges: async ({ changes }) => {},
  });


问:
Expression Tree - Clone and Change Types of MethodCalls, Lambdas (Parameters, Return Types, Anonymous Types etc)
The below Linq query receives entitySet as an T type (which is of an Interface type). The generated expression tree fails to transform to Sql due to this Interface type, and hence during the expression tree query evaluation I need a way to transform all Lambdas, MethodCalls (along with their parameters, returntypes (which could be AnonymousType_of_Interface) to a supplied concrete type.

```<code> IQueryable<T> GetMasterConfigsForMasterConfigExport<T>(IQueryable<T> entitySet, GetMasterConfigsForMasterConfigExportParams p)
        {
            var selectedMasterConfigIds = p.SelectedMasterConfigIds.IsNotBlank() ? p.SelectedMasterConfigIds.ConvertCSVToLong() : Enumerable.Empty<long>();

            var query = from masterConfig in entitySet
                        join selectedMasterConfigId in (Repository.ConvertToBigIntTable(selectedMasterConfigIds, "selectedMasterConfigId") as IQueryable<ConvertCSVToBigIntTableResult>)
                        on masterConfig.Id equals selectedMasterConfigId.Id into selectedMasterConfigIdsRS
                        from selectedMasterConfigId in selectedMasterConfigIdsRS.DefaultIfEmpty()
                        where masterConfig.IsActive && selectedMasterConfigId == null
                        select masterConfig;
            return query;
        }

</code>```

The Generated Expression tree looks like this, I would like to replace all occurrences of IMasterConfig to some other supplied concrete object somehow:

```<code>.Call System.Linq.Queryable.Count(.Call System.Linq.Queryable.Select(
        .Call System.Linq.Queryable.Where(
            .Call System.Linq.Queryable.SelectMany(
                .Extension<Microsoft.EntityFrameworkCore.Query.QueryRootExpression>,
                '(.Lambda #Lambda1<System.Func`2[IMasterConfig,System.Collections.Generic.IEnumerable`1[Lw.Sys.Repository.ParsedBigInt]]>),
                '(.Lambda #Lambda2<System.Func`3[IMasterConfig,Lw.Sys.Repository.ParsedBigInt,<>f__AnonymousType325`2[IMasterConfig,Lw.Sys.Repository.ParsedBigInt]]>))
            ,
            '(.Lambda #Lambda3<System.Func`2[<>f__AnonymousType325`2[IMasterConfig,Lw.Sys.Repository.ParsedBigInt],System.Boolean]>))
        ,
        '(.Lambda #Lambda4<System.Func`2[<>f__AnonymousType325`2[IMasterConfig,Lw.Sys.Repository.ParsedBigInt],IMasterConfig]>))
)

.Lambda #Lambda1<System.Func`2[IMasterConfig,System.Collections.Generic.IEnumerable`1[Lw.Sys.Repository.ParsedBigInt]]>(IMasterConfig $masterConfig)
{
    .Call System.Linq.Queryable.DefaultIfEmpty(.Call System.Linq.Queryable.Where(
            .Call $__p_0.ConvertCSVToBigIntTable(
                $__List_1,
                $__Delim_2),
            '(.Lambda #Lambda5<System.Func`2[Lw.Sys.Repository.ParsedBigInt,System.Boolean]>)))
}

.Lambda #Lambda2<System.Func`3[IMasterConfig,Lw.Sys.Repository.ParsedBigInt,<>f__AnonymousType325`2[IMasterConfig,Lw.Sys.Repository.ParsedBigInt]]>(
    IMasterConfig $masterConfig,
    Lw.Sys.Repository.ParsedBigInt $selectedMasterConfigId) {
    .New <>f__AnonymousType325`2[IMasterConfig,Lw.Sys.Repository.ParsedBigInt](
        $masterConfig,
        $selectedMasterConfigId)
}

.Lambda #Lambda3<System.Func`2[<>f__AnonymousType325`2[IMasterConfig,Lw.Sys.Repository.ParsedBigInt],System.Boolean]>(<>f__AnonymousType325`2[IMasterConfig,Lw.Sys.Repository.ParsedBigInt] $<>h__TransparentIdentifier0)
{
    ($<>h__TransparentIdentifier0.masterConfig).IsActive && $<>h__TransparentIdentifier0.selectedMasterConfigId == null
}

.Lambda #Lambda4<System.Func`2[<>f__AnonymousType325`2[IMasterConfig,Lw.Sys.Repository.ParsedBigInt],IMasterConfig]>(<>f__AnonymousType325`2[IMasterConfig,Lw.Sys.Repository.ParsedBigInt] $<>h__TransparentIdentifier0)
{
    $<>h__TransparentIdentifier0.masterConfig
}

.Lambda #Lambda5<System.Func`2[Lw.Sys.Repository.ParsedBigInt,System.Boolean]>(Lw.Sys.Repository.ParsedBigInt $selectedMasterConfigId)
{
    $masterConfig.Id == $selectedMasterConfigId.Id
}

</code>```

答:
As cited by @IvonStoev, using the following code solves the issue in EFCore6:

```<code> protected override Expression VisitMethodCall(MethodCallExpression node)
        {
            if (node.Method.DeclaringType == typeof(Queryable) && node.Method.Name == nameof(Queryable.GroupJoin) && node.Arguments.Count == 5)
            {
                var outer = Visit(node.Arguments[0]);
                var inner = Visit(node.Arguments[1]);
                var outerKeySelector = Visit(node.Arguments[2]).UnwrapLambdaFromQuote();
                var innerKeySelector = Visit(node.Arguments[3]).UnwrapLambdaFromQuote();
                var resultSelector = Visit(node.Arguments[4]).UnwrapLambdaFromQuote();

                var outerKey = outerKeySelector.Body.ReplaceParameter(outerKeySelector.Parameters[0], resultSelector.Parameters[0]);
                var innerKey = innerKeySelector.Body;
                var keyMatch = MatchKeys(outerKey, innerKey);

                var innerQuery = Expression.Call(
                    typeof(Queryable), nameof(Queryable.Where), new[] { innerKeySelector.Parameters[0].Type },
                    inner, Expression.Lambda(keyMatch, innerKeySelector.Parameters));

                var asEnumerableInnerQuery = Expression.Call(
                                typeof(Enumerable),
                                nameof(Enumerable.AsEnumerable),
                                new Type[] { innerKeySelector.Parameters[0].Type }, innerQuery);

                var resultTypes = resultSelector.Parameters.Select(p => p.Type).ToArray();
                var tempProjectionType = typeof(Tuple<,>).MakeGenericType(resultTypes);
                var tempProjection = Expression.New(
                    tempProjectionType.GetConstructor(resultTypes),
                    new Expression[] { resultSelector.Parameters[0], asEnumerableInnerQuery },
                    tempProjectionType.GetProperty("Item1"), tempProjectionType.GetProperty("Item2"));

                var tempQuery = Expression.Call(
                    typeof(Queryable), nameof(Queryable.Select), new[] { outerKeySelector.Parameters[0].Type, tempProjectionType },
                    outer, Expression.Lambda(tempProjection, resultSelector.Parameters[0]));

                var tempResult = Expression.Parameter(tempProjectionType, "p");
                var projection = resultSelector.Body
                    .ReplaceParameter(resultSelector.Parameters[0], Expression.Property(tempResult, "Item1"))
                    .ReplaceParameter(resultSelector.Parameters[1], Expression.Property(tempResult, "Item2"));

                var query = Expression.Call(
                    typeof(Queryable), nameof(Queryable.Select), new[] { tempProjectionType, projection.Type },
                    tempQuery, Expression.Lambda(projection, tempResult));
                return query;
            }
            return base.VisitMethodCall(node);
        }
</code>```

Body:
The below Linq query receives entitySet as an T type (which is of an Interface type). The generated expression tree fails to transform to Sql due to this Interface type, and hence during the expression tree query evaluation I need a way to transform all Lambdas, MethodCalls (along with their parameters, returntypes (which could be AnonymousType_of_Interface) to a supplied concrete type.

 IQueryable<T> GetMasterConfigsForMasterConfigExport<T>(IQueryable<T> entitySet, GetMasterConfigsForMasterConfigExportParams p)
        {
            var selectedMasterConfigIds = p.SelectedMasterConfigIds.IsNotBlank() ? p.SelectedMasterConfigIds.ConvertCSVToLong() : Enumerable.Empty<long>();

            var query = from masterConfig in entitySet
                        join selectedMasterConfigId in (Repository.ConvertToBigIntTable(selectedMasterConfigIds, "selectedMasterConfigId") as IQueryable<ConvertCSVToBigIntTableResult>)
                        on masterConfig.Id equals selectedMasterConfigId.Id into selectedMasterConfigIdsRS
                        from selectedMasterConfigId in selectedMasterConfigIdsRS.DefaultIfEmpty()
                        where masterConfig.IsActive && selectedMasterConfigId == null
                        select masterConfig;
            return query;
        }

The Generated Expression tree looks like this, I would like to replace all occurrences of IMasterConfig to some other supplied concrete object somehow:

.Call System.Linq.Queryable.Count(.Call System.Linq.Queryable.Select(
        .Call System.Linq.Queryable.Where(
            .Call System.Linq.Queryable.SelectMany(
                .Extension<Microsoft.EntityFrameworkCore.Query.QueryRootExpression>,
                '(.Lambda #Lambda1<System.Func`2[IMasterConfig,System.Collections.Generic.IEnumerable`1[Lw.Sys.Repository.ParsedBigInt]]>),
                '(.Lambda #Lambda2<System.Func`3[IMasterConfig,Lw.Sys.Repository.ParsedBigInt,<>f__AnonymousType325`2[IMasterConfig,Lw.Sys.Repository.ParsedBigInt]]>))
            ,
            '(.Lambda #Lambda3<System.Func`2[<>f__AnonymousType325`2[IMasterConfig,Lw.Sys.Repository.ParsedBigInt],System.Boolean]>))
        ,
        '(.Lambda #Lambda4<System.Func`2[<>f__AnonymousType325`2[IMasterConfig,Lw.Sys.Repository.ParsedBigInt],IMasterConfig]>))
)

.Lambda #Lambda1<System.Func`2[IMasterConfig,System.Collections.Generic.IEnumerable`1[Lw.Sys.Repository.ParsedBigInt]]>(IMasterConfig $masterConfig)
{
    .Call System.Linq.Queryable.DefaultIfEmpty(.Call System.Linq.Queryable.Where(
            .Call $__p_0.ConvertCSVToBigIntTable(
                $__List_1,
                $__Delim_2),
            '(.Lambda #Lambda5<System.Func`2[Lw.Sys.Repository.ParsedBigInt,System.Boolean]>)))
}

.Lambda #Lambda2<System.Func`3[IMasterConfig,Lw.Sys.Repository.ParsedBigInt,<>f__AnonymousType325`2[IMasterConfig,Lw.Sys.Repository.ParsedBigInt]]>(
    IMasterConfig $masterConfig,
    Lw.Sys.Repository.ParsedBigInt $selectedMasterConfigId) {
    .New <>f__AnonymousType325`2[IMasterConfig,Lw.Sys.Repository.ParsedBigInt](
        $masterConfig,
        $selectedMasterConfigId)
}

.Lambda #Lambda3<System.Func`2[<>f__AnonymousType325`2[IMasterConfig,Lw.Sys.Repository.ParsedBigInt],System.Boolean]>(<>f__AnonymousType325`2[IMasterConfig,Lw.Sys.Repository.ParsedBigInt] $<>h__TransparentIdentifier0)
{
    ($<>h__TransparentIdentifier0.masterConfig).IsActive && $<>h__TransparentIdentifier0.selectedMasterConfigId == null
}

.Lambda #Lambda4<System.Func`2[<>f__AnonymousType325`2[IMasterConfig,Lw.Sys.Repository.ParsedBigInt],IMasterConfig]>(<>f__AnonymousType325`2[IMasterConfig,Lw.Sys.Repository.ParsedBigInt] $<>h__TransparentIdentifier0)
{
    $<>h__TransparentIdentifier0.masterConfig
}

.Lambda #Lambda5<System.Func`2[Lw.Sys.Repository.ParsedBigInt,System.Boolean]>(Lw.Sys.Repository.ParsedBigInt $selectedMasterConfigId)
{
    $masterConfig.Id == $selectedMasterConfigId.Id
}

Body:
As cited by @IvonStoev, using the following code solves the issue in EFCore6:

 protected override Expression VisitMethodCall(MethodCallExpression node)
        {
            if (node.Method.DeclaringType == typeof(Queryable) && node.Method.Name == nameof(Queryable.GroupJoin) && node.Arguments.Count == 5)
            {
                var outer = Visit(node.Arguments[0]);
                var inner = Visit(node.Arguments[1]);
                var outerKeySelector = Visit(node.Arguments[2]).UnwrapLambdaFromQuote();
                var innerKeySelector = Visit(node.Arguments[3]).UnwrapLambdaFromQuote();
                var resultSelector = Visit(node.Arguments[4]).UnwrapLambdaFromQuote();

                var outerKey = outerKeySelector.Body.ReplaceParameter(outerKeySelector.Parameters[0], resultSelector.Parameters[0]);
                var innerKey = innerKeySelector.Body;
                var keyMatch = MatchKeys(outerKey, innerKey);

                var innerQuery = Expression.Call(
                    typeof(Queryable), nameof(Queryable.Where), new[] { innerKeySelector.Parameters[0].Type },
                    inner, Expression.Lambda(keyMatch, innerKeySelector.Parameters));

                var asEnumerableInnerQuery = Expression.Call(
                                typeof(Enumerable),
                                nameof(Enumerable.AsEnumerable),
                                new Type[] { innerKeySelector.Parameters[0].Type }, innerQuery);

                var resultTypes = resultSelector.Parameters.Select(p => p.Type).ToArray();
                var tempProjectionType = typeof(Tuple<,>).MakeGenericType(resultTypes);
                var tempProjection = Expression.New(
                    tempProjectionType.GetConstructor(resultTypes),
                    new Expression[] { resultSelector.Parameters[0], asEnumerableInnerQuery },
                    tempProjectionType.GetProperty("Item1"), tempProjectionType.GetProperty("Item2"));

                var tempQuery = Expression.Call(
                    typeof(Queryable), nameof(Queryable.Select), new[] { outerKeySelector.Parameters[0].Type, tempProjectionType },
                    outer, Expression.Lambda(tempProjection, resultSelector.Parameters[0]));

                var tempResult = Expression.Parameter(tempProjectionType, "p");
                var projection = resultSelector.Body
                    .ReplaceParameter(resultSelector.Parameters[0], Expression.Property(tempResult, "Item1"))
                    .ReplaceParameter(resultSelector.Parameters[1], Expression.Property(tempResult, "Item2"));

                var query = Expression.Call(
                    typeof(Queryable), nameof(Queryable.Select), new[] { tempProjectionType, projection.Type },
                    tempQuery, Expression.Lambda(projection, tempResult));
                return query;
            }
            return base.VisitMethodCall(node);
        }


问:
Why ic_launcher larger or not fit in my phone, but perfect in android studio?
I import an image assets from png. And android studio create all image for all size.
Looks like perfect in android studio. But when I install, the phone, zoom image or use wrong size. I don't understand.

Thanks any idea.

答: resize the image with photoshop or any image editing software and make the logo smaller. Maintain the image dimensions but make the contents smaller</p>


问:
Combining two or more Worksheet_Change Event in VBA
I have two sets of codes to run on VBA:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

If Intersect(Target, Range("A1")) Is Nothing Then Exit Sub
If IsNumeric(Target.Value) Then
    If Target.Value < 20 Then
        ActiveSheet.Shapes("Oval 1").Fill.ForeColor.RGB = RGB(171, 171, 171)
    Else
        ActiveSheet.Shapes("Oval 1").Fill.ForeColor.RGB = RGB(175, 96, 137)
    End If

   End If

End Sub
</code>```

And

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

If Intersect(Target, Range("A2")) Is Nothing Then Exit Sub
If IsNumeric(Target.Value) Then
    If Target.Value < 20 Then
        ActiveSheet.Shapes("Oval 2").Fill.ForeColor.RGB = RGB(171, 171, 171)
    Else
        ActiveSheet.Shapes("Oval 2").Fill.ForeColor.RGB = RGB(175, 96, 137)
        End If
    End If

End Sub
</code>```

I can't use both codes because of ambiguous Worksheet_Change in VBA. Is there any other way where I can run both codes without showing any error?

答:
You could combine both sets of code like this.

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    If Intersect(Target, Range("A1:A2")) Is Nothing Then Exit Sub

    If IsNumeric(Target.Value) Then
        If Target.Value < 20 Then
            Me.Shapes("Oval " & Target.Row).Fill.ForeColor.RGB = RGB(171, 171, 171)
        Else
            Me.Shapes("Oval " & Target.Row).Fill.ForeColor.RGB = RGB(175, 96, 137)
        End If
    End If

End Sub

```

Body:
I have two sets of codes to run on VBA:

Private Sub Worksheet_Change(ByVal Target As Range)

If Intersect(Target, Range("A1")) Is Nothing Then Exit Sub
If IsNumeric(Target.Value) Then
    If Target.Value < 20 Then
        ActiveSheet.Shapes("Oval 1").Fill.ForeColor.RGB = RGB(171, 171, 171)
    Else
        ActiveSheet.Shapes("Oval 1").Fill.ForeColor.RGB = RGB(175, 96, 137)
    End If

   End If

End Sub

And

Private Sub Worksheet_Change(ByVal Target As Range)

If Intersect(Target, Range("A2")) Is Nothing Then Exit Sub
If IsNumeric(Target.Value) Then
    If Target.Value < 20 Then
        ActiveSheet.Shapes("Oval 2").Fill.ForeColor.RGB = RGB(171, 171, 171)
    Else
        ActiveSheet.Shapes("Oval 2").Fill.ForeColor.RGB = RGB(175, 96, 137)
        End If
    End If

End Sub

I can't use both codes because of ambiguous Worksheet_Change in VBA. Is there any other way where I can run both codes without showing any error?


问:
How to fix position image on another image
I have the following code (also pasted below), where I want to make a layout of two columns. In the first one I am putting two images, and in the second displaying some text.

In the first column, I want to have the first image with width:70% and the second one with position:absolute on it. The final result should be like this

As you see the second image partially located in first one in every screens above to 768px.

I can partially locate second image on first one, but that is not dynamic, if you change screen dimensions you can see how that collapse.

But no matter how hard I try, I can not achieve this result.

.checkoutWrapper {
  display: grid;
  grid-template-columns: 50% 50%;
}

.coverIMGLast {
  width: 70%;
  height: 100vh;
}

/* this .phone class should be dynamically  located partially on first image */
.phone {
  position: absolute;
  height: 90%;
  top: 5%;
  bottom: 5%;
  margin-left: 18%;
}

.CheckoutProcess {
  padding: 5.8rem 6.4rem;
}

.someContent {
  border: 1px solid red;
}

/* removing for demo purposes
@media screen and (max-width: 768px) {
  .checkoutWrapper {
    display: grid;
    grid-template-columns: 100%;
  }
  img {
    display: none;
  }
  .CheckoutProcess {
    padding: 0;
  }
}
*/```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="checkoutWrapper">
  <img src="https://via.placeholder.com/300" class="coverIMGLast" />
  <img src="https://via.placeholder.com/300/ff0000" class="phone" />

  <div class="CheckoutProcess">
    <Content />
  </div>
</div></code>```

答:
I edited your code

everything that you wrote is correct.

You just forget to add margin-left: 25%. no matter which screen you use, it always be partially located on first one. (by center)

Body:
I have the following code (also pasted below), where I want to make a layout of two columns. In the first one I am putting two images, and in the second displaying some text.

In the first column, I want to have the first image with width:70% and the second one with position:absolute on it. The final result should be like this

As you see the second image partially located in first one in every screens above to 768px.

I can partially locate second image on first one, but that is not dynamic, if you change screen dimensions you can see how that collapse.

But no matter how hard I try, I can not achieve this result.

.checkoutWrapper {
  display: grid;
  grid-template-columns: 50% 50%;
}

.coverIMGLast {
  width: 70%;
  height: 100vh;
}

/* this .phone class should be dynamically  located partially on first image */
.phone {
  position: absolute;
  height: 90%;
  top: 5%;
  bottom: 5%;
  margin-left: 18%;
}

.CheckoutProcess {
  padding: 5.8rem 6.4rem;
}

.someContent {
  border: 1px solid red;
}

/* removing for demo purposes
@media screen and (max-width: 768px) {
  .checkoutWrapper {
    display: grid;
    grid-template-columns: 100%;
  }
  img {
    display: none;
  }
  .CheckoutProcess {
    padding: 0;
  }
}
*/

    <Content />


问:
SQL script to bulk update a field depending on a condition
I have a table with 2 date fields - OperativeTo and OperativeFrom. I have to check for the records for which OperativeTo is missing, then update OperativeTo as follows

```<code>OperativeTo  = OperativeFrom [Year+1] - 1 day
</code>```

That is, the operative date is equal to the OperativeFrom date of the same record in the following year minus 1 day. e.g. if a record has OperativeFrom date as 1/07/2015 then
OperativeTo will be 30/06/2016.

答:
Try this:

```<code>BEGIN TRAN
SELECT * FROM YourTable

    UPDATE YourTable
    SET OperativeTo = DATEADD( DAY, -1, DATEADD( YEAR, 1, OperativeFrom))
    WHERE OperativeTo IS NULL

SELECT * FROM YourTable
ROLLBACK
</code>```

If it gives you desired result, get rid of BEGIN TRAN/ROLLBACK and run the query again. Also read about DATEADD() function.

Body:
I have a table with 2 date fields - OperativeTo and OperativeFrom. I have to check for the records for which OperativeTo is missing, then update OperativeTo as follows

OperativeTo  = OperativeFrom [Year+1] - 1 day

That is, the operative date is equal to the OperativeFrom date of the same record in the following year minus 1 day. e.g. if a record has OperativeFrom date as 1/07/2015 then
OperativeTo will be 30/06/2016.

Body:
Try this:

BEGIN TRAN
SELECT * FROM YourTable

    UPDATE YourTable
    SET OperativeTo = DATEADD( DAY, -1, DATEADD( YEAR, 1, OperativeFrom))
    WHERE OperativeTo IS NULL

SELECT * FROM YourTable
ROLLBACK

If it gives you desired result, get rid of BEGIN TRAN/ROLLBACK and run the query again. Also read about DATEADD() function.


问:
Using pipes with FFMpeg as an input
I'm using FFMPEG library to manipulate video on user upload.

```<code>public async Task ManageVide(IFormFile file)
{
   ... process file
   string command = $"-i inputFile.mp4 -vf -s 800x600 outFile.mp4";
   ...
}
</code>```

is it possible to use memory stram as an input and output of the ffmpeg command? I read somewhere that for this can be used ffmpeg pipe. But I don't know how to structure the command

```<code>public async Task ManageVide(MemoryStream stream)
{
    string command = $"-i pipe:{stream} -vf -s 800x600 test.mp4";
    ...
}
</code>```

答:
I've been using the library CliWrap to work with FFMPEG. A simple example, of reading and writing from a memorystream:</p>
```<code>await Cli.Wrap("Path/to/exe")
         .WithArguments(arguments)
         .WithStandardInputPipe(PipeSource.FromStream(source))
         .WithStandardOutputPipe(PipeTarget.ToStream(destinationStream))
         .ExecuteAsync(cancellationToken);

destinationStream.Position = 0;
</code>```

Title: Using pipes with FFMpeg as an input

Body:
I'm using FFMPEG library to manipulate video on user upload.

public async Task ManageVide(IFormFile file)
{
   ... process file
   string command = $"-i inputFile.mp4 -vf -s 800x600 outFile.mp4";
   ...
}

is it possible to use memory stram as an input and output of the ffmpeg command? I read somewhere that for this can be used ffmpeg pipe. But I don't know how to structure the command

public async Task ManageVide(MemoryStream stream)
{
    string command = $"-i pipe:{stream} -vf -s 800x600 test.mp4";
    ...
}

Body:
I've been using the library CliWrap to work with FFMPEG. A simple example, of reading and writing from a memorystream:

await Cli.Wrap("Path/to/exe")
         .WithArguments(arguments)
         .WithStandardInputPipe(PipeSource.FromStream(source))
         .WithStandardOutputPipe(PipeTarget.ToStream(destinationStream))
         .ExecuteAsync(cancellationToken);

destinationStream.Position = 0;


问:
some module has no attribute 'something' for tkinter to work with two python files
I trying to execute file 'B'. But I get some error as :
'module 'B' has no attribute 'view_note''

'''                                file >> A.py                         '''

```<code> import B as b
 #from B import obj_2

 class obj_1:
     def __init__(self):
         print('obj_1 >> __init__')

     def obj_1_func_1(self):
         print('obj_1 >> obj_1_func_1')

         b.view_note.set("Infomation Updating...")
         # b.obj_2.display(self)
</code>```

'''                                file >> B.py                         '''

```<code> import A as a

 from tkinter import *
 import tkinter as tk

 class obj_2:
     def __init__(self):
         print('obj_2 >> __init__')

         self.view_note = StringVar()

         root.title("TK TEST")
         root.geometry("150x100+10+8")

         n1 = tk.Label(root, textvariable = self.view_note, fg='black')
         n1.pack()

         self.obj_2_func_2()

     def display(self):
         self.view_note.set("Infomation Updating...")

     def obj_2_func_2(self):
         print('obj_2 >> obj_2_func_2')

         a.obj_1.obj_1_func_1(self)

 if __name__ == '__main__':
     root = Tk()
     application = obj_2()
     root.mainloop()
</code>```

答:
As the error says, module "B" has no attribute "view_note". What it has is a class obj_2 objects of which have view_note attributes.
If you want to use this attribute in A first you have to instantiate the class with something like obj_b = b.obj_2() and then access it with obj_b.view_note.

Body:
I trying to execute file 'B'. But I get some error as :
'module 'B' has no attribute 'view_note''

'''                                file >> A.py                         '''

 import B as b
 #from B import obj_2

 class obj_1:
     def __init__(self):
         print('obj_1 >> __init__')

     def obj_1_func_1(self):
         print('obj_1 >> obj_1_func_1')

         b.view_note.set("Infomation Updating...")
         # b.obj_2.display(self)

'''                                file >> B.py                         '''

 import A as a

 from tkinter import *
 import tkinter as tk

 class obj_2:
     def __init__(self):
         print('obj_2 >> __init__')

         self.view_note = StringVar()

         root.title("TK TEST")
         root.geometry("150x100+10+8")

         n1 = tk.Label(root, textvariable = self.view_note, fg='black')
         n1.pack()

         self.obj_2_func_2()

     def display(self):
         self.view_note.set("Infomation Updating...")

     def obj_2_func_2(self):
         print('obj_2 >> obj_2_func_2')

         a.obj_1.obj_1_func_1(self)

 if __name__ == '__main__':
     root = Tk()
     application = obj_2()
     root.mainloop()


问:
How to capture pygame screen?
How can I capture and save a sequence of images or a video of a pygame screen?

Basically I want to share my game video on youtube. Also, want to make a tutorial.

The game is rendered mainly in a loop:

```<code>def main():
    while True:
        GetInput()
        Move()
        Shift()
        Draw()
</code>```

With the Draw() function doing all the blit() and stuff before doing the pygame.display.flip()

答:
The accepted answer said you could save the current screen with the pygame.image.save method

This is a good idea, however you might not want to save the images on the hard drive while the game is running, also pointed out by the question. Instead, you should save the screens in the program and then process them after the game has stopped running.

Here is my code with comments, that only shows the general idea of how a screen recording might work. It uses opencv (with numpy) and pygame but you have to install ffmpeg to convert the images to a video (try ffmpg in the terminal to test). Don't let the program run too long, because the saving still takes quite a while and is about proportional to the recorded frames. For more efficiency, you could only record every second frame or so.

from contextlib import contextmanager
import os
import time

import cv2
import numpy as np
import pygame as pg
from pygame import surfarray

def pg_to_cv2(cvarray:np.ndarray)->np.ndarray:
    cvarray = cvarray.swapaxes(0,1) #rotate
    cvarray = cv2.cvtColor(cvarray, cv2.COLOR_RGB2BGR) #RGB to BGR
    return cvarray

def timer_wrapper(func):
    def inner(*args, **kwargs):
        start = time.time()
        func(*args, **kwargs)
        end = time.time()
        #print("Finished:" ,func.__name__ ,end-start)
        return end - start
    return inner

@contextmanager
def video_writer(*args,**kwargs):
    video = cv2.VideoWriter(*args,**kwargs)
    try:
        yield video
    finally:
        video.release()

@timer_wrapper
def save_frames(frames: list, average_dt: float|list, file_type: str = "mp4", name: str = "screen_recording"):
    if type(average_dt) is list: average_dt = sum(average_dt)/len(average_dt) # force average_dt to be a float
    size = frames[0].get_size()
    codec_dict={
        "avi":'DIVX',
        "mp4":'MP4V'
    }
    codec = cv2.VideoWriter_fourcc(*codec_dict[file_type])
    with video_writer(name+"."+file_type, codec, 1000/average_dt, size) as video: # file_name, codec, average_fps, dimensions
        for frame in frames:
            try:
                pg_frame = surfarray.pixels3d(frame) # convert the surface to a np array. Only works with depth 24 or 32, not less
            except:
                pg_frame = surfarray.array3d(frame) # convert the surface to a np array. Works with any depth
            cv_frame = pg_to_cv2(pg_frame)  # then convert the np array so it is compatible with opencv
            video.write(cv_frame)   #write the frame to the video using opencv

def draw_fps(s:pg.Surface,clock:time.Clock):
    fps = clock.get_fps()
    sysfont.render_to(s,(100,100),str(fps),fgcolor=nice_green)

# initializing globals (colors, fonts, window, etc.)
pg.init()
sysfont = pg.freetype.SysFont(None,40)
BLACK = (0,)*3
nice_green = pg.Color("chartreuse2")
size=(1000, 600)
pg.display.set_caption("Screen Recording")
window = pg.display.set_mode(size)
# this is to save the frames
frames = []
dts = []
clock = pg.time.Clock()

running=True
try:
    while running:
        dt = clock.tick(60) # aim for ... fps
        for event in pg.event.get():
            if event.type == pg.QUIT:
                running=False
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_ESCAPE:
                    running=False
        window.fill(BLACK)
        draw_fps(window,clock)
        window_copy = window.copy() # if we don't copy the window then we will have the same image in all frames at the end
        frames.append(window_copy) # We save the current frame together with the time passed between the frames
        dts.append(dt)
        pg.display.flip()
        #if len(frames) >= 100: running = False # uncomment this to stop the game after ... frames for similar results in every run"
finally:
    pg.quit()
    # At this stage, the game ended and the cleanup process can start. For this we convert the frames to opencv images
    # Only then we will write the video to the hard drive (That is what makes the save so slow).
    # General information about the recording
    frame_num = len(frames)
    dt_sum = sum(dts)
    average_dt = dt_sum/frame_num
    # This is only an approximation:
    # for each frame we have width * height many pixels -> frame_num * width * height
    # A Surface needs get_bytesize() many bytes per pixel (In this case 4 bytes, because we set the depth of the display to 32 bits)
    memory_usage_approx = frame_num * size[0] * size[1] * frames[0].get_bytesize()  #https://www.pygame.org/docs/ref/surface.html#pygame.Surface.get_bytesize
    print("Total time:" , dt_sum/1000,"s")
    print("Average time per frame:" , average_dt,"ms")
    print("Number of frames:", frame_num)
    print("Memory usage approximation" , memory_usage_approx/1000, "KB")
    args = (frames,dts,"avi","screen_recording")
    time_for_save = save_frames(*args)
    file_name = args[3]+"."+args[2]
    video_memory_usage = os.path.getsize(file_name)
    print("Video memory usage:" , video_memory_usage/1000, "KB")
    with open("test.txt", "a") as f:
        print("Total time:" , dt_sum/1000,"s\nNumber of frames:", frame_num,"\nSize:",size,"\nTime for save:",time_for_save,"s\nSaved in file:",file_name,file=f)
        print("_"*100,file=f)
```

Or you just use a lib like Pygame Recorder.

Title: How to capture pygame screen?

Body:
How can I capture and save a sequence of images or a video of a pygame screen?

Basically I want to share my game video on youtube. Also, want to make a tutorial.

The game is rendered mainly in a loop:

def main():
    while True:
        GetInput()
        Move()
        Shift()
        Draw()

With the Draw() function doing all the blit() and stuff before doing the pygame.display.flip()

Body:
The accepted answer said you could save the current screen with the pygame.image.save method

This is a good idea, however you might not want to save the images on the hard drive while the game is running, also pointed out by the question. Instead, you should save the screens in the program and then process them after the game has stopped running.

Here is my code with comments, that only shows the general idea of how a screen recording might work. It uses opencv (with numpy) and pygame but you have to install ffmpeg to convert the images to a video (try ffmpg in the terminal to test). Don't let the program run too long, because the saving still takes quite a while and is about proportional to the recorded frames. For more efficiency, you could only record every second frame or so.

from contextlib import contextmanager
import os
import time

import cv2
import numpy as np
import pygame as pg
from pygame import surfarray

def pg_to_cv2(cvarray:np.ndarray)->np.ndarray:
    cvarray = cvarray.swapaxes(0,1) #rotate
    cvarray = cv2.cvtColor(cvarray, cv2.COLOR_RGB2BGR) #RGB to BGR
    return cvarray

def timer_wrapper(func):
    def inner(*args, **kwargs):
        start = time.time()
        func(*args, **kwargs)
        end = time.time()
        #print("Finished:" ,func.__name__ ,end-start)
        return end - start
    return inner

@contextmanager
def video_writer(*args,**kwargs):
    video = cv2.VideoWriter(*args,**kwargs)
    try:
        yield video
    finally:
        video.release()

@timer_wrapper
def save_frames(frames: list, average_dt: float|list, file_type: str = "mp4", name: str = "screen_recording"):
    if type(average_dt) is list: average_dt = sum(average_dt)/len(average_dt) # force average_dt to be a float
    size = frames[0].get_size()
    codec_dict={
        "avi":'DIVX',
        "mp4":'MP4V'
    }
    codec = cv2.VideoWriter_fourcc(*codec_dict[file_type])
    with video_writer(name+"."+file_type, codec, 1000/average_dt, size) as video: # file_name, codec, average_fps, dimensions
        for frame in frames:
            try:
                pg_frame = surfarray.pixels3d(frame) # convert the surface to a np array. Only works with depth 24 or 32, not less
            except:
                pg_frame = surfarray.array3d(frame) # convert the surface to a np array. Works with any depth
            cv_frame = pg_to_cv2(pg_frame)  # then convert the np array so it is compatible with opencv
            video.write(cv_frame)   #write the frame to the video using opencv

def draw_fps(s:pg.Surface,clock:time.Clock):
    fps = clock.get_fps()
    sysfont.render_to(s,(100,100),str(fps),fgcolor=nice_green)

# initializing globals (colors, fonts, window, etc.)
pg.init()
sysfont = pg.freetype.SysFont(None,40)
BLACK = (0,)*3
nice_green = pg.Color("chartreuse2")
size=(1000, 600)
pg.display.set_caption("Screen Recording")
window = pg.display.set_mode(size)
# this is to save the frames
frames = []
dts = []
clock = pg.time.Clock()

running=True
try:
    while running:
        dt = clock.tick(60) # aim for ... fps
        for event in pg.event.get():
            if event.type == pg.QUIT:
                running=False
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_ESCAPE:
                    running=False
        window.fill(BLACK)
        draw_fps(window,clock)
        window_copy = window.copy() # if we don't copy the window then we will have the same image in all frames at the end
        frames.append(window_copy) # We save the current frame together with the time passed between the frames
        dts.append(dt)
        pg.display.flip()
        #if len(frames) >= 100: running = False # uncomment this to stop the game after ... frames for similar results in every run"
finally:
    pg.quit()
    # At this stage, the game ended and the cleanup process can start. For this we convert the frames to opencv images
    # Only then we will write the video to the hard drive (That is what makes the save so slow).
    # General information about the recording
    frame_num = len(frames)
    dt_sum = sum(dts)
    average_dt = dt_sum/frame_num
    # This is only an approximation:
    # for each frame we have width * height many pixels -> frame_num * width * height
    # A Surface needs get_bytesize() many bytes per pixel (In this case 4 bytes, because we set the depth of the display to 32 bits)
    memory_usage_approx = frame_num * size[0] * size[1] * frames[0].get_bytesize()  #https://www.pygame.org/docs/ref/surface.html#pygame.Surface.get_bytesize
    print("Total time:" , dt_sum/1000,"s")
    print("Average time per frame:" , average_dt,"ms")
    print("Number of frames:", frame_num)
    print("Memory usage approximation" , memory_usage_approx/1000, "KB")
    args = (frames,dts,"avi","screen_recording")
    time_for_save = save_frames(*args)
    file_name = args[3]+"."+args[2]
    video_memory_usage = os.path.getsize(file_name)
    print("Video memory usage:" , video_memory_usage/1000, "KB")
    with open("test.txt", "a") as f:
        print("Total time:" , dt_sum/1000,"s\nNumber of frames:", frame_num,"\nSize:",size,"\nTime for save:",time_for_save,"s\nSaved in file:",file_name,file=f)
        print("_"*100,file=f)

Or you just use a lib like Pygame Recorder.


问:
How to create an array of objects with all objects from multiple arrays?
Given de following arrays:

```<code>const classes = [
  {
    students: [
       Student1,
       Student2,
    ]
  },
  {
    students: [
       Student3,
       Student4,
    ]
  }
]
</code>```

What's the best way performance-wise to generate an array of objects with a similar structure to this:

```<code>const allStudents = [
  Student1,
  Student2,
  Student3,
  Student4
]

</code>```

答:
const classes = [
  {
    students: ['Student1', 'Student2'],
  },
  {
    students: ['Student3', 'Student4'],
  },
];
const allStudents = classes.reduce((acc, curr) => {
  return [...acc, ...curr.students];
}, []);
console.log(allStudents);```

Body:
Given de following arrays:

const classes = [
  {
    students: [
       Student1,
       Student2,
    ]
  },
  {
    students: [
       Student3,
       Student4,
    ]
  }
]

What's the best way performance-wise to generate an array of objects with a similar structure to this:

const allStudents = [
  Student1,
  Student2,
  Student3,
  Student4
]


问:
getting error while viewing pdf file in an email from postmark email attachment feature
I don't know which encoding to do while sending email attachment from postmark attachments feature in the Content field.

I have already tried the following method to convert the pdf file to base64 but not find working:

```<code>fs.readFileSync("./filename.pdf").toString('base64')
////////
pdf2base64("./filename.pdf").then(
        (response) => {
            base= response //cGF0aC90by9maWxlLmpwZw==
        }
    ).catch(
        (error) => {
            console.log(error); //Exepection error....
        }
    )
/////
 function base64_encode(file) {
    // read binary data
    var bitmap = fs.readFileSync(file);
    // convert binary data to base64 encoded string
    return new Buffer.from(bitmap.toString('utf-8'),'base64');
}
</code>```

The code from which I am trying to send email is below:

```<code>var client = new postmark.ServerClient("*****");
  client.sendEmail({
    "From": "example@abc.com",
    "To": "abc@abc.com",
    "Subject": "Test",
    "TextBody": "please find attached file of your agreement",
    "Attachments": [
      {
        "Name":  'index.pdf',
     "Content":fs.readFileSync("./filename.pdf").toString('base64'),
       "ContentType": "application/pdf"
      }
    ]
  }).then((result) => {
    console.log("the result is :", result)
  }).catch((err) => {
    console.log("error is : ", err)
  });
</code>```

All I want it to find the method of how to encode as per the requirement for this email attachment. What should I put in the content field to send the errorless file

答:
First you have to convert your file in Base64 string.

For this, you can use the following function.

```<code>const blobToBase64 = blob => {
        const reader = new FileReader();
        reader.readAsDataURL(blob);
        return new Promise(resolve => {
          reader.onloadend = () => {
            resolve(reader.result);
          };
        });
      };
</code>```

After blob/file converting to Base64 string, you have remove the following substring from Base64 string.

data:application/pdf;base64

You can do it by following code:

```<code>        const updatedBase64String = res.replace("data:application/pdf;base64,", "")
</code>```

Now you can use the string in your content.

The complete code for you would like as

```<code>const blobToBase64 = blob => {
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    return new Promise(resolve => {
      reader.onloadend = () => {
        resolve(reader.result);
      };
    });
  };

   blobToBase64(pdfConvertedToBlob).then(res => {
       const updatedBase64String =  res.replace("data:application/pdf;base64,", "")

       client.sendEmail({
          "From": "example@abc.com",
          "To": "abc@abc.com",
          "Subject": "Test",
          "TextBody": "please find attached file of your agreement",
          "Attachments": [
              {
                  "Name":  'index.pdf',
                  "Content": updatedBase64String,
                  "ContentType": "application/pdf"
              }
           ]
       }).then((result) => {
           console.log("the result is :", result)
       }).catch((err) => {
           console.log("error is : ", err)
       });
    }
</code>```

One thing, to remember. First you have to convert your local PDF file to BLOB

For this, you have two choices.
First get the file from API, and get it in BLOB format like as

```<code>axios({
    method: "post",
    url: deployedServer,
    data: data,
    headers: { "Content-Type": "application/json" },
    responseType: 'blob',
 })
  .then((pdfConvertedToBlob) => {
      // it is blob data
   });
</code>```

Second you can convert it by input type file, and uploading local file there, and using it. You can use it as below.

```<code><input type="file" id="files" name="files" />

// now js code

if (window.File && window.FileReader && window.FileList && window.Blob) {
    document.getElementById('files').addEventListener('change', handleFileSelect, false);
 } else {
     alert('The File APIs are not fully supported in this browser.');
 }

 function handleFileSelect(evt) {
    let pdfConvertedToBlob = evt.target.files[0]; // FileList object

 }
</code>```

Hope it will helpful to you.

Body:
I don't know which encoding to do while sending email attachment from postmark attachments feature in the Content field.

I have already tried the following method to convert the pdf file to base64 but not find working:

fs.readFileSync("./filename.pdf").toString('base64')
////////
pdf2base64("./filename.pdf").then(
        (response) => {
            base= response //cGF0aC90by9maWxlLmpwZw==
        }
    ).catch(
        (error) => {
            console.log(error); //Exepection error....
        }
    )
/////
 function base64_encode(file) {
    // read binary data
    var bitmap = fs.readFileSync(file);
    // convert binary data to base64 encoded string
    return new Buffer.from(bitmap.toString('utf-8'),'base64');
}

The code from which I am trying to send email is below:

var client = new postmark.ServerClient("*****");
  client.sendEmail({
    "From": "example@abc.com",
    "To": "abc@abc.com",
    "Subject": "Test",
    "TextBody": "please find attached file of your agreement",
    "Attachments": [
      {
        "Name":  'index.pdf',
     "Content":fs.readFileSync("./filename.pdf").toString('base64'),
       "ContentType": "application/pdf"
      }
    ]
  }).then((result) => {
    console.log("the result is :", result)
  }).catch((err) => {
    console.log("error is : ", err)
  });

All I want it to find the method of how to encode as per the requirement for this email attachment. What should I put in the content field to send the errorless file

Body:
First you have to convert your file in Base64 string.

For this, you can use the following function.

const blobToBase64 = blob => {
        const reader = new FileReader();
        reader.readAsDataURL(blob);
        return new Promise(resolve => {
          reader.onloadend = () => {
            resolve(reader.result);
          };
        });
      };

After blob/file converting to Base64 string, you have remove the following substring from Base64 string.

data:application/pdf;base64

You can do it by following code:

        const updatedBase64String = res.replace("data:application/pdf;base64,", "")

Now you can use the string in your content.

The complete code for you would like as

const blobToBase64 = blob => {
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    return new Promise(resolve => {
      reader.onloadend = () => {
        resolve(reader.result);
      };
    });
  };

   blobToBase64(pdfConvertedToBlob).then(res => {
       const updatedBase64String =  res.replace("data:application/pdf;base64,", "")

       client.sendEmail({
          "From": "example@abc.com",
          "To": "abc@abc.com",
          "Subject": "Test",
          "TextBody": "please find attached file of your agreement",
          "Attachments": [
              {
                  "Name":  'index.pdf',
                  "Content": updatedBase64String,
                  "ContentType": "application/pdf"
              }
           ]
       }).then((result) => {
           console.log("the result is :", result)
       }).catch((err) => {
           console.log("error is : ", err)
       });
    }

One thing, to remember. First you have to convert your local PDF file to BLOB

For this, you have two choices.
First get the file from API, and get it in BLOB format like as

axios({
    method: "post",
    url: deployedServer,
    data: data,
    headers: { "Content-Type": "application/json" },
    responseType: 'blob',
 })
  .then((pdfConvertedToBlob) => {
      // it is blob data
   });

Second you can convert it by input type file, and uploading local file there, and using it. You can use it as below.

<input type="file" id="files" name="files" />

// now js code

if (window.File && window.FileReader && window.FileList && window.Blob) {
    document.getElementById('files').addEventListener('change', handleFileSelect, false);
 } else {
     alert('The File APIs are not fully supported in this browser.');
 }

 function handleFileSelect(evt) {
    let pdfConvertedToBlob = evt.target.files[0]; // FileList object

 }

Hope it will helpful to you.


问:
Python Dictionary not being filled?
I'm trying to generate a random graph by first adding 20 vertices to it and then randomly match each of these with another vertex. The adjacency list is a dictionary.
When I try to add these to the graph I just get a key error and I'm not sure why.
Is the dictionary not being filled correctly?

Below is the code.

'''

```<code>class Vertex:

    # Constructor for a new Vertex object. All vertex objects
    # start with a distance of positive infinity.
    def __init__(self, label):
        self.label = label
        self.distance = float('inf')
        self.pred_vertex = None

class Graph:
    def __init__(self):
        self.adjacency_list = {}
        self.edge_weights = {}

    def add_vertex(self, new_vertex):
        self.adjacency_list[new_vertex] = []

    def add_directed_edge(self, from_vertex, to_vertex, weight = 1.0):
        self.edge_weights[(from_vertex, to_vertex)] = weight
        self.adjacency_list[from_vertex].append(to_vertex)

    def add_undirected_edge(self, vertex_a, vertex_b, weight = 1.0):
        self.add_directed_edge(vertex_a, vertex_b, weight)
        self.add_directed_edge(vertex_b, vertex_a, weight)

g = Graph()
l = []

#add vertices 0-19 to the graph
for i in range(20):
    l.append(i)
    s = str(i)
    g.add_vertex(Vertex(s))

#connect a random vertex (0-19) with another random vertex
edges = [[random.choice(l), random.randrange(0, 20)] for i in range(10)]

#add these random edges to the graph
for i in range(10):
    g.add_undirected_edge(str(edges[i][0]), str(edges[i][1]), random.randint(0,100))
</code>```

'''

Thank you!

答:
The keys in your adjacency list are not numbers, but Vertex objects.  That is why you are getting a key error, you are trying to look up the vertex using an str(integer), but you need to pass a Vertex object.

The simplest solution is to remove the Vertex class and just use the strings of the integers for your vertex labels and adjacency keys.  That would reduce your code to this:

class Graph:
    def __init__(self):
        self.adjacency_list = {}
        self.edge_weights = {}

    def add_vertex(self, new_vertex):
        self.adjacency_list[new_vertex] = []

    def add_directed_edge(self, from_vertex, to_vertex, weight = 1.0):
        self.edge_weights[(from_vertex, to_vertex)] = weight
        self.adjacency_list[from_vertex].append(to_vertex)

    def add_undirected_edge(self, vertex_a, vertex_b, weight = 1.0):
        self.add_directed_edge(vertex_a, vertex_b, weight)
        self.add_directed_edge(vertex_b, vertex_a, weight)

g = Graph()
l = []

#add vertices 0-19 to the graph
for i in range(20):
    l.append(i)
    s = str(i)
    g.add_vertex(s)

#connect a random vertex (0-19) with another random vertex
edges = [[random.choice(l), random.randrange(0, 20)] for i in range(10)]

#add these random edges to the graph
for i in range(10):
    g.add_undirected_edge(str(edges[i][0]), str(edges[i][1]), random.randint(0,100))
```
<p>Another option is to store the adjacency using the string labels, but also store a mapping between the labels and the Vertex objects so they can be retrieved.</p>
<pre class="lang-py prettyprint-override"><code>class Vertex:

    # Constructor for a new Vertex object. All vertex objects
    # start with a distance of positive infinity.
    def __init__(self, label):
        self.label = label
        self.distance = float('inf')
        self.pred_vertex = None
    def __repr__(self):
        return f'<Vertex {self.label!r}>'

class Graph:
    def __init__(self):
        self.adjacency_list = {}
        self.vertex_map = {}
        self.edge_weights = {}

    def add_vertex(self, vertex_label):
        self.adjacency_list[vertex_label] = []
        self.vertex_map[vertex_label] = Vertex(vertex_label)

    def add_directed_edge(self, from_vertex, to_vertex, weight = 1.0):
        self.edge_weights[(from_vertex, to_vertex)] = weight
        self.adjacency_list[from_vertex].append(to_vertex)

    def add_undirected_edge(self, vertex_a, vertex_b, weight = 1.0):
        self.add_directed_edge(vertex_a, vertex_b, weight)
        self.add_directed_edge(vertex_b, vertex_a, weight)

g = Graph()
l = []

#add vertices 0-19 to the graph
for i in range(20):
    l.append(i)
    s = str(i)
    g.add_vertex(s)

#connect a random vertex (0-19) with another random vertex
edges = [[random.choice(l), random.randrange(0, 20)] for i in range(10)]

#add these random edges to the graph
for i in range(10):
    g.add_undirected_edge(str(edges[i][0]), str(edges[i][1]), random.randint(0,100))
</code>```

Title: Python Dictionary not being filled?

Body:
I'm trying to generate a random graph by first adding 20 vertices to it and then randomly match each of these with another vertex. The adjacency list is a dictionary.
When I try to add these to the graph I just get a key error and I'm not sure why.
Is the dictionary not being filled correctly?

Below is the code.

'''

class Vertex:

    # Constructor for a new Vertex object. All vertex objects
    # start with a distance of positive infinity.
    def __init__(self, label):
        self.label = label
        self.distance = float('inf')
        self.pred_vertex = None

class Graph:
    def __init__(self):
        self.adjacency_list = {}
        self.edge_weights = {}

    def add_vertex(self, new_vertex):
        self.adjacency_list[new_vertex] = []

    def add_directed_edge(self, from_vertex, to_vertex, weight = 1.0):
        self.edge_weights[(from_vertex, to_vertex)] = weight
        self.adjacency_list[from_vertex].append(to_vertex)

    def add_undirected_edge(self, vertex_a, vertex_b, weight = 1.0):
        self.add_directed_edge(vertex_a, vertex_b, weight)
        self.add_directed_edge(vertex_b, vertex_a, weight)

g = Graph()
l = []

#add vertices 0-19 to the graph
for i in range(20):
    l.append(i)
    s = str(i)
    g.add_vertex(Vertex(s))

#connect a random vertex (0-19) with another random vertex
edges = [[random.choice(l), random.randrange(0, 20)] for i in range(10)]

#add these random edges to the graph
for i in range(10):
    g.add_undirected_edge(str(edges[i][0]), str(edges[i][1]), random.randint(0,100))

'''

Thank you!

Body:
The keys in your adjacency list are not numbers, but Vertex objects.  That is why you are getting a key error, you are trying to look up the vertex using an str(integer), but you need to pass a Vertex object.

The simplest solution is to remove the Vertex class and just use the strings of the integers for your vertex labels and adjacency keys.  That would reduce your code to this:

class Graph:
    def __init__(self):
        self.adjacency_list = {}
        self.edge_weights = {}

    def add_vertex(self, new_vertex):
        self.adjacency_list[new_vertex] = []

    def add_directed_edge(self, from_vertex, to_vertex, weight = 1.0):
        self.edge_weights[(from_vertex, to_vertex)] = weight
        self.adjacency_list[from_vertex].append(to_vertex)

    def add_undirected_edge(self, vertex_a, vertex_b, weight = 1.0):
        self.add_directed_edge(vertex_a, vertex_b, weight)
        self.add_directed_edge(vertex_b, vertex_a, weight)

g = Graph()
l = []

#add vertices 0-19 to the graph
for i in range(20):
    l.append(i)
    s = str(i)
    g.add_vertex(s)

#connect a random vertex (0-19) with another random vertex
edges = [[random.choice(l), random.randrange(0, 20)] for i in range(10)]

#add these random edges to the graph
for i in range(10):
    g.add_undirected_edge(str(edges[i][0]), str(edges[i][1]), random.randint(0,100))

Another option is to store the adjacency using the string labels, but also store a mapping between the labels and the Vertex objects so they can be retrieved.

class Vertex:

    # Constructor for a new Vertex object. All vertex objects
    # start with a distance of positive infinity.
    def __init__(self, label):
        self.label = label
        self.distance = float('inf')
        self.pred_vertex = None
    def __repr__(self):
        return f'<Vertex {self.label!r}>'

class Graph:
    def __init__(self):
        self.adjacency_list = {}
        self.vertex_map = {}
        self.edge_weights = {}

    def add_vertex(self, vertex_label):
        self.adjacency_list[vertex_label] = []
        self.vertex_map[vertex_label] = Vertex(vertex_label)

    def add_directed_edge(self, from_vertex, to_vertex, weight = 1.0):
        self.edge_weights[(from_vertex, to_vertex)] = weight
        self.adjacency_list[from_vertex].append(to_vertex)

    def add_undirected_edge(self, vertex_a, vertex_b, weight = 1.0):
        self.add_directed_edge(vertex_a, vertex_b, weight)
        self.add_directed_edge(vertex_b, vertex_a, weight)

g = Graph()
l = []

#add vertices 0-19 to the graph
for i in range(20):
    l.append(i)
    s = str(i)
    g.add_vertex(s)

#connect a random vertex (0-19) with another random vertex
edges = [[random.choice(l), random.randrange(0, 20)] for i in range(10)]

#add these random edges to the graph
for i in range(10):
    g.add_undirected_edge(str(edges[i][0]), str(edges[i][1]), random.randint(0,100))


问:
JPackage update "PATH" environment variable
when creating an installer (eg .msi) with jpackage, is there any way to update the PATH environment variable? This is quite important for console utilities.

Did not see anything about it in the jpackage documentation. Maybe one day it will be supported... but, meanwhile, is there any workaround? (I mean, besides asking the users to manually update PATH by themselves...)

答:
Is It Possible?

YES.

Jpackage provides the ability to further customize the installer package built with WiX.

You'll have to use --resource-dir for that, as explained in Packaging Tool User's Guide.

Get Default main.wxs

Use the following command:

```<code>jpackage --input my_app [...] --temp "some/dir"
</code>```

You'll have the following file structure generated:

```<code>\some\dir
   \config
      my_app.ico
      my_app.properties
      main.wxs
      MsiInstallerStrings_en.wxl
      MsiInstallerStrings_ja.wxl
      MsiInstallerStrings_zh.wxl
      overrides.wxi
   \images
   \wixobj
</code>```

Copy the main.wxs file into the directory of choice, e.g. my_resource_dir.

You aren't gonna need anything else, so you can safely delete it as well as the installation package generated.

Change main.wxs to Append Your Installation Directory to the Path Variable

Change lines in my_resource_dir/main.wxs:

```<code><Feature Id="DefaultFeature" Title="!(loc.MainFeatureTitle)" Level="1">
  <ComponentGroupRef Id="Shortcuts"/>
  <ComponentGroupRef Id="Files"/>
  <ComponentGroupRef Id="FileAssociations"/>
</Feature>
</code>```

to:

```<code><Feature Id="DefaultFeature" Title="!(loc.MainFeatureTitle)" Level="1">
  <ComponentGroupRef Id="Shortcuts"/>
  <ComponentGroupRef Id="Files"/>
  <ComponentGroupRef Id="FileAssociations"/>
  <Component Id="pathEnvironmentVariable" Guid="{YOUR_GUID}" KeyPath="yes" Directory="TARGETDIR">
    <Environment Id="MyPathVariable" Name="Path" Value="[INSTALLDIR]" Action="set" System="no" Permanent="no" Part="last" Separator=";" />
  </Component>
</Feature>
</code>```

Make sure to replace YOUR_GUID with the GUID generated with the generator tool. For example: [...] Guid="{607ea423-79e0-4866-9ed7-62005b88d225}"

Create the Installer that Appends to Path:

Run the following command:

```<code>jpackage --input my_app [...] --resource-dir "my_resource_dir" --verbose
</code>```

In the log output you should see something similar to:

```<code>[...] Using custom main.wxs file [...]
</code>```

Result

The installer built now appends your INSTALLDIR to the Path on installation and removes it during uninstall.

Body:
Is It Possible?

YES.

Jpackage provides the ability to further customize the installer package built with WiX.

You'll have to use --resource-dir for that, as explained in Packaging Tool User's Guide.

Get Default main.wxs

Use the following command:

jpackage --input my_app [...] --temp "some/dir"

You'll have the following file structure generated:

\some\dir
   \config
      my_app.ico
      my_app.properties
      main.wxs
      MsiInstallerStrings_en.wxl
      MsiInstallerStrings_ja.wxl
      MsiInstallerStrings_zh.wxl
      overrides.wxi
   \images
   \wixobj

Copy the main.wxs file into the directory of choice, e.g. my_resource_dir.

You aren't gonna need anything else, so you can safely delete it as well as the installation package generated.

Change main.wxs to Append Your Installation Directory to the Path Variable

Change lines in my_resource_dir/main.wxs:

<Feature Id="DefaultFeature" Title="!(loc.MainFeatureTitle)" Level="1">
  <ComponentGroupRef Id="Shortcuts"/>
  <ComponentGroupRef Id="Files"/>
  <ComponentGroupRef Id="FileAssociations"/>
</Feature>

to:

<Feature Id="DefaultFeature" Title="!(loc.MainFeatureTitle)" Level="1">
  <ComponentGroupRef Id="Shortcuts"/>
  <ComponentGroupRef Id="Files"/>
  <ComponentGroupRef Id="FileAssociations"/>
  <Component Id="pathEnvironmentVariable" Guid="{YOUR_GUID}" KeyPath="yes" Directory="TARGETDIR">
    <Environment Id="MyPathVariable" Name="Path" Value="[INSTALLDIR]" Action="set" System="no" Permanent="no" Part="last" Separator=";" />
  </Component>
</Feature>

Make sure to replace YOUR_GUID with the GUID generated with the generator tool. For example: [...] Guid="{607ea423-79e0-4866-9ed7-62005b88d225}"

Create the Installer that Appends to Path:

Run the following command:

jpackage --input my_app [...] --resource-dir "my_resource_dir" --verbose

In the log output you should see something similar to:

[...] Using custom main.wxs file [...]

Result

The installer built now appends your INSTALLDIR to the Path on installation and removes it during uninstall.