问:
onClick handler does not update innerHTML of elements
I have an onClick function that is attached to rows of a table by the characterID that is provided from an array of objects (instantiated from a constructor function).

I'm using styled-components, hence the odd tag names further down.

Here's the function:

```<code>    //this is an onClick function for use in record rows in the JSX populated table for characters
    function barkCharData(idIn){
        console.log("==========================");

        try{
            //Get the fields...
            let idField = document.getElementById("txt_idField");
            let nameField = document.getElementsByName("first_name_field");

            //Set the fields
            idField.innerHTML = String(ar_charBin[idIn-1].id);
            console.log("\n---> idField: "+idField);
            console.log("---> idField.innerHTML: "+idField.innerHTML+"\n")

            nameField.innerHTML = String(ar_charBin[idIn-1].id);
            console.log("\n---> nameField: "+nameField);
            console.log("---> nameField.innerHTML: "+nameField.innerHTML+"\n")

        }
        catch(error)
        {
            console.log("Pants were shat in the 'barkCharData' function [line 72]:\n\t" +error)
        }
    }
}
</code>```

I can access each objects properties fine because they're all stored in an array called ar_charBin. Had them console logged earlier with no issues.

The problem I'm having is that I want to put these properties in to disabled text boxes.

These are defined as JSX here:

```<code>export const ExpTable = () => {

    let Char1 = new char_Obj(1,"Saloth", "Saar", 45, "Male", "Dragonborn", "Sorcerer", 10);
    let Char2 = new char_Obj(2,"Kaedwen", "Isaani", 36, "Male", "Dragonborn", "Sorcerer", 8);
    let Char3 = new char_Obj(3,"Euridice", "Swiftblade", 23, "Female", "Human", "Bard", 5);

    //array to store characters
    let ar_charBin = [];

    //push all chars into the array
    ar_charBin.push(Char1, Char2, Char3);

    return(
        <>
...table head stuff...

                    <tbody>
                        {ar_charBin.map((character) => (
                        <TableRow key={character.id} onClick={() => barkCharData(character.id)}>
                            <td>{character.full_name}</td>
                            <td>Level {character.level} {character.classType}</td>
                        </TableRow>
                        ))}
                    </tbody>
                </Table>

                <Wrapper>
                <h2>Object elements</h2>
                <p>These fields should update with object<br/>attributes when the records above are clicked</p>

                <input type="text" id="txt_idField" name ="id_field" placeholder="ID"/>
                <input type="text" id="txt_fNameField" name ="first_name_field" placeholder="First Name" disabled={true} />
                <input type="text" id="txt_sNameField" placeholder="Second Name" disabled={true} />
                <input type="text" id="txt_ageField" placeholder="Age" disabled={true} />
                <input type="text" id="txt_cNameField" placeholder="Full Name" disabled={true} />
                <input type="text" id="txt_genderField" placeholder="Gender" disabled={true} />
                <input type="text" id="txt_raceField" placeholder="Race" disabled={true} />
                <input type="text" id="txt_classField" placeholder="Class" disabled={true} />
                <input type="text" id="txt_levelField" placeholder="Level" disabled={true} />
            </Wrapper>
            </Wrapper>
        </>
    )
</code>```

So in the onClick function, it doesn't update the innerHTML of any element. Not sure why. I've tried inputting strings in VScode and in the page when I run npm start too but nothing seems to change them.

Screenshot of the app:

Looked for solutions but got nowhere so far. What am I doing wrong?

答:
React avoids re-rendering unless state was changed. Since all of the changes happen on local variable scale and no state updates were caused by your onClick event, React will keep all HTML as it was.
Try holding the ID of the selected character in the state and hopefully you should see some updates of HTML.</p>

Body:
I have an onClick function that is attached to rows of a table by the characterID that is provided from an array of objects (instantiated from a constructor function).

I'm using styled-components, hence the odd tag names further down.

Here's the function:

    //this is an onClick function for use in record rows in the JSX populated table for characters
    function barkCharData(idIn){
        console.log("==========================");

        try{
            //Get the fields...
            let idField = document.getElementById("txt_idField");
            let nameField = document.getElementsByName("first_name_field");

            //Set the fields
            idField.innerHTML = String(ar_charBin[idIn-1].id);
            console.log("\n---> idField: "+idField);
            console.log("---> idField.innerHTML: "+idField.innerHTML+"\n")

            nameField.innerHTML = String(ar_charBin[idIn-1].id);
            console.log("\n---> nameField: "+nameField);
            console.log("---> nameField.innerHTML: "+nameField.innerHTML+"\n")

        }
        catch(error)
        {
            console.log("Pants were shat in the 'barkCharData' function [line 72]:\n\t" +error)
        }
    }
}

I can access each objects properties fine because they're all stored in an array called ar_charBin. Had them console logged earlier with no issues.

The problem I'm having is that I want to put these properties in to disabled text boxes.

These are defined as JSX here:

export const ExpTable = () => {

    let Char1 = new char_Obj(1,"Saloth", "Saar", 45, "Male", "Dragonborn", "Sorcerer", 10);
    let Char2 = new char_Obj(2,"Kaedwen", "Isaani", 36, "Male", "Dragonborn", "Sorcerer", 8);
    let Char3 = new char_Obj(3,"Euridice", "Swiftblade", 23, "Female", "Human", "Bard", 5);

    //array to store characters
    let ar_charBin = [];

    //push all chars into the array
    ar_charBin.push(Char1, Char2, Char3);

    return(
        <>
...table head stuff...

                        {ar_charBin.map((character) => (
                        <TableRow key={character.id} onClick={() => barkCharData(character.id)}>
                            {character.full_name}
                            Level {character.level} {character.classType}
                        </TableRow>
                        ))}

                <Wrapper>

Object elements

These fields should update with object
attributes when the records above are clicked

                <input type="text" id="txt_idField" name ="id_field" placeholder="ID"/>
                <input type="text" id="txt_fNameField" name ="first_name_field" placeholder="First Name" disabled={true} />
                <input type="text" id="txt_sNameField" placeholder="Second Name" disabled={true} />
                <input type="text" id="txt_ageField" placeholder="Age" disabled={true} />
                <input type="text" id="txt_cNameField" placeholder="Full Name" disabled={true} />
                <input type="text" id="txt_genderField" placeholder="Gender" disabled={true} />
                <input type="text" id="txt_raceField" placeholder="Race" disabled={true} />
                <input type="text" id="txt_classField" placeholder="Class" disabled={true} />
                <input type="text" id="txt_levelField" placeholder="Level" disabled={true} />
            </Wrapper>
            </Wrapper>
        </>
    )

So in the onClick function, it doesn't update the innerHTML of any element. Not sure why. I've tried inputting strings in VScode and in the page when I run npm start too but nothing seems to change them.

Screenshot of the app:

Looked for solutions but got nowhere so far. What am I doing wrong?


来源: stackexchange

问:
Insertion sort using vectors, not working
Im trying to create an insertion sort algorithm using vectors, but instead of parsing the elements from the start of the array (vector here), i tried doing it from the end. The code does nothing but sort the element for the first time, and delete the first element of my vector. I want to know what correction to my code can I make for this to work.
Basic procedure:

Start by element towards last (second last element)

Insert it in correct position in the 'sorted' subarray (vector) after it

Delete it from its initial position

Continue with algorithm, traversing backwards until vector's beginning

Code:

```<code>#include <iostream>
#include <vector>
using namespace std;

template <class T>
void isort(vector <T> &ar){
    //start from second last element upto first element
    for(auto i = ar.end()-2; i >= ar.begin(); i--){
        //iterator pointing towards element next to insertion element
        auto j = i + 1;
        //traverse and increase the pointer until condition met
        while(j != ar.end() && *i < *j) j++;
        //insert the insertion element at final position of the pointer
        ar.insert(j,*i);
        //erase the original element
        ar.erase(i);
    }
}
template <class T>
void display(vector <T> &ar){
    for(auto i = ar.begin(); i != ar.end(); i++){
        cout << *i << ' ';
    }
    cout << endl;
}
int main() {
    vector <int> X {6,1,7,1,3,2,6723,4,1,6};
    display <int>(X);
    isort <int>(X);
    display <int>(X);
}
</code>```

Expected output:

```<code>6 1 7 1 3 2 6723 4 1 6
1 1 1 2 3 4 6 6 7 6723
</code>```

Output attained:

```<code>6 1 7 1 3 2 6723 4 1 6
1 7 1 3 2 6723 4 1 6 1
</code>```

答:
This is my implementation of Insertion reverse algo.

```<code>template <class T>
void isort(vector <T> &ar){
    if(ar.size() < 2)
        return;
    //start from second last element upto first element
    for(auto i = ar.end()-2; i >= ar.begin(); i--){

        auto j = i;
        //swap values until condition met
        while((j + 1) != ar.end() && *(j + 1) < *j) {
            //swap values
            auto tmp = *j;
            *j = *(j + 1);
            *(j + 1) = tmp;
            ++j;
        }
    }
}
</code>```

The difference here it swaps the two values instead of insert/erase.

```<code>while(j != ar.end() && *i < *j) j++;
//insert the insertion element at final position of the pointer
ar.insert(j,*i);
//erase the original element
ar.erase(i);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Im trying to create an insertion sort algorithm using vectors, but instead of parsing the elements from the start of the array (vector here), i tried doing it from the end. The code does nothing but sort the element for the first time, and delete the first element of my vector. I want to know what correction to my code can I make for this to work.
Basic procedure:

Start by element towards last (second last element)

Insert it in correct position in the 'sorted' subarray (vector) after it

Delete it from its initial position

Continue with algorithm, traversing backwards until vector's beginning

Code:

#include <iostream>
#include <vector>
using namespace std;

template <class T>
void isort(vector <T> &ar){
    //start from second last element upto first element
    for(auto i = ar.end()-2; i >= ar.begin(); i--){
        //iterator pointing towards element next to insertion element
        auto j = i + 1;
        //traverse and increase the pointer until condition met
        while(j != ar.end() && *i < *j) j++;
        //insert the insertion element at final position of the pointer
        ar.insert(j,*i);
        //erase the original element
        ar.erase(i);
    }
}
template <class T>
void display(vector <T> &ar){
    for(auto i = ar.begin(); i != ar.end(); i++){
        cout << *i << ' ';
    }
    cout << endl;
}
int main() {
    vector <int> X {6,1,7,1,3,2,6723,4,1,6};
    display <int>(X);
    isort <int>(X);
    display <int>(X);
}

Expected output:

6 1 7 1 3 2 6723 4 1 6
1 1 1 2 3 4 6 6 7 6723

Output attained:

6 1 7 1 3 2 6723 4 1 6
1 7 1 3 2 6723 4 1 6 1

Body:
This is my implementation of Insertion reverse algo.

template <class T>
void isort(vector <T> &ar){
    if(ar.size() < 2)
        return;
    //start from second last element upto first element
    for(auto i = ar.end()-2; i >= ar.begin(); i--){

        auto j = i;
        //swap values until condition met
        while((j + 1) != ar.end() && *(j + 1) < *j) {
            //swap values
            auto tmp = *j;
            *j = *(j + 1);
            *(j + 1) = tmp;
            ++j;
        }
    }
}

The difference here it swaps the two values instead of insert/erase.

while(j != ar.end() && *i < *j) j++;
//insert the insertion element at final position of the pointer
ar.insert(j,*i);
//erase the original element
ar.erase(i);


问:
Apache Pulsar on Windows
I'm very new to Pulsar. Looking at the documentation about how to install a Standalone Pulsar system, I see the following sentence :

"Currently, Pulsar is available for 64-bit macOS, Linux, and Windows. To use Pulsar, you need to install 64-bit JRE/JDK 8 or later versions."

So Windows is supported. I downloaded the Pulsar binaries and unzip it to some location on my workstation.

But the /bin folder does not contain any Windows batch/executable. Only Unix shell script a provided.

My question is how do we start a Stand alone Pulsar on Windows as obviously the command "bin/pulsar standalone" does not work on Windows systems.

Thanks

答:
You can run Pulsar on Docker or K8.   That is your best option for Windows.

you can try Windows with Linux subsystem.

I don't really recommend using the standalone Pulsar on Windows.

C# for Windows client is solid though.

Run a training environment free here https://www.academy.streamnative.io/

Title: Apache Pulsar on Windows


问:
adding class to current day with javascript
im making a calendar and i want to add a className to current day so i could highlight it but i got some troubles and i wanna please you for help</p>
```<code>function getCurrentDayClass() {
        return day.format("DD-MM-YY") === dayjs().format("DD-MM-YY")
        //   document.getElementById().className += "current-day"
    }
</code>```
```<code><header>
                {rowIdx === 0 && (
                    <p>
                        {day.format('ddd').toUpperCase()}
                    </p>
                )}

                <p className="calendar-day">
                    {day.format("DD")}

                </p>

            </header>
</code>```

答:
This solve your problem</p>
```<code><p className=`${getCurrentDayClass() ? 'current-day-class' : ''}`
</code>```

Body:
im making a calendar and i want to add a className to current day so i could highlight it but i got some troubles and i wanna please you for help

function getCurrentDayClass() {
        return day.format("DD-MM-YY") === dayjs().format("DD-MM-YY")
        //   document.getElementById().className += "current-day"
    }

                {rowIdx === 0 && (

                        {day.format('ddd').toUpperCase()}

                )}

                    {day.format("DD")}

Body:
This solve your problem

<p className=`${getCurrentDayClass() ? 'current-day-class' : ''}`


问:
Regex to match Hebrew and English characters except numbers
I have a question:
I want to do a validation for the first and the last name with RegEx.
I want to do it with only Hebrew and English without numbers.
Someone can help me to do that code?</p>

答: You can also use \p{Hebrew} in your regex to detect any Hebrew unicode characters (if you're regex engine supports it).

ContentLicense: CC BY-SA 3.0


问:
AWS EC2 Local Storage Volumes/nvme volume
I am using "m5d.8xlarge" ec2 instance, which comes ready with 2*600G SSD Volumes, directly attached. They are appearing on the OS, however no mention on the console, as I can't retrieve any info about them.

And it is showing as well the serial of the volumes as AWS-*** not as normal EBS volumes vol***.

I read that these are ephemeral or something; I want to have any AWS official docs that thoroughly explain how this local storage works, as we are hosting prod workload on it, appreciate if someone can explain or provide docs.

答:
"m5d.8xlarge" ec2 instances comes with 2 ephimeral storage which are instance store volume.

Instance store volumes (docs) are directly attached to underlying hardware to reduce latency and increase IOPS and data throughput.

However there is a caveat, if you ec2 instance is terminated,stops, hibernated or stopped or underlying hardware gets shutdown due to some glitch all the data stored on on these ephemeral storage will be lost.
Generally instance store volumes are used for buffer,cache.

In order to confirm you can follow this  https://aws.amazon.com/premiumsupport/knowledge-center/ec2-linux-instance-store-volumes/ :-

ssh into ec2 instance

install nvme-cli tool -> sudo yum instal nvme-cli

sudo nvme list - to list all instance store volumes

if you want data to persist you should go for EBS or EFS

EBS docs, EFS docs

In short If you want to access data with super low latency and you can afford to loose data go for instance store but if it is business critical data for example database workload go for EBS, YOu can still achieve very high IOPS and throughput using IO1,IO2 volume types or if you have a want to go even further use nitro ec2 instance type which gives maximum 64000 IOPS.

Play with EBS volume types to increase IOPS and throughput https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volume-types.html


问:
Vue js 3 - Property 'projects' does not exist on type 'CreateComponentPublicInstance<{}, {}, {}, {}, {},

Issue:

```<code>Property 'projects' does not exist on type 'CreateComponentPublicInstance<{}, {}, {}, {}, {}, ComponentOptionsMixin, ComponentOptionsMixin, EmitsOptions, {}, {}, false, OptionTypesType<{}, ... 4 more ..., {}>, ... 5 more ..., {}>'
</code>```

For some reason it's screaming on computed, You can see my this.project or this.message.

I have no idea how to fix it, please help.
package.json

```<code> "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^4.18.0",
    "@typescript-eslint/parser": "^4.18.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-plugin-router": "~4.5.0",
    "@vue/cli-plugin-typescript": "~4.5.0",
    "@vue/cli-plugin-vuex": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "@vue/compiler-sfc": "^3.0.0",
    "@vue/eslint-config-prettier": "^6.0.0",
    "@vue/eslint-config-typescript": "^7.0.0",
    "eslint": "^6.7.2",
    "eslint-plugin-prettier": "^3.3.1",
    "eslint-plugin-vue": "^7.0.0",
    "cross-env": "^7.0.3",
    "css-loader": "^5.2.6",
    "fork-ts-checker-webpack-plugin": "^6.2.10",
    "less": "^3.0.4",
    "less-loader": "^5.0.0",
    "sass-loader": "10.1.1",
    "terser-webpack-plugin": "^4.2.3",
    "prettier": "^2.2.1",
    "typescript": "~4.1.5"
  }
</code>```

The issue is coming from when i add to shims-vue.d.ts:

```<code>import { ComponentCustomProperties } from 'vue'
import { Store } from 'vuex'

declare module '@vue/runtime-core' {
  // declare your own store states
  interface State {
    count: number
  }

  // provide typings for `this.$store`
  interface ComponentCustomProperties {
    $store: Store<State>
  }
}
</code>```

Then it showing my error.
If i remove the store declaration, it's screaming on the store but not on the computed.

答:
I lost a lot of time with this error, in my case also related to the ''data'' attributes of vue. First I had some problem with node modules, after uninstalling global, local and reinstalling packages, I noticed that blank projects (created by vue-cli) now worked, only my main project kept reporting this error.

The problem with my project now was that only the components registered globally were not correctly recognized by either vetur or volar, so I kept getting this thread's error only on them.

I ended up discovering a solution by accident, I'll keep it until I find out what's really going on. Typescript only stops returning this error when I declare "data" like this:

```<code>data: () => {
</code>```

Other variations, like this one, don't work

```<code>    //data() { also not works
    data: function () {
        return {
            comida: 1,
        }
    },
    methods: {
        setupVisitsCategoryCard() {
            this.comida = 2 //Property 'comida' does not exist on type 'CreateComponentPublicInstance<...'
        }
    }
    ```
```

Body:
Issue:

Property 'projects' does not exist on type 'CreateComponentPublicInstance<{}, {}, {}, {}, {}, ComponentOptionsMixin, ComponentOptionsMixin, EmitsOptions, {}, {}, false, OptionTypesType<{}, ... 4 more ..., {}>, ... 5 more ..., {}>'

For some reason it's screaming on computed, You can see my this.project or this.message.

I have no idea how to fix it, please help.
package.json

 "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^4.18.0",
    "@typescript-eslint/parser": "^4.18.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-plugin-router": "~4.5.0",
    "@vue/cli-plugin-typescript": "~4.5.0",
    "@vue/cli-plugin-vuex": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "@vue/compiler-sfc": "^3.0.0",
    "@vue/eslint-config-prettier": "^6.0.0",
    "@vue/eslint-config-typescript": "^7.0.0",
    "eslint": "^6.7.2",
    "eslint-plugin-prettier": "^3.3.1",
    "eslint-plugin-vue": "^7.0.0",
    "cross-env": "^7.0.3",
    "css-loader": "^5.2.6",
    "fork-ts-checker-webpack-plugin": "^6.2.10",
    "less": "^3.0.4",
    "less-loader": "^5.0.0",
    "sass-loader": "10.1.1",
    "terser-webpack-plugin": "^4.2.3",
    "prettier": "^2.2.1",
    "typescript": "~4.1.5"
  }

The issue is coming from when i add to shims-vue.d.ts:

import { ComponentCustomProperties } from 'vue'
import { Store } from 'vuex'

declare module '@vue/runtime-core' {
  // declare your own store states
  interface State {
    count: number
  }

  // provide typings for `this.$store`
  interface ComponentCustomProperties {
    $store: Store<State>
  }
}

Then it showing my error.
If i remove the store declaration, it's screaming on the store but not on the computed.

Body:
I lost a lot of time with this error, in my case also related to the ''data'' attributes of vue. First I had some problem with node modules, after uninstalling global, local and reinstalling packages, I noticed that blank projects (created by vue-cli) now worked, only my main project kept reporting this error.

The problem with my project now was that only the components registered globally were not correctly recognized by either vetur or volar, so I kept getting this thread's error only on them.

I ended up discovering a solution by accident, I'll keep it until I find out what's really going on. Typescript only stops returning this error when I declare "data" like this:

data: () => {

Other variations, like this one, don't work

    //data() { also not works
    data: function () {
        return {
            comida: 1,
        }
    },
    methods: {
        setupVisitsCategoryCard() {
            this.comida = 2 //Property 'comida' does not exist on type 'CreateComponentPublicInstance<...'
        }
    }
    ```


问:
How to assign the shared_ptr object to the function of type raw pointer using C++
I am creating the shared_ptr in a function and returning raw pointer from that function.
To get the underlying raw pointer from the shared_ptr I am using .get()

If i am using the raw pointer in a function and assigning to the function of type raw pointer it is working without any issue.
But if i create the shared_ptr and while returning, it is calling the destructor and deleting the memory assigned to the object and crashing.

How to assign the shared_ptr object to the function of type raw pointer?

```<code>CMyClass::CMyClass()
{
}

CMyClass::~CMyClass()
{
}

CMyClass* CreateClassInstance()
{
std::shared_ptr<CMyClass> l_MyClassInterface = std::make_shared<CMyClass>();
return l_MyClassInterface.get();
}

CMyClass* CreateClassInstance()
{
CMyClass* l_MyClassInterface = new CMyClass();
return l_MyClassInterface;
}

auto l_pMyClassInterface = CreateClassInstance();
</code>```

答:
Yes, what @user17732522 said.

In the code as written, l_MyClassInterface is going out of scope when your first version of CreateClassInstance returns, taking your newly created object with it.  When you return a shared_ptr, as opposed to the pointer returned by get(), the mechanism that it uses to keep track of the reference count for your object kicks in and stops that from happening. (Well, in principle.  In practise, copy elision usually / always ensures that the shared_ptr created by make_shared is returned directly to the caller, but that's a detail.)

The other (inferior) solution would be to return the pointer returned by new directly and assign it to a shared_ptr in the caller.  But that is error-prone, and not recommended.

Body:
I am creating the shared_ptr in a function and returning raw pointer from that function.
To get the underlying raw pointer from the shared_ptr I am using .get()

If i am using the raw pointer in a function and assigning to the function of type raw pointer it is working without any issue.
But if i create the shared_ptr and while returning, it is calling the destructor and deleting the memory assigned to the object and crashing.

How to assign the shared_ptr object to the function of type raw pointer?

CMyClass::CMyClass()
{
}

CMyClass::~CMyClass()
{
}

CMyClass* CreateClassInstance()
{
std::shared_ptr<CMyClass> l_MyClassInterface = std::make_shared<CMyClass>();
return l_MyClassInterface.get();
}

CMyClass* CreateClassInstance()
{
CMyClass* l_MyClassInterface = new CMyClass();
return l_MyClassInterface;
}

auto l_pMyClassInterface = CreateClassInstance();


问:
PSQL throwing error: relation "serial" does not exist, when creating a table
It happens when i run this code:

```<code>CREATE TABLE distributors (
 did    integer PRIMARY KEY DEFAULT nextval('serial'),
 name   varchar(40) NOT NULL CHECK (name <> '')
);
</code>```

I have tried remover the nextval('serial') but to no avail

答:
nextval('someseries') relies on having an existing series. You can create that with:

```<code>CREATE SEQUENCE someseries;
</code>```

When you removed the nextval, you probably still had the DEFAULT keyword there, which expects a value afterward to define what the default for the column is.

Body:
It happens when i run this code:

CREATE TABLE distributors (
 did    integer PRIMARY KEY DEFAULT nextval('serial'),
 name   varchar(40) NOT NULL CHECK (name <> '')
);

I have tried remover the nextval('serial') but to no avail

Body:
nextval('someseries') relies on having an existing series. You can create that with:

CREATE SEQUENCE someseries;

When you removed the nextval, you probably still had the DEFAULT keyword there, which expects a value afterward to define what the default for the column is.


问:
How to modify items based on selected items on vuetify data table
Lets the items are:

```<code>desserts: [
     {
       name: 'Frozen Yogurt',
       calories: 159,
       fat: 6.0,
       carbs: 24,
       protein: 4.0,
       iron: '1%'
    },
    {
       name: 'Ice cream sandwich',
       calories: 237,
       fat: 9.0,
       carbs: 37,
       protein: 4.3,
       iron: '1%'
    },
    {
      name: 'Eclair',
      calories: 262,
      fat: 16.0,
      carbs: 23,
      protein: 6.0,
      iron: '7%'
    }
]
</code>```

I want to add additional property with all objects such as isActive: true or isActive: false based on the selection. So, if user select Frozen Yogurt & Ice cream sandwich columns and click on a custom button, Add Selected button, I should get the array of the objects like this way:

```<code>desserts: [
         {
           name: 'Frozen Yogurt',
           calories: 159,
           fat: 6.0,
           carbs: 24,
           protein: 4.0,
           iron: '1%',
           isActive: true
        },
        {
           name: 'Ice cream sandwich',
           calories: 237,
           fat: 9.0,
           carbs: 37,
           protein: 4.3,
           iron: '1%',
           isActive: true
        },
        {
          name: 'Eclair',
          calories: 262,
          fat: 16.0,
          carbs: 23,
          protein: 6.0,
          iron: '7%',
          isActive: false
        }
    ]
</code>```

Are there any vuetify way to do this? Or should we do this with pure javascript in the custom function bind with the click event:

```<code><v-btn
   @click="sendData"
  >
    Add Selected
</v-btn>
</code>```

How to do this efficiently?

.... UPDATE: .......

I think I have achieved the desired output at console.log(submittedData). but I think my sendData function is a bit complicated now. Can you please help me to simplify it?

Codepen Demo

答:
Looping through desserts

spread each item with a new isActive property

assign Boolean return value from the .includes method to isActive

sendData() {

    let result = this.desserts.map((item) => ({ ...item, isActive: this.selected.includes(item) }));
    console.log(result);

}
```

Code Pen Demo

Body:
Lets the items are:

desserts: [
     {
       name: 'Frozen Yogurt',
       calories: 159,
       fat: 6.0,
       carbs: 24,
       protein: 4.0,
       iron: '1%'
    },
    {
       name: 'Ice cream sandwich',
       calories: 237,
       fat: 9.0,
       carbs: 37,
       protein: 4.3,
       iron: '1%'
    },
    {
      name: 'Eclair',
      calories: 262,
      fat: 16.0,
      carbs: 23,
      protein: 6.0,
      iron: '7%'
    }
]

I want to add additional property with all objects such as isActive: true or isActive: false based on the selection. So, if user select Frozen Yogurt & Ice cream sandwich columns and click on a custom button, Add Selected button, I should get the array of the objects like this way:

desserts: [
         {
           name: 'Frozen Yogurt',
           calories: 159,
           fat: 6.0,
           carbs: 24,
           protein: 4.0,
           iron: '1%',
           isActive: true
        },
        {
           name: 'Ice cream sandwich',
           calories: 237,
           fat: 9.0,
           carbs: 37,
           protein: 4.3,
           iron: '1%',
           isActive: true
        },
        {
          name: 'Eclair',
          calories: 262,
          fat: 16.0,
          carbs: 23,
          protein: 6.0,
          iron: '7%',
          isActive: false
        }
    ]

Are there any vuetify way to do this? Or should we do this with pure javascript in the custom function bind with the click event:

<v-btn
   @click="sendData"
  >
    Add Selected
</v-btn>

How to do this efficiently?

.... UPDATE: .......

I think I have achieved the desired output at console.log(submittedData). but I think my sendData function is a bit complicated now. Can you please help me to simplify it?

Codepen Demo

Body:
Looping through desserts

spread each item with a new isActive property

assign Boolean return value from the .includes method to isActive

sendData() {

    let result = this.desserts.map((item) => ({ ...item, isActive: this.selected.includes(item) }));
    console.log(result);

}

Code Pen Demo


问:
Send pdf instead of TextSnippet in goole automl enrity extraction
I have created a custom processor using google AutoML entity extractor and trained few pdfs. The Pdf's actually contains Photo identity card. I was able to test it in their UI and it was able to extract the entity properly. Now Im using their Java client library to do it using code given below. Here is the sample

https://github.com/googleapis/java-automl/blob/b4c760c01efbd2174d93af85c5fbab3c09eee9f2/samples/snippets/src/main/java/com/example/automl/LanguageEntityExtractionPredict.java

Here I see that they pass the text content into the library instead I want to send the PDF content. I don't want to use the google cloud storage bucket instead I want to load file locally and sent it to the entity extractor. I tried using the Document class as below

Document.parseDelimitedFrom(FileInputStream("test.pdf")) but it gives me an error.

Any help is highly appriciated.

答:
Document.parseDelimitedFrom(FileInputStream("test.pdf")) throws an error because the parseDelimitedFrom() method expects a protobuf message for parsing not the InputStream of the local PDF file. That being said, currently, there is no provision to send local files for prediction as seen in this REST API documentation. The DocumentInputConfig parameter supports only GCS source.

Feature Request

I have raised this requirement as a feature request in Google’s Issue Tracker. The issue can be found here- Issue #218865096. You can STAR the issue to receive automatic updates and give it traction by referring to this link. Also, please be reminded that there is no timeline nor implementation guarantee for feature requests. All communication regarding this feature request will be done on the Issue Tracker.


问:
How to ensure that the messages will be enqueued in chronological order on multithreaded Asio io_service?
Following Michael Caisse's cppcon talk I created a connection handler MyUserConnection which has a sendMessage method. sendMessage method adds a message to the queue similarly to the send() in the cppcon talk. My sendMessage method is called from multiple threads outside of the connection handler in high intervals. The messages must be enqueued chronologically.

When I run my code with only one Asio io_service::run call (aka one io_service thread) it async_write's and empties my queue as expected (FIFO), however, the problem occurs when there are, for example, 4 io_service::run calls, then the queue is not filled or the send calls are not called chronologically.

class MyUserConnection : public std::enable_shared_from_this<MyUserConnection> {
public:
  MyUserConnection(asio::io_service& io_service, SslSocket socket) :
      service_(io_service),
      socket_(std::move(socket)),
      strand_(io_service) {
  }

  void sendMessage(std::string msg) {
    auto self(shared_from_this());
    service_.post(strand_.wrap([self, msg]() {
      self->queueMessage(msg);
    }));
  }

private:
  void queueMessage(const std::string& msg) {
    bool writeInProgress = !sendPacketQueue_.empty();
    sendPacketQueue_.push_back(msg);
    if (!writeInProgress) {
      startPacketSend();
    }
  }

  void startPacketSend() {
    auto self(shared_from_this());
    asio::async_write(socket_,
                      asio::buffer(sendPacketQueue_.front().data(), sendPacketQueue_.front().length()),
                      strand_.wrap([self](const std::error_code& ec, std::size_t /*n*/) {
                        self->packetSendDone(ec);
                      }));
  }

  void packetSendDone(const std::error_code& ec) {
    if (!ec) {
      sendPacketQueue_.pop_front();
      if (!sendPacketQueue_.empty()) { startPacketSend(); }
    } else {
      // end(); // My end call
    }
  }

  asio::io_service& service_;
  SslSocket socket_;
  asio::io_service::strand strand_;
  std::deque<std::string> sendPacketQueue_;
};
```

I'm quite sure that I misinterpreted the strand and io_service::post when running the connection handler on multithreaded io_service. I'm also quite sure that the messages are not enqueued chronologically instead of messages not being async_write chronologically. How to ensure that the messages will be enqueued in chronological order in sendMessage call on multithreaded io_service?

答:
If you use a strand, the order is guaranteed to be the order in which you post the operations to the strand.

Of course, if there is some kind of "correct ordering" between threads that post then you have to synchronize the posting between them, that's your application domain.

Here's a modernized, simplified take on your MyUserConnection class with a self-contained server test program:

Live On Coliru

```<code>#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <deque>
#include <iostream>
#include <mutex>

namespace asio = boost::asio;
namespace ssl  = asio::ssl;
using asio::ip::tcp;
using boost::system::error_code;
using SslSocket = ssl::stream<tcp::socket>;

class MyUserConnection : public std::enable_shared_from_this<MyUserConnection> {
  public:
    MyUserConnection(SslSocket&& socket) : socket_(std::move(socket)) {}

    void start() {
        std::cerr << "Handshake initiated" << std::endl;
        socket_.async_handshake(ssl::stream_base::handshake_type::server,
                                [self = shared_from_this()](error_code ec) {
                                    std::cerr << "Handshake complete" << std::endl;
                                });
    }

    void sendMessage(std::string msg) {
        post(socket_.get_executor(),
             [self = shared_from_this(), msg = std::move(msg)]() {
                 self->queueMessage(msg);
             });
    }

  private:
    void queueMessage(std::string msg) {
        outbox_.push_back(std::move(msg));
        if (outbox_.size() == 1)
            sendLoop();
    }

    void sendLoop() {
        std::cerr << "Sendloop " << outbox_.size() << std::endl;
        if (outbox_.empty())
            return;

        asio::async_write( //
            socket_, asio::buffer(outbox_.front()),
            [this, self = shared_from_this()](error_code ec, std::size_t) {
                if (!ec) {
                    outbox_.pop_front();
                    sendLoop();
                } else {
                    end();
                }
            });
    }

    void end() {}

    SslSocket                socket_;
    std::deque<std::string>  outbox_;
};

int main() {
    asio::thread_pool ioc;
    ssl::context      ctx(ssl::context::sslv23_server);
    ctx.set_password_callback([](auto...) { return "test"; });
    ctx.use_certificate_file("server.pem", ssl::context::file_format::pem);
    ctx.use_private_key_file("server.pem", ssl::context::file_format::pem);
    ctx.use_tmp_dh_file("dh2048.pem");

    tcp::acceptor a(ioc, {{}, 8989u});

    for (;;) {
        auto s = a.accept(make_strand(ioc.get_executor()));
        std::cerr << "accepted " << s.remote_endpoint() << std::endl;
        auto sess = make_shared<MyUserConnection>(SslSocket(std::move(s), ctx));
        sess->start();
        for(int i = 0; i<30; ++i) {
            post(ioc, [sess, i] {
                std::string msg = "message #" + std::to_string(i) + "\n";
                {
                    static std::mutex mx;
                    // Lock so console output is guaranteed in the same order
                    // as the sendMessage call
                    std::lock_guard lk(mx);
                    std::cout << "Sending " << msg << std::flush;
                    sess->sendMessage(std::move(msg));
                }
            });
        }

        break; // for online demo
    }

    ioc.join();
}
</code>```

If you run it a few times, you will see that

the order in which the threads post is not deterministic (that's up to the kernel scheduling)

the order in which messages are sent (and received) is exactly the order in which they are posted.

See live demo runs on my machine:

Body:
Following Michael Caisse's cppcon talk I created a connection handler MyUserConnection which has a sendMessage method. sendMessage method adds a message to the queue similarly to the send() in the cppcon talk. My sendMessage method is called from multiple threads outside of the connection handler in high intervals. The messages must be enqueued chronologically.

When I run my code with only one Asio io_service::run call (aka one io_service thread) it async_write's and empties my queue as expected (FIFO), however, the problem occurs when there are, for example, 4 io_service::run calls, then the queue is not filled or the send calls are not called chronologically.

class MyUserConnection : public std::enable_shared_from_this<MyUserConnection> {
public:
  MyUserConnection(asio::io_service& io_service, SslSocket socket) :
      service_(io_service),
      socket_(std::move(socket)),
      strand_(io_service) {
  }

  void sendMessage(std::string msg) {
    auto self(shared_from_this());
    service_.post(strand_.wrap([self, msg]() {
      self->queueMessage(msg);
    }));
  }

private:
  void queueMessage(const std::string& msg) {
    bool writeInProgress = !sendPacketQueue_.empty();
    sendPacketQueue_.push_back(msg);
    if (!writeInProgress) {
      startPacketSend();
    }
  }

  void startPacketSend() {
    auto self(shared_from_this());
    asio::async_write(socket_,
                      asio::buffer(sendPacketQueue_.front().data(), sendPacketQueue_.front().length()),
                      strand_.wrap([self](const std::error_code& ec, std::size_t /*n*/) {
                        self->packetSendDone(ec);
                      }));
  }

  void packetSendDone(const std::error_code& ec) {
    if (!ec) {
      sendPacketQueue_.pop_front();
      if (!sendPacketQueue_.empty()) { startPacketSend(); }
    } else {
      // end(); // My end call
    }
  }

  asio::io_service& service_;
  SslSocket socket_;
  asio::io_service::strand strand_;
  std::deque<std::string> sendPacketQueue_;
};

I'm quite sure that I misinterpreted the strand and io_service::post when running the connection handler on multithreaded io_service. I'm also quite sure that the messages are not enqueued chronologically instead of messages not being async_write chronologically. How to ensure that the messages will be enqueued in chronological order in sendMessage call on multithreaded io_service?

Body:
If you use a strand, the order is guaranteed to be the order in which you post the operations to the strand.

Of course, if there is some kind of "correct ordering" between threads that post then you have to synchronize the posting between them, that's your application domain.

Here's a modernized, simplified take on your MyUserConnection class with a self-contained server test program:

Live On Coliru

#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <deque>
#include <iostream>
#include <mutex>

namespace asio = boost::asio;
namespace ssl  = asio::ssl;
using asio::ip::tcp;
using boost::system::error_code;
using SslSocket = ssl::stream<tcp::socket>;

class MyUserConnection : public std::enable_shared_from_this<MyUserConnection> {
  public:
    MyUserConnection(SslSocket&& socket) : socket_(std::move(socket)) {}

    void start() {
        std::cerr << "Handshake initiated" << std::endl;
        socket_.async_handshake(ssl::stream_base::handshake_type::server,
                                [self = shared_from_this()](error_code ec) {
                                    std::cerr << "Handshake complete" << std::endl;
                                });
    }

    void sendMessage(std::string msg) {
        post(socket_.get_executor(),
             [self = shared_from_this(), msg = std::move(msg)]() {
                 self->queueMessage(msg);
             });
    }

  private:
    void queueMessage(std::string msg) {
        outbox_.push_back(std::move(msg));
        if (outbox_.size() == 1)
            sendLoop();
    }

    void sendLoop() {
        std::cerr << "Sendloop " << outbox_.size() << std::endl;
        if (outbox_.empty())
            return;

        asio::async_write( //
            socket_, asio::buffer(outbox_.front()),
            [this, self = shared_from_this()](error_code ec, std::size_t) {
                if (!ec) {
                    outbox_.pop_front();
                    sendLoop();
                } else {
                    end();
                }
            });
    }

    void end() {}

    SslSocket                socket_;
    std::deque<std::string>  outbox_;
};

int main() {
    asio::thread_pool ioc;
    ssl::context      ctx(ssl::context::sslv23_server);
    ctx.set_password_callback([](auto...) { return "test"; });
    ctx.use_certificate_file("server.pem", ssl::context::file_format::pem);
    ctx.use_private_key_file("server.pem", ssl::context::file_format::pem);
    ctx.use_tmp_dh_file("dh2048.pem");

    tcp::acceptor a(ioc, {{}, 8989u});

    for (;;) {
        auto s = a.accept(make_strand(ioc.get_executor()));
        std::cerr << "accepted " << s.remote_endpoint() << std::endl;
        auto sess = make_shared<MyUserConnection>(SslSocket(std::move(s), ctx));
        sess->start();
        for(int i = 0; i<30; ++i) {
            post(ioc, [sess, i] {
                std::string msg = "message #" + std::to_string(i) + "\n";
                {
                    static std::mutex mx;
                    // Lock so console output is guaranteed in the same order
                    // as the sendMessage call
                    std::lock_guard lk(mx);
                    std::cout << "Sending " << msg << std::flush;
                    sess->sendMessage(std::move(msg));
                }
            });
        }

        break; // for online demo
    }

    ioc.join();
}

If you run it a few times, you will see that

the order in which the threads post is not deterministic (that's up to the kernel scheduling)

the order in which messages are sent (and received) is exactly the order in which they are posted.

See live demo runs on my machine:


问:
Any free XLSX ( Excel 2007 or above) reader and writer Helper Class or Library
Now I am in need of a Excel Library.
Any free XLSX ( Excel 2007 or above) reader and writer Helper Class or Library</p>

答: Check out the OpenXML SDK.  There are also a number of questions on SO that relate to using the OpenXML SDK, so this site is a great resource as well.</p>


问:
preg_match unconditionally return key for unmatched optional capture group
```<code>$pattern = "/^(?<animal>DOG|CAT)?(?<color>BLUE|RED)?$/i";
$str = "DOG";

preg_match($pattern, $str, $matches);
$matches = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);

// $str = "dog" returns [animal] => DOG

//$str = "dogBLUE" returns [animal] => dog and [color] => BLUE
print_r($matches);
</code>```

I have an example http://sandbox.onlinephpfunctions.com/code/2428bc68adcf9929557d86dc1ae72552c3681b58 too

Both named capture groups are optional and so keys will only be returned if a match is found.

My Question

How can I unconditionally return keys for any of my possible named capture groups? Empty String '' would be great if it group ain't found.

Input of "DOG" resulting in [animal] => 'DOG', [color] => '' is what I'm looking for.

I was hoping for a flag on preg_match to do this, but couldn't find anything.

Update: I just want to avoid doing isset($matches[OPTIONAL_GROUP])

Thanks!

答:
You can use andre at koethur dot de's solution:

$pattern = "/^(?<animal>DOG|CAT)?(?<color>BLUE|RED)?$/i";
$str = "DOG";

if (preg_match($pattern, $str, $matches)) {
  $matches = array_merge(array('animal' => '', 'color' => ''), $matches);
  $matches = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
  print_r($matches);
}
```
<p>See the PHP demo.
Output:</p>
<pre class="lang-none prettyprint-override"><code>Array
(
    [animal] => DOG
    [color] =>
)
</code>```

The idea is that you need to "assign a name to all subpatterns you are interested in, and merge $matches afterwards with an constant array containing some reasonable default values".

Body:
$pattern = "/^(?<animal>DOG|CAT)?(?<color>BLUE|RED)?$/i";
$str = "DOG";

preg_match($pattern, $str, $matches);
$matches = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);

// $str = "dog" returns [animal] => DOG

//$str = "dogBLUE" returns [animal] => dog and [color] => BLUE
print_r($matches);

I have an example http://sandbox.onlinephpfunctions.com/code/2428bc68adcf9929557d86dc1ae72552c3681b58 too

Both named capture groups are optional and so keys will only be returned if a match is found.

My Question

How can I unconditionally return keys for any of my possible named capture groups? Empty String '' would be great if it group ain't found.

Input of "DOG" resulting in [animal] => 'DOG', [color] => '' is what I'm looking for.

I was hoping for a flag on preg_match to do this, but couldn't find anything.

Update: I just want to avoid doing isset($matches[OPTIONAL_GROUP])

Thanks!

Body:
You can use andre at koethur dot de's solution:

$pattern = "/^(?<animal>DOG|CAT)?(?<color>BLUE|RED)?$/i";
$str = "DOG";

if (preg_match($pattern, $str, $matches)) {
  $matches = array_merge(array('animal' => '', 'color' => ''), $matches);
  $matches = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
  print_r($matches);
}

See the PHP demo.
Output:

Array
(
    [animal] => DOG
    [color] =>
)

The idea is that you need to "assign a name to all subpatterns you are interested in, and merge $matches afterwards with an constant array containing some reasonable default values".


问:
A line in a self define function not working in pandas
I try and defined a function to process a df (like adding columns and convert all cols head to lower case) before doing the analysis. All other line works fine except the line that I tried to rearrange the columns orders.

the function looks like this

```<code>def cleanDf(df):
    df.columns = df.columns.str.replace(' ','_')
    df.columns = df.columns.str.lower()
    df['date1'] = pd.to_datetime(df['date'].astype(str) + ' ' + df['time'].astype(str))
    df['weekday'] =  df['date1'].dt.day_name()

    business_hour_mask = (df['date1'].dt.hour >=9) & (df['date1'].dt.hour <=18)
    df['business_hour'] = np.where(business_hour_mask, "Yes","No")
    df['week_number'] = df.date1.dt.week

    df = df.reindex(['date1','week_number','weekday','business_hour','changed_by','customer','field_name','new_value','old_value','new_value.1','old_value.1','date','time','company_code','sales_organization','distribution_channel','division'], axis=1)
    #problem line, i've tried both with and without "df = " in front of this line

    return df
</code>```

my current workaround is to insert that line after i call the function then it works

```<code>cleanDf(df)

df = df.reindex(['date1','week_number','weekday','business_hour','changed_by','customer','field_name','new_value','old_value','new_value.1','old_value.1','date','time','company_code','sales_organization','distribution_channel','division'], axis=1)

df.head()
</code>```

Appreciate if you can advise why the line does not inside the function, but ok when executed separately.

thank you very much

答:
It's because you're reassigning the df variable inside the function, where it's just a parameter. Since you're returing df though, it's simple. Just write df = cleanDf(df) instead of just cleanDf(df):

```<code>df = cleanDf(df)
df.head()
</code>```

Per @mozway's comment, you should also define your cleanDf function like so:

```<code>def cleanDf(df):
    df = df.copy()
    # ... do your stuff ...
    return df
</code>```

Body:
I try and defined a function to process a df (like adding columns and convert all cols head to lower case) before doing the analysis. All other line works fine except the line that I tried to rearrange the columns orders.

the function looks like this

def cleanDf(df):
    df.columns = df.columns.str.replace(' ','_')
    df.columns = df.columns.str.lower()
    df['date1'] = pd.to_datetime(df['date'].astype(str) + ' ' + df['time'].astype(str))
    df['weekday'] =  df['date1'].dt.day_name()

    business_hour_mask = (df['date1'].dt.hour >=9) & (df['date1'].dt.hour <=18)
    df['business_hour'] = np.where(business_hour_mask, "Yes","No")
    df['week_number'] = df.date1.dt.week

    df = df.reindex(['date1','week_number','weekday','business_hour','changed_by','customer','field_name','new_value','old_value','new_value.1','old_value.1','date','time','company_code','sales_organization','distribution_channel','division'], axis=1)
    #problem line, i've tried both with and without "df = " in front of this line

    return df

my current workaround is to insert that line after i call the function then it works

cleanDf(df)

df = df.reindex(['date1','week_number','weekday','business_hour','changed_by','customer','field_name','new_value','old_value','new_value.1','old_value.1','date','time','company_code','sales_organization','distribution_channel','division'], axis=1)

df.head()

Appreciate if you can advise why the line does not inside the function, but ok when executed separately.

thank you very much

Body:
It's because you're reassigning the df variable inside the function, where it's just a parameter. Since you're returing df though, it's simple. Just write df = cleanDf(df) instead of just cleanDf(df):

df = cleanDf(df)
df.head()

Per @mozway's comment, you should also define your cleanDf function like so:

def cleanDf(df):
    df = df.copy()
    # ... do your stuff ...
    return df


问:
Trying to re-create HMAC using SHA1 in PHP
I have the following decrypted message, which has previously been encrypted using AES-256-CBC

```<code>240dcbefc0f82fadc00ef8494488aaa81400000c2def01e79fec6c4d9a822358dd8a910cac606e8afcb607793cb442093a56b7b40b0b0b0b0b0b0b0b0b0b0b0b
</code>```

I derive the following 20 BYTE HMAC from this message:

```<code>dd8a910cac606e8afcb607793cb442093a56b7b4
</code>```

My goal is to re-create this HMAC using PHP, I attempt with the following code:

```<code>$iv = hex2bin('240dcbefc0f82fadc00ef8494488aaa8'); // random iv - first 16 bytes of the message
$message = hex2bin('1400000c2def01e79fec6c4d9a822358'); // the actual message being decrypted - next 16 bytes
$key = hex2bin('b109124b62e2c8b8248e9865990325fddcc61143'); // encryption key

$hmac = hash_hmac('sha1', $iv.$message, $key);
print($hmac); // 03634ba3f4a0c854a0b791d27f331ecdfad1e87e

$attempt2 = hash('sha256', $iv.$message, true);
$hmac = hash_hmac('sha1', $attempt2, $key);
print($hmac); // 39ad1fb94ab251cdaf3f21cf8673e070733f4e16
</code>```

I know I'm missing something but I'm struggling to understand the HMAC process as it's very confusing to me.  Any help or advise is appreciated, thanks.

答:
I found a solution on a random blog post online :D

here is what worked for me:

```<code>function check_mac($seq, $type, $msg, $key) {
    $SequenceNumber = pack("NN", 0, $seq);
    $Type = pack("Cnn", $type, 0x0303, strlen($msg));
    $data = $SequenceNumber . $Type . $msg;
    $calculated_mac = hash_hmac("sha1", $data, $key, true);
    print(bin2hex($calculated_mac) . "\n");
}
</code>```

Also, the IV does not need to be included, just the message by itself as the $msg variable

Blog Post:
https://adayinthelifeof.nl/2013/12/30/decoding-tls-with-php/

Body:
I have the following decrypted message, which has previously been encrypted using AES-256-CBC

240dcbefc0f82fadc00ef8494488aaa81400000c2def01e79fec6c4d9a822358dd8a910cac606e8afcb607793cb442093a56b7b40b0b0b0b0b0b0b0b0b0b0b0b

I derive the following 20 BYTE HMAC from this message:

dd8a910cac606e8afcb607793cb442093a56b7b4

My goal is to re-create this HMAC using PHP, I attempt with the following code:

$iv = hex2bin('240dcbefc0f82fadc00ef8494488aaa8'); // random iv - first 16 bytes of the message
$message = hex2bin('1400000c2def01e79fec6c4d9a822358'); // the actual message being decrypted - next 16 bytes
$key = hex2bin('b109124b62e2c8b8248e9865990325fddcc61143'); // encryption key

$hmac = hash_hmac('sha1', $iv.$message, $key);
print($hmac); // 03634ba3f4a0c854a0b791d27f331ecdfad1e87e

$attempt2 = hash('sha256', $iv.$message, true);
$hmac = hash_hmac('sha1', $attempt2, $key);
print($hmac); // 39ad1fb94ab251cdaf3f21cf8673e070733f4e16

I know I'm missing something but I'm struggling to understand the HMAC process as it's very confusing to me.  Any help or advise is appreciated, thanks.

Body:
I found a solution on a random blog post online :D

here is what worked for me:

function check_mac($seq, $type, $msg, $key) {
    $SequenceNumber = pack("NN", 0, $seq);
    $Type = pack("Cnn", $type, 0x0303, strlen($msg));
    $data = $SequenceNumber . $Type . $msg;
    $calculated_mac = hash_hmac("sha1", $data, $key, true);
    print(bin2hex($calculated_mac) . "\n");
}

Also, the IV does not need to be included, just the message by itself as the $msg variable

Blog Post:
https://adayinthelifeof.nl/2013/12/30/decoding-tls-with-php/


问:
Extension Methods - Changing the Namespace
I'm using a third party library which contains a bunch of extension methods on top of IQueryable. To use these extension methods i don't wish to have my application littered with using statements to the third party namespace in which the extension method resides in.

This is so that i can switch it out the library sometime in the near future as easily as possible. However i'm not sure what's the best way of doing this. One option i did contemplate was to create my own set of extension methods within the project (then i can control the namespace). The problem with this is i can't see how i can maintain the name of the existing extension method. For example:

```<code>namespace MyProject.Extensions {
    public static class IQueryableExtension {
        public static IQueryable<T> Fetch<T, K>(this IQueryable<T> queryable, Expression<Func<T, K>> selector) {
            return queryable.Fetch(selector);
        }
    }
}
</code>```

You may see the problem here. Where i am trying to call the third party extension method within mine it actually calls itself creating an infinite loop.

I'd appreciate the help. Thanks

答:
To solve the problem with the name, you could easily invoke the extension method as the static method it really is:

```<code>return Third.Party.Namespace.Fetch(queryable, selector);
</code>```

Having said that, I don't understand your motivation. Why don't you just want to use the third party namespace? What is your problem with using directive at the beginning of the file that needs this extension method? You will have numerous using directives anyway. If this list is too long for you for some reason, simply wrap it in a region and collapse that region:

```<code>#region

using Namespace1;
using Namespace2;
using Namespace3;

#endregion
</code>```

Body:
I'm using a third party library which contains a bunch of extension methods on top of IQueryable. To use these extension methods i don't wish to have my application littered with using statements to the third party namespace in which the extension method resides in.

This is so that i can switch it out the library sometime in the near future as easily as possible. However i'm not sure what's the best way of doing this. One option i did contemplate was to create my own set of extension methods within the project (then i can control the namespace). The problem with this is i can't see how i can maintain the name of the existing extension method. For example:

namespace MyProject.Extensions {
    public static class IQueryableExtension {
        public static IQueryable<T> Fetch<T, K>(this IQueryable<T> queryable, Expression<Func<T, K>> selector) {
            return queryable.Fetch(selector);
        }
    }
}

You may see the problem here. Where i am trying to call the third party extension method within mine it actually calls itself creating an infinite loop.

I'd appreciate the help. Thanks

Body:
To solve the problem with the name, you could easily invoke the extension method as the static method it really is:

return Third.Party.Namespace.Fetch(queryable, selector);

Having said that, I don't understand your motivation. Why don't you just want to use the third party namespace? What is your problem with using directive at the beginning of the file that needs this extension method? You will have numerous using directives anyway. If this list is too long for you for some reason, simply wrap it in a region and collapse that region:

#region

using Namespace1;
using Namespace2;
using Namespace3;

#endregion


问:
What is causing __builder does not exist in current context error from compiler?
"Error  CS0103  The name '__builder' does not exist in the current context"

Here is my code that causes the error:

@code {
    public void Calc()
    {
        for (int i = 0; i < 55; )
        {

This is the number"  @i

        }
    }
}
```

答:
The correct answer is at this SO link.

In short you cannot mix markup with C# code inside @code block.

Consider make a component for reusing the markup.


答:
When you push class with id in reactJS

```<code>   document.getElementById(id).classList.add("active")
</code>```

When you push class with class in reactJS

```<code>    document.getElementsByClassName("example").classList.add("active")

</code>```

Title: adding class to current day with javascript

Body:
im making a calendar and i want to add a className to current day so i could highlight it but i got some troubles and i wanna please you for help

function getCurrentDayClass() {
        return day.format("DD-MM-YY") === dayjs().format("DD-MM-YY")
        //   document.getElementById().className += "current-day"
    }

                {rowIdx === 0 && (

                        {day.format('ddd').toUpperCase()}

                )}

                    {day.format("DD")}

Body:
When you push class with id in reactJS

   document.getElementById(id).classList.add("active")

When you push class with class in reactJS

    document.getElementsByClassName("example").classList.add("active")


问:
Exclude from file one the lines in common with file two and preserve line order
one

```<code>pl
a
ff
c
b
nn
</code>```

two

```<code>b
a
z
k
c
d
</code>```

I want to remove from the first file all lines that are also in the second (common lines). And I want to maintain the file_one lines order.

It's possible to work in a line by line check mode, something like:

```<code>while read line; do
  if ! grep $line two; then
    echo $line >> one_only
  fi
done < one
</code>```

But it likely isn't the best option for a fast check.
An other way would be using "comm" command on the files previously sorted:

```<code>comm -1 -2 <(sort one) <(sort two) \
  | tr '\n' '\|' \
  | sed 's/|/\\|/g;s/\\|$/\n/' \
  > common_lines

grep -v "$(cat common_lines)" one
</code>```

first command creates a "logical OR pattern":

```<code>a\|b\|c
</code>```

which can be reuse with grep to exclude common lines from the "one" file. In this way the original order of "one" lines is preserved. And the result will be:

```<code>pl
ff
nn
</code>```

Can you suggest any other idea to minimize compute time even more?

Real input files are much more populated and contain short names (software names):

```<code>blender
gimp
vim
emacs
mozilla-firefox
google-earth
</code>```

and so on...

答:
Using the lines of two as patterns, with grep

grep -Fx -f two -v one
```

Body:
one

pl
a
ff
c
b
nn

two

b
a
z
k
c
d

I want to remove from the first file all lines that are also in the second (common lines). And I want to maintain the file_one lines order.

It's possible to work in a line by line check mode, something like:

while read line; do
  if ! grep $line two; then
    echo $line >> one_only
  fi
done < one

But it likely isn't the best option for a fast check.
An other way would be using "comm" command on the files previously sorted:

comm -1 -2 <(sort one) <(sort two) \
  | tr '\n' '\|' \
  | sed 's/|/\\|/g;s/\\|$/\n/' \
  > common_lines

grep -v "$(cat common_lines)" one

first command creates a "logical OR pattern":

a\|b\|c

which can be reuse with grep to exclude common lines from the "one" file. In this way the original order of "one" lines is preserved. And the result will be:

pl
ff
nn

Can you suggest any other idea to minimize compute time even more?

Real input files are much more populated and contain short names (software names):

blender
gimp
vim
emacs
mozilla-firefox
google-earth

and so on...


问:
How to set an XSLT boolean variable to true if an attribute is empty or doesn't exist?
When an attribute is missing or is empty, I want my variable set to false().

XML:

```<code><cd name="One" />
<cd name="Two" incollection=""/>
<cd name="Three" incollection="true"/>
</code>```

XSL:

```<code><!-- this will only set to false when attribute is missing -->
<xsl:variable name="incollection" select="boolean(@incollection)"/>
<!-- this will set to false both when attribute is missing or is empty-->
<xsl:variable name="incollection2" select="boolean(@incollection) or @incollection=''"/>
</code>```

Although the second expression works for me, I was wondering whether there was a better and more idiomatic way of writing this expression?

答:
Personally I would be inclined to try something like

select="count(@incollection != '') > 0

(untested)

Body:
When an attribute is missing or is empty, I want my variable set to false().

XML:

<cd name="One" />
<cd name="Two" incollection=""/>
<cd name="Three" incollection="true"/>

XSL:

<xsl:variable name="incollection" select="boolean(@incollection)"/>

<xsl:variable name="incollection2" select="boolean(@incollection) or @incollection=''"/>

Although the second expression works for me, I was wondering whether there was a better and more idiomatic way of writing this expression?


问:
Can I send a Whatsapp message in python when a condition == True without defining a specific time?
```<code>import pywhatkit as pwk

pwk.sendwhatmsg("phone_number", "Automated message", 10, 0)
</code>```

I have this code but I want to send a message without setting a specific time.

答:
Didn't find any way to do this using pywhatkit.

A solution I found is to use pyautogui on WhatsApp Web, selecting the message input box.

The program types the message and presses enter:

```<code>import pyautogui
import time

def send_msg(msg):
    pyautogui.typewrite(msg)
    time.sleep(0.1)
    pyautogui.press("enter")

send_msg("Hello, world")
</code>```

Body:
import pywhatkit as pwk

pwk.sendwhatmsg("phone_number", "Automated message", 10, 0)

I have this code but I want to send a message without setting a specific time.

Body:
Didn't find any way to do this using pywhatkit.

A solution I found is to use pyautogui on WhatsApp Web, selecting the message input box.

The program types the message and presses enter:

import pyautogui
import time

def send_msg(msg):
    pyautogui.typewrite(msg)
    time.sleep(0.1)
    pyautogui.press("enter")

send_msg("Hello, world")


问:
Foundry-Workshop - Charts with multiple layers
I would like to know what are the settings capabilities on workshop charts when implementing multiple layers.

Here is an example of a chart with 2 layers (3 objects):

Among the global settings options, I would like to know:

how to have only one legend per group, instead of one per layer?

how to manage colors? Is it possible to change default?

is there any way to display dotted lines for example?

Thanks in advance

答:
how to have only one legend per group, instead of one per layer?

Currently all the legend "flattens" all the series across all the Plot Layers and there isn't any way to change the grouping. If you really wanted to, you could use a couple metric widgets in List or Tag mode and build your own legend alongside the chart, assuming you'd made overrides for all the potential series and series segments (see below).

how to manage colors? Is it possible to change default?

Yes, you can change the color for each series on the chart. If the series has no "Segement By" config, then you can choose the color directly. If you choose to segment by some other property, then you need to add a Segment Display Override for each segment value that you want to change.

is there any way to display dotted lines for example?

You can change the style from solid to dashed in the same place that you can change the color


问:
How to check the sub string is exists or not in main string
Is there any way to check the sub string is exists in main string or not. If exits, no need any another action. If not exists, I want to add some another string to main string.

For an example:

```<code>$a = 'Hello world';
$b = 'Hello';
</code>```

I want to check the $b is exists in $a or not. If exists, i am sending that variable to database. If not exists, I want to use str_replace('Hello', $b.'World', $b).

答:
```<code>if (strpos($a, $b) !== false) {
    // $b is in $a
} else {
    // $b is not in $a
    str_replace('Hello', $b . 'World', $b);
}
</code>```

Body:
Is there any way to check the sub string is exists in main string or not. If exits, no need any another action. If not exists, I want to add some another string to main string.

For an example:

$a = 'Hello world';
$b = 'Hello';

I want to check the $b is exists in $a or not. If exists, i am sending that variable to database. If not exists, I want to use str_replace('Hello', $b.'World', $b).


问:
Pytube us of on_progress_callback
I'm working with the Pytube library. There are some callback functions that I would like to use to update a loading bar. I can't seem to get it to work. Looking at other issues as well it appears to me that the code is correct. I can't identify why progress_callback is never called in any case.

```<code>def on_progress(self, chunk: bytes, file_handler: BinaryIO, bytes_remaining: int):
    print(' progress:', on_progress)
video = pytube.YouTube( "https://www.youtube.com/watch?v=Ipa0KsyBViA", on_progress_callback=on_progress)

</code>```

I have doubts about the callback parameters, I've seen some that pointed to additional parameters as well.

EDIT

Looking at the source code I set the exact same parameters. Unfortunately to no avail, it seems that the function is never called.

答:
I noticed that the latest version of pytube (11.0.2) produces an error AttributeError: 'NoneType' object has no attribute 'span' due to the fact that youtube changed something on their end, so even a simple example from the official docs wouldnt work. Maybe this is the root of your problem. Temporary solution (found via this github issue):

Uninstall pytube, reinstall hotfixed version:

```<code>pip uninstall pytube
pip install git+https://github.com/glubsy/pytube@nfunc_regex_patch
</code>```

Test if pytube works correctly:

```<code>from pytube import Youtube
YouTube('https://youtu.be/9bZkp7q19f0').streams.first().download()
</code>```

If that works, move on. If not - look for another solution. It seems that currently there can be changes every day because Youtube changes things.

Your described code should work, however it is not doing alot. With the help of this post i figured that an on_progress callback requires arguments in the order: stream, chunk and bytes_remaining. Also, printing your function will sumply return the reference of a function object without any actual value. However, it should still run, so i figure your problem was probably the points described in 1. and 2., so check if you can download a file first.

Functional, complete example:

```<code>from pytube import YouTube

def on_progress(stream, chunk, bytes_remaining):
    """Callback function"""
    total_size = stream.filesize
    bytes_downloaded = total_size - bytes_remaining
    pct_completed = bytes_downloaded / total_size * 100
    print(f"Status: {round(pct_completed, 2)} %")

url = "https://youtube.com/watch?v=9bZkp7q19f0"
yt = YouTube(url, on_progress_callback=on_progress)

out = yt.streams\
    .filter(progressive=True, file_extension='mp4')\
    .order_by('resolution')\
    .desc()\
    .first()\
    .download()

print(f"Download complete: {out}")
</code>```

Title: Pytube us of on_progress_callback

Body:
I'm working with the Pytube library. There are some callback functions that I would like to use to update a loading bar. I can't seem to get it to work. Looking at other issues as well it appears to me that the code is correct. I can't identify why progress_callback is never called in any case.

def on_progress(self, chunk: bytes, file_handler: BinaryIO, bytes_remaining: int):
    print(' progress:', on_progress)
video = pytube.YouTube( "https://www.youtube.com/watch?v=Ipa0KsyBViA", on_progress_callback=on_progress)

I have doubts about the callback parameters, I've seen some that pointed to additional parameters as well.

EDIT

Looking at the source code I set the exact same parameters. Unfortunately to no avail, it seems that the function is never called.

Body:
I noticed that the latest version of pytube (11.0.2) produces an error AttributeError: 'NoneType' object has no attribute 'span' due to the fact that youtube changed something on their end, so even a simple example from the official docs wouldnt work. Maybe this is the root of your problem. Temporary solution (found via this github issue):

Uninstall pytube, reinstall hotfixed version:

pip uninstall pytube
pip install git+https://github.com/glubsy/pytube@nfunc_regex_patch

Test if pytube works correctly:

from pytube import Youtube
YouTube('https://youtu.be/9bZkp7q19f0').streams.first().download()

If that works, move on. If not - look for another solution. It seems that currently there can be changes every day because Youtube changes things.

Your described code should work, however it is not doing alot. With the help of this post i figured that an on_progress callback requires arguments in the order: stream, chunk and bytes_remaining. Also, printing your function will sumply return the reference of a function object without any actual value. However, it should still run, so i figure your problem was probably the points described in 1. and 2., so check if you can download a file first.

Functional, complete example:

from pytube import YouTube

def on_progress(stream, chunk, bytes_remaining):
    """Callback function"""
    total_size = stream.filesize
    bytes_downloaded = total_size - bytes_remaining
    pct_completed = bytes_downloaded / total_size * 100
    print(f"Status: {round(pct_completed, 2)} %")

url = "https://youtube.com/watch?v=9bZkp7q19f0"
yt = YouTube(url, on_progress_callback=on_progress)

out = yt.streams\
    .filter(progressive=True, file_extension='mp4')\
    .order_by('resolution')\
    .desc()\
    .first()\
    .download()

print(f"Download complete: {out}")


问:
How to fix Platform Exception error "auth_in_progress" for flutter local authentication?
I'm trying to implement fingerpritn authentication in my flutter app using local_auth plugin. But it is throwing me Platform Exception Error:

"PlatformException(auth_in_progress, Authentication in progress, null)"

```<code>final LocalAuthentication _localAuth = LocalAuthentication();
bool authenticated = false;
try {
  authenticated = await _localAuth.authenticateWithBiometrics(
    localizedReason: 'Scan your fingerprint to authenticate',
    useErrorDialogs: true,
    stickyAuth: false
  );
} on PlatformException
catch(e) {
  print(e);
}
return authenticated; }
</code>```

答:
I got same issue. But none of the above answers useful. Tricky solution is to set "sensitiveTransaction" value to false. By default this value is true.

When user clicks on biometric button, by default it will come two dialogs. One is faceid or fingerprint recognition and 2nd one is for confirmation dialog. At this case, if user clicks on cancel, permission denied and it will never asks again. If "sensitiveTransaction" sets  to false will not ask for confirm after verified with faceid or fingerprint.

```<code>await localAuthObject.authenticate(
              localizedReason:
                  'Scan your fingerprint (or face or whatever) to authenticate',
              useErrorDialogs: false,
              sensitiveTransaction: false,
              stickyAuth: true,
              biometricOnly:
                  false);
</code>```

Body:
I'm trying to implement fingerpritn authentication in my flutter app using local_auth plugin. But it is throwing me Platform Exception Error:

"PlatformException(auth_in_progress, Authentication in progress, null)"

final LocalAuthentication _localAuth = LocalAuthentication();
bool authenticated = false;
try {
  authenticated = await _localAuth.authenticateWithBiometrics(
    localizedReason: 'Scan your fingerprint to authenticate',
    useErrorDialogs: true,
    stickyAuth: false
  );
} on PlatformException
catch(e) {
  print(e);
}
return authenticated; }

Body:
I got same issue. But none of the above answers useful. Tricky solution is to set "sensitiveTransaction" value to false. By default this value is true.

When user clicks on biometric button, by default it will come two dialogs. One is faceid or fingerprint recognition and 2nd one is for confirmation dialog. At this case, if user clicks on cancel, permission denied and it will never asks again. If "sensitiveTransaction" sets  to false will not ask for confirm after verified with faceid or fingerprint.

await localAuthObject.authenticate(
              localizedReason:
                  'Scan your fingerprint (or face or whatever) to authenticate',
              useErrorDialogs: false,
              sensitiveTransaction: false,
              stickyAuth: true,
              biometricOnly:
                  false);


问:
How to prevent Pulumi cli from shuffling configurations in stack settings file
I am trying to organize configuration values in stack settings file (Pulumi.dev.yaml) from top to bottom sequentially i.e. first Resource Group, then Storage Account, then Virtual Network, AKS and so on as following:

secretsprovider: xxx
encryptedkey: xxx
config:
  azure-native:location: japaneast

  #
  # Resource Group
  #
  ns:MainResourceGroupArgs:
    ResourceGroupName: xxx
    Tags:
      TestTag: xxx
  #
  # Storage Account
  #
  ns:MainStorageAccountArgs:
    AccountKind: StorageV2
    AccountName: xxxsa
    AccountSku: Standard_LRS
    Tags:
      TestTag: xxx
  #
  # Spoke VNet
  #
  ns:SpokeVirtualNetworkArgs:
    AddressPrefixes:
    - 10.10.0.0/18
    Subnets:
      # ... ... ...
  #
  # Hub VNet
  #
  # ... ... ...

  #
  # AKS
  #
  # ... ... ...
```

But every time a Pulumi command is executed (i.e. pulumi preview -s dev or pulumi up -s dev) followings are happening:

configuration values are being shuffled, for example before executing command Resource Group was at top but after executing command Resource Group is at bottom. This is very annoying and bad when we have huge number of configurations

yaml comments are being removed

How to solve this issue?

I want to keep yaml comments in stack settings file and prevent Pulumi cli from shuffling configuration values.

Info: Pulumi cli v3.17.1

答:
With Pulumi 3.24.1 and PULUMI_EXPERIMENTAL=true, you might check if Pulumi.dev.yaml has its content still reshuffled after:

```<code> pulumi preview -s dev --save-plan plan.json
</code>```

Because after that, you can do:

```<code> pulumi up --plan-file plan.json
</code>```

See:

Announcing the public preview of Update Plans

Before today, there is no guarantee that the pulumi up operation will do only what was previewed; if the program, or your infrastructure, changes between the preview and the update, the update might make additional changes to bring your infrastructure back in line with what’s defined in your program.

We’ve heard from many of you that you need a strong guarantee about exactly which changes an update will make to your infrastructure, especially in critical and production environments.

Today (Feb. 9th, 2022), I’m excited to announce the public preview of Update Plans, a new Pulumi feature which guarantees that operations shown in pulumi preview will run on pulumi up.

Update Plans also help catch any unexpected changes that might happen between when you preview a change and when you apply that change.

Update Plans work by saving the results of a pulumi preview to a plan file, which enables you to restrict subsequent pulumi up operations to only the actions saved in the plan file.

This helps you ensure that what you saw in the pulumi preview is what will actually happen when you run pulumi up.

Body:
I am trying to organize configuration values in stack settings file (Pulumi.dev.yaml) from top to bottom sequentially i.e. first Resource Group, then Storage Account, then Virtual Network, AKS and so on as following:

secretsprovider: xxx
encryptedkey: xxx
config:
  azure-native:location: japaneast

  #
  # Resource Group
  #
  ns:MainResourceGroupArgs:
    ResourceGroupName: xxx
    Tags:
      TestTag: xxx
  #
  # Storage Account
  #
  ns:MainStorageAccountArgs:
    AccountKind: StorageV2
    AccountName: xxxsa
    AccountSku: Standard_LRS
    Tags:
      TestTag: xxx
  #
  # Spoke VNet
  #
  ns:SpokeVirtualNetworkArgs:
    AddressPrefixes:
    - 10.10.0.0/18
    Subnets:
      # ... ... ...
  #
  # Hub VNet
  #
  # ... ... ...

  #
  # AKS
  #
  # ... ... ...

But every time a Pulumi command is executed (i.e. pulumi preview -s dev or pulumi up -s dev) followings are happening:

configuration values are being shuffled, for example before executing command Resource Group was at top but after executing command Resource Group is at bottom. This is very annoying and bad when we have huge number of configurations

yaml comments are being removed

How to solve this issue?

I want to keep yaml comments in stack settings file and prevent Pulumi cli from shuffling configuration values.

Info: Pulumi cli v3.17.1

Body:
With Pulumi 3.24.1 and PULUMI_EXPERIMENTAL=true, you might check if Pulumi.dev.yaml has its content still reshuffled after:

 pulumi preview -s dev --save-plan plan.json

Because after that, you can do:

 pulumi up --plan-file plan.json

See:

Announcing the public preview of Update Plans

Before today, there is no guarantee that the pulumi up operation will do only what was previewed; if the program, or your infrastructure, changes between the preview and the update, the update might make additional changes to bring your infrastructure back in line with what’s defined in your program.

We’ve heard from many of you that you need a strong guarantee about exactly which changes an update will make to your infrastructure, especially in critical and production environments.

Today (Feb. 9th, 2022), I’m excited to announce the public preview of Update Plans, a new Pulumi feature which guarantees that operations shown in pulumi preview will run on pulumi up.

Update Plans also help catch any unexpected changes that might happen between when you preview a change and when you apply that change.

Update Plans work by saving the results of a pulumi preview to a plan file, which enables you to restrict subsequent pulumi up operations to only the actions saved in the plan file.

This helps you ensure that what you saw in the pulumi preview is what will actually happen when you run pulumi up.


问:
"Error: Cannot find module 'mysql2/promise'" when running "docker-compose up"
I want to use docker compose to connect a node program, in one container, to a MySQL database, in another container. The database seems to start fine, but my index.js file throws an error: Cannot find module 'mysql2/promise'

I've tried installing different packages with npm, and even edited various lines in my package.json file in desperation, but to no avail; always the same error. Here are the relevant files, and the output of the commands that work so far.

$ npm install mysql2

```<code>npm WARN simplyanything@1.0.0 No repository field.
npm WARN simplyanything@1.0.0 No license field.

+ mysql2@2.3.3
updated 1 package and audited 101 packages in 3.302s
found 0 vulnerabilities
</code>```

$ sudo npm install mysql2-promise

```<code>+ mysql2-promise@0.1.4
updated 1 package and audited 101 packages in 3.772s
found 0 vulnerabilities
</code>```

package.json

```<code>{
    "name": "simplyanything",
    "version": "1.0.0",
    "scripts": {
        "start": "node index.js"
    },
    "description": "Actions party game",
    "dependencies": {
        "express": "^4.17.1",
        "mysql2": "^2.3.3",
        "mysql2-promise": "^0.1.4",
        "socket.io": "^4.4.1"
    },
    "author": "Chris DeHaan"
}
</code>```

index.js

```<code>const express = require('express');
let app = express();
let http = require('http').createServer(app);
const io = require('socket.io')(http, {pingTimeout: 60000});

app.use(express.static('public'));
app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); });
http.listen(3000, () => { console.log('listening on *:3000'); });

const mysql = require('mysql2/promise');
const pool = mysql.createPool({
    connectionLimit : 100,
    host: process.env.MYSQL_HOST,
    user: process.env.MYSQL_USER,
[.... and so on]
</code>```

Dockerfile

```<code>FROM node:latest
WORKDIR /sa/
COPY package.json .
RUN npm install
COPY . .
</code>```

docker-compose.yml

```<code>version: '3.8'
services:
    web:
      build:
          context: .
      env_file: ./.env
      command: npm start
      volumes:
          - .:/sa/
          - /sa/node_modules
      ports:
          - $NODE_LOCAL_PORT:$NODE_DOCKER_PORT
      depends_on:
          - mysqldb
      environment:
          MYSQL_HOST: mysqldb
    mysqldb:
      image: mysql
      env_file: ./.env
      environment:
          MYSQL_ROOT_PASSWORD: $MYSQL_ROOT_PASSWORD
          MYSQL_DATABASE: $MYSQL_DATABASE
      ports:
          - $MYSQL_LOCAL_PORT:$MYSQL_DOCKER_PORT
      volumes:
          - mysql:/var/lib/mysql
          - mysql_config:/etc/mysql
volumes:
    mysql:
    mysql_config:
</code>```

.env

```<code>MYSQL_USER=simplyanythingUser
MYSQL_ROOT_PASSWORD=[Well, you don't need to know this]
MYSQL_DATABASE=simplyanything
MYSQL_LOCAL_PORT=3306
MYSQL_DOCKER_PORT=3306

NODE_LOCAL_PORT=3000
NODE_DOCKER_PORT=3000
</code>```

$ sudo docker build -t sa .

```<code>Sending build context to Docker daemon  9.526MB
Step 1/5 : FROM node:latest
 ---> e6bed6a65a54
Step 2/5 : WORKDIR /sa/
 ---> Using cache
 ---> 3da61e5a5928
Step 3/5 : COPY package.json .
 ---> Using cache
 ---> 1e7bbeaaa894
Step 4/5 : RUN npm install
 ---> Using cache
 ---> 52f36e54d698
Step 5/5 : COPY . .
 ---> e0a50567567b
Successfully built e0a50567567b
Successfully tagged sa:latest
</code>```

$ node index.js

```<code>Debugger listening on ws://127.0.0.1:44273/a1b49bfc-83e7-47dd-ba53-64a8df19ccc9
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
listening on *:3000
</code>```

(and it works in the browser at this point)

$ sudo docker-compose up

```<code>Starting sa_mysqldb_1 ... done
Starting sa_web_1     ... done
Attaching to sa_mysqldb_1, sa_web_1
mysqldb_1  | 2022-02-08 08:31:21+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.28-1debian10 started.
mysqldb_1  | 2022-02-08 08:31:21+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
mysqldb_1  | 2022-02-08 08:31:21+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.28-1debian10 started.
mysqldb_1  | 2022-02-08T08:31:21.660916Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.28) starting as process 1
mysqldb_1  | 2022-02-08T08:31:21.747461Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
web_1      |
web_1      | > simplyanything@1.0.0 start
web_1      | > node index.js
web_1      |
mysqldb_1  | 2022-02-08T08:31:23.587278Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
web_1      | node:internal/modules/cjs/loader:936
web_1      |   throw err;
web_1      |   ^
web_1      |
web_1      | Error: Cannot find module 'mysql2/promise'
web_1      | Require stack:
web_1      | - /sa/index.js
web_1      |     at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
web_1      |     at Function.Module._load (node:internal/modules/cjs/loader:778:27)
web_1      |     at Module.require (node:internal/modules/cjs/loader:999:19)
web_1      |     at require (node:internal/modules/cjs/helpers:102:18)
web_1      |     at Object.<anonymous> (/sa/index.js:13:15)
web_1      |     at Module._compile (node:internal/modules/cjs/loader:1097:14)
web_1      |     at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
web_1      |     at Module.load (node:internal/modules/cjs/loader:975:32)
web_1      |     at Function.Module._load (node:internal/modules/cjs/loader:822:12)
web_1      |     at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12) {
web_1      |   code: 'MODULE_NOT_FOUND',
web_1      |   requireStack: [ '/sa/index.js' ]
web_1      | }
web_1      |
web_1      | Node.js v17.4.0
mysqldb_1  | 2022-02-08T08:31:25.086275Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
mysqldb_1  | 2022-02-08T08:31:25.086445Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
mysqldb_1  | 2022-02-08T08:31:25.277625Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
mysqldb_1  | 2022-02-08T08:31:25.354311Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock
mysqldb_1  | 2022-02-08T08:31:25.355558Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.28'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server - GPL.
</code>```

I'm really stuck because everything it needs seems to be installed, and it works when I run it on the command line with node index.js so obviously there's something I'm missing in setting up my container, or getting compose to connect them. Any advice would be much appreciated. Cheers.

答:
Good afternoon, I had the same problem. You could try to use

npm install mysql2```

Body:
I want to use docker compose to connect a node program, in one container, to a MySQL database, in another container. The database seems to start fine, but my index.js file throws an error: Cannot find module 'mysql2/promise'

I've tried installing different packages with npm, and even edited various lines in my package.json file in desperation, but to no avail; always the same error. Here are the relevant files, and the output of the commands that work so far.

$ npm install mysql2

npm WARN simplyanything@1.0.0 No repository field.
npm WARN simplyanything@1.0.0 No license field.

+ mysql2@2.3.3
updated 1 package and audited 101 packages in 3.302s
found 0 vulnerabilities

$ sudo npm install mysql2-promise

+ mysql2-promise@0.1.4
updated 1 package and audited 101 packages in 3.772s
found 0 vulnerabilities

package.json

{
    "name": "simplyanything",
    "version": "1.0.0",
    "scripts": {
        "start": "node index.js"
    },
    "description": "Actions party game",
    "dependencies": {
        "express": "^4.17.1",
        "mysql2": "^2.3.3",
        "mysql2-promise": "^0.1.4",
        "socket.io": "^4.4.1"
    },
    "author": "Chris DeHaan"
}

index.js

const express = require('express');
let app = express();
let http = require('http').createServer(app);
const io = require('socket.io')(http, {pingTimeout: 60000});

app.use(express.static('public'));
app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); });
http.listen(3000, () => { console.log('listening on *:3000'); });

const mysql = require('mysql2/promise');
const pool = mysql.createPool({
    connectionLimit : 100,
    host: process.env.MYSQL_HOST,
    user: process.env.MYSQL_USER,
[.... and so on]

Dockerfile

FROM node:latest
WORKDIR /sa/
COPY package.json .
RUN npm install
COPY . .

docker-compose.yml

version: '3.8'
services:
    web:
      build:
          context: .
      env_file: ./.env
      command: npm start
      volumes:
          - .:/sa/
          - /sa/node_modules
      ports:
          - $NODE_LOCAL_PORT:$NODE_DOCKER_PORT
      depends_on:
          - mysqldb
      environment:
          MYSQL_HOST: mysqldb
    mysqldb:
      image: mysql
      env_file: ./.env
      environment:
          MYSQL_ROOT_PASSWORD: $MYSQL_ROOT_PASSWORD
          MYSQL_DATABASE: $MYSQL_DATABASE
      ports:
          - $MYSQL_LOCAL_PORT:$MYSQL_DOCKER_PORT
      volumes:
          - mysql:/var/lib/mysql
          - mysql_config:/etc/mysql
volumes:
    mysql:
    mysql_config:

.env

MYSQL_USER=simplyanythingUser
MYSQL_ROOT_PASSWORD=[Well, you don't need to know this]
MYSQL_DATABASE=simplyanything
MYSQL_LOCAL_PORT=3306
MYSQL_DOCKER_PORT=3306

NODE_LOCAL_PORT=3000
NODE_DOCKER_PORT=3000

$ sudo docker build -t sa .

Sending build context to Docker daemon  9.526MB
Step 1/5 : FROM node:latest
 ---> e6bed6a65a54
Step 2/5 : WORKDIR /sa/
 ---> Using cache
 ---> 3da61e5a5928
Step 3/5 : COPY package.json .
 ---> Using cache
 ---> 1e7bbeaaa894
Step 4/5 : RUN npm install
 ---> Using cache
 ---> 52f36e54d698
Step 5/5 : COPY . .
 ---> e0a50567567b
Successfully built e0a50567567b
Successfully tagged sa:latest

$ node index.js

Debugger listening on ws://127.0.0.1:44273/a1b49bfc-83e7-47dd-ba53-64a8df19ccc9
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
listening on *:3000

(and it works in the browser at this point)

$ sudo docker-compose up

Starting sa_mysqldb_1 ... done
Starting sa_web_1     ... done
Attaching to sa_mysqldb_1, sa_web_1
mysqldb_1  | 2022-02-08 08:31:21+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.28-1debian10 started.
mysqldb_1  | 2022-02-08 08:31:21+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
mysqldb_1  | 2022-02-08 08:31:21+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.28-1debian10 started.
mysqldb_1  | 2022-02-08T08:31:21.660916Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.28) starting as process 1
mysqldb_1  | 2022-02-08T08:31:21.747461Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
web_1      |
web_1      | > simplyanything@1.0.0 start
web_1      | > node index.js
web_1      |
mysqldb_1  | 2022-02-08T08:31:23.587278Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
web_1      | node:internal/modules/cjs/loader:936
web_1      |   throw err;
web_1      |   ^
web_1      |
web_1      | Error: Cannot find module 'mysql2/promise'
web_1      | Require stack:
web_1      | - /sa/index.js
web_1      |     at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
web_1      |     at Function.Module._load (node:internal/modules/cjs/loader:778:27)
web_1      |     at Module.require (node:internal/modules/cjs/loader:999:19)
web_1      |     at require (node:internal/modules/cjs/helpers:102:18)
web_1      |     at Object.<anonymous> (/sa/index.js:13:15)
web_1      |     at Module._compile (node:internal/modules/cjs/loader:1097:14)
web_1      |     at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
web_1      |     at Module.load (node:internal/modules/cjs/loader:975:32)
web_1      |     at Function.Module._load (node:internal/modules/cjs/loader:822:12)
web_1      |     at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12) {
web_1      |   code: 'MODULE_NOT_FOUND',
web_1      |   requireStack: [ '/sa/index.js' ]
web_1      | }
web_1      |
web_1      | Node.js v17.4.0
mysqldb_1  | 2022-02-08T08:31:25.086275Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
mysqldb_1  | 2022-02-08T08:31:25.086445Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
mysqldb_1  | 2022-02-08T08:31:25.277625Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
mysqldb_1  | 2022-02-08T08:31:25.354311Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock
mysqldb_1  | 2022-02-08T08:31:25.355558Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.28'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server - GPL.

I'm really stuck because everything it needs seems to be installed, and it works when I run it on the command line with node index.js so obviously there's something I'm missing in setting up my container, or getting compose to connect them. Any advice would be much appreciated. Cheers.