问:
How to echo names of last upload file
I was asked that the output file should only output the name and id of the last person who uploaded a file with a specific name. confusing right? even I am confused. so let me give an example

let us say that you have 3 employees registered in your company. lets call them

Pikachu,

Raichu and

Pichu.

Pikachu has 3 files uploaded in the company, Raichu has 2 files uploaded and Pichu has also 2 files uploaded. The files must also be ordered according to employeename(ASC) and filename(DESC). Mine is already in ordered by. This is my only problem. In this case the output should look like this:

*noticed that the employee name and employee id is in the last file uploaded?? does anyone knows how to do that?please i beg you guys to help me out here T-T the task is way too hard and im just a rookie

Im thinking of using 2 tables here. table 1 for the employee id and employee name, table 2 for the file name, etc. so i guess this would also involve 2 while clause. i have the idea but i dont know how to mix them all up.

my code before I edited it like sir vincent look like this:

```<code>if ($_SESSION[$fgmembersite->GetLoginSessionVar()] == 'sa'
   OR $_SESSION[$fgmembersite->GetLoginSessionVar()] == 'admin')
{

  $sql= "select * from gmdc_employee
         where employee_name like '%$search%'
         AND employee_name like '$listname%'";
} else {
  $sql = "select b.* from gmdc_user a, gmdc_employee b
          where a.username = '".$_SESSION[$fgmembersite->GetLoginSessionVar()]."'
          AND a.company_id = b.company_id
          AND b.employee_name like '$listname%'
          AND b.employee_name like '%$search%'";
}
$query = mysql_query("$sql ORDER BY employee_name,confirmation DESC
                     ,file_id DESC,file_date DESC
                      LIMIT $offset,$limit") or die ( mysql_error () );
$result = mysql_query($sql) or die (mysql_error());
$total = mysql_num_rows($result);

if(!$result || mysql_num_rows($result) <= 0)
{
  $fgmembersite->HandleError("No file found.");
  return false;
}
while ($row = mysql_fetch_assoc($query))
{
  $file_id = $row['file_id'];
  $file_desc = $row['file_description'];
  $file_date = $row['file_date'];
  $file_name = $row['file_name'];
  $file_accs = $row['folder_access'];
  $file_employee  = $row['employee_id'];
  $file_confir = $row['confirmation'];
  $file_ename = ucwords($row['employee_name']);

  $info = pathinfo($file_name);
  $file_ext = $info['extension'];

  echo '<tr><td> </td></tr>
        <tr class="subone"><td class="sub" width="100">'.$file_employee.'<br />
         </td>';
  if($_SESSION[$fgmembersite->GetLoginSessionVar()] == 'sa')
  {
    ?>
    <td class="sub" width="100">
    <a href="" onclick = javascript:newPopup('addfile.php?emp=
    <?php echo $file_employee ?>');><?php echo$file_ename?></a>
    <br /> </td>
    <?php
  } else {
    echo '<td class="sub" width="182">'.$file_ename.'<br /> </td>';
  }
  echo'<td  class="sub" width="218">
       <a href="'.$file_accs.$file_name.'" target="_blank"
        style="text-decoration: underline;">'.$file_desc.'</a>
       <br /> </td><td  class="sub" width="100">
      '.date('M d, Y',mktime(0,0,0,substr($file_date,5,2)
       ,substr($file_date,8,2),substr($file_date,0,4))).'
       <br /> </td><td  class="sub" width="100">'.$file_confir.'
       <br /> </td>';

  if($_SESSION[$fgmembersite->GetLoginSessionVar()] == 'sa')
  {
    if($file_confir == 'Pending' OR $file_confir == 'NotApproved')
    {
      if(isset($_GET['id']))
      {
        $fgmembersite->Delete_Db($_GET['id']);
      }
      echo '<td  class="sub" width="100">
            <a href="index.php?id='.$file_id.'">Delete</a>
            <br /> </td>';
    }
  }
  else if($_SESSION[$fgmembersite->GetLoginSessionVar()] == 'admin')
  {
    if($file_confir == 'Pending')
      {
        if(isset($_GET['yes']))
        {
          $fgmembersite->UpdateYesDB($_GET['yes']);
          //echo "<script>location.reload();</script>";
        }
        else if(isset($_GET['no']))
        {
          $fgmembersite->UpdateNoDB($_GET['no']);
          //echo "<script>location.reload();</script>";
        }
        if (!isset($_GET['offset'])) {
          $prevoffset = 0;
        } else {
          $prevoffset = $_GET['offset'];
          echo'<td  class="sub" width="100">
          <a href="index.php?offset='.$prevoffset.'&searchfile='.$search.'
           &namelist='.$listname.'&yes='.$file_id.'">Approve</a>
           //there's a link here<br /><br />
           <a href="index.php?offset='.$prevoffset.'&searchfile='.$search.'
            &namelist='.$listname.'&no='.$file_id.'">NotApprove</a>
            //there's a link here
             </td> ';
      }
    }
  }?>
</code>```

Just ignore every if($_SESSION[$fgmembersite->GetLoginSessionVar()] == 'admin') and whatever, this is for different output since my file can be logged into by 3 different users. SA(programmers), admin(the approver of the file uploaded), and user(company). There are TD and TR there as well, I don't know why wont it appear here.

output looked like this:

```<code>employee_id  +   employee_name  +  file_name
3            |   pichu          |  file6
3            |   pichu          |  file1
1            |   pikachu        |  file7
1            |   pikachu        |  file4
1            |   pikachi        |  file3
2            |   raichu         |  file8
2            |   raichu         |  file5
2            |   raichu         |  file2
</code>```

and I want my output to be like this:

```<code>***OUTPUT***

**employee_id        employee_name              file_name**
    3                      pichu                        file6
                                                        file1
    1                     pikachu                       file7
                                                        file4
                                                        file3
    2                     raichu                        file5
                                                        file2
</code>```

for example that raichu uploaded another file, the output should now look like this:

OUTPUT

```<code>**employee_id        employee_name            file_name**
    3                      pichu                      file6
                                                      file1
    1                      pikachu                    file7
                                                      file4
                                                      file3
    2                      raichu                     file8
                                                      file5
                                                      file2
</code>```

答:
assuming you use MySQL and assuming we have establish a database connection using a reference $db:

```<code>$query = 'SELECT employee_id, employee_name FROM `employee` ORDER BY employee_name ASC';
$result = mysql_query($query) or die(mysql_error($db));

echo '<table>';
echo '<tr><th>employee_id</th><th>employee_name</th><th>file_name</th></tr>';

while ($row = mysql_fetch_assoc($result)) {
    echo '<tr>';
    echo '<td>'.$row['employee_id'].'<td>';
    echo '<td>'.$row['employee_name'].'</td>';
    echo '<td>';

    $query2 = 'SELECT file_name FROM `file` WHERE employee_id='.$row['employee_id'].' ORDER BY file_id DESC';
    $result2 = mysql_query($query2) or die(mysql_error($db));

    while ($row2 = mysql_fetch_assoc($result2)) {
        echo $row2['file_name'].'<br />';
    }

    echo '</td>';
    echo '</tr>';
}

echo '</table>';
</code>```

this piece of code will work.

Title: How to echo names of last upload file

Body:
I was asked that the output file should only output the name and id of the last person who uploaded a file with a specific name. confusing right? even I am confused. so let me give an example

let us say that you have 3 employees registered in your company. lets call them

Pikachu,

Raichu and

Pichu.

Pikachu has 3 files uploaded in the company, Raichu has 2 files uploaded and Pichu has also 2 files uploaded. The files must also be ordered according to employeename(ASC) and filename(DESC). Mine is already in ordered by. This is my only problem. In this case the output should look like this:

*noticed that the employee name and employee id is in the last file uploaded?? does anyone knows how to do that?please i beg you guys to help me out here T-T the task is way too hard and im just a rookie

Im thinking of using 2 tables here. table 1 for the employee id and employee name, table 2 for the file name, etc. so i guess this would also involve 2 while clause. i have the idea but i dont know how to mix them all up.

my code before I edited it like sir vincent look like this:

if ($_SESSION[$fgmembersite->GetLoginSessionVar()] == 'sa'
   OR $_SESSION[$fgmembersite->GetLoginSessionVar()] == 'admin')
{

  $sql= "select * from gmdc_employee
         where employee_name like '%$search%'
         AND employee_name like '$listname%'";
} else {
  $sql = "select b.* from gmdc_user a, gmdc_employee b
          where a.username = '".$_SESSION[$fgmembersite->GetLoginSessionVar()]."'
          AND a.company_id = b.company_id
          AND b.employee_name like '$listname%'
          AND b.employee_name like '%$search%'";
}
$query = mysql_query("$sql ORDER BY employee_name,confirmation DESC
                     ,file_id DESC,file_date DESC
                      LIMIT $offset,$limit") or die ( mysql_error () );
$result = mysql_query($sql) or die (mysql_error());
$total = mysql_num_rows($result);

if(!$result || mysql_num_rows($result) <= 0)
{
  $fgmembersite->HandleError("No file found.");
  return false;
}
while ($row = mysql_fetch_assoc($query))
{
  $file_id = $row['file_id'];
  $file_desc = $row['file_description'];
  $file_date = $row['file_date'];
  $file_name = $row['file_name'];
  $file_accs = $row['folder_access'];
  $file_employee  = $row['employee_id'];
  $file_confir = $row['confirmation'];
  $file_ename = ucwords($row['employee_name']);

  $info = pathinfo($file_name);
  $file_ext = $info['extension'];

  echo '

'.$file_employee.'

         	';
  if($_SESSION[$fgmembersite->GetLoginSessionVar()] == 'sa')
  {
    ?>

    <a href="" onclick = javascript:newPopup('addfile.php?emp=
    <?php echo $file_employee ?>');><?php echo$file_ename?>

    <?php
  } else {
    echo ''.$file_ename.'
 	';
  }
  echo'
       '.$file_desc.'

      '.date('M d, Y',mktime(0,0,0,substr($file_date,5,2)
       ,substr($file_date,8,2),substr($file_date,0,4))).'

 	'.$file_confir.'

 	';

  if($_SESSION[$fgmembersite->GetLoginSessionVar()] == 'sa')
  {
    if($file_confir == 'Pending' OR $file_confir == 'NotApproved')
    {
      if(isset($_GET['id']))
      {
        $fgmembersite->Delete_Db($_GET['id']);
      }
      echo '
            Delete

 	';
    }
  }
  else if($_SESSION[$fgmembersite->GetLoginSessionVar()] == 'admin')
  {
    if($file_confir == 'Pending')
      {
        if(isset($_GET['yes']))
        {
          $fgmembersite->UpdateYesDB($_GET['yes']);
          //echo "";
        }
        else if(isset($_GET['no']))
        {
          $fgmembersite->UpdateNoDB($_GET['no']);
          //echo "";
        }
        if (!isset($_GET['offset'])) {
          $prevoffset = 0;
        } else {
          $prevoffset = $_GET['offset'];
          echo'
          Approve
           //there's a link here

           NotApprove
            //there's a link here
             	 ';
      }
    }
  }?>

Just ignore every if($_SESSION[$fgmembersite->GetLoginSessionVar()] == 'admin') and whatever, this is for different output since my file can be logged into by 3 different users. SA(programmers), admin(the approver of the file uploaded), and user(company). There are TD and TR there as well, I don't know why wont it appear here.

output looked like this:

employee_id  +   employee_name  +  file_name
3            |   pichu          |  file6
3            |   pichu          |  file1
1            |   pikachu        |  file7
1            |   pikachu        |  file4
1            |   pikachi        |  file3
2            |   raichu         |  file8
2            |   raichu         |  file5
2            |   raichu         |  file2

and I want my output to be like this:

***OUTPUT***

**employee_id        employee_name              file_name**
    3                      pichu                        file6
                                                        file1
    1                     pikachu                       file7
                                                        file4
                                                        file3
    2                     raichu                        file5
                                                        file2

for example that raichu uploaded another file, the output should now look like this:

OUTPUT

**employee_id        employee_name            file_name**
    3                      pichu                      file6
                                                      file1
    1                      pikachu                    file7
                                                      file4
                                                      file3
    2                      raichu                     file8
                                                      file5
                                                      file2

Body:
assuming you use MySQL and assuming we have establish a database connection using a reference $db:

$query = 'SELECT employee_id, employee_name FROM `employee` ORDER BY employee_name ASC';
$result = mysql_query($query) or die(mysql_error($db));

echo '<table>';
echo '<tr><th>employee_id</th><th>employee_name</th><th>file_name</th></tr>';

while ($row = mysql_fetch_assoc($result)) {
    echo '<tr>';
    echo '<td>'.$row['employee_id'].'<td>';
    echo '<td>'.$row['employee_name'].'</td>';
    echo '<td>';

    $query2 = 'SELECT file_name FROM `file` WHERE employee_id='.$row['employee_id'].' ORDER BY file_id DESC';
    $result2 = mysql_query($query2) or die(mysql_error($db));

    while ($row2 = mysql_fetch_assoc($result2)) {
        echo $row2['file_name'].'<br />';
    }

    echo '</td>';
    echo '</tr>';
}

echo '</table>';

this piece of code will work.


来源: stackexchange

问:
Running a ubuntu container in background using docker compose
I am able to run a docker container using following docker command:

```<code>docker run -it  ubuntu /bin/bash
</code>```

Now I am trying to do it by using docker-compose:

```<code>version: "3"
services:
  ubuntu:
    container_name: ubuntu
    image: ubuntu
    restart: on-failure
    command: "/bin/bash"
</code>```

Now when I do :

```<code> docker-compose up -d
</code>```

Can see docker container starting and exiting immediately.

I tried looking at the logs :

```<code>docker logs b8 //b8 is container id
</code>```

But there are no error logs.

How do I keep ubuntu container running in background using docker.
( I am using docker on windows , linux version)

答:
This is normal.

You are starting an ubuntu container with bash as the command (thus the root process). The thing is to keep bash alive you need to attach it with a terminal. This is why when you want to get a bash in a container, you're using -ti with your command :

```<code>docker container exec -ti [my_container_id] bash
</code>```

So if you want to keep your ubuntu container alive and don't want to attach it to a terminal, you'll have to use a process that will stay alive for as long as you want.

Below is an example with sleep infinity as your main process

```<code>version: "3"
services:
  ubuntu:
    container_name: ubuntu
    image: ubuntu
    restart: on-failure
    command: ["sleep","infinity"]
</code>```

With this example, you container will stay running indefinitely.

ContentLicense: CC BY-SA 4.0

Body:
I am able to run a docker container using following docker command:

docker run -it  ubuntu /bin/bash

Now I am trying to do it by using docker-compose:

version: "3"
services:
  ubuntu:
    container_name: ubuntu
    image: ubuntu
    restart: on-failure
    command: "/bin/bash"

Now when I do :

 docker-compose up -d

Can see docker container starting and exiting immediately.

I tried looking at the logs :

docker logs b8 //b8 is container id

But there are no error logs.

How do I keep ubuntu container running in background using docker.
( I am using docker on windows , linux version)

Body:
This is normal.

You are starting an ubuntu container with bash as the command (thus the root process). The thing is to keep bash alive you need to attach it with a terminal. This is why when you want to get a bash in a container, you're using -ti with your command :

docker container exec -ti [my_container_id] bash

So if you want to keep your ubuntu container alive and don't want to attach it to a terminal, you'll have to use a process that will stay alive for as long as you want.

Below is an example with sleep infinity as your main process

version: "3"
services:
  ubuntu:
    container_name: ubuntu
    image: ubuntu
    restart: on-failure
    command: ["sleep","infinity"]

With this example, you container will stay running indefinitely.


问:
where to get certificates for font request?
I've been reviewing the official documentation for adding the EmojiCompa library here https://developer.android.com/guide/topics/ui/look-and-feel/emoji-compat . It has this code:

```<code>public class MyApplication extends Application {
  @Override
   public void onCreate() {
     super.onCreate();
     FontRequest fontRequest = new FontRequest(
       "com.example.fontprovider",
       "com.example",
       "emoji compat Font Query",
       CERTIFICATES);
     EmojiCompat.Config config = new FontRequestEmojiCompatConfig(this, fontRequest);
     EmojiCompat.init(config);
   }
}
</code>```

but it doesn't have any information on where/how to retrieve CERTIFICATES. I checked the font request section and wasn't able to find anything there either.

EDIT: To clarify, I see this:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="certs">
       <item>MIIEqDCCA5CgAwIBAgIJA071MA0GCSqGSIb3DQEBBAUAMIGUMQsww...</item>
    </string-array>
</resources>
</code>```

But do not see any information on where MIIEqDCCA5CgAwIBAgIJA071MA0GCSqGSIb3DQEBBAUAMIGUMQsww... is retrieved, especially with regards to EmojiCompat.

答:
Answer inspired by : Custom and Downloadable Fonts on Android

Follow the steps to add a certificate here

Then replace CERTIFICATES with R.array.certs like so, where R.array.certs is the name of the certificate you added.

val fontRequest = FontRequest(
                "com.example.fontprovider",
                "com.example",
                "emoji compat Font Query",
                R.array.certs
        )

Body:
I've been reviewing the official documentation for adding the EmojiCompa library here https://developer.android.com/guide/topics/ui/look-and-feel/emoji-compat . It has this code:

public class MyApplication extends Application {
  @Override
   public void onCreate() {
     super.onCreate();
     FontRequest fontRequest = new FontRequest(
       "com.example.fontprovider",
       "com.example",
       "emoji compat Font Query",
       CERTIFICATES);
     EmojiCompat.Config config = new FontRequestEmojiCompatConfig(this, fontRequest);
     EmojiCompat.init(config);
   }
}

but it doesn't have any information on where/how to retrieve CERTIFICATES. I checked the font request section and wasn't able to find anything there either.

EDIT: To clarify, I see this:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="certs">
       <item>MIIEqDCCA5CgAwIBAgIJA071MA0GCSqGSIb3DQEBBAUAMIGUMQsww...</item>
    </string-array>
</resources>

But do not see any information on where MIIEqDCCA5CgAwIBAgIJA071MA0GCSqGSIb3DQEBBAUAMIGUMQsww... is retrieved, especially with regards to EmojiCompat.


问:
JOLT TRANSFORM in Json List/Array cases
I was trying to do a JOLT Transform,but I'm facing some difficulties in writing the spec for the same. I want to move some json elements from one list to another.

```<code>INPUT JSON
{
  "billingsystem": {
    "request": {
      "profile": {
        "identification_details": [
          {
            "identification_type": "1",
            "identification_number": "4321221",
            "id_issue_date": "11/11/2014",
            "id_expiry_date": "11/11/2040",
            "issuer_id": "vx",
            "comment": "other"
          }
        ],
        "addresses": [
          {
            "language_id": "1",
            "subscriber_level": "0",
            "address_type": "0",
            "addr_line1": "13 B, Sea View",
            "addr_line2": "3rd Cross",
            "addr_line3": "Chicago",
            "addr_line4": "Illinois",
            "addr_line5": "60601",
            "country_id": "1"
          }
        ]
      }
    }
  }
}
</code>```

i want to change this to given output json. I need a spec through which i can solve the issue. Need a spec that deals with the

```<code>OUTPUT JSON
{
  "billingsystem": {
    "request": {
      "profile": {
        "identification_details": [
          {
            "identification_type": "1",
            "identification_number": "4321221",
            "id_issue_date": "11/11/2014",
            "id_expiry_date": "11/11/2040",
            "issuer_id": "vx",
            "comment": "other",
            "addr_line3": "Chicago",
            "addr_line4": "Illinois",
            "addr_line5": "60601",
            "country_id": "1"
          }
        ],
        "addresses": [
          {
            "language_id": "1",
            "subscriber_level": "0",
            "address_type": "0",
            "addr_line1": "13 B, Sea View",
            "addr_line2": "3rd Cross",

          }
        ]
      }
    }
  }
}
</code>```

答:
the most important thing when you working with arrays(in jolt) indexes from where to where you want to shift the parameters and also knowing about "@,*,(index)" it will help you to come out from there

solution - spec :

```<code>[
  {
    "operation": "shift",
    "spec": {
      "billingsystem": {
        "request": {
          "profile": {
            "addresses": {
              "*": {
                "language_id": "request.profile.addresses[&1].language_id",
                "subscriber_level": "request.profile.addresses[&1].subscriber_level",
                "address_type": "request.profile.addresses[&1].address_type",
                "addr_line1": "request.profile.addresses[&1].addr_line1",
                "addr_line2": "request.profile.addresses[&1].addr_line2"
              }
            },
            "identification_details": {
              "*": {
                "identification_type": "request.profile.identification_details[&1].identification_type",
                "identification_number": "request.profile.identification_details[&1].identification_number",
                "id_issue_date": "request.profile.identification_details[&1].id_issue_date",
                "id_expiry_date": "request.profile.identification_details[&1].id_issue_date",
                "issuer_id": "request.profile.identification_details[&1].id_expiry_date",
                "comment": "request.profile.identification_details[&1].comment",
                "@(2,addresses[&].addr_line3)": "request.profile.identification_details[&1].addr_line3",
                "@(2,addresses[&].addr_line4)": "request.profile.identification_details[&1].addr_line4",
                "@(2,addresses[&].addr_line5)": "request.profile.identification_details[&1].addr_line5"
              }
            }
          }
        }
      }
    }
  }

  ]
</code>```

Title: JOLT TRANSFORM in Json List/Array cases

Body:
I was trying to do a JOLT Transform,but I'm facing some difficulties in writing the spec for the same. I want to move some json elements from one list to another.

INPUT JSON
{
  "billingsystem": {
    "request": {
      "profile": {
        "identification_details": [
          {
            "identification_type": "1",
            "identification_number": "4321221",
            "id_issue_date": "11/11/2014",
            "id_expiry_date": "11/11/2040",
            "issuer_id": "vx",
            "comment": "other"
          }
        ],
        "addresses": [
          {
            "language_id": "1",
            "subscriber_level": "0",
            "address_type": "0",
            "addr_line1": "13 B, Sea View",
            "addr_line2": "3rd Cross",
            "addr_line3": "Chicago",
            "addr_line4": "Illinois",
            "addr_line5": "60601",
            "country_id": "1"
          }
        ]
      }
    }
  }
}

i want to change this to given output json. I need a spec through which i can solve the issue. Need a spec that deals with the

OUTPUT JSON
{
  "billingsystem": {
    "request": {
      "profile": {
        "identification_details": [
          {
            "identification_type": "1",
            "identification_number": "4321221",
            "id_issue_date": "11/11/2014",
            "id_expiry_date": "11/11/2040",
            "issuer_id": "vx",
            "comment": "other",
            "addr_line3": "Chicago",
            "addr_line4": "Illinois",
            "addr_line5": "60601",
            "country_id": "1"
          }
        ],
        "addresses": [
          {
            "language_id": "1",
            "subscriber_level": "0",
            "address_type": "0",
            "addr_line1": "13 B, Sea View",
            "addr_line2": "3rd Cross",

          }
        ]
      }
    }
  }
}

Body:
the most important thing when you working with arrays(in jolt) indexes from where to where you want to shift the parameters and also knowing about "@,*,(index)" it will help you to come out from there

solution - spec :

[
  {
    "operation": "shift",
    "spec": {
      "billingsystem": {
        "request": {
          "profile": {
            "addresses": {
              "*": {
                "language_id": "request.profile.addresses[&1].language_id",
                "subscriber_level": "request.profile.addresses[&1].subscriber_level",
                "address_type": "request.profile.addresses[&1].address_type",
                "addr_line1": "request.profile.addresses[&1].addr_line1",
                "addr_line2": "request.profile.addresses[&1].addr_line2"
              }
            },
            "identification_details": {
              "*": {
                "identification_type": "request.profile.identification_details[&1].identification_type",
                "identification_number": "request.profile.identification_details[&1].identification_number",
                "id_issue_date": "request.profile.identification_details[&1].id_issue_date",
                "id_expiry_date": "request.profile.identification_details[&1].id_issue_date",
                "issuer_id": "request.profile.identification_details[&1].id_expiry_date",
                "comment": "request.profile.identification_details[&1].comment",
                "@(2,addresses[&].addr_line3)": "request.profile.identification_details[&1].addr_line3",
                "@(2,addresses[&].addr_line4)": "request.profile.identification_details[&1].addr_line4",
                "@(2,addresses[&].addr_line5)": "request.profile.identification_details[&1].addr_line5"
              }
            }
          }
        }
      }
    }
  }

  ]


问:
How to check if particular data is present in CSV file or not in java?
I have created a CSV file and put values by connecting with the database in java.

Now, I have to check if a particular data/ID is present in the CSV file or not? The CSV file contains multiple columns but I have to perform check on a single column of the CSV file.

答:
First of all you need a way to iterate the rows of your CSV file, then get the value in the column you want, and then compare that to the value you're searching for.

Fortunately there is an abundance of libraries that will simplify the handling of CVS files. Apache Commons has one that will read a file into an Iterable of CSVRecords. Check the docs here

A function that does what you ask for could be:

    public boolean columnContainsValue(String pathToFile, int columnIndex, String targetValue) throws IOException {

        Reader in = new FileReader(pathToFile);
        Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(in);

        for (CSVRecord record : records) {
            String rowValue = record.get(columnIndex);
            if (targetValue.equals(rowValue) )
                return true;
        }
        return false;
    }
```


问:
'property' object cannot be intepreted as an integer
I discovered Python properties recently and I have been using it as a way to get 'read only' members, but now troubles arrive...

I have some 'read-only' numbers stored into properties inside a config class and I want to re-use those number in numpy/tensorflow, something a bit like:

class MyConfig:
    def __init__(self, val):
        self._val = val

    @property
    def val(self):
        return self._val

conf = MyConfig(10)
np.ones(conf.val)
```

<p>Error:</p>

```TypeError: expected sequence object with len >= 0 or a single integer
```

In my real code, the error is triggered by a np.reshape and the error message is a little different (TypeError: 'property' object cannot be interpreted as integer). I assume the cause for the error is the same as in this little example and only the error helper message differs.

Am I doing something wrong?
Can't properties be used in other functions for the values they embed?

答: I've tested your snippet and there is no error from this. The issue might be somewhere else. Debug it

Body:
I discovered Python properties recently and I have been using it as a way to get 'read only' members, but now troubles arrive...

I have some 'read-only' numbers stored into properties inside a config class and I want to re-use those number in numpy/tensorflow, something a bit like:

class MyConfig:
    def __init__(self, val):
        self._val = val

    @property
    def val(self):
        return self._val

conf = MyConfig(10)
np.ones(conf.val)

Error:

TypeError: expected sequence object with len >= 0 or a single integer

In my real code, the error is triggered by a np.reshape and the error message is a little different (TypeError: 'property' object cannot be interpreted as integer). I assume the cause for the error is the same as in this little example and only the error helper message differs.

Am I doing something wrong?
Can't properties be used in other functions for the values they embed?


问:
Share angular cli result over multiple azure pipeline jobs
How do I share my angular cli across steps?
Currently I put almost everything except in one big step in order to share the result of npm ci over all the tasks. This makes it complicated to define conditions and task parallelization.

I'm trying to set up an azure pipeline that does the following in separate steps

prepares environment (get source, installs angular cli)

validates (npm run lint, npm run test, publish test results)

creates artifacts (build demo and prod binaries, zip them, publish them as artifacts)

release to demo environments

release to prod environments

Some of the steps are conditional on the trigger or the master/feature branch and some of the steps could run in parallel. Splitting them in steps triggers completely new agents that don't have the result of my previous tasks anymore.

答:
There is no default way to share a task result. For some tasks, like installs angular cli, you have to install it on each new agent, unless you use self-hosted agent. For tasks, like publish test results, if you want to reuse the result, you need to publish the result to a public location.

I'd like to suggest you use task group. A task group allows you to encapsulate a sequence of tasks, already defined in a build or a release pipeline, into a single reusable task that can be added to a build or release pipeline, just like any other task. With task group, you don't have to add so many tasks in your pipeline.

Task groups are not supported in YAML pipelines. Instead, in that case you can use templates. See YAML schema reference.


问:
Make the layout below button
In one of my fragment class, it has two buttons (A and B) on top, used to switch to another fragment when clicked using viewPager.

When buttonA is clicked, it should switch to page A and so on.

When I click button A, how can I make the text in A show below the two buttons?

fragment_menu.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/buttonA"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="10dp"
        android:padding="15dp"
        android:text="ButtonA"
        android:textSize="12sp" />

    <Button
        android:id="@+id/buttonB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="15dp"
        android:layout_toRightOf="@+id/buttonB"
        android:backgroundTint="@color/materialGrey600"
        android:padding="15dp"
        android:text="ButtonB"
        android:textSize="12sp" />

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>
</code>```

MenuFragment

```<code>public class MenuFragment extends BaseFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_menu, container, false);
        final ViewPager viewPager = (ViewPager) v.findViewById(R.id.pager);
        viewPager.setAdapter(new ViewPagerAdapter(getActivity().getFragmentManager()));

        Button btnA = (Button) v.findViewById(R.id.buttonA);
        Button btnB = (Button) v.findViewById(R.id.buttonB);

        btnA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewPager.setCurrentItem(0, true);
            }
        });

        btnB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewPager.setCurrentItem(1, true);
            }
        });
        return v;
    }
}
</code>```

ViewPagerAdapter

```<code>  public class ViewPagerAdapter extends FragmentPagerAdapter {

        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position)
            {
                case 0:
                    return new A()
                case 1:
                    return new B()

            }
            return null;
        }

        @Override
        public int getCount() {
            return 2;
        }
    }
</code>```

Output

答:
try with below code.hope it is helpful for you ;)
P.S. You just need to set button style as you want :)</p>

```<code>  <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.viewpager.widget.ViewPager
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_above="@id/llButton"
            android:layout_height="match_parent" />

        <LinearLayout
            android:id="@+id/llButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_alignParentBottom="true"
            android:layout_marginBottom="10dp">

            <Button
                android:id="@+id/buttonA"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:padding="15dp"
                android:text="ButtonA"
                android:textSize="12sp" />

            <Button
                android:id="@+id/buttonB"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="15dp"
                android:layout_marginTop="10dp"
                android:layout_marginRight="15dp"
                android:backgroundTint="@color/colorAccent"
                android:padding="15dp"
                android:text="ButtonB"
                android:textSize="12sp" />

        </LinearLayout>

    </RelativeLayout>
</code>```

Title: Make the layout below button

Body:
In one of my fragment class, it has two buttons (A and B) on top, used to switch to another fragment when clicked using viewPager.

When buttonA is clicked, it should switch to page A and so on.

When I click button A, how can I make the text in A show below the two buttons?

fragment_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/buttonA"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="10dp"
        android:padding="15dp"
        android:text="ButtonA"
        android:textSize="12sp" />

    <Button
        android:id="@+id/buttonB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="15dp"
        android:layout_toRightOf="@+id/buttonB"
        android:backgroundTint="@color/materialGrey600"
        android:padding="15dp"
        android:text="ButtonB"
        android:textSize="12sp" />

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

MenuFragment

public class MenuFragment extends BaseFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_menu, container, false);
        final ViewPager viewPager = (ViewPager) v.findViewById(R.id.pager);
        viewPager.setAdapter(new ViewPagerAdapter(getActivity().getFragmentManager()));

        Button btnA = (Button) v.findViewById(R.id.buttonA);
        Button btnB = (Button) v.findViewById(R.id.buttonB);

        btnA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewPager.setCurrentItem(0, true);
            }
        });

        btnB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewPager.setCurrentItem(1, true);
            }
        });
        return v;
    }
}

ViewPagerAdapter

  public class ViewPagerAdapter extends FragmentPagerAdapter {

        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position)
            {
                case 0:
                    return new A()
                case 1:
                    return new B()

            }
            return null;
        }

        @Override
        public int getCount() {
            return 2;
        }
    }

Output

Body:
try with below code.hope it is helpful for you ;)
P.S. You just need to set button style as you want :)

  <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.viewpager.widget.ViewPager
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_above="@id/llButton"
            android:layout_height="match_parent" />

        <LinearLayout
            android:id="@+id/llButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_alignParentBottom="true"
            android:layout_marginBottom="10dp">

            <Button
                android:id="@+id/buttonA"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:padding="15dp"
                android:text="ButtonA"
                android:textSize="12sp" />

            <Button
                android:id="@+id/buttonB"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="15dp"
                android:layout_marginTop="10dp"
                android:layout_marginRight="15dp"
                android:backgroundTint="@color/colorAccent"
                android:padding="15dp"
                android:text="ButtonB"
                android:textSize="12sp" />

        </LinearLayout>

    </RelativeLayout>


问:
How to free() an array of structs allocated by malloc()?
I've been working on a project that uses structs as storage for strings. I declared a struct consists of char type members:

```<code>struct datastore1
{
    char name[50];
    char address[50];
    char email[50];
    char number[50];
    char idnum[50];
};
</code>```

I'm aware that I can just do char *name, char *address... but let's say we specified it with max length of 50. Then on my function which uses the struct, I malloc'ed it with index size of 30:

```<code>struct datastore1 *dsdata = malloc(30 * sizeof(struct datastore1));
</code>```

Supposedly I finished copying all strings into the struct by accessing each index, How should i free the allocated memory that was used after calling malloc? I tried doing free(dsdata) on the end of the program but I am not sure if it's the right way. Should i free each indexes individually? Please enlighten me. Thank you in advance for the feedback!

答:
Both answers above are correct, but to fully understand how does it work I recommend you to learn how to use valgrind.

To check if program released memory correctly use

```<code>valgrind -v --leak-check=full --track-origins=yes ./your-program
</code>```

This will execute your program on valgrind's virtual processor and give you full feedback about used resources.

Basically operator [] in C programming language in array definition context causes creation of (lets say to simplify) static array - this means that array is included in size of structure (if defined as part of structure) or is stored on the stack (if defined in function or globally).

The malloc function returns address of block of data you can use. Size of this block is at least as big as you requested. When you use free you release this block wich in this case means all data in block pointed by this address will be released.

Body:
I've been working on a project that uses structs as storage for strings. I declared a struct consists of char type members:

struct datastore1
{
    char name[50];
    char address[50];
    char email[50];
    char number[50];
    char idnum[50];
};

I'm aware that I can just do char *name, char *address... but let's say we specified it with max length of 50. Then on my function which uses the struct, I malloc'ed it with index size of 30:

struct datastore1 *dsdata = malloc(30 * sizeof(struct datastore1));

Supposedly I finished copying all strings into the struct by accessing each index, How should i free the allocated memory that was used after calling malloc? I tried doing free(dsdata) on the end of the program but I am not sure if it's the right way. Should i free each indexes individually? Please enlighten me. Thank you in advance for the feedback!

Body:
Both answers above are correct, but to fully understand how does it work I recommend you to learn how to use valgrind.

To check if program released memory correctly use

valgrind -v --leak-check=full --track-origins=yes ./your-program

This will execute your program on valgrind's virtual processor and give you full feedback about used resources.

Basically operator [] in C programming language in array definition context causes creation of (lets say to simplify) static array - this means that array is included in size of structure (if defined as part of structure) or is stored on the stack (if defined in function or globally).

The malloc function returns address of block of data you can use. Size of this block is at least as big as you requested. When you use free you release this block wich in this case means all data in block pointed by this address will be released.


问:
Compute combination of a pair variables for a given operation in R
From a given dataframe:

```<code># Create dataframe with 4 variables and 10 obs
set.seed(1)
df<-data.frame(replicate(4,sample(0:1,10,rep=TRUE)))
</code>```

I would like to compute a substract operation between in all columns combinations by pairs, but only keeping one substact, i.e column A- column B but not column B-column A and so on.

What I got is very manual, and this tend to be not so easy when there are lots of variables.

```<code># Result
df_result <- as.data.frame(list(df$X1-df$X2,
df$X1-df$X3,
df$X1-df$X4,

df$X2-df$X3,
df$X2-df$X4,

df$X3-df$X4))
</code>```

Also the colname of the feature name should describe the operation i.e.(x1_x2) being x1-x2.

答:
You can use combn:</p>

```<code>COMBI = combn(colnames(df),2)
res = data.frame(apply(COMBI,2,function(i)df[,i[1]]-df[,i[2]]))
colnames(res) = apply(COMBI,2,paste0,collapse="minus")

head(res)
  X1minusX2 X1minusX3 X1minusX4 X2minusX3 X2minusX4 X3minusX4
1         0         0        -1         0        -1        -1
2         1         1         0         0        -1        -1
3         0         0         0         0         0         0
4         0         0        -1         0        -1        -1
5         1         1         1         0         0         0
6        -1         0         0         1         1         0
</code>```

Body:
From a given dataframe:

# Create dataframe with 4 variables and 10 obs
set.seed(1)
df<-data.frame(replicate(4,sample(0:1,10,rep=TRUE)))

I would like to compute a substract operation between in all columns combinations by pairs, but only keeping one substact, i.e column A- column B but not column B-column A and so on.

What I got is very manual, and this tend to be not so easy when there are lots of variables.

# Result
df_result <- as.data.frame(list(df$X1-df$X2,
df$X1-df$X3,
df$X1-df$X4,

df$X2-df$X3,
df$X2-df$X4,

df$X3-df$X4))

Also the colname of the feature name should describe the operation i.e.(x1_x2) being x1-x2.

Body:
You can use combn:

COMBI = combn(colnames(df),2)
res = data.frame(apply(COMBI,2,function(i)df[,i[1]]-df[,i[2]]))
colnames(res) = apply(COMBI,2,paste0,collapse="minus")

head(res)
  X1minusX2 X1minusX3 X1minusX4 X2minusX3 X2minusX4 X3minusX4
1         0         0        -1         0        -1        -1
2         1         1         0         0        -1        -1
3         0         0         0         0         0         0
4         0         0        -1         0        -1        -1
5         1         1         1         0         0         0
6        -1         0         0         1         1         0


问:
How do you save a file to a directory given by an input type="text" with php?
I have a html page with jQuery and I used ajax to send data to the a php file to save the data.

I have seen other questions like this but none of them seemed to match my purpose.

The data is an iframe's srcdoc.

My html looks like this:

<input type="text" placeholder="Filename to save as..." id="fn">
<input type="button" value="Save" onclick="saveDoc(document.querySelector('#fn').value)">```
</div>
</div>
</p>

<p>My jQuery and JS looks like this:</p>

```function saveDoc(e) {
  let iframe = document.querySelector("#iframe");
  let data = {"srcdoc": iframe.srcdoc, "lnk": e};

  $.ajax({
    type: "POST",
    url: "saver.php",
    dataType : "text",
    contentType: "application/json",
    data: data,
    cache: false,
    timeout: 3000,
    success: function (data) {
        alert("SUCCESS");
        console.log(data);
    },
    error: function (e) {
        alert(e);
    }
  });
}
```

<p>And my php code looks like this:</p>

```<!doctype html>

<?php
  if (isset($_POST["lnk"]) && isset($_POST["srcdoc"])) {
    $myfile = fopen($_POST["link"], "w");
    fwrite($myfile, $_POST["srcdoc"]);
    fclose($myfile);
    echo $_POST["lnk"];
    echo "\n
";
    echo $_POST["srcdoc"];
  } else {
    echo "Error";
  }
?>

```

<p>When I run it, I get an alert message saying "SUCCESS". And the console.log gives me:</p>

```<!doctype html>

Error

```

What is happening here, and what am I doing wrong?

答:
```<code>contentType: "application/json"
</code>```

You are explicitly sending this to the server as JSON - so you can not access it via $_POST. (PHP only populates $_POST for Content-Types application/x-www-form-urlencoded or multipart/form-data.)

Either remove contentType, so that it can fall back to the normal way of sending form data, or go read up on how to actually read POSTed JSON data in PHP. (That would involve reading the data from php://input first, see Receive JSON POST with PHP)

Body:
I have a html page with jQuery and I used ajax to send data to the a php file to save the data.

I have seen other questions like this but none of them seemed to match my purpose.

The data is an iframe's srcdoc.

My html looks like this:

<input type="text" placeholder="Filename to save as..." id="fn">
<input type="button" value="Save" onclick="saveDoc(document.querySelector('#fn').value)">

My jQuery and JS looks like this:

function saveDoc(e) {
  let iframe = document.querySelector("#iframe");
  let data = {"srcdoc": iframe.srcdoc, "lnk": e};

  $.ajax({
    type: "POST",
    url: "saver.php",
    dataType : "text",
    contentType: "application/json",
    data: data,
    cache: false,
    timeout: 3000,
    success: function (data) {
        alert("SUCCESS");
        console.log(data);
    },
    error: function (e) {
        alert(e);
    }
  });
}

And my php code looks like this:

<!doctype html>

<?php
  if (isset($_POST["lnk"]) && isset($_POST["srcdoc"])) {
    $myfile = fopen($_POST["link"], "w");
    fwrite($myfile, $_POST["srcdoc"]);
    fclose($myfile);
    echo $_POST["lnk"];
    echo "\n
";
    echo $_POST["srcdoc"];
  } else {
    echo "Error";
  }
?>

When I run it, I get an alert message saying "SUCCESS". And the console.log gives me:

<!doctype html>

Error

What is happening here, and what am I doing wrong?

Body:
contentType: "application/json"

You are explicitly sending this to the server as JSON - so you can not access it via $_POST. (PHP only populates $_POST for Content-Types application/x-www-form-urlencoded or multipart/form-data.)

Either remove contentType, so that it can fall back to the normal way of sending form data, or go read up on how to actually read POSTed JSON data in PHP. (That would involve reading the data from php://input first, see Receive JSON POST with PHP)


问:
How to start two foreach loops dispatcher invoke simultaneously c# wpf
Is it possible to display strings char by char in two labels at the same time using
two different Dispatcher.BeginInvoke(new Action(() ?

I have two foreach loops like this:

```<code>        string str1 = "NUMBER OF PASSED:" + "\t\t" + passed1.ToString() + Environment.NewLine + "NUMBER OF FAILED:" + "\t" + failed1.ToString();

        foreach (var ch1 in str1)
        {
            var char_by_char1 = ch1;
            Dispatcher.BeginInvoke(new Action(() =>
            {
                first_result.Content += char_by_char1.ToString();
                System.Threading.Thread.Sleep(5);
            }), DispatcherPriority.Background);
        }

        string str2 = "NUMBER OF PASSED:" + "\t\t" + passed2.ToString() + Environment.NewLine + "NUMBER OF FAILED:" + "\t" + failed2.ToString();

        foreach (var ch2 in str2)
        {
            var char_by_char2 = ch2;
            Dispatcher.BeginInvoke(new Action(() =>
            {
                second_result.Content += char_by_char2.ToString();
                System.Threading.Thread.Sleep(5);
            }), DispatcherPriority.Background);
        }
</code>```

答:
The answer is yes.

But not like you're doing it there.

Dispatcher begininvoke will run your action on the UI thread.

That thread is the thing that does everything to do with the UI though. Including things you probably don't want to interrupt. Like displaying your new character.

As a rule of thumb.

Never sleep the UI thread, because it'll freeze the ui.

In this case the "other" invoke can't do anything because you burned the thread you're trying to run it on.  The first of those invokes that starts is the only thing will do anything for a while and you won't see the results before it has finished.

I suggest you remove the lines have:

```<code>  System.Threading.Thread.Sleep(5);
</code>```

There will now be no delay but your ui will not be frozen.

Make that action async.

Insert a line:

```<code>await Task.Delay(5);
</code>```

Where that sleep was.

How long a delay were you expecting?

That 5 is 5 milliseconds.

Maybe you want 500 or 5000.

You're then freeing up that thread and you they should have a chance of behaving more like you expected.

Depending on exactly what you're trying to do, you might do better appending to a list of actions with each action changing a letter.

Then you could iterate through with the await task.delay to introduce a delay.

Body:
Is it possible to display strings char by char in two labels at the same time using
two different Dispatcher.BeginInvoke(new Action(() ?

I have two foreach loops like this:

        string str1 = "NUMBER OF PASSED:" + "\t\t" + passed1.ToString() + Environment.NewLine + "NUMBER OF FAILED:" + "\t" + failed1.ToString();

        foreach (var ch1 in str1)
        {
            var char_by_char1 = ch1;
            Dispatcher.BeginInvoke(new Action(() =>
            {
                first_result.Content += char_by_char1.ToString();
                System.Threading.Thread.Sleep(5);
            }), DispatcherPriority.Background);
        }

        string str2 = "NUMBER OF PASSED:" + "\t\t" + passed2.ToString() + Environment.NewLine + "NUMBER OF FAILED:" + "\t" + failed2.ToString();

        foreach (var ch2 in str2)
        {
            var char_by_char2 = ch2;
            Dispatcher.BeginInvoke(new Action(() =>
            {
                second_result.Content += char_by_char2.ToString();
                System.Threading.Thread.Sleep(5);
            }), DispatcherPriority.Background);
        }

Body:
The answer is yes.

But not like you're doing it there.

Dispatcher begininvoke will run your action on the UI thread.

That thread is the thing that does everything to do with the UI though. Including things you probably don't want to interrupt. Like displaying your new character.

As a rule of thumb.

Never sleep the UI thread, because it'll freeze the ui.

In this case the "other" invoke can't do anything because you burned the thread you're trying to run it on.  The first of those invokes that starts is the only thing will do anything for a while and you won't see the results before it has finished.

I suggest you remove the lines have:

  System.Threading.Thread.Sleep(5);

There will now be no delay but your ui will not be frozen.

Make that action async.

Insert a line:

await Task.Delay(5);

Where that sleep was.

How long a delay were you expecting?

That 5 is 5 milliseconds.

Maybe you want 500 or 5000.

You're then freeing up that thread and you they should have a chance of behaving more like you expected.

Depending on exactly what you're trying to do, you might do better appending to a list of actions with each action changing a letter.

Then you could iterate through with the await task.delay to introduce a delay.


问:
EditText text formatting for forms
I'm looking for a simple way for Android, when a user taps a in a edit text box, it will add a hyphen inbetween the number set. Sort of like a phone number, but will be set in a custom position.

For example Book number 05, CD number 15, track number5 =  0515-5.  So when they start typing, the app will automatically enter the hyphen.

Should I use some type of listener and count how many characters are entered, then when it hits that number of characters, it will add the hyphen?

Thanks!

答:
Use an InputFilter.

See my answers here: press "." many times (validate ip address in EditText while typing) and here: How to set Edittext view allow only two numeric values and two decimal values like ##.## for ideas on how to implement it

ContentLicense: CC BY-SA 3.0

Title: EditText text formatting for forms


问:
How to use the variable beyond it's scope in Javascript?
I want to use the "labels" variable beyond its scope, how can I do it ? I know its not a good practice but I still want to use the values in labels array. I tried cloning the variable but the scope issue persists

```<code>const client = new vision.ImageAnnotatorClient();
// Performs label detection on the image file
client
    .labelDetection(`${filename}`)
    .then(results => {
        var labels = results[0].labelAnnotations;

        console.log('Labels: ');
        labels.forEach(label => console.log(label.description));
    })

    .catch(err => {
        console.error('ERROR: ', err);
    });
</code>```

EDIT 1:
I want to use the label this way

```<code>const client = new vision.ImageAnnotatorClient();
    // Performs label detection on the image file
    client
        .labelDetection(`${filename}`)
        .then(results => {
            var labels = results[0].labelAnnotations;

            console.log('Labels: ');
            labels.forEach(label => console.log(label.description));
        })

        .catch(err => {
            console.error('ERROR: ', err);
        });

console.log('Labels: ');
                labels.forEach(label => console.log(label.description));
</code>```

But the console shows the error "Cannot use undefined for forEach"

答:
You can only access the value using a .then(), or outside of the promise when you're in an async context:

```<code>(async () => {
  const client = new vision.ImageAnnotatorClient();
  const labels = client
    .labelDetection(`${filename}`)
    .then(results => results[0].labelAnnotations)
    .catch(err => console.error('ERROR: ', err))

  console.log('Labels: ');
  labels.forEach(label => console.log(label.description));
})()
</code>```

Here's a working example, where getLabels is a substitute for your current code:

(async () => {
  const fakeData = [{
    labelAnnotations: [
      { description: 'label 1' },
      { description: 'label 2' },
      { description: 'label 3' },
    ]
  }]

  const getLabels = () => new Promise(r => setTimeout(r, 1000, fakeData))
  const results = await getLabels()
  const labels = results[0].labelAnnotations

  console.log('Labels: ');
  labels.forEach(label => console.log(label.description));
})()```

Body:
I want to use the "labels" variable beyond its scope, how can I do it ? I know its not a good practice but I still want to use the values in labels array. I tried cloning the variable but the scope issue persists

const client = new vision.ImageAnnotatorClient();
// Performs label detection on the image file
client
    .labelDetection(`${filename}`)
    .then(results => {
        var labels = results[0].labelAnnotations;

        console.log('Labels: ');
        labels.forEach(label => console.log(label.description));
    })

    .catch(err => {
        console.error('ERROR: ', err);
    });

EDIT 1:
I want to use the label this way

const client = new vision.ImageAnnotatorClient();
    // Performs label detection on the image file
    client
        .labelDetection(`${filename}`)
        .then(results => {
            var labels = results[0].labelAnnotations;

            console.log('Labels: ');
            labels.forEach(label => console.log(label.description));
        })

        .catch(err => {
            console.error('ERROR: ', err);
        });

console.log('Labels: ');
                labels.forEach(label => console.log(label.description));

But the console shows the error "Cannot use undefined for forEach"

Body:
You can only access the value using a .then(), or outside of the promise when you're in an async context:

(async () => {
  const client = new vision.ImageAnnotatorClient();
  const labels = client
    .labelDetection(`${filename}`)
    .then(results => results[0].labelAnnotations)
    .catch(err => console.error('ERROR: ', err))

  console.log('Labels: ');
  labels.forEach(label => console.log(label.description));
})()

Here's a working example, where getLabels is a substitute for your current code:

(async () => {
  const fakeData = [{
    labelAnnotations: [
      { description: 'label 1' },
      { description: 'label 2' },
      { description: 'label 3' },
    ]
  }]

  const getLabels = () => new Promise(r => setTimeout(r, 1000, fakeData))
  const results = await getLabels()
  const labels = results[0].labelAnnotations

  console.log('Labels: ');
  labels.forEach(label => console.log(label.description));
})()


问:
How to set default values for shadow property
I have the following entity:

```<code>public class Person
{
    public Guid Id { get; set; }

    public string Name { get; set; }
}
</code>```

This is my DB context

```<code>public class PersonDbContext : DbContext
{
    private static readonly ILoggerFactory
        Logger = LoggerFactory.Create(x => x.AddConsole());

    public DbSet<Person> Persons { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder
            .UseLoggerFactory(Logger)
            .UseSqlServer(
                "Server=(localdb)\\mssqllocaldb;Database=PersonDb;Trusted_Connection=True;MultipleActiveResultSets=true");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder
            .Entity<Person>()
            .Property<DateTime>("Created")
            .HasDefaultValueSql("GETUTCDATE()")
            .ValueGeneratedOnAdd();

        modelBuilder
            .Entity<Person>()
            .Property<DateTime>("Updated")
            .HasDefaultValueSql("GETUTCDATE()")
            .ValueGeneratedOnAddOrUpdate();
    }
}
</code>```

As can be seen from OnModelCreating override, I'm adding shadow properties Updated/Created to Person entity.

I set those properties to be populated with SQL default values

Created when value is added

Updated when value is added or updated

Below is client code

```<code>var personId = Guid.Parse("CF5EE27D-C694-408A-9F7B-080FF6315843");

using (var dbContext = new PersonDbContext())
{
    var person = new Person
    {
        Id = personId,
        Name = "New Person"
    };

    dbContext.Add(person);

    await dbContext.SaveChangesAsync();
}

using (var dbContext = new PersonDbContext())
{
    var person = dbContext.Persons.Find(personId);

    var personName = person.Name;

    person.Name = $"{personName} {DateTime.UtcNow}";

    dbContext.SaveChanges();
}
</code>```

I can confirm that both properties are set to UTC date when inserting a new person.
However, on update, Updated property is not being set.

This is the t-sql generated:

```<code>info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (1ms) [Parameters=[@p1='?' (DbType = Guid), @p0='?' (Size = 4000)], CommandType='Text', CommandTimeout='30']
      SET NOCOUNT ON;
      UPDATE [Persons] SET [Name] = @p0
      WHERE [Id] = @p1;
      SELECT [Updated]
      FROM [Persons]
      WHERE @@ROWCOUNT = 1 AND [Id] = @p1;
</code>```

Reading documentation on genereted value on add or update I see the following warning:

However, if you specify that a DateTime property is generated on add
  or update, then you must setup a way for the values to be generated.
  One way to do this, is to configure a default value of GETDATE() (see
  Default Values) to generate values for new rows. You could then use a
  database trigger to generate values during updates (such as the
  following example trigger).

I don't get what's the purpose of ValueGeneratedOnAddOrUpdate() then, if it behaves like ValueGeneratedOnAdd() and I have to manually intervene (creating a trigger) to set this property.

Indeed, if I change the definition of Updated shadow property to

```<code>modelBuilder
    .Entity<Person>()
    .Property<DateTime>("Updated")
    .HasDefaultValueSql("GETUTCDATE()")
    .ValueGeneratedOnAdd();
</code>```

And override SaveChanges on the PersonDbContext

```<code>public override int SaveChanges()
{
    ChangeTracker.DetectChanges();

    foreach (var entry in ChangeTracker.Entries().Where(entity => entity.State == EntityState.Modified))
    {
        entry.Property("Updated").CurrentValue = DateTime.UtcNow;
    }

    return base.SaveChanges();
}
</code>```

This does what is expected.

So the question is - what's the proper way to set default values for shadow properties in EF Core.

This is simplified example from my bigger project, so using HasData on the entities in OnModelCreating override is not a good option (due to many entities).

I'm using EF Core 3.1.1

```<code><PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.1"/>
</code>```

答:
I found dicussion where it is pointed that name ValueGeneratedOnAddOrUpdate() is not descriptive enough.

@rowanmiller Thanks for the quick reply! Now I know how it works, but
  I think it's a bit confusing. The naming "ValueGeneratedOnAddOrUpdate"
  suggests that a value actually is generated on insert and update.

And the docs says: "Value generated on add" "Value generated on add
  means that if you don’t specify a value, one will be generated for
  you."

"Value generated on add or update" "Value generated on add or update
  means that a new value is generated every time the record is saved
  (insert or update)."

Maybe add a section in the docs that describes how you supply your own
  value generator?

However, advice from EF team is to follow the warning section and apply manual steps to generate values for Update case manually.

@bcbeatty the detailed explanation is included in the main section,
  and there is a caution box in the Fluent and Data Annotation sections
  that points back to the detailed note.

This just lets EF know that values are generated for added entities,
  it does not guarantee that EF will setup the actual mechanism to
  generate values. See Value generated on add section for more details.

So it seems, that at least for DateTime shadow properties, approach in OP is the way to go.

Body:
I have the following entity:

public class Person
{
    public Guid Id { get; set; }

    public string Name { get; set; }
}

This is my DB context

public class PersonDbContext : DbContext
{
    private static readonly ILoggerFactory
        Logger = LoggerFactory.Create(x => x.AddConsole());

    public DbSet<Person> Persons { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder
            .UseLoggerFactory(Logger)
            .UseSqlServer(
                "Server=(localdb)\\mssqllocaldb;Database=PersonDb;Trusted_Connection=True;MultipleActiveResultSets=true");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder
            .Entity<Person>()
            .Property<DateTime>("Created")
            .HasDefaultValueSql("GETUTCDATE()")
            .ValueGeneratedOnAdd();

        modelBuilder
            .Entity<Person>()
            .Property<DateTime>("Updated")
            .HasDefaultValueSql("GETUTCDATE()")
            .ValueGeneratedOnAddOrUpdate();
    }
}

As can be seen from OnModelCreating override, I'm adding shadow properties Updated/Created to Person entity.

I set those properties to be populated with SQL default values

Created when value is added

Updated when value is added or updated

Below is client code

var personId = Guid.Parse("CF5EE27D-C694-408A-9F7B-080FF6315843");

using (var dbContext = new PersonDbContext())
{
    var person = new Person
    {
        Id = personId,
        Name = "New Person"
    };

    dbContext.Add(person);

    await dbContext.SaveChangesAsync();
}

using (var dbContext = new PersonDbContext())
{
    var person = dbContext.Persons.Find(personId);

    var personName = person.Name;

    person.Name = $"{personName} {DateTime.UtcNow}";

    dbContext.SaveChanges();
}

I can confirm that both properties are set to UTC date when inserting a new person.
However, on update, Updated property is not being set.

This is the t-sql generated:

info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (1ms) [Parameters=[@p1='?' (DbType = Guid), @p0='?' (Size = 4000)], CommandType='Text', CommandTimeout='30']
      SET NOCOUNT ON;
      UPDATE [Persons] SET [Name] = @p0
      WHERE [Id] = @p1;
      SELECT [Updated]
      FROM [Persons]
      WHERE @@ROWCOUNT = 1 AND [Id] = @p1;

Reading documentation on genereted value on add or update I see the following warning:

However, if you specify that a DateTime property is generated on add
  or update, then you must setup a way for the values to be generated.
  One way to do this, is to configure a default value of GETDATE() (see
  Default Values) to generate values for new rows. You could then use a
  database trigger to generate values during updates (such as the
  following example trigger).

I don't get what's the purpose of ValueGeneratedOnAddOrUpdate() then, if it behaves like ValueGeneratedOnAdd() and I have to manually intervene (creating a trigger) to set this property.

Indeed, if I change the definition of Updated shadow property to

modelBuilder
    .Entity<Person>()
    .Property<DateTime>("Updated")
    .HasDefaultValueSql("GETUTCDATE()")
    .ValueGeneratedOnAdd();

And override SaveChanges on the PersonDbContext

public override int SaveChanges()
{
    ChangeTracker.DetectChanges();

    foreach (var entry in ChangeTracker.Entries().Where(entity => entity.State == EntityState.Modified))
    {
        entry.Property("Updated").CurrentValue = DateTime.UtcNow;
    }

    return base.SaveChanges();
}

This does what is expected.

So the question is - what's the proper way to set default values for shadow properties in EF Core.

This is simplified example from my bigger project, so using HasData on the entities in OnModelCreating override is not a good option (due to many entities).

I'm using EF Core 3.1.1

<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.1"/>


问:
How to detect drag in a mouse hook procedure
I've successfully set up a mouse hook for a window, and I'd like to detect a drag operation when the left mouse button is clicked. I've tried using DragDetect, as shown below, but it never returns TRUE, and it never suppresses the subsequent mouse-up event (in this code, hwnd is the target window):

```<code>LRESULT CALLBACK MouseHookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    if (nCode < 0)
    {
        return CallNextHookEx(NULL, nCode, wParam, lParam);
    }

    switch (wParam)
    {
        case WM_LBUTTONDOWN:
        {
            // Get the click point
            LPMOUSEHOOKSTRUCT pMouseHookStruct = reinterpret_cast<LPMOUSEHOOKSTRUCT>(lParam);
            CPoint ptClick = pMouseHookStruct->pt;

            // Drag detect
            BOOL fDrag = DragDetect(hwnd, ptClick);
            if (fDrag)
            {
                MessageBox(NULL, L"Drag", NULL, MB_OK);
            }
        break;
        }
    }
    return CallNextHookEx(NULL, nCode, wParam, lParam);
}
</code>```

Does DragDetect not work within hook procedures, or am I just doing something wrong?

答:
As comments pointed, DragDetect does not predict the future. But you can compare the POINT of WM_LBUTTONDOWN and WM_MOUSEMOVE in a click-time.

Sample:

```<code>#include <windows.h>
#include <iostream>
using namespace std;
typedef BOOL(*SETHOOK)(HWND hWnd);
typedef BOOL(*UNHOOK)();
LRESULT CALLBACK WndProcFunc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
    }
    return DefWindowProc(hwnd, message, wParam, lParam);
}
int main(int argc, char* argv[])
{
    WNDCLASS wc{};
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = WndProcFunc;
    wc.hInstance = GetModuleHandle(NULL);
    wc.lpszClassName = L"Class_Name";
    wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
    RegisterClass(&wc);

    HWND hWnd = CreateWindow(L"Class_Name", L"Test", WS_OVERLAPPEDWINDOW, 0, 0, 1000, 500, NULL, NULL, GetModuleHandle(NULL), NULL);

    SETHOOK SetHook;
    UNHOOK UnHook;
    HMODULE h = LoadLibraryA("PATH\\DLL4.dll");
    SetHook = (SETHOOK)GetProcAddress(h, "SetHook");
    UnHook = (UNHOOK)GetProcAddress(h, "UnHook");
    BOOL i = SetHook(hWnd);

    ShowWindow(hWnd, 1);
    UpdateWindow(hWnd);

    MSG Msg;
    while (GetMessage(&Msg, NULL, 0, 0))
    {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }

    UnHook();
    return 0;
}
</code>```

DLL:

```<code>// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#define PRESS TRUE
#define RELEASE FALSE
HHOOK tHook;
HMODULE hinstDLL;
BOOL button = RELEASE;
BOOL Drag = FALSE;
HWND hWnd;
POINT pt = { 0 };
LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam) {
    if (nCode < 0)
    {
        return CallNextHookEx(NULL, nCode, wParam, lParam);
    }
    LPMOUSEHOOKSTRUCT pMouseHookStruct = reinterpret_cast<LPMOUSEHOOKSTRUCT>(lParam);
    if (pMouseHookStruct->hwnd != hWnd)
    {
        button = RELEASE;
        Drag = FALSE;
    }
    else {
        switch (wParam)
        {
        case WM_LBUTTONDOWN:
        {
            button = PRESS;
            Drag = FALSE;
            printf("WM_LBUTTONDOWN\n");
            printf("%d , %d\n", pMouseHookStruct->pt.x, pMouseHookStruct->pt.y);
            pt.x = pMouseHookStruct->pt.x;
            pt.y = pMouseHookStruct->pt.y;
            break;
        }
        case WM_LBUTTONUP:
        {
            button = RELEASE;
            Drag = FALSE;
            printf("WM_LBUTTONUP\n");
            break;
        }
        case WM_MOUSEMOVE:
        {
            if (button == PRESS)
            {
                printf("%d , %d\n", pMouseHookStruct->pt.x, pMouseHookStruct->pt.y);
                if (Drag == FALSE && (abs(pt.x - pMouseHookStruct->pt.x) >= GetSystemMetrics(SM_CXDRAG) || abs(pt.y - pMouseHookStruct->pt.y) >= GetSystemMetrics(SM_CYDRAG)))
                {
                    printf("Drag\n");
                    Drag = TRUE;
                }
            }
            break;
        }
        }
    }
    return CallNextHookEx(NULL, nCode, wParam, lParam);
}
extern "C" __declspec(dllexport) BOOL SetHook(HWND hwnd)
{
    hWnd = hwnd;
    tHook = SetWindowsHookEx(WH_MOUSE, MouseProc, hinstDLL, 0);

    if (tHook == NULL)
        return FALSE;
    else
        return TRUE;
}
extern "C" __declspec(dllexport) BOOL UnHook()
{
    return UnhookWindowsHookEx(tHook);
}

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
        hinstDLL = hModule;
        break;
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}
</code>```

Body:
I've successfully set up a mouse hook for a window, and I'd like to detect a drag operation when the left mouse button is clicked. I've tried using DragDetect, as shown below, but it never returns TRUE, and it never suppresses the subsequent mouse-up event (in this code, hwnd is the target window):

LRESULT CALLBACK MouseHookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    if (nCode < 0)
    {
        return CallNextHookEx(NULL, nCode, wParam, lParam);
    }

    switch (wParam)
    {
        case WM_LBUTTONDOWN:
        {
            // Get the click point
            LPMOUSEHOOKSTRUCT pMouseHookStruct = reinterpret_cast<LPMOUSEHOOKSTRUCT>(lParam);
            CPoint ptClick = pMouseHookStruct->pt;

            // Drag detect
            BOOL fDrag = DragDetect(hwnd, ptClick);
            if (fDrag)
            {
                MessageBox(NULL, L"Drag", NULL, MB_OK);
            }
        break;
        }
    }
    return CallNextHookEx(NULL, nCode, wParam, lParam);
}

Does DragDetect not work within hook procedures, or am I just doing something wrong?

Body:
As comments pointed, DragDetect does not predict the future. But you can compare the POINT of WM_LBUTTONDOWN and WM_MOUSEMOVE in a click-time.

Sample:

#include <windows.h>
#include <iostream>
using namespace std;
typedef BOOL(*SETHOOK)(HWND hWnd);
typedef BOOL(*UNHOOK)();
LRESULT CALLBACK WndProcFunc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
    }
    return DefWindowProc(hwnd, message, wParam, lParam);
}
int main(int argc, char* argv[])
{
    WNDCLASS wc{};
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = WndProcFunc;
    wc.hInstance = GetModuleHandle(NULL);
    wc.lpszClassName = L"Class_Name";
    wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
    RegisterClass(&wc);

    HWND hWnd = CreateWindow(L"Class_Name", L"Test", WS_OVERLAPPEDWINDOW, 0, 0, 1000, 500, NULL, NULL, GetModuleHandle(NULL), NULL);

    SETHOOK SetHook;
    UNHOOK UnHook;
    HMODULE h = LoadLibraryA("PATH\\DLL4.dll");
    SetHook = (SETHOOK)GetProcAddress(h, "SetHook");
    UnHook = (UNHOOK)GetProcAddress(h, "UnHook");
    BOOL i = SetHook(hWnd);

    ShowWindow(hWnd, 1);
    UpdateWindow(hWnd);

    MSG Msg;
    while (GetMessage(&Msg, NULL, 0, 0))
    {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }

    UnHook();
    return 0;
}

DLL:

// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#define PRESS TRUE
#define RELEASE FALSE
HHOOK tHook;
HMODULE hinstDLL;
BOOL button = RELEASE;
BOOL Drag = FALSE;
HWND hWnd;
POINT pt = { 0 };
LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam) {
    if (nCode < 0)
    {
        return CallNextHookEx(NULL, nCode, wParam, lParam);
    }
    LPMOUSEHOOKSTRUCT pMouseHookStruct = reinterpret_cast<LPMOUSEHOOKSTRUCT>(lParam);
    if (pMouseHookStruct->hwnd != hWnd)
    {
        button = RELEASE;
        Drag = FALSE;
    }
    else {
        switch (wParam)
        {
        case WM_LBUTTONDOWN:
        {
            button = PRESS;
            Drag = FALSE;
            printf("WM_LBUTTONDOWN\n");
            printf("%d , %d\n", pMouseHookStruct->pt.x, pMouseHookStruct->pt.y);
            pt.x = pMouseHookStruct->pt.x;
            pt.y = pMouseHookStruct->pt.y;
            break;
        }
        case WM_LBUTTONUP:
        {
            button = RELEASE;
            Drag = FALSE;
            printf("WM_LBUTTONUP\n");
            break;
        }
        case WM_MOUSEMOVE:
        {
            if (button == PRESS)
            {
                printf("%d , %d\n", pMouseHookStruct->pt.x, pMouseHookStruct->pt.y);
                if (Drag == FALSE && (abs(pt.x - pMouseHookStruct->pt.x) >= GetSystemMetrics(SM_CXDRAG) || abs(pt.y - pMouseHookStruct->pt.y) >= GetSystemMetrics(SM_CYDRAG)))
                {
                    printf("Drag\n");
                    Drag = TRUE;
                }
            }
            break;
        }
        }
    }
    return CallNextHookEx(NULL, nCode, wParam, lParam);
}
extern "C" __declspec(dllexport) BOOL SetHook(HWND hwnd)
{
    hWnd = hwnd;
    tHook = SetWindowsHookEx(WH_MOUSE, MouseProc, hinstDLL, 0);

    if (tHook == NULL)
        return FALSE;
    else
        return TRUE;
}
extern "C" __declspec(dllexport) BOOL UnHook()
{
    return UnhookWindowsHookEx(tHook);
}

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
        hinstDLL = hModule;
        break;
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}


问:
bash variable with double-quotes
There is an exported env-variable X:

```<code>X="-t \"2 2.1\""
</code>```

The following command is parsed wrong when using this variable:

```<code>yarn jest $X
</code>```

```<code>yarn jest -t '"2' '2.1"'
</code>```

Instead of:

```<code>yarn jest -t "2 2.1"
</code>```

I have read a-lot of similar questions but none of them worked. Any help?

答:
Consider using shell array for this:

```<code>arr=('-t' '2 2.1')
</code>```

then use it as:

```<code>yarn jest "${arr[@]}"
</code>```

Title: bash variable with double-quotes

Body:
There is an exported env-variable X:

X="-t \"2 2.1\""

The following command is parsed wrong when using this variable:

yarn jest $X

yarn jest -t '"2' '2.1"'

Instead of:

yarn jest -t "2 2.1"

I have read a-lot of similar questions but none of them worked. Any help?

Body:
Consider using shell array for this:

arr=('-t' '2 2.1')

then use it as:

yarn jest "${arr[@]}"