问:
Base Address of ELF
I am trying to find the base address of ELF files. I know that you can use readelf to find the Program Entry Point and different section details (base address, size, flags and so on).

For example, programs for x86 architecture are based at 0x8048000 by linker. using readelf I can see the program entry point but no specific field in the output tells the base address.

```<code>$ readelf -e test
ELF Header:
  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
  Class:                             ELF32
  Data:                              2's complement, little endian
  Version:                           1 (current)
  OS/ABI:                            UNIX - System V
  ABI Version:                       0
  Type:                              EXEC (Executable file)
  Machine:                           Intel 80386
  Version:                           0x1
  Entry point address:               0x8048390
  Start of program headers:          52 (bytes into file)
  Start of section headers:          4436 (bytes into file)
  Flags:                             0x0
  Size of this header:               52 (bytes)
  Size of program headers:           32 (bytes)
  Number of program headers:         9
  Size of section headers:           40 (bytes)
  Number of section headers:         30

Section Headers:
  [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
  [ 0]                   NULL            00000000 000000 000000 00      0   0  0
  [ 1] .interp           PROGBITS        08048154 000154 000013 00   A  0   0  1
  [ 2] .note.ABI-tag     NOTE            08048168 000168 000020 00   A  0   0  4
  [ 3] .note.gnu.build-i NOTE            08048188 000188 000024 00   A  0   0  4
  [ 4] .gnu.hash         GNU_HASH        080481ac 0001ac 000024 04   A  5   0  4
  [ 5] .dynsym           DYNSYM          080481d0 0001d0 000070 10   A  6   1  4
</code>```

In the section details, I can see that the Offset is calculated with respect to the base address of the ELF.

So, .dynsym section starts at address, 0x080481d0 and offset is 0x1d0. This would mean the base address is, 0x08048000. Is this correct?

similarly, for programs compiled on different architectures like PPC, ARM, MIPS, I cannot see their base address but only the OEP, Section Headers.

答:
The ELF mapping base Address of the .text section is defined by the ld(1) loader script in the binutils project under script template elf.sc on Linux.

The script define the following variables used by the loader ld(1):

```<code>#       TEXT_START_ADDR - the first byte of the text segment, after any
#               headers.
#       TEXT_BASE_ADDRESS - the first byte of the text segment.
#       TEXT_START_SYMBOLS - symbols that appear at the start of the
#               .text section.
</code>```

You can inspect the current values using the command:

```<code>~$ ld --verbose |grep SEGMENT_START
  PROVIDE (__executable_start = SEGMENT_START("text-segment", 0x400000)); . = SEGMENT_START("text-segment", 0x400000) + SIZEOF_HEADERS;
  . = SEGMENT_START("ldata-segment", .);
</code>```

The text-segment mapping values are:

0x08048000 on 32 Bits

0x400000 on 64 Bits

Also the interpreter base address of an ELF program is defined in the Auxiliary vector array at the index AT_BASE. The Auxiliary vector array is an array of the Elf_auxv_t structure and located after the envp in the process stack. It's configured while loading the ELF binary in the function create_elf_tables() of Linux kernel fs/binfmt_elf.c. The following code snippet show how to read the value:

```<code>$ cat at_base.c
#include <stdio.h>
#include <elf.h>

int
main(int argc, char* argv[], char* envp[])
{
        Elf64_auxv_t *auxp;
        while(*envp++ != NULL);

        for (auxp = (Elf64_auxv_t *)envp; auxp->a_type != 0; auxp++) {
            if (auxp->a_type == 7) {
                printf("AT_BASE: 0x%lx\n", auxp->a_un.a_val);
            }
        }

}
$ clang -o at_base at_base.c
$ ./at_base
AT_BASE: 0x7fcfd4025000
</code>```

Linux Auxiliary Vector definition
Auxiliary Vector Reference

It used to be a fixed address on x86 32 bits architecture, but with ASLR now, it's randomized. You can use setarch i386 -R to disable randomization if you want.

Title: Base Address of ELF

Body:
I am trying to find the base address of ELF files. I know that you can use readelf to find the Program Entry Point and different section details (base address, size, flags and so on).

For example, programs for x86 architecture are based at 0x8048000 by linker. using readelf I can see the program entry point but no specific field in the output tells the base address.

$ readelf -e test
ELF Header:
  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
  Class:                             ELF32
  Data:                              2's complement, little endian
  Version:                           1 (current)
  OS/ABI:                            UNIX - System V
  ABI Version:                       0
  Type:                              EXEC (Executable file)
  Machine:                           Intel 80386
  Version:                           0x1
  Entry point address:               0x8048390
  Start of program headers:          52 (bytes into file)
  Start of section headers:          4436 (bytes into file)
  Flags:                             0x0
  Size of this header:               52 (bytes)
  Size of program headers:           32 (bytes)
  Number of program headers:         9
  Size of section headers:           40 (bytes)
  Number of section headers:         30

Section Headers:
  [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
  [ 0]                   NULL            00000000 000000 000000 00      0   0  0
  [ 1] .interp           PROGBITS        08048154 000154 000013 00   A  0   0  1
  [ 2] .note.ABI-tag     NOTE            08048168 000168 000020 00   A  0   0  4
  [ 3] .note.gnu.build-i NOTE            08048188 000188 000024 00   A  0   0  4
  [ 4] .gnu.hash         GNU_HASH        080481ac 0001ac 000024 04   A  5   0  4
  [ 5] .dynsym           DYNSYM          080481d0 0001d0 000070 10   A  6   1  4

In the section details, I can see that the Offset is calculated with respect to the base address of the ELF.

So, .dynsym section starts at address, 0x080481d0 and offset is 0x1d0. This would mean the base address is, 0x08048000. Is this correct?

similarly, for programs compiled on different architectures like PPC, ARM, MIPS, I cannot see their base address but only the OEP, Section Headers.

Body:
The ELF mapping base Address of the .text section is defined by the ld(1) loader script in the binutils project under script template elf.sc on Linux.

The script define the following variables used by the loader ld(1):

#       TEXT_START_ADDR - the first byte of the text segment, after any
#               headers.
#       TEXT_BASE_ADDRESS - the first byte of the text segment.
#       TEXT_START_SYMBOLS - symbols that appear at the start of the
#               .text section.

You can inspect the current values using the command:

~$ ld --verbose |grep SEGMENT_START
  PROVIDE (__executable_start = SEGMENT_START("text-segment", 0x400000)); . = SEGMENT_START("text-segment", 0x400000) + SIZEOF_HEADERS;
  . = SEGMENT_START("ldata-segment", .);

The text-segment mapping values are:

0x08048000 on 32 Bits

0x400000 on 64 Bits

Also the interpreter base address of an ELF program is defined in the Auxiliary vector array at the index AT_BASE. The Auxiliary vector array is an array of the Elf_auxv_t structure and located after the envp in the process stack. It's configured while loading the ELF binary in the function create_elf_tables() of Linux kernel fs/binfmt_elf.c. The following code snippet show how to read the value:

$ cat at_base.c
#include <stdio.h>
#include <elf.h>

int
main(int argc, char* argv[], char* envp[])
{
        Elf64_auxv_t *auxp;
        while(*envp++ != NULL);

        for (auxp = (Elf64_auxv_t *)envp; auxp->a_type != 0; auxp++) {
            if (auxp->a_type == 7) {
                printf("AT_BASE: 0x%lx\n", auxp->a_un.a_val);
            }
        }

}
$ clang -o at_base at_base.c
$ ./at_base
AT_BASE: 0x7fcfd4025000

Linux Auxiliary Vector definition
Auxiliary Vector Reference

It used to be a fixed address on x86 32 bits architecture, but with ASLR now, it's randomized. You can use setarch i386 -R to disable randomization if you want.


来源: stackexchange

问:
What is "app:layout_constraintHorizontal_bias" used for?
Can anyone please explain what app:layout_constraintHorizontal_bias is used for?

答:
The default when encountering such opposite constraints is to center the widget; but you can tweak the positioning to favor one side over another using the bias attributes:

layout_constraintHorizontal_bias
layout_constraintVertical_bias

Basically for this type of questions you should check Official Documentation instead of posting here... here is link to official documnetation for Bias....
Learn More About Bias

ContentLicense: CC BY-SA 4.0


问:
What is the difference between mm and spmm in Pytorch
What is the difference between mm and spmm in Pytorch? I know that spmm does sparse matrix multiplication, but what exactly does that mean? Why would you ever choose mm as opposed to spmm if spmm has the potential to save space? </p>

答:
In order to use spmm you need your tensor arguments to actually be of sparse type.

Although torch.sparse representation does have the potential of saving space, sparse support does not yet covers all tensor operations and functions.


问:
Why is not working when i try to add a to a string to my array location
I'm still learning JavaScript, and now I'm in the array chapter and I'm doing this project I have to ask the user for 5 names and stored and my array, then have to sort the names by the location in the array, so i could separed in odd and in even, then i have to add a lastname to the odds, and different last name to the even, but is that part that is not working any help ... THANKS</p>

```<code>var numberfirstNames = 5;
var userMessage = " Please enter a first Name" ;
var secondArray = [];
var odd2 = [];
var even2 = [];
for (var i = 0; i < numberfirstNames; i++) // loop 5 times  LOOL ASKING FOR "5" FIRST NAMES>> STORING IN NAMES
{
    secondArray[i] = getFirstname();
    window.alert("second " + secondArray[i] );
}
for (var i = 0; i < secondArray.length; i++) {
    if(i % 2 === 0)  // index is even
    {
        even2.push(secondArray[i]);
        for ( var i=0 ; i<even2.length; i++)
            even2[i]+=" Chavez"
    }
    else
    {
        odd2.push(secondArray[i]);
        for ( var i=0 ; i<odd2.length; i++)
            odd2[i]+=" McCain"
    }
}

document.write(" \n all the names: "+ secondArray+'<br>');
document.write(" \n even names: "+ even2+'<br>');
document.write(" \n odd names: "+ odd2+'<br>');
</code>```

答:
You don't need to loop again to add the specific last name. You can just prepend it while you are inserting it into the array like below. </p>

```<code>var numberfirstNames = 5;
var userMessage = " Please enter a first Name";
var secondArray = [];
var odd2 = [];
var even2 = [];

// loop 5 times LOOP ASKING FOR "5" FIRST NAMES >> STORING IN NAMES
for (var i = 0; i < numberfirstNames; i++) {
    secondArray[i] = getFirstname();
    window.alert("second " + secondArray[i]);

    if (i % 2 === 0) {
        even2.push(secondArray[i] + " Chavez");
    } else {
        odd2.push(secondArray[i] + " McCain");
    }

}

document.write(" \n all the names: " + secondArray.join(",") + '<br>');
document.write(" \n even names: " + even2.join(",") + '<br>');
document.write(" \n odd names: " + odd2.join(",") + '<br>');
</code>```

Body:
I'm still learning JavaScript, and now I'm in the array chapter and I'm doing this project I have to ask the user for 5 names and stored and my array, then have to sort the names by the location in the array, so i could separed in odd and in even, then i have to add a lastname to the odds, and different last name to the even, but is that part that is not working any help ... THANKS

var numberfirstNames = 5;
var userMessage = " Please enter a first Name" ;
var secondArray = [];
var odd2 = [];
var even2 = [];
for (var i = 0; i < numberfirstNames; i++) // loop 5 times  LOOL ASKING FOR "5" FIRST NAMES>> STORING IN NAMES
{
    secondArray[i] = getFirstname();
    window.alert("second " + secondArray[i] );
}
for (var i = 0; i < secondArray.length; i++) {
    if(i % 2 === 0)  // index is even
    {
        even2.push(secondArray[i]);
        for ( var i=0 ; i<even2.length; i++)
            even2[i]+=" Chavez"
    }
    else
    {
        odd2.push(secondArray[i]);
        for ( var i=0 ; i<odd2.length; i++)
            odd2[i]+=" McCain"
    }
}

document.write(" \n all the names: "+ secondArray+'
');
document.write(" \n even names: "+ even2+'
');
document.write(" \n odd names: "+ odd2+'
');

Body:
You don't need to loop again to add the specific last name. You can just prepend it while you are inserting it into the array like below.

var numberfirstNames = 5;
var userMessage = " Please enter a first Name";
var secondArray = [];
var odd2 = [];
var even2 = [];

// loop 5 times LOOP ASKING FOR "5" FIRST NAMES >> STORING IN NAMES
for (var i = 0; i < numberfirstNames; i++) {
    secondArray[i] = getFirstname();
    window.alert("second " + secondArray[i]);

    if (i % 2 === 0) {
        even2.push(secondArray[i] + " Chavez");
    } else {
        odd2.push(secondArray[i] + " McCain");
    }

}

document.write(" \n all the names: " + secondArray.join(",") + '<br>');
document.write(" \n even names: " + even2.join(",") + '<br>');
document.write(" \n odd names: " + odd2.join(",") + '<br>');


问:
Show a specific component based on Dynamic Angular Routing path
My routes:

/dashboard

/dashboard/view-all

/dashboard/edit/:id

Basically, I have a table in the /dashboard/view-all and for each row, I have an Edit Button to take me to the /dashboard/edit/:id, and it works fine.

The Problem: I can't show/hide the EditComponent according to the Dynamic Router. I usually show/hide Angular Component based on Router using something like this:

<app-view-all *ngIf="route.url == '/dashboard/view-all'"></app-view-all>```
</div>
</div>
</p>

<p>For a dynamic router, when I am trying to write it like:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><app-edit *ngIf="route.url == '/dashboard/edit/:id'"></app-edit></code>```

It doesn't work, but it works when I change it to something like: /dashboard/edit/26. I am new to Angular, and I didn't find such a duplicate question on SOF, maybe it's a very basic Angular question? :D

Thank You!!

答:
I've solved it using indexOf JavaScript Method, and I consider it a hacky solution:

<app-edit *ngIf="route.url.indexOf('/dashboard/edit/') >= 0" ></app-edit>```

It returns true if the path has the /dashboard/edit/ part, otherwise, it returns false.

I do wonder; Is there a better, conventional solution?

Body:
My routes:

/dashboard

/dashboard/view-all

/dashboard/edit/:id

Basically, I have a table in the /dashboard/view-all and for each row, I have an Edit Button to take me to the /dashboard/edit/:id, and it works fine.

The Problem: I can't show/hide the EditComponent according to the Dynamic Router. I usually show/hide Angular Component based on Router using something like this:

<app-view-all *ngIf="route.url == '/dashboard/view-all'"></app-view-all>

For a dynamic router, when I am trying to write it like:

<app-edit *ngIf="route.url == '/dashboard/edit/:id'"></app-edit>

It doesn't work, but it works when I change it to something like: /dashboard/edit/26. I am new to Angular, and I didn't find such a duplicate question on SOF, maybe it's a very basic Angular question? :D

Thank You!!

Body:
I've solved it using indexOf JavaScript Method, and I consider it a hacky solution:

<app-edit *ngIf="route.url.indexOf('/dashboard/edit/') >= 0" ></app-edit>

It returns true if the path has the /dashboard/edit/ part, otherwise, it returns false.

I do wonder; Is there a better, conventional solution?


问:
Why is my Javascript fizzbuzz code not working?
I am trying to create a JS function that will print Fizz when a number divisible by 3 appears and Buzz if it is divisible by 5 and Fizzbuzz if both 5 and 3 but keeps printing "undefined" on chrome>sources>snippets. I have previously managed to run JS there but now it is just printing "undefined". Please help what is wrong with my code? Thank you in advance

This is my code:

```<code>var output = [];
var count = 1;

function fizzBuzz() {
  if (count % 3 === 0) {
    output.push("Fizz");
  }
  if (count % 5 === 0) {
    output.push("Buzz");
  }
  if (count % 15 === 0) {
    output.push("FizzBuzz");
  } else {
    output.push(count);
  }

  count++;

  console.log(output);
};
</code>```

答:
You need to call the function using fizzBuzz(). You'd likely want to do this in a loop until it reaches a certain number.

In the example below, I use a while loop to call the function until count reaches 100. I've also moved the console.log() call to the end of the loop, as it doesn't make sense to log the entire array after each iteration.

Also, consider using else if statements so that Fizz or Buzz are only pushed if FizzBuzz has not been pushed. Otherwise, you may find that all three are pushed instead of just FizzBuzz.

var output = [];
var count = 1;

function fizzBuzz() {
  if (count % 15 === 0) {
    output.push("FizzBuzz");
  }
  else if (count % 3 === 0) {
    output.push("Fizz");
  }
  else if (count % 5 === 0) {
    output.push("Buzz");
  }
  else {
    output.push(count);
  }

  count++;
};

while(count < 100) {
    fizzBuzz();
}
console.log(output)```

Body:
I am trying to create a JS function that will print Fizz when a number divisible by 3 appears and Buzz if it is divisible by 5 and Fizzbuzz if both 5 and 3 but keeps printing "undefined" on chrome>sources>snippets. I have previously managed to run JS there but now it is just printing "undefined". Please help what is wrong with my code? Thank you in advance

This is my code:

var output = [];
var count = 1;

function fizzBuzz() {
  if (count % 3 === 0) {
    output.push("Fizz");
  }
  if (count % 5 === 0) {
    output.push("Buzz");
  }
  if (count % 15 === 0) {
    output.push("FizzBuzz");
  } else {
    output.push(count);
  }

  count++;

  console.log(output);
};


问:
'Specified cast is not valid.' while populate ComboBoxe
I am trying to fill ComboBox in button click, but however I get the following error:

System.InvalidCastException: 'Specified cast is not valid.'

```<code>    public void FillOrgUnit()
    {
        try
        {
            using (SqlConnection conn = new SqlConnection(@"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True"))
            {
                conn.Open();
                string query = "SELECT DISTINCT OrgUnitID FROM tblZaposleni_AD ORDER BY OrgUnitID ASC";
                SqlCommand cmd = new SqlCommand(query, conn);
                using (SqlDataReader saReader = cmd.ExecuteReader())
                {
                    while (saReader.Read())
                    {
                        string name = saReader.GetInt32(0).ToString();
                        ddlStatus.Items.Add(name);
                    }
                }
            }
        }
        catch (Exception)
        {
            throw;
        }
    }
</code>```

I tried to convert string name to int but this doesn't work. I have no idea where the mistake comes from.

BTW : OrgUnitId in database is type bigint

答:
BigInt equivalent in C# is Int64.

```<code>string name = saReader.GetInt64(0).ToString();
</code>```

Reference - https://stackoverflow.com/a/968734/1182982

Body:
I am trying to fill ComboBox in button click, but however I get the following error:

System.InvalidCastException: 'Specified cast is not valid.'

    public void FillOrgUnit()
    {
        try
        {
            using (SqlConnection conn = new SqlConnection(@"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True"))
            {
                conn.Open();
                string query = "SELECT DISTINCT OrgUnitID FROM tblZaposleni_AD ORDER BY OrgUnitID ASC";
                SqlCommand cmd = new SqlCommand(query, conn);
                using (SqlDataReader saReader = cmd.ExecuteReader())
                {
                    while (saReader.Read())
                    {
                        string name = saReader.GetInt32(0).ToString();
                        ddlStatus.Items.Add(name);
                    }
                }
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

I tried to convert string name to int but this doesn't work. I have no idea where the mistake comes from.

BTW : OrgUnitId in database is type bigint

Body:
BigInt equivalent in C# is Int64.

string name = saReader.GetInt64(0).ToString();

Reference - https://stackoverflow.com/a/968734/1182982


问:
Call a function after previous function is complete reactjs
I want to call function this.onLoggin() after this.props.verifyCode(params); already done, how can i do it.
here is myfunction:

```<code>onSubmit = (e) => {
        e.preventDefault();
        let params = {
            email: this.props.email,
            codeVerify: this.state.code
        }
        this.props.verifyCode(params);
        this.onLoggin();

    }

onLoggin = () =>{
        if(this.props.isVerify === true){
            const body = {
                username: this.props.user.username,
                password: this.props.user.password
            }
            this.props.loggin(body);
        }
    }
</code>```

verifyCode come from redux:

```<code>const AUTHEN_URL = 'http://localhost:8080/client/user-info-client/regist';

const verifyCode = (params) => dispatch => {
    axios.post(AUTHEN_URL, null, {params})
        .then(res => {
            dispatch({
            type: VERIFY_CODE,
            payload: res.data.data,
        })});
}

export default verifyCode;
</code>```

here is my reducer:

```<code>const initialState = {
        isVerify: false
};

const verifyCode = (state = initialState, action) => {
    switch (action.type){
        case VERIFY_CODE:
            return {
                isVerify: true
            }
        default:
            return state;

    }
}

export default verifyCode;
</code>```

答:
Noticed that this.props.verifyCode(params) is an asynchronous function. You have to either use async await method or .then.

Using .then:

```<code>this.props.verifyCode(params).then(response => this.onLoggin()).catch(error => error)
</code>```

Using async await:

```<code>onSubmit = async (e) => {
        e.preventDefault();
        let params = {
            email: this.props.email,
            codeVerify: this.state.code
        }
        try{
            await this.props.verifyCode(params);
            this.onLoggin();
        }
        catch(error){
             return error
        }

    }
</code>```

The axios request

```<code>const verifyCode = (params) => dispatch => {
    return axios.post(AUTHEN_URL, null, {params})
        .then(res => {
            dispatch({
            type: VERIFY_CODE,
            payload: res.data.data,
        })
        return res.data
      });
}

</code>```

If this doesn't work. Can you try the async await method?

Hope this helps

Body:
I want to call function this.onLoggin() after this.props.verifyCode(params); already done, how can i do it.
here is myfunction:

onSubmit = (e) => {
        e.preventDefault();
        let params = {
            email: this.props.email,
            codeVerify: this.state.code
        }
        this.props.verifyCode(params);
        this.onLoggin();

    }

onLoggin = () =>{
        if(this.props.isVerify === true){
            const body = {
                username: this.props.user.username,
                password: this.props.user.password
            }
            this.props.loggin(body);
        }
    }

verifyCode come from redux:

const AUTHEN_URL = 'http://localhost:8080/client/user-info-client/regist';

const verifyCode = (params) => dispatch => {
    axios.post(AUTHEN_URL, null, {params})
        .then(res => {
            dispatch({
            type: VERIFY_CODE,
            payload: res.data.data,
        })});
}

export default verifyCode;

here is my reducer:

const initialState = {
        isVerify: false
};

const verifyCode = (state = initialState, action) => {
    switch (action.type){
        case VERIFY_CODE:
            return {
                isVerify: true
            }
        default:
            return state;

    }
}

export default verifyCode;

Body:
Noticed that this.props.verifyCode(params) is an asynchronous function. You have to either use async await method or .then.

Using .then:

this.props.verifyCode(params).then(response => this.onLoggin()).catch(error => error)

Using async await:

onSubmit = async (e) => {
        e.preventDefault();
        let params = {
            email: this.props.email,
            codeVerify: this.state.code
        }
        try{
            await this.props.verifyCode(params);
            this.onLoggin();
        }
        catch(error){
             return error
        }

    }

The axios request

const verifyCode = (params) => dispatch => {
    return axios.post(AUTHEN_URL, null, {params})
        .then(res => {
            dispatch({
            type: VERIFY_CODE,
            payload: res.data.data,
        })
        return res.data
      });
}

If this doesn't work. Can you try the async await method?

Hope this helps


问:
why virtualenv (version 20) is much faster than python3 -m venv
I have tested on my 2015 macbook, virtualenv is 6 times faster.

virtualenv version is 20.0.21

```<code>$ time virtualenv $RANDOM
created virtual environment CPython3.8.3.final.0-64 in 340ms
  creator CPython3Posix(dest=/private/tmp/4997, clear=False, global=False)
  seeder FromAppData(download=False, pip=latest, setuptools=latest, wheel=latest, via=copy, app_data_dir=/Users/noname/Library/Application Support/virtualenv/seed-app-data/v1.0.1)
  activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator

real    0m0.489s
user    0m0.269s
sys     0m0.283s
</code>```

```<code>$ time /usr/local/opt/python@3.8/bin/python3 -m venv $RANDOM

real    0m3.112s
user    0m2.334s
sys     0m0.731s
</code>```

python3.8 is installed via homebrew.

even with --creator venv --always-copy options, virtualenv is faster:

```<code>$ time virtualenv --creator venv --always-copy $RANDOM
created virtual environment CPython3.8.3.final.0-64 in 418ms
  creator Venv(dest=/private/tmp/28878, clear=False, global=False, describe=CPython3Posix)
  seeder FromAppData(download=False, pip=latest, setuptools=latest, wheel=latest, via=copy, app_data_dir=/Users/noname/Library/Application Support/virtualenv/seed-app-data/v1.0.1)
  activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator

real    0m0.554s
user    0m0.316s
sys     0m0.309s
</code>```

why don't they have the same performance?

答: Virtualenv 20.x simply has optimizations and tricks up its sleeve that makes it faster; venv the standard library module doesn't have those, and probably won't get them either.

Body:
I have tested on my 2015 macbook, virtualenv is 6 times faster.

virtualenv version is 20.0.21

$ time virtualenv $RANDOM
created virtual environment CPython3.8.3.final.0-64 in 340ms
  creator CPython3Posix(dest=/private/tmp/4997, clear=False, global=False)
  seeder FromAppData(download=False, pip=latest, setuptools=latest, wheel=latest, via=copy, app_data_dir=/Users/noname/Library/Application Support/virtualenv/seed-app-data/v1.0.1)
  activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator

real    0m0.489s
user    0m0.269s
sys     0m0.283s

$ time /usr/local/opt/python@3.8/bin/python3 -m venv $RANDOM

real    0m3.112s
user    0m2.334s
sys     0m0.731s

python3.8 is installed via homebrew.

even with --creator venv --always-copy options, virtualenv is faster:

$ time virtualenv --creator venv --always-copy $RANDOM
created virtual environment CPython3.8.3.final.0-64 in 418ms
  creator Venv(dest=/private/tmp/28878, clear=False, global=False, describe=CPython3Posix)
  seeder FromAppData(download=False, pip=latest, setuptools=latest, wheel=latest, via=copy, app_data_dir=/Users/noname/Library/Application Support/virtualenv/seed-app-data/v1.0.1)
  activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator

real    0m0.554s
user    0m0.316s
sys     0m0.309s

why don't they have the same performance?


问:
RFlutter_Alert - How to validate and return a TextFormField
I am using rflutter_alert throughout my app and now i need to get a reason for a request being made by the user. So I started with the example on the rflutter_alert page, and have as far as the code below.

I can't get the validation to work and I can't get the value entered to use with my web service.

Not sure if I have a small problem in the code or if I'm doing it all wrong.

Any ideas? Thanks.

```<code>Future<bool> saveRequest({context, int rId}) {
  String _reason = '';
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  TextEditingController reasonController = TextEditingController();

  TextStyle _style = TextStyle(
      fontFamily: 'Montserrat', fontSize: 18.0, fontWeight: FontWeight.normal);

  InputDecoration _textFormFieldDecoration({String hintText, double padding}) =>
      InputDecoration(
        //contentPadding: EdgeInsets.fromLTRB(8.0, 8.0, 8.0, 8.0),
        contentPadding: EdgeInsets.all(padding),
        isDense: true,
        hintText: hintText,
        hintStyle: TextStyle(color: kHintText),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.all(Radius.circular(5)),
        ),
      );

  return Alert(
    context: context,
    title: 'New Request',
    //desc: 'Reason',
    content: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        SizedBox(height: 20.0),
        Text('Reason', textAlign: TextAlign.left, style: _style),
        SizedBox(height: 10.0),
        TextFormField(
          validator: (value) {
            if (value.isEmpty) {
              return "please enter reason";
            }
            return null;
          },
          onSaved: (value) {
            _reason = value;
          },
          decoration: _textFormFieldDecoration(
            hintText: 'reason for request',
            padding: 8.0,
          ),
          controller: reasonController,
        ),
        SizedBox(height: 10.0),
      ],
    ),
    buttons: [
      DialogButton(
        child:
            Text('Save', style: TextStyle(color: Colors.white, fontSize: 20)),
        color: kMainColor,
        onPressed: () async {
          if (_formKey.currentState.validate()) {
            _formKey.currentState.save();
            var saved = await doSaveRequest(pReason: _reason);
            Navigator.pop(context, false);
            if (saved.savedOK) {
              Navigator.of(context).pop();
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => UserRequests(
                    rId: rId,
                  ),
                ),
              );
            } else {
              Navigator.pop(context, false);
            }
          }
        },
      ),
      DialogButton(
        child:
            Text('Cancel', style: TextStyle(color: Colors.white, fontSize: 20)),
        color: kMainColor,
        onPressed: () {
          Navigator.pop(context, false);
        },
      ),
    ],
  ).show();
}
</code>```

答:
You can copy paste run full code below

You can use wrap your content with Form and provide key

code snippet

```<code>content: Form(
        key: _formKey,
        child: Column(
</code>```

working demo

output

```<code>I/flutter (11913): abc
</code>```

full code

```<code>import 'package:flutter/material.dart';
import 'package:rflutter_alert/rflutter_alert.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  Color kMainColor = Colors.blue;
  Color kHintText = Colors.blue;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  Future<bool> saveRequest({context, int rId}) {
    String _reason = '';
    GlobalKey<FormState> _formKey = GlobalKey<FormState>();

    TextEditingController reasonController = TextEditingController();

    TextStyle _style = TextStyle(
        fontFamily: 'Montserrat',
        fontSize: 18.0,
        fontWeight: FontWeight.normal);

    InputDecoration _textFormFieldDecoration(
            {String hintText, double padding}) =>
        InputDecoration(
          //contentPadding: EdgeInsets.fromLTRB(8.0, 8.0, 8.0, 8.0),
          contentPadding: EdgeInsets.all(padding),
          isDense: true,
          hintText: hintText,
          hintStyle: TextStyle(color: kHintText),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.all(Radius.circular(5)),
          ),
        );

    return Alert(
      context: context,
      title: 'New Request',
      //desc: 'Reason',
      content: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            SizedBox(height: 20.0),
            Text('Reason', textAlign: TextAlign.left, style: _style),
            SizedBox(height: 10.0),
            TextFormField(
              validator: (value) {
                if (value.isEmpty) {
                  return "please enter reason";
                }
                return null;
              },
              onSaved: (value) {
                _reason = value;
              },
              decoration: _textFormFieldDecoration(
                hintText: 'reason for request',
                padding: 8.0,
              ),
              controller: reasonController,
            ),
            SizedBox(height: 10.0),
          ],
        ),
      ),
      buttons: [
        DialogButton(
          child:
              Text('Save', style: TextStyle(color: Colors.white, fontSize: 20)),
          color: kMainColor,
          onPressed: () async {
            if (_formKey.currentState.validate()) {
              _formKey.currentState.save();
              print(_reason);

              //var saved = await doSaveRequest(pReason: _reason);
              Navigator.pop(context, false);
              /*if (saved.savedOK) {
                Navigator.of(context).pop();
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => UserRequests(
                      rId: rId,
                    ),
                  ),
                );
              } else {
                Navigator.pop(context, false);
              }*/
            }
          },
        ),
        DialogButton(
          child: Text('Cancel',
              style: TextStyle(color: Colors.white, fontSize: 20)),
          color: kMainColor,
          onPressed: () {
            Navigator.pop(context, false);
          },
        ),
      ],
    ).show();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              child: Text('Basic Alert'),
              onPressed: () => saveRequest(context: context, rId: 123),
            ),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}
</code>```

Body:
I am using rflutter_alert throughout my app and now i need to get a reason for a request being made by the user. So I started with the example on the rflutter_alert page, and have as far as the code below.

I can't get the validation to work and I can't get the value entered to use with my web service.

Not sure if I have a small problem in the code or if I'm doing it all wrong.

Any ideas? Thanks.

Future<bool> saveRequest({context, int rId}) {
  String _reason = '';
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  TextEditingController reasonController = TextEditingController();

  TextStyle _style = TextStyle(
      fontFamily: 'Montserrat', fontSize: 18.0, fontWeight: FontWeight.normal);

  InputDecoration _textFormFieldDecoration({String hintText, double padding}) =>
      InputDecoration(
        //contentPadding: EdgeInsets.fromLTRB(8.0, 8.0, 8.0, 8.0),
        contentPadding: EdgeInsets.all(padding),
        isDense: true,
        hintText: hintText,
        hintStyle: TextStyle(color: kHintText),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.all(Radius.circular(5)),
        ),
      );

  return Alert(
    context: context,
    title: 'New Request',
    //desc: 'Reason',
    content: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        SizedBox(height: 20.0),
        Text('Reason', textAlign: TextAlign.left, style: _style),
        SizedBox(height: 10.0),
        TextFormField(
          validator: (value) {
            if (value.isEmpty) {
              return "please enter reason";
            }
            return null;
          },
          onSaved: (value) {
            _reason = value;
          },
          decoration: _textFormFieldDecoration(
            hintText: 'reason for request',
            padding: 8.0,
          ),
          controller: reasonController,
        ),
        SizedBox(height: 10.0),
      ],
    ),
    buttons: [
      DialogButton(
        child:
            Text('Save', style: TextStyle(color: Colors.white, fontSize: 20)),
        color: kMainColor,
        onPressed: () async {
          if (_formKey.currentState.validate()) {
            _formKey.currentState.save();
            var saved = await doSaveRequest(pReason: _reason);
            Navigator.pop(context, false);
            if (saved.savedOK) {
              Navigator.of(context).pop();
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => UserRequests(
                    rId: rId,
                  ),
                ),
              );
            } else {
              Navigator.pop(context, false);
            }
          }
        },
      ),
      DialogButton(
        child:
            Text('Cancel', style: TextStyle(color: Colors.white, fontSize: 20)),
        color: kMainColor,
        onPressed: () {
          Navigator.pop(context, false);
        },
      ),
    ],
  ).show();
}

Body:
You can copy paste run full code below

You can use wrap your content with Form and provide key

code snippet

content: Form(
        key: _formKey,
        child: Column(

working demo

output

I/flutter (11913): abc

full code

import 'package:flutter/material.dart';
import 'package:rflutter_alert/rflutter_alert.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  Color kMainColor = Colors.blue;
  Color kHintText = Colors.blue;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  Future<bool> saveRequest({context, int rId}) {
    String _reason = '';
    GlobalKey<FormState> _formKey = GlobalKey<FormState>();

    TextEditingController reasonController = TextEditingController();

    TextStyle _style = TextStyle(
        fontFamily: 'Montserrat',
        fontSize: 18.0,
        fontWeight: FontWeight.normal);

    InputDecoration _textFormFieldDecoration(
            {String hintText, double padding}) =>
        InputDecoration(
          //contentPadding: EdgeInsets.fromLTRB(8.0, 8.0, 8.0, 8.0),
          contentPadding: EdgeInsets.all(padding),
          isDense: true,
          hintText: hintText,
          hintStyle: TextStyle(color: kHintText),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.all(Radius.circular(5)),
          ),
        );

    return Alert(
      context: context,
      title: 'New Request',
      //desc: 'Reason',
      content: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            SizedBox(height: 20.0),
            Text('Reason', textAlign: TextAlign.left, style: _style),
            SizedBox(height: 10.0),
            TextFormField(
              validator: (value) {
                if (value.isEmpty) {
                  return "please enter reason";
                }
                return null;
              },
              onSaved: (value) {
                _reason = value;
              },
              decoration: _textFormFieldDecoration(
                hintText: 'reason for request',
                padding: 8.0,
              ),
              controller: reasonController,
            ),
            SizedBox(height: 10.0),
          ],
        ),
      ),
      buttons: [
        DialogButton(
          child:
              Text('Save', style: TextStyle(color: Colors.white, fontSize: 20)),
          color: kMainColor,
          onPressed: () async {
            if (_formKey.currentState.validate()) {
              _formKey.currentState.save();
              print(_reason);

              //var saved = await doSaveRequest(pReason: _reason);
              Navigator.pop(context, false);
              /*if (saved.savedOK) {
                Navigator.of(context).pop();
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => UserRequests(
                      rId: rId,
                    ),
                  ),
                );
              } else {
                Navigator.pop(context, false);
              }*/
            }
          },
        ),
        DialogButton(
          child: Text('Cancel',
              style: TextStyle(color: Colors.white, fontSize: 20)),
          color: kMainColor,
          onPressed: () {
            Navigator.pop(context, false);
          },
        ),
      ],
    ).show();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              child: Text('Basic Alert'),
              onPressed: () => saveRequest(context: context, rId: 123),
            ),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}


问:
How to Create a Python Dictionary after iterating over three Lists for matching words
I need to create a Dictionary after iterating over three LISTs.
For matching sentences (list_sent as KEYs) and list of words (list_wordset as VALUEs) for matching
 keywords (list_keywords). Please see below LISTs and expected output Dictionary with explanation.  Please suggest.

```<code>list_sent = ['one more shock like Covid-19',
             'The number of people suffering acute',
             'people must collectively act now',
             'handling the novel coronavirus outbreak',
              'After a three-week nationwide',
              'strengthening medical quarantine']

list_wordset = [['people','suffering','acute'],
                ['Covid-19','Corona','like'],
                ['people','jersy','country'],
                ['novel', 'coronavirus', 'outbreak']]

list_keywords = ['people', 'Covid-19', 'nationwide','quarantine','handling']
</code>```

'Covid-19' key word is present in list_sent and list_wordset, so they are captured in Dictionary.
'people' key word is present in 2 different items in list_sent and 2 different lists in list_wordset, so they needs to be captured.  Even if single word from the list_wordset is matching with keyword, then also its a match.

Expected Output is:

out_dict =

```<code>{'one more shock like Covid-19': ['Covid-19','Corona','like'],
 'The number of people suffering acute': [['people','suffering','acute'],['people','jersy','country']],
 'people must collectively act now' : [['people','suffering','acute'],['people','jersy','country']]}
</code>```

答:
I am able to use all 3 lists, to create the required output in Dictionary format.  To remove empty Values, used additional step.

```<code>out_dict = {sent: [wordset for wordset in list_wordset if any(key in sent and key in wordset for key in list_keywords)]
 for sent in list_sent}
</code>```

Results:

```<code>{'one more shock like Covid-19': [['Covid-19', 'Corona', 'like']],
 'The number of people suffering acute': [['people', 'suffering', 'acute'],
  ['people', 'jersy', 'country']],
 'people must collectively act now': [['people', 'suffering', 'acute'],
  ['people', 'jersy', 'country']],
 'handling the novel coronavirus outbreak': [],
 'After a three-week nationwide': [],
 'strengthening medical quarantine': []}
</code>```

To remove the Empty List values:

```<code>out_dict = dict( [(k,v) for k,v in out_dict.items() if len(v)>0])
</code>```

Final Results:

```<code>{'one more shock like Covid-19': [['Covid-19', 'Corona', 'like']],
 'The number of people suffering acute': [['people', 'suffering', 'acute'],
  ['people', 'jersy', 'country']],
 'people must collectively act now': [['people', 'suffering', 'acute'],
  ['people', 'jersy', 'country']]}
</code>```

Body:
I need to create a Dictionary after iterating over three LISTs.
For matching sentences (list_sent as KEYs) and list of words (list_wordset as VALUEs) for matching
 keywords (list_keywords). Please see below LISTs and expected output Dictionary with explanation.  Please suggest.

list_sent = ['one more shock like Covid-19',
             'The number of people suffering acute',
             'people must collectively act now',
             'handling the novel coronavirus outbreak',
              'After a three-week nationwide',
              'strengthening medical quarantine']

list_wordset = [['people','suffering','acute'],
                ['Covid-19','Corona','like'],
                ['people','jersy','country'],
                ['novel', 'coronavirus', 'outbreak']]

list_keywords = ['people', 'Covid-19', 'nationwide','quarantine','handling']

'Covid-19' key word is present in list_sent and list_wordset, so they are captured in Dictionary.
'people' key word is present in 2 different items in list_sent and 2 different lists in list_wordset, so they needs to be captured.  Even if single word from the list_wordset is matching with keyword, then also its a match.

Expected Output is:

out_dict =

{'one more shock like Covid-19': ['Covid-19','Corona','like'],
 'The number of people suffering acute': [['people','suffering','acute'],['people','jersy','country']],
 'people must collectively act now' : [['people','suffering','acute'],['people','jersy','country']]}

Body:
I am able to use all 3 lists, to create the required output in Dictionary format.  To remove empty Values, used additional step.

out_dict = {sent: [wordset for wordset in list_wordset if any(key in sent and key in wordset for key in list_keywords)]
 for sent in list_sent}

Results:

{'one more shock like Covid-19': [['Covid-19', 'Corona', 'like']],
 'The number of people suffering acute': [['people', 'suffering', 'acute'],
  ['people', 'jersy', 'country']],
 'people must collectively act now': [['people', 'suffering', 'acute'],
  ['people', 'jersy', 'country']],
 'handling the novel coronavirus outbreak': [],
 'After a three-week nationwide': [],
 'strengthening medical quarantine': []}

To remove the Empty List values:

out_dict = dict( [(k,v) for k,v in out_dict.items() if len(v)>0])

Final Results:

{'one more shock like Covid-19': [['Covid-19', 'Corona', 'like']],
 'The number of people suffering acute': [['people', 'suffering', 'acute'],
  ['people', 'jersy', 'country']],
 'people must collectively act now': [['people', 'suffering', 'acute'],
  ['people', 'jersy', 'country']]}


问:
EventHandle in ReactJS for a particular element in a list
I have component, where I make an API call and I get a response as an array of objects. Then I'm mapping through it and printing the data as rows and columns as follow:

```<code>{
  this.state.listUser.map((list, index) => {
    return (
      <tbody key={index}>
        <tr>
          <th>{list.first_name}</th>
          <th>{list.last_name}</th>
          <th>
            <img id={index} src={list.avatar} onClick={this.showEmailAddress} />
          </th>
          {this.state.showEmail && <th>{list.email}</th>}
        </tr>
      </tbody>
    );
  });
}
</code>```

And onClicking the Img tag, I wanted to show the email address of that particular user. I'm not able to find how to do it for that particular item in the list. Now it show the email for all the items of the list. I want to write a showEmailAddress handler which will show the email for that particular item instead of all. Thanks in advance.

Here's my component:

```<code>import React from "react";
import axios from "axios";

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      listUser: "",
      showEmail: "",
    };
  }

  showEmailAddress(email) {
    this.setState({ showEmail: email });
  }

  componentDidMount() {
    axios
      .get("https://reqres.in/api/users?page=2")
      .then((res) => {
        console.log(res.data.data);
        this.setState({ listUser: res.data.data });
      })
      .catch((err) => {
        console.log(err);
      });
  }

  render() {
    if (!this.state.listUser) {
      return <div>...loading</div>;
    }

    return (
      <div>
        <thead>
          <tr>
            <th>first_name</th>
            <th>last_name</th>
            <th>avatar</th>
          </tr>
        </thead>
        {this.state.listUser.map((list, index) => {
          return (
            <tbody key={index}>
              <tr>
                <th>{list.first_name}</th>
                <th>{list.last_name}</th>
                <th>
                  <img
                    alt="test"
                    id={index}
                    src={list.avatar}
                    onClick={this.showEmailAddress.bind(this, list.email)}
                  />
                </th>
                <th>{this.state.showEmail}</th>
              </tr>
            </tbody>
          );
        })}
      </div>
    );
  }
}

export default App;
</code>```

答:
You could do this:
Here's a working link: https://codesandbox.io/s/unisis-test-8fejo?file=/src/App.js:0-1605

The issue was you were showing the email against each of the items. It should have been shown conditionally though against only that item which was clicked.

So, created an array showList: [] which would contain the items that need to be shown and put a condition
{this.state.showList.includes(list.id) && list.email} where it needs to be shown.

```<code>import React from "react";
import axios from "axios";

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      listUser: "",
      showEmail: "",
      showList: []
    };
  }

  showEmailAddress(item) {
    debugger;
    this.setState({ showEmail: item.email });
    var list = this.state.showList;
    list.push(item.id);
    this.setState({showList: list})
  }

  componentDidMount() {
    axios
      .get("https://reqres.in/api/users?page=2")
      .then(res => {
        console.log(res.data.data);
        this.setState({ listUser: res.data.data });
      })
      .catch(err => {
        console.log(err);
      });
  }

  render() {
    if (!this.state.listUser) {
      return <div>...loading</div>;
    }

    return (
      <div>
        <thead>
          <tr>
            <th>first_name</th>
            <th>last_name</th>
            <th>avatar</th>
          </tr>
        </thead>
        {this.state.listUser.map((list, index) => {
          return (
            <tbody key={index}>
              <tr>
                <th>{list.first_name}</th>
                <th>{list.last_name}</th>
                <th>
                  <img
                    alt="test"
                    id={index}
                    src={list.avatar}
                    onClick={this.showEmailAddress.bind(this, list)}
                  />
                  <span>{this.state.showList.includes(list.id) && list.email}</span>
                </th>
              </tr>
            </tbody>
          );
        })}
      </div>
    );
  }
}

export default App;
</code>```

Body:
I have component, where I make an API call and I get a response as an array of objects. Then I'm mapping through it and printing the data as rows and columns as follow:

{
  this.state.listUser.map((list, index) => {
    return (

          {list.first_name}
          {list.last_name}

          {this.state.showEmail && {list.email}	}

    );
  });
}

And onClicking the Img tag, I wanted to show the email address of that particular user. I'm not able to find how to do it for that particular item in the list. Now it show the email for all the items of the list. I want to write a showEmailAddress handler which will show the email for that particular item instead of all. Thanks in advance.

Here's my component:

import React from "react";
import axios from "axios";

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      listUser: "",
      showEmail: "",
    };
  }

  showEmailAddress(email) {
    this.setState({ showEmail: email });
  }

  componentDidMount() {
    axios
      .get("https://reqres.in/api/users?page=2")
      .then((res) => {
        console.log(res.data.data);
        this.setState({ listUser: res.data.data });
      })
      .catch((err) => {
        console.log(err);
      });
  }

  render() {
    if (!this.state.listUser) {
      return
...loading
;
    }

    return (

            first_name
            last_name
            avatar

        {this.state.listUser.map((list, index) => {
          return (

                {list.first_name}
                {list.last_name}

                {this.state.showEmail}

          );
        })}

    );
  }
}

export default App;

Body:
You could do this:
Here's a working link: https://codesandbox.io/s/unisis-test-8fejo?file=/src/App.js:0-1605

The issue was you were showing the email against each of the items. It should have been shown conditionally though against only that item which was clicked.

So, created an array showList: [] which would contain the items that need to be shown and put a condition
{this.state.showList.includes(list.id) && list.email} where it needs to be shown.

import React from "react";
import axios from "axios";

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      listUser: "",
      showEmail: "",
      showList: []
    };
  }

  showEmailAddress(item) {
    debugger;
    this.setState({ showEmail: item.email });
    var list = this.state.showList;
    list.push(item.id);
    this.setState({showList: list})
  }

  componentDidMount() {
    axios
      .get("https://reqres.in/api/users?page=2")
      .then(res => {
        console.log(res.data.data);
        this.setState({ listUser: res.data.data });
      })
      .catch(err => {
        console.log(err);
      });
  }

  render() {
    if (!this.state.listUser) {
      return <div>...loading</div>;
    }

    return (
      <div>
        <thead>
          <tr>
            <th>first_name</th>
            <th>last_name</th>
            <th>avatar</th>
          </tr>
        </thead>
        {this.state.listUser.map((list, index) => {
          return (
            <tbody key={index}>
              <tr>
                <th>{list.first_name}</th>
                <th>{list.last_name}</th>
                <th>
                  <img
                    alt="test"
                    id={index}
                    src={list.avatar}
                    onClick={this.showEmailAddress.bind(this, list)}
                  />
                  <span>{this.state.showList.includes(list.id) && list.email}</span>
                </th>
              </tr>
            </tbody>
          );
        })}
      </div>
    );
  }
}

export default App;


问:
setResult does not work when BACK button pressed
I am trying to setResult after the BACK button was pressed. I call in onDestroy

```<code>Intent data = new Intent();
setResult(RESULT_OK, data)
</code>```

But when it comes to

```<code>onActivityResult(int requestCode, int resultCode, Intent data)
</code>```

the resultCode is 0 (RESULT_CANCELED) and data is 'null'.

So, how can I pass result from activity terminated by BACK button?

答:
You need to overide the onBackPressed() method and set the result before the call to superclass, i.e

```<code>@Override
public void onBackPressed() {
    Bundle bundle = new Bundle();
    bundle.putString(FIELD_A, mA.getText().toString());

    Intent mIntent = new Intent();
    mIntent.putExtras(bundle);
    setResult(RESULT_OK, mIntent);
    super.onBackPressed();
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to setResult after the BACK button was pressed. I call in onDestroy

Intent data = new Intent();
setResult(RESULT_OK, data)

But when it comes to

onActivityResult(int requestCode, int resultCode, Intent data)

the resultCode is 0 (RESULT_CANCELED) and data is 'null'.

So, how can I pass result from activity terminated by BACK button?

Body:
You need to overide the onBackPressed() method and set the result before the call to superclass, i.e

@Override
public void onBackPressed() {
    Bundle bundle = new Bundle();
    bundle.putString(FIELD_A, mA.getText().toString());

    Intent mIntent = new Intent();
    mIntent.putExtras(bundle);
    setResult(RESULT_OK, mIntent);
    super.onBackPressed();
}


问:
RuntimeError: Expected object of device type cuda but got device type cpu for argument #3 'index' in call to _th_index_select site:stackoverflow.com
I am using the bert on the SMILE dataset. I have written following code can you guide me where I am getting wrong.
I have written training code which is evaluating correctly but the when I try to run evaluate code for validation it is giving error. I tried to pass the parameters directly to cuda. still I am facing the issue

```<code>'''

def evaluate(dataloader_val):

  print("in evaluate")
  model.eval()

  loss_val_total = 0
  predictions, true_value = [],[]

  for batch in dataloader_val:

    print("in for loop of dataloader")
    barch = tuple(b.to(device) for b in batch)

    inputs = {
               'input_ids':  batch[0],
                'attention_mask': batch[1],
                 'labels' : batch[2],
    }

    with torch.no_grad():
      outputs = model(**inputs)

    loss = outputs[0]
    logits = outputs[1]
    loss_val_total += loss.item()

    print("before logit")

    logits = logits.to(device)
    print("in the for batch evaluate: ",logits)
    label_ids = inputs['labels'].to(device)
    true_vals.append(label_ids)

  loss_val_avg = loss_val_total/len(dataloader_val)

  predictions = np.concatenate(predictions, axis = 0)
  true_vals = np.concatenate(true_vals,axis = 0)

  return loss_val_avg, predictions, true_vals
'''
</code>```

and another function is

```<code>'''
for epoch in tqdm(range(1, epochs+1)):
  model.train()

  loss_train_total = 0

  progress_bar = tqdm(dataloader_train,
                      desc = 'Epoch {:1d}'.format(epoch),
                      leave = False,
                      disable = False)
  for batch in progress_bar:

    model.zero_grad()

    batch = tuple(b.to(device) for b in batch)

    inputs = {

            'input_ids'      : batch[0],
            'attention_mask' : batch[1],
            'labels'         : batch[2]
    }

    outputs = model(**inputs)

    loss = outputs[0]
    loss_train_total += loss.item()
    loss.backward()

    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)

    optimizer.step()
    scheduler.step()

    progress_bar.set_postfix({'training_loss' : '{:.3f}'.format(loss.item()/len(batch))})

  torch.save(model.state_dict(), f'/content/drive/My Drive/Bert/Coursera/SMILE/Bert_ft_epoch{epoch}.model')

  tqdm.write(f'\n Epoch {epoch}')

  loss_train_avg = loss_train_total / len(dataloader_train)

  tqdm.write(f'Training Loss: {loss_train_avg}')

  val_loss, predictions, true_vals = evaluate(dataloader_val)
  val_f1 = f1_score_func(predictions, true_vals)
  tqdm.write(f'Validation loss : {val_loss}')
  tqdm.write(f'F1 score(weighted): {val_f1}')
'''
</code>```

答:
You have a typo in your evaluation function:

barch = tuple(b.to(device) for b in batch)
```

You assign the gpu data to barch instead of batch.

Body:
I am using the bert on the SMILE dataset. I have written following code can you guide me where I am getting wrong.
I have written training code which is evaluating correctly but the when I try to run evaluate code for validation it is giving error. I tried to pass the parameters directly to cuda. still I am facing the issue

'''

def evaluate(dataloader_val):

  print("in evaluate")
  model.eval()

  loss_val_total = 0
  predictions, true_value = [],[]

  for batch in dataloader_val:

    print("in for loop of dataloader")
    barch = tuple(b.to(device) for b in batch)

    inputs = {
               'input_ids':  batch[0],
                'attention_mask': batch[1],
                 'labels' : batch[2],
    }

    with torch.no_grad():
      outputs = model(**inputs)

    loss = outputs[0]
    logits = outputs[1]
    loss_val_total += loss.item()

    print("before logit")

    logits = logits.to(device)
    print("in the for batch evaluate: ",logits)
    label_ids = inputs['labels'].to(device)
    true_vals.append(label_ids)

  loss_val_avg = loss_val_total/len(dataloader_val)

  predictions = np.concatenate(predictions, axis = 0)
  true_vals = np.concatenate(true_vals,axis = 0)

  return loss_val_avg, predictions, true_vals
'''

and another function is

'''
for epoch in tqdm(range(1, epochs+1)):
  model.train()

  loss_train_total = 0

  progress_bar = tqdm(dataloader_train,
                      desc = 'Epoch {:1d}'.format(epoch),
                      leave = False,
                      disable = False)
  for batch in progress_bar:

    model.zero_grad()

    batch = tuple(b.to(device) for b in batch)

    inputs = {

            'input_ids'      : batch[0],
            'attention_mask' : batch[1],
            'labels'         : batch[2]
    }

    outputs = model(**inputs)

    loss = outputs[0]
    loss_train_total += loss.item()
    loss.backward()

    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)

    optimizer.step()
    scheduler.step()

    progress_bar.set_postfix({'training_loss' : '{:.3f}'.format(loss.item()/len(batch))})

  torch.save(model.state_dict(), f'/content/drive/My Drive/Bert/Coursera/SMILE/Bert_ft_epoch{epoch}.model')

  tqdm.write(f'\n Epoch {epoch}')

  loss_train_avg = loss_train_total / len(dataloader_train)

  tqdm.write(f'Training Loss: {loss_train_avg}')

  val_loss, predictions, true_vals = evaluate(dataloader_val)
  val_f1 = f1_score_func(predictions, true_vals)
  tqdm.write(f'Validation loss : {val_loss}')
  tqdm.write(f'F1 score(weighted): {val_f1}')
'''

Body:
You have a typo in your evaluation function:

barch = tuple(b.to(device) for b in batch)

You assign the gpu data to barch instead of batch.


问:
Unexpected difference between char* and string with std::getenv
I have code that looks something like this:

```<code>#include <cstdlib>
#include <iostream>
#include <string>

std::string string_from_env(std::string var) {
  std::string out = std::getenv(var.c_str());
  return out;
}

int main() {
  const char* x1 = string_from_env("TEST_HOST").c_str();
  const char* x2 = string_from_env("TEST_USER").c_str();
  const char* x3 = string_from_env("TEST_NAME").c_str();

  std::cout << x1 << " " << x2 << " " << x3 << std::endl;

  const std::string y1 = string_from_env("TEST_HOST");
  const std::string y2 = string_from_env("TEST_USER");
  const std::string y3 = string_from_env("TEST_NAME");

  std::cout << y1 << " " << y2 << " " << y3 << std::endl;
}
</code>```

If I run

```<code>export TEST_HOST=host
export TEST_USER=user
export TEST_NAME=name
g++ --std=c++2a test.cc  # version 9.3.0
./a.out
</code>```

Then the output is

```<code>name name name
host user name
</code>```

Why does the char* version result in x1,x2,x3 all printing name, while the std::string version works as expected?

Is there a way I can modify the string_from_env function so that the same code prints host user name instead of name name name?

答:
The pointer returned by std::string::c_str points to memory owned by the string object.  When the string is destroyed (or even mutated in certain ways), that pointer becomes invalid.

Since the temporary string objects returned by string_from_env in your first three calls aren't immediately bound to references, they are destroyed at the end of the full expression containing the function call.  That means that x1, x2, and x3 all become invalid immediately after being created.  Attempting to read from them will result in undefined behavior.

Body:
I have code that looks something like this:

#include <cstdlib>
#include <iostream>
#include <string>

std::string string_from_env(std::string var) {
  std::string out = std::getenv(var.c_str());
  return out;
}

int main() {
  const char* x1 = string_from_env("TEST_HOST").c_str();
  const char* x2 = string_from_env("TEST_USER").c_str();
  const char* x3 = string_from_env("TEST_NAME").c_str();

  std::cout << x1 << " " << x2 << " " << x3 << std::endl;

  const std::string y1 = string_from_env("TEST_HOST");
  const std::string y2 = string_from_env("TEST_USER");
  const std::string y3 = string_from_env("TEST_NAME");

  std::cout << y1 << " " << y2 << " " << y3 << std::endl;
}

If I run

export TEST_HOST=host
export TEST_USER=user
export TEST_NAME=name
g++ --std=c++2a test.cc  # version 9.3.0
./a.out

Then the output is

name name name
host user name

Why does the char* version result in x1,x2,x3 all printing name, while the std::string version works as expected?

Is there a way I can modify the string_from_env function so that the same code prints host user name instead of name name name?


问:
what is wrong in my solution? help me to impove it or any other solution?
A classroom has several students, half of whom are boys and half of whom are girls. You need to arrange all of them in a line for the morning assembly such that the following conditions are satisfied:

The students must be in the order of non-decreasing height.
Two boys or two girls must not be adjacent to each other.
You have been given the heights of the boys in the array and the heights of the girls in the array. Find out whether you can arrange them in an order which satisfies the given conditions. Print "YES" if it is possible, or "NO" if it is not.
This one is mine but I am getting the wrong answer in 3 testcases.
here, a is the array of boys height and b is the array of girls.

```<code>a=sorted(a)
b=sorted(b)
i=0
n=len(a)
j=0
x=""

while i<n and j<n:
    if a[i]<b[j]:
        x+="b"
        i+=1
    elif a[i]==b[j]:
        if len(x)==0:
            x+="b"
            i+=1
        elif x[-1]=="b":
            x+="g"
            j+=1
        else:
            x+="b"
            i+=1

    else:
        x+="g"
        j+=1

while i<n:
    x+="b"
    i+=1
while j<n:
    x+="g"
    j+=1

p=re.findall(r"[g]{2,}(?=[b]{2})",x)
q=re.findall(r"[b]{2,}(?=[g]{2})",x)
if q or p:
    return "NO"
else:
    return "YES"
</code>```

答:
This is mine, it's failing only for 1 test case where

```<code>a = [32, 2]
b = [28, 37]
</code>```

Solution:

```<code>function arrangeStudents(a, b) {
    const result = []

    let i = 0;
    let j = 0;

    while (i < a.length && j < b.length) {
        if (a[i] < b[j]) {
            if (i > 0 && j > 0 && a[i - 1] !== b[j - 1] && result[result.length - 1] == a[i - 1]) {
                return 'NO'
            }else if (j == 0 && i > 0 && result[result.length - 1] == a[i - 1]){
                return 'NO'
            }else {
                result.push(a[i])
            }
            i++
        }else if(a[i] > b[j]) {
            if (i > 0 && j > 0 && a[i - 1] !== b[j - 1] && result[result.length - 1] == b[j - 1]) {
                return 'NO'
            }else if (i == 0 && j > 0 && result[result.length - 1] == b[j - 1]){
                return 'NO'
            }else {
                result.push(b[j])
            }

            j++;
        }else {
            if (i > 0 && result[result.length - 1] == a[i -1]) {
                result.push(b[j], a[i])
            }else {
                result.push(a[i], b[j])
            }
            i++
            j++
        }
    }
    return 'YES'

}
</code>```

Body:
A classroom has several students, half of whom are boys and half of whom are girls. You need to arrange all of them in a line for the morning assembly such that the following conditions are satisfied:

The students must be in the order of non-decreasing height.
Two boys or two girls must not be adjacent to each other.
You have been given the heights of the boys in the array and the heights of the girls in the array. Find out whether you can arrange them in an order which satisfies the given conditions. Print "YES" if it is possible, or "NO" if it is not.
This one is mine but I am getting the wrong answer in 3 testcases.
here, a is the array of boys height and b is the array of girls.

a=sorted(a)
b=sorted(b)
i=0
n=len(a)
j=0
x=""

while i<n and j<n:
    if a[i]<b[j]:
        x+="b"
        i+=1
    elif a[i]==b[j]:
        if len(x)==0:
            x+="b"
            i+=1
        elif x[-1]=="b":
            x+="g"
            j+=1
        else:
            x+="b"
            i+=1

    else:
        x+="g"
        j+=1

while i<n:
    x+="b"
    i+=1
while j<n:
    x+="g"
    j+=1

p=re.findall(r"[g]{2,}(?=[b]{2})",x)
q=re.findall(r"[b]{2,}(?=[g]{2})",x)
if q or p:
    return "NO"
else:
    return "YES"

Body:
This is mine, it's failing only for 1 test case where

a = [32, 2]
b = [28, 37]

Solution:

function arrangeStudents(a, b) {
    const result = []

    let i = 0;
    let j = 0;

    while (i < a.length && j < b.length) {
        if (a[i] < b[j]) {
            if (i > 0 && j > 0 && a[i - 1] !== b[j - 1] && result[result.length - 1] == a[i - 1]) {
                return 'NO'
            }else if (j == 0 && i > 0 && result[result.length - 1] == a[i - 1]){
                return 'NO'
            }else {
                result.push(a[i])
            }
            i++
        }else if(a[i] > b[j]) {
            if (i > 0 && j > 0 && a[i - 1] !== b[j - 1] && result[result.length - 1] == b[j - 1]) {
                return 'NO'
            }else if (i == 0 && j > 0 && result[result.length - 1] == b[j - 1]){
                return 'NO'
            }else {
                result.push(b[j])
            }

            j++;
        }else {
            if (i > 0 && result[result.length - 1] == a[i -1]) {
                result.push(b[j], a[i])
            }else {
                result.push(a[i], b[j])
            }
            i++
            j++
        }
    }
    return 'YES'

}


答:
consider this line

```<code>const char* x1 = string_from_env("TEST_HOST").c_str();
</code>```

You do not store the result of calling string_from_env("TEST_HOST"), so the temporary string it returns will be destroyed at the end of the expression. So x1 will point to the inner buffer of an already destroyed string. Your code has undefined behavior.

The reason x1, x2 and x3 all point to the same string has to do with small string optimization which is an implementation detail of std::string

Title: Unexpected difference between char* and string with std::getenv

Body:
consider this line

const char* x1 = string_from_env("TEST_HOST").c_str();

You do not store the result of calling string_from_env("TEST_HOST"), so the temporary string it returns will be destroyed at the end of the expression. So x1 will point to the inner buffer of an already destroyed string. Your code has undefined behavior.

The reason x1, x2 and x3 all point to the same string has to do with small string optimization which is an implementation detail of std::string


答:
verifyCode() function return a promise so you can catch the promise and then after finishing function you can call this.onLoggin().</p>

```<code> onSubmit = (e) => {
            e.preventDefault();
            let params = {
                email: this.props.email,
                codeVerify: this.state.code
            }
            const data = this.props.verifyCode(params);
            data.then(result => {
               this.onLoggin();
            }).catch(error => {
                console.log(error);
            });
        }
</code>```

Title: Call a function after previous function is complete reactjs

Body:
I want to call function this.onLoggin() after this.props.verifyCode(params); already done, how can i do it.
here is myfunction:

onSubmit = (e) => {
        e.preventDefault();
        let params = {
            email: this.props.email,
            codeVerify: this.state.code
        }
        this.props.verifyCode(params);
        this.onLoggin();

    }

onLoggin = () =>{
        if(this.props.isVerify === true){
            const body = {
                username: this.props.user.username,
                password: this.props.user.password
            }
            this.props.loggin(body);
        }
    }

verifyCode come from redux:

const AUTHEN_URL = 'http://localhost:8080/client/user-info-client/regist';

const verifyCode = (params) => dispatch => {
    axios.post(AUTHEN_URL, null, {params})
        .then(res => {
            dispatch({
            type: VERIFY_CODE,
            payload: res.data.data,
        })});
}

export default verifyCode;

here is my reducer:

const initialState = {
        isVerify: false
};

const verifyCode = (state = initialState, action) => {
    switch (action.type){
        case VERIFY_CODE:
            return {
                isVerify: true
            }
        default:
            return state;

    }
}

export default verifyCode;

Body:
verifyCode() function return a promise so you can catch the promise and then after finishing function you can call this.onLoggin().

 onSubmit = (e) => {
            e.preventDefault();
            let params = {
                email: this.props.email,
                codeVerify: this.state.code
            }
            const data = this.props.verifyCode(params);
            data.then(result => {
               this.onLoggin();
            }).catch(error => {
                console.log(error);
            });
        }


问:
Getting flake8 returned a non none zero code : 1 in docker
I was following this article.
https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/#production-dockerfile

In the Production Dockerfile section, the Dockerfile.prod file has these lines.

```<code># lint
RUN pip install --upgrade pip
RUN pip install flake8
COPY . /usr/src/app/
RUN flake8 --ignore=E501,F401 .
</code>```

When I run the below command,

```<code>docker-compose -f docker-compose.prod.yml up -d --build
</code>```

I'm getting the below error.

```<code>ERROR: Service 'web' failed to build: The command '/bin/sh -c flake8 --ignore=E501,F401' returned a non-zero code: 1
</code>```

I'm not much aware of flake8, When I commented the 'RUN flake8 --ignore=E501,F401 .' line from the Dockerfile.prod file everything worked.

Can anyone please tell me why I'm facing this issue and tell me a fix instead of removing that line from the Dockerfile. I'm not much aware of flak8 and I'm quite new to Docker too and your help will be much appreciated :)

Thanks.

答:
I had the same problem and user13641454s solution worked great. If you are still getting the same error I suggest you run flake8 from the terminal to see the actual errors:

```<code>install flake8
flake8 --ignore=E501,F401 ./hello_django
</code>```

It's likely something trivial like an extra line or something in your code.

Body:
I was following this article.
https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/#production-dockerfile

In the Production Dockerfile section, the Dockerfile.prod file has these lines.

# lint
RUN pip install --upgrade pip
RUN pip install flake8
COPY . /usr/src/app/
RUN flake8 --ignore=E501,F401 .

When I run the below command,

docker-compose -f docker-compose.prod.yml up -d --build

I'm getting the below error.

ERROR: Service 'web' failed to build: The command '/bin/sh -c flake8 --ignore=E501,F401' returned a non-zero code: 1

I'm not much aware of flake8, When I commented the 'RUN flake8 --ignore=E501,F401 .' line from the Dockerfile.prod file everything worked.

Can anyone please tell me why I'm facing this issue and tell me a fix instead of removing that line from the Dockerfile. I'm not much aware of flak8 and I'm quite new to Docker too and your help will be much appreciated :)

Thanks.

Body:
I had the same problem and user13641454s solution worked great. If you are still getting the same error I suggest you run flake8 from the terminal to see the actual errors:

install flake8
flake8 --ignore=E501,F401 ./hello_django

It's likely something trivial like an extra line or something in your code.


问:
Lookup a company by either name or ticker in a Microsoft Access form
I can't get my Microsoft Access form to match the Company Name to the Company Ticker. If I select a company from my combo box, the ticker does NOT correspond to the company's actual ticker. For example, when I select "Altria Group" the ticker should be "MO", but I'm getting the ticker "cr" which doesn't correspond to the company selected.

Combo box code.

```<code>SELECT tblCompanies.CompanyName
FROM tblCompanies
ORDER BY tblCompanies.CompanyName;
</code>```

See my table of Companies and my form below.

答:
The way that I normally do this is to use two combo boxes in the form's header for navigation - one to show the company name, and one to show the company code. Each of these are unbound, column count set to 2, and the first column width set to 0, so it is not shown, and the RowSource would look like:

```<code>SELECT CompanyID, CompanyName
FROM tblCompanies
ORDER BY CompanyName
</code>```

Then, in the AfterUpdate event:

```<code>Private Sub cboCompanyNameSearch_AfterUpdate()
    Me.RecordsetClone.FindFirst "CompanyID=" & Me!cboCompanyNameSearch
    Me.Bookmark = Me.RecordsetClone.Bookmark
End Sub
</code>```

In the body of the form, you would have text boxes to actually show the company name and other description, so that this information can be edited if required.

Regards,

Body:
I can't get my Microsoft Access form to match the Company Name to the Company Ticker. If I select a company from my combo box, the ticker does NOT correspond to the company's actual ticker. For example, when I select "Altria Group" the ticker should be "MO", but I'm getting the ticker "cr" which doesn't correspond to the company selected.

Combo box code.

SELECT tblCompanies.CompanyName
FROM tblCompanies
ORDER BY tblCompanies.CompanyName;

See my table of Companies and my form below.

Body:
The way that I normally do this is to use two combo boxes in the form's header for navigation - one to show the company name, and one to show the company code. Each of these are unbound, column count set to 2, and the first column width set to 0, so it is not shown, and the RowSource would look like:

SELECT CompanyID, CompanyName
FROM tblCompanies
ORDER BY CompanyName

Then, in the AfterUpdate event:

Private Sub cboCompanyNameSearch_AfterUpdate()
    Me.RecordsetClone.FindFirst "CompanyID=" & Me!cboCompanyNameSearch
    Me.Bookmark = Me.RecordsetClone.Bookmark
End Sub

In the body of the form, you would have text boxes to actually show the company name and other description, so that this information can be edited if required.

Regards,


问:
Notification is coming sometimes and sometimes not coming when the app is in foreground using firebase notifications in Flutter for android
I am using firebase messaging as firebase notifications plugin in flutter to send and receive notifications. But when I trigger the notification from one phone to other,it triggers but notification is not being fetched in other phone when app is in background. And OnMessage does not receive any notification on other phone I am not able to understand why it is happening sometime and not everytime
I here by put my notifications code here for you to understand how I had done this</p>

```<code>import 'dart:convert';
import 'dart:io';
import 'package:device_info/device_info.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:mangoo/ui/Calls/VideoCall/calls.dart';
import 'package:mangoo/ui/Calls/VoiceCall/voice_call.dart';

class FirebaseNotifications {
  FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

//  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
  BuildContext context;

  void setUpFirebase(BuildContext context) {
    print("in Firebase Setup");
//    _firebaseMessaging = FirebaseMessaging();
    this.context = context;
//    flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
//    firebaseCloudMessaging_Listeners();
    initNotification();
  }

  initNotification() {
    print("initNotification ")

    _firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        print('on messagemessage ${message}');
        if (message.containsKey('data')) {
          String channel_name = message['data']['channel_name'];
          String phoneNumber = message['data']['phone_number'];
          String screen_id = message['data']['screen_id'];
          if (screen_id == "0") {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => CallPage(
                  channelName: channel_name,
                  phoneNumber: phoneNumber,
                ),
              ),
            );
          } else if (screen_id == "1") {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => VoiceCallPage(
                  channelName: channel_name,
                  phoneNumber: phoneNumber,
                ),
              ),
            );
          }
        }

        // initialise the plugin. app_icon needs to be a added as a drawable resource to the Android head project
//        displayNotification(message);
//        Navigator.push(
//            context, MaterialPageRoute(builder: (context) => CallPage()));
        // _showItemDialog(message);
      },
      onBackgroundMessage: myBackgroundMessageHandler,
//        print('on backgroundmessage ${message}');
//      },
      onResume: (Map<String, dynamic> message) async {
        print('on messageResume ${message}');
//        displayNotification(message);
      },
      onLaunch: (Map<String, dynamic> message) async {
        print('on messageLaunch ${message}');
//        displayNotification(message);
      },
    );
  }

  Widget ShowDialog(String channelName, String phoneNumber) {
    return Container(
        width: MediaQuery.of(context).size.width / 2,
        height: MediaQuery.of(context).size.height / 4,
        child: Column(
          children: <Widget>[
            Container(
                color: Colors.yellowAccent,
                width: MediaQuery.of(context).size.width,
                height: 50,
                child: Text("Incoming Video call")),
            SizedBox(
              height: 5.0,
            ),
            Container(
              child: Row(
                children: <Widget>[
                  RaisedButton(
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => CallPage(
                            channelName: channelName,
                            phoneNumber: phoneNumber,
                          ),
                        ),
                      );
                    },
//                  textColor: Colors.black,
                    child: Text(
                      "ACCEPT",
                      style: TextStyle(color: Colors.black, fontSize: 12),
                    ),
                  ),
                  VerticalDivider(
                    width: 3,
                  ),
                  RaisedButton(
                    onPressed: () {},
                    color: Colors.green,
                    child: Text(
                      "REJECT",
                      style: TextStyle(color: Colors.black, fontSize: 12),
                    ),
                  )
                ],
              ),
            )
          ],
        ));
  }
}
</code>```

答:
I had a similar problem where the notifications were delivered sometimes and I found an easy work around to that just define your myBackgroundMessageHandler as:

```<code>Future<void> myBackgroundMessageHandler(Map<String, dynamic> message) async {
      final prefs = await SharedPreferences.getInstance();
      // SharedPreferences could have been modified in the UI isolate, so we have to fetch it from the host platform.
      await prefs.reload();
}
</code>```

You can also go through this blog which explains how to setup firebase messaging on Flutter https://medium.com/@sylvainduch/firebase-messaging-catch-them-all-3f9c594734d7

Body:
I am using firebase messaging as firebase notifications plugin in flutter to send and receive notifications. But when I trigger the notification from one phone to other,it triggers but notification is not being fetched in other phone when app is in background. And OnMessage does not receive any notification on other phone I am not able to understand why it is happening sometime and not everytime
I here by put my notifications code here for you to understand how I had done this

import 'dart:convert';
import 'dart:io';
import 'package:device_info/device_info.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:mangoo/ui/Calls/VideoCall/calls.dart';
import 'package:mangoo/ui/Calls/VoiceCall/voice_call.dart';

class FirebaseNotifications {
  FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

//  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
  BuildContext context;

  void setUpFirebase(BuildContext context) {
    print("in Firebase Setup");
//    _firebaseMessaging = FirebaseMessaging();
    this.context = context;
//    flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
//    firebaseCloudMessaging_Listeners();
    initNotification();
  }

  initNotification() {
    print("initNotification ")

    _firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        print('on messagemessage ${message}');
        if (message.containsKey('data')) {
          String channel_name = message['data']['channel_name'];
          String phoneNumber = message['data']['phone_number'];
          String screen_id = message['data']['screen_id'];
          if (screen_id == "0") {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => CallPage(
                  channelName: channel_name,
                  phoneNumber: phoneNumber,
                ),
              ),
            );
          } else if (screen_id == "1") {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => VoiceCallPage(
                  channelName: channel_name,
                  phoneNumber: phoneNumber,
                ),
              ),
            );
          }
        }

        // initialise the plugin. app_icon needs to be a added as a drawable resource to the Android head project
//        displayNotification(message);
//        Navigator.push(
//            context, MaterialPageRoute(builder: (context) => CallPage()));
        // _showItemDialog(message);
      },
      onBackgroundMessage: myBackgroundMessageHandler,
//        print('on backgroundmessage ${message}');
//      },
      onResume: (Map<String, dynamic> message) async {
        print('on messageResume ${message}');
//        displayNotification(message);
      },
      onLaunch: (Map<String, dynamic> message) async {
        print('on messageLaunch ${message}');
//        displayNotification(message);
      },
    );
  }

  Widget ShowDialog(String channelName, String phoneNumber) {
    return Container(
        width: MediaQuery.of(context).size.width / 2,
        height: MediaQuery.of(context).size.height / 4,
        child: Column(
          children: <Widget>[
            Container(
                color: Colors.yellowAccent,
                width: MediaQuery.of(context).size.width,
                height: 50,
                child: Text("Incoming Video call")),
            SizedBox(
              height: 5.0,
            ),
            Container(
              child: Row(
                children: <Widget>[
                  RaisedButton(
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => CallPage(
                            channelName: channelName,
                            phoneNumber: phoneNumber,
                          ),
                        ),
                      );
                    },
//                  textColor: Colors.black,
                    child: Text(
                      "ACCEPT",
                      style: TextStyle(color: Colors.black, fontSize: 12),
                    ),
                  ),
                  VerticalDivider(
                    width: 3,
                  ),
                  RaisedButton(
                    onPressed: () {},
                    color: Colors.green,
                    child: Text(
                      "REJECT",
                      style: TextStyle(color: Colors.black, fontSize: 12),
                    ),
                  )
                ],
              ),
            )
          ],
        ));
  }
}

Body:
I had a similar problem where the notifications were delivered sometimes and I found an easy work around to that just define your myBackgroundMessageHandler as:

Future<void> myBackgroundMessageHandler(Map<String, dynamic> message) async {
      final prefs = await SharedPreferences.getInstance();
      // SharedPreferences could have been modified in the UI isolate, so we have to fetch it from the host platform.
      await prefs.reload();
}

You can also go through this blog which explains how to setup firebase messaging on Flutter https://medium.com/@sylvainduch/firebase-messaging-catch-them-all-3f9c594734d7


问:
Behind the scene- If I use Aync but doesn't use await in it, would it be identical with normal function?
due to everyone's help, I got the logic behind async, promise, then, await.

I have one curisosity on top of its basic nature, which is what if
I declare async function but doesn't use await in it.

technically every argument within async function is invisibly capsulated by '.then()'
but how it works would be exactly same as synchronous function execution.
For example,

```<code>async function trackUserHandler() {

  var positiondata= await getPosition();
  var timerdata = await setTimer(2000)

  console.log(positiondata, timerdata);

setTimer(1000).then(() => {
    console.log('Timer done!');
  });
  console.log('one');

}
</code>```

The console below doesn't run till the first two await function is done due to await(s) sitting before this.

```<code> console.log(positiondata, timerdata);
</code>```

What if I don't put any await(s) in the async like below?

```<code>async function trackUserHandler() {

  var positiondata=  getPosition();
  var timerdata =  setTimer(2000)

  console.log(positiondata, timerdata);

setTimer(1000).then(() => {
    console.log('Timer done!');
  });
  console.log('one');

}
</code>```

I test-run this code and behaves seemigly same as regular function without 'async'.
Of course behind the scene, everything in the function is encapsulated into 'then()' though.

Am I understanding right?

Thank you in advance.

答:
Yes, an async function runs synchronously till the first await, so it behaves like a regular function. It does return a Promise though:</p>

```<code> function trackUserHandler() {
   // ... code
   return Promise.resolve(undefined);
 }
</code>```

Body:
due to everyone's help, I got the logic behind async, promise, then, await.

I have one curisosity on top of its basic nature, which is what if
I declare async function but doesn't use await in it.

technically every argument within async function is invisibly capsulated by '.then()'
but how it works would be exactly same as synchronous function execution.
For example,

async function trackUserHandler() {

  var positiondata= await getPosition();
  var timerdata = await setTimer(2000)

  console.log(positiondata, timerdata);

setTimer(1000).then(() => {
    console.log('Timer done!');
  });
  console.log('one');

}

The console below doesn't run till the first two await function is done due to await(s) sitting before this.

 console.log(positiondata, timerdata);

What if I don't put any await(s) in the async like below?

async function trackUserHandler() {

  var positiondata=  getPosition();
  var timerdata =  setTimer(2000)

  console.log(positiondata, timerdata);

setTimer(1000).then(() => {
    console.log('Timer done!');
  });
  console.log('one');

}

I test-run this code and behaves seemigly same as regular function without 'async'.
Of course behind the scene, everything in the function is encapsulated into 'then()' though.

Am I understanding right?

Thank you in advance.

Body:
Yes, an async function runs synchronously till the first await, so it behaves like a regular function. It does return a Promise though:

 function trackUserHandler() {
   // ... code
   return Promise.resolve(undefined);
 }


问:
How to generate an invoice from a custom module in Odoo13?
I am developing a custom module.

I tried to add it through an object button with the following code but doesn't seem to work

    def create_invoice(self):
        rslt = self.env['account.invoice'].create({
                    'partner_id': self.instructor.id,
                    'name': 'customer invoice',
                    'type': 'out_invoice',
                    'date_invoice': 'create_date'
                })
        return rslt
```

How can I add a button that generates an invoice?

答:
desu

From Odoo13 there is a change in invoice object, It is now account.move instead of account.invoice.You can take this reference demo example.

```<code>invoice = self.env['account.move'].create({
    'type': 'out_invoice',
    'journal_id': journal.id,
    'partner_id': product_id.id,
    'invoice_date': date_invoice,
    'date': date_invoice,
    'invoice_line_ids': [(0, 0, {
        'product_id': product_id.id,
        'quantity': 40.0,
        'name': 'product test 1',
        'discount': 10.00,
        'price_unit': 2.27,
    })]
})
</code>```

Body:
I am developing a custom module.

I tried to add it through an object button with the following code but doesn't seem to work

    def create_invoice(self):
        rslt = self.env['account.invoice'].create({
                    'partner_id': self.instructor.id,
                    'name': 'customer invoice',
                    'type': 'out_invoice',
                    'date_invoice': 'create_date'
                })
        return rslt

How can I add a button that generates an invoice?

Body:
desu

From Odoo13 there is a change in invoice object, It is now account.move instead of account.invoice.You can take this reference demo example.

invoice = self.env['account.move'].create({
    'type': 'out_invoice',
    'journal_id': journal.id,
    'partner_id': product_id.id,
    'invoice_date': date_invoice,
    'date': date_invoice,
    'invoice_line_ids': [(0, 0, {
        'product_id': product_id.id,
        'quantity': 40.0,
        'name': 'product test 1',
        'discount': 10.00,
        'price_unit': 2.27,
    })]
})