问:
How can I shorten the next repeated statement?
How can I shorten the next repeated statement?
I want to show 4~7, 5~7, 6~7, 7 for case 1,2,3,4.

The code below is very messy and I was wondering if there is a way to reduce it.

```<code>function selectTeeShotCount() {
    console.log(document.teeShotInfoForm.TeeCount);
    const radioTeeShot = document.teeShotInfoForm.TeeCount;
    let prev = null;
    for (const radioTeeShotElement of radioTeeShot) {
        radioTeeShotElement.addEventListener('change', event => {
            (prev) ? console.log(prev.value): null;
            if (this !== prev) {
                prev = this;
            }

            document.querySelector('#teeShotInfoForm > div:nth-child(3)').classList.remove('d-none');
            document.querySelector('#teeShotInfoForm > div:nth-child(4)').classList.remove('d-none');
            document.querySelector('#teeShotInfoForm > div:nth-child(5)').classList.remove('d-none');
            document.querySelector('#teeShotInfoForm > div:nth-child(6)').classList.remove('d-none');
            document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.remove('d-none');

            switch (parseInt(radioTeeShot.value)) {
                case 1:
                    document.querySelector('#teeShotInfoForm > div:nth-child(4)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(5)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(6)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.add('d-none');
                    break;
                case 2:
                    document.querySelector('#teeShotInfoForm > div:nth-child(5)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(6)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.add('d-none');
                    break;
                case 3:
                    document.querySelector('#teeShotInfoForm > div:nth-child(6)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.add('d-none');
                    break;
                case 4:
                    document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.add('d-none');
                    break;
            }
        });
    }
}
</code>```

答:
you can provide document.querySelector to the function.

Like this.

function selectTeeShotCount() {
  const teeShotInfoFormChild = (nthChildNumber = 0) => document.querySelector(`#teeShotInfoForm > div:nth-child(${nthChildNumber})`)

  console.log(document.teeShotInfoForm.TeeCount);
  const radioTeeShot = document.teeShotInfoForm.TeeCount;
  let prev = null;

  for (const radioTeeShotElement of radioTeeShot) {
      radioTeeShotElement.addEventListener('change', event => {
          (prev) ? console.log(prev.value): null;
          if (this !== prev) {
              prev = this;
          }

          teeShotInfoFormChild(3).classList.remove('d-none');
          teeShotInfoFormChild(4).classList.remove('d-none');
          teeShotInfoFormChild(5).classList.remove('d-none');
          teeShotInfoFormChild(6).classList.remove('d-none');
          teeShotInfoFormChild(7).classList.remove('d-none');

          switch (parseInt(radioTeeShot.value)) {
              case 1:
                  teeShotInfoFormChild(4).classList.add('d-none');
                  teeShotInfoFormChild(5).classList.add('d-none');
                  teeShotInfoFormChild(6).classList.add('d-none');
                  teeShotInfoFormChild(7).classList.add('d-none');
                  break;
              case 2:
                  teeShotInfoFormChild(5).classList.add('d-none');
                  teeShotInfoFormChild(6).classList.add('d-none');
                  teeShotInfoFormChild(7).classList.add('d-none');
                  break;
              case 3:
                  teeShotInfoFormChild(6).classList.add('d-none');
                  teeShotInfoFormChild(7).classList.add('d-none');
                  break;
              case 4:
                  teeShotInfoFormChild(7).classList.add('d-none');
                  break;
          }
      });
  }
}
```
<p>In next step you can add teeShotInfoFromChild 3-7 to the array and use forEach, like this:</p>
<pre class="lang-js prettyprint-override"><code>function selectTeeShotCount() {
  const teeShotInfoFormChild = (nthChildNumber = 0) => document.querySelector(`#teeShotInfoForm > div:nth-child(${nthChildNumber})`)

  console.log(document.teeShotInfoForm.TeeCount);
  const radioTeeShot = document.teeShotInfoForm.TeeCount;
  let prev = null;

  for (const radioTeeShotElement of radioTeeShot) {
      radioTeeShotElement.addEventListener('change', event => {
          (prev) ? console.log(prev.value): null;
          if (this !== prev) {
              prev = this;
          }

          [
            teeShotInfoFormChild(3),
            teeShotInfoFormChild(4),
            teeShotInfoFormChild(5),
            teeShotInfoFormChild(6),
            teeShotInfoFormChild(7)
          ].forEach((child) => child.classList.remove('d-none'))

          switch (parseInt(radioTeeShot.value)) {
              case 1:
                  teeShotInfoFormChild(4).classList.add('d-none');
                  teeShotInfoFormChild(5).classList.add('d-none');
                  teeShotInfoFormChild(6).classList.add('d-none');
                  teeShotInfoFormChild(7).classList.add('d-none');
                  break;
              case 2:
                  teeShotInfoFormChild(5).classList.add('d-none');
                  teeShotInfoFormChild(6).classList.add('d-none');
                  teeShotInfoFormChild(7).classList.add('d-none');
                  break;
              case 3:
                  teeShotInfoFormChild(6).classList.add('d-none');
                  teeShotInfoFormChild(7).classList.add('d-none');
                  break;
              case 4:
                  teeShotInfoFormChild(7).classList.add('d-none');
                  break;
          }
      });
  }
}
</code>```

The next step to optimise your code is to fix your switch with remove "break" and duplicating code.

function selectTeeShotCount() {
  const teeShotInfoFormChild = (nthChildNumber = 0) =>
    document.querySelector(
      `#teeShotInfoForm > div:nth-child(${nthChildNumber})`
    );

  console.log(document.teeShotInfoForm.TeeCount);
  const radioTeeShot = document.teeShotInfoForm.TeeCount;
  let prev = null;

  for (const radioTeeShotElement of radioTeeShot) {
    radioTeeShotElement.addEventListener("change", (event) => {
      prev ? console.log(prev.value) : null;
      if (this !== prev) {
        prev = this;
      }

      [
        teeShotInfoFormChild(3),
        teeShotInfoFormChild(4),
        teeShotInfoFormChild(5),
        teeShotInfoFormChild(6),
        teeShotInfoFormChild(7)
      ].forEach((child) => child.classList.remove("d-none"));

      switch (parseInt(radioTeeShot.value)) {
        case 1:
            teeShotInfoFormChild(4).classList.add("d-none");
        case 2:
            teeShotInfoFormChild(5).classList.add("d-none");
        case 3:
            teeShotInfoFormChild(6).classList.add("d-none");
        case 4:
            teeShotInfoFormChild(7).classList.add("d-none");
            break;
        default:
          break;
      }
    });
  }
}
```

Body:
How can I shorten the next repeated statement?
I want to show 4~7, 5~7, 6~7, 7 for case 1,2,3,4.

The code below is very messy and I was wondering if there is a way to reduce it.

function selectTeeShotCount() {
    console.log(document.teeShotInfoForm.TeeCount);
    const radioTeeShot = document.teeShotInfoForm.TeeCount;
    let prev = null;
    for (const radioTeeShotElement of radioTeeShot) {
        radioTeeShotElement.addEventListener('change', event => {
            (prev) ? console.log(prev.value): null;
            if (this !== prev) {
                prev = this;
            }

            document.querySelector('#teeShotInfoForm > div:nth-child(3)').classList.remove('d-none');
            document.querySelector('#teeShotInfoForm > div:nth-child(4)').classList.remove('d-none');
            document.querySelector('#teeShotInfoForm > div:nth-child(5)').classList.remove('d-none');
            document.querySelector('#teeShotInfoForm > div:nth-child(6)').classList.remove('d-none');
            document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.remove('d-none');

            switch (parseInt(radioTeeShot.value)) {
                case 1:
                    document.querySelector('#teeShotInfoForm > div:nth-child(4)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(5)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(6)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.add('d-none');
                    break;
                case 2:
                    document.querySelector('#teeShotInfoForm > div:nth-child(5)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(6)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.add('d-none');
                    break;
                case 3:
                    document.querySelector('#teeShotInfoForm > div:nth-child(6)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.add('d-none');
                    break;
                case 4:
                    document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.add('d-none');
                    break;
            }
        });
    }
}

Body:
you can provide document.querySelector to the function.

Like this.

function selectTeeShotCount() {
  const teeShotInfoFormChild = (nthChildNumber = 0) => document.querySelector(`#teeShotInfoForm > div:nth-child(${nthChildNumber})`)

  console.log(document.teeShotInfoForm.TeeCount);
  const radioTeeShot = document.teeShotInfoForm.TeeCount;
  let prev = null;

  for (const radioTeeShotElement of radioTeeShot) {
      radioTeeShotElement.addEventListener('change', event => {
          (prev) ? console.log(prev.value): null;
          if (this !== prev) {
              prev = this;
          }

          teeShotInfoFormChild(3).classList.remove('d-none');
          teeShotInfoFormChild(4).classList.remove('d-none');
          teeShotInfoFormChild(5).classList.remove('d-none');
          teeShotInfoFormChild(6).classList.remove('d-none');
          teeShotInfoFormChild(7).classList.remove('d-none');

          switch (parseInt(radioTeeShot.value)) {
              case 1:
                  teeShotInfoFormChild(4).classList.add('d-none');
                  teeShotInfoFormChild(5).classList.add('d-none');
                  teeShotInfoFormChild(6).classList.add('d-none');
                  teeShotInfoFormChild(7).classList.add('d-none');
                  break;
              case 2:
                  teeShotInfoFormChild(5).classList.add('d-none');
                  teeShotInfoFormChild(6).classList.add('d-none');
                  teeShotInfoFormChild(7).classList.add('d-none');
                  break;
              case 3:
                  teeShotInfoFormChild(6).classList.add('d-none');
                  teeShotInfoFormChild(7).classList.add('d-none');
                  break;
              case 4:
                  teeShotInfoFormChild(7).classList.add('d-none');
                  break;
          }
      });
  }
}

In next step you can add teeShotInfoFromChild 3-7 to the array and use forEach, like this:

function selectTeeShotCount() {
  const teeShotInfoFormChild = (nthChildNumber = 0) => document.querySelector(`#teeShotInfoForm > div:nth-child(${nthChildNumber})`)

  console.log(document.teeShotInfoForm.TeeCount);
  const radioTeeShot = document.teeShotInfoForm.TeeCount;
  let prev = null;

  for (const radioTeeShotElement of radioTeeShot) {
      radioTeeShotElement.addEventListener('change', event => {
          (prev) ? console.log(prev.value): null;
          if (this !== prev) {
              prev = this;
          }

          [
            teeShotInfoFormChild(3),
            teeShotInfoFormChild(4),
            teeShotInfoFormChild(5),
            teeShotInfoFormChild(6),
            teeShotInfoFormChild(7)
          ].forEach((child) => child.classList.remove('d-none'))

          switch (parseInt(radioTeeShot.value)) {
              case 1:
                  teeShotInfoFormChild(4).classList.add('d-none');
                  teeShotInfoFormChild(5).classList.add('d-none');
                  teeShotInfoFormChild(6).classList.add('d-none');
                  teeShotInfoFormChild(7).classList.add('d-none');
                  break;
              case 2:
                  teeShotInfoFormChild(5).classList.add('d-none');
                  teeShotInfoFormChild(6).classList.add('d-none');
                  teeShotInfoFormChild(7).classList.add('d-none');
                  break;
              case 3:
                  teeShotInfoFormChild(6).classList.add('d-none');
                  teeShotInfoFormChild(7).classList.add('d-none');
                  break;
              case 4:
                  teeShotInfoFormChild(7).classList.add('d-none');
                  break;
          }
      });
  }
}

The next step to optimise your code is to fix your switch with remove "break" and duplicating code.

function selectTeeShotCount() {
  const teeShotInfoFormChild = (nthChildNumber = 0) =>
    document.querySelector(
      `#teeShotInfoForm > div:nth-child(${nthChildNumber})`
    );

  console.log(document.teeShotInfoForm.TeeCount);
  const radioTeeShot = document.teeShotInfoForm.TeeCount;
  let prev = null;

  for (const radioTeeShotElement of radioTeeShot) {
    radioTeeShotElement.addEventListener("change", (event) => {
      prev ? console.log(prev.value) : null;
      if (this !== prev) {
        prev = this;
      }

      [
        teeShotInfoFormChild(3),
        teeShotInfoFormChild(4),
        teeShotInfoFormChild(5),
        teeShotInfoFormChild(6),
        teeShotInfoFormChild(7)
      ].forEach((child) => child.classList.remove("d-none"));

      switch (parseInt(radioTeeShot.value)) {
        case 1:
            teeShotInfoFormChild(4).classList.add("d-none");
        case 2:
            teeShotInfoFormChild(5).classList.add("d-none");
        case 3:
            teeShotInfoFormChild(6).classList.add("d-none");
        case 4:
            teeShotInfoFormChild(7).classList.add("d-none");
            break;
        default:
          break;
      }
    });
  }
}


来源: stackexchange

问:
Align button and image vertically
I wanted to align button and Image vertically in center, right now button is showing on top of line, I am using bootstrap, can anyone help?

```<code><div class="col-md-12">
<div class="col-md-5" style="margin-left: -37px;"><p class="imageSveMsg" style="display:none">Save</p><button style="display:none" fieldid="81" class="saveimgbtn fileUpload btn btn-primary">Save Image</button>
<div class="fileUpload hideFileUpload btn btn-primary">  <span class="chooseimagetext"><b>Change Image</b></span><input rowid="submission_81" id="uploadImage" onchange="PreviewImage();" tabindex="13" type="file" name="matrix_submission_data81" accept="image/png, image/jpeg , image/jpeg" class="upload   matrix_submission_draft  ">
 </div></div>
 <div class="col-md-4">
<input type="hidden" name="oldmatrix_submission_data81" value="16440505543.png"><img id="uploadPreview" src="https://staging-reconresearchlive.kinsta.cloud/wp-content/plugins/matrix-engine/includes/submission_images/16440505543.png" width="50px !important;" height="50px !important;" style="margin-left:30px;max-width: 200px;max-height: 100px;min-height: 100px;vertical-align: middle !important;"></div></div>
</code>```

css:

```<code>.fileUpload {
    position: relative;
    overflow: hidden;
    margin: 10px;
    background-color: #E2A169 !important;
    border-color: #E2A169 !important;
}
img{
margin-left: 30px;
    max-width: 200px;
    max-height: 100px;
    min-height: 100px;
    vertical-align: middle !important;
}
</code>```

Output:
Current Output Image

答:
Try Changing the first div elements class to
 instead of

ContentLicense: CC BY-SA 4.0

Title: Align button and image vertically

Body:
I wanted to align button and Image vertically in center, right now button is showing on top of line, I am using bootstrap, can anyone help?

Save
<button style="display:none" fieldid="81" class="saveimgbtn fileUpload btn btn-primary">Save Image</button>

  Change Image<input rowid="submission_81" id="uploadImage" onchange="PreviewImage();" tabindex="13" type="file" name="matrix_submission_data81" accept="image/png, image/jpeg , image/jpeg" class="upload   matrix_submission_draft  ">

<input type="hidden" name="oldmatrix_submission_data81" value="16440505543.png">

css:

.fileUpload {
    position: relative;
    overflow: hidden;
    margin: 10px;
    background-color: #E2A169 !important;
    border-color: #E2A169 !important;
}
img{
margin-left: 30px;
    max-width: 200px;
    max-height: 100px;
    min-height: 100px;
    vertical-align: middle !important;
}

Output:
Current Output Image

Body: Try Changing the first div elements class to <div class="row align-items-center"> instead of <div class="col-md-12">


问:
How to rotate the 3D scatter plots in google colaboratory?
I am generating a 3d scatter plot in google colab, but the problem is that the generated fig is static and is not rotatable.
I also tried the command

%matplotlib notebook

to enable the 3D scatter rotation as it apparently work in jupyter notebook environment,but it seems this doesn't work in google colab environment.

you can find my code here

答:
As of now, you cannot rotate 3D plots generated by MatPlotlib in Colab. Plotly is a better alternative.

However, you can use the view_init method to change the view. It has two parameters (elev for elevation and azim for azimuth angles) to set to rotate the axes. You will get a different viewpoint.

By default, the view_init is set as azim=-60, elev=30. The angles are specified in degrees.
In your code, change the values of elev and azim to something else before using the scatter method. An example that uses ax.view_init(elev=30, azim=-120) is shown below:

```<code>import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import axes3d

fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')

x1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y1 = np.random.randint(10, size=10)
z1 = np.random.randint(10, size=10)

x2 = [-1, -2, -3, -4, -5, -6, -7, -8, -9, -10]
y2 = np.random.randint(-10, 0, size=10)
z2 = np.random.randint(10, size=10)

ax.view_init(elev=30, azim=-120)
ax.scatter(x1, y1, z1, c='b', marker='o', label='blue')
ax.scatter(x2, y2, z2, c='g', marker='D', label='green')

ax.set_xlabel('x axis')
ax.set_ylabel('y axis')
ax.set_zlabel('z axis')
plt.title("3D Scatter Plot Example")
plt.legend()
plt.tight_layout()
plt.show()
</code>```

This produces the following plot:

Note:

ax.view_init(elev=0, azim=60): A zero elevation makes the plot as if we are looking horizontally.

ax.view_init(elev=-30, azim=60): A negative elevation inverts vertically.

This figure explains the meaning of azimuth and elevation better.

Body:
As of now, you cannot rotate 3D plots generated by MatPlotlib in Colab. Plotly is a better alternative.

However, you can use the view_init method to change the view. It has two parameters (elev for elevation and azim for azimuth angles) to set to rotate the axes. You will get a different viewpoint.

By default, the view_init is set as azim=-60, elev=30. The angles are specified in degrees.
In your code, change the values of elev and azim to something else before using the scatter method. An example that uses ax.view_init(elev=30, azim=-120) is shown below:

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import axes3d

fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')

x1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y1 = np.random.randint(10, size=10)
z1 = np.random.randint(10, size=10)

x2 = [-1, -2, -3, -4, -5, -6, -7, -8, -9, -10]
y2 = np.random.randint(-10, 0, size=10)
z2 = np.random.randint(10, size=10)

ax.view_init(elev=30, azim=-120)
ax.scatter(x1, y1, z1, c='b', marker='o', label='blue')
ax.scatter(x2, y2, z2, c='g', marker='D', label='green')

ax.set_xlabel('x axis')
ax.set_ylabel('y axis')
ax.set_zlabel('z axis')
plt.title("3D Scatter Plot Example")
plt.legend()
plt.tight_layout()
plt.show()

This produces the following plot:

Note:

ax.view_init(elev=0, azim=60): A zero elevation makes the plot as if we are looking horizontally.

ax.view_init(elev=-30, azim=60): A negative elevation inverts vertically.

This figure explains the meaning of azimuth and elevation better.


问:
update specific field data on sql database
so i have a table of data in web ui

as soon as I click the button. all of the field data in "Status Email" changed. not just selected field that i meant.
this is the sintaks sql

```<code>if($mail->Send())
{
    $query = "UPDATE nearly_inactive SET EmailSent = 'Sudah Kirim Email' WHERE  EmailSent = 'Belum Kirim Email'";
    $update = $con->prepare($query);
    $update->execute();
}
</code>```

how can i get the "update" only the data that I click on the button??

答:
Get specific field

In order to get the specific field from a MYSQL database

```<code>Select column FROM databse WHERE x = y
</code>```

Example:

```<code>SELECT id, firstname, lastname FROM MyGuests WHERE lastname='Doe'
</code>```

The issue

It's best to get a unique identifier, which no other user has used. For example a 10 digit user id code. Check that this code doesn't exist, for it to be unique.

UPDATE:

Easily use the UNIQUE SQL tag to resolve this issue.

```<code>CREATE TABLE X (
    ID INT UNIQUE
)
</code>```

Example:

```<code>SELECT id, firstname, lastname FROM MyGuests WHERE id=ryan9273__2
</code>```

Update a specific field

Now that we have fixed the issue we can easily

UPDATE x SET y=z WHERE id=b
```
<p><strong>Lets fix your code:</strong></p>
<pre class="lang-sql prettyprint-override"><code>UPDATE nearly_inactive SET EmailSent = 'Sudah Kirim Email' WHERE EmailSent = 'Belum Kirim Email'
</code>```

Lets make it more dynamic

UPDATE nearly_inactive SET :email = :emailaddr WHERE EmailSent = :id
```
<h2><strong>final code:</strong></h2>
```    $query = $con->prepare("UPDATE nearly_inactive SET :email = :emailaddr WHERE EmailSent = :id");
    $query->bindParam(':email', $email, PDO::PARAM_STR);
    $query->bindParam(':emailaddr', $emailaddr, PDO::PARAM_STR);
    $query->bindParam(':id', $id, PDO::PARAM_STR);
    $update->execute();
```

Security Matters

You are using PDO, so use bindParam aswell. Secret code enthusiast answer isn't as secure as the current code i provided!

Practice Makes Perfect

Please don't copy my code right away. learn from it and code it again ! Make it better. Also check the official PHP documentation for more info on these topics

Stay safe !

Regards,

Ryan

Body:
so i have a table of data in web ui

as soon as I click the button. all of the field data in "Status Email" changed. not just selected field that i meant.
this is the sintaks sql

if($mail->Send())
{
    $query = "UPDATE nearly_inactive SET EmailSent = 'Sudah Kirim Email' WHERE  EmailSent = 'Belum Kirim Email'";
    $update = $con->prepare($query);
    $update->execute();
}

how can i get the "update" only the data that I click on the button??

Body:
Get specific field

In order to get the specific field from a MYSQL database

Select column FROM databse WHERE x = y

Example:

SELECT id, firstname, lastname FROM MyGuests WHERE lastname='Doe'

The issue

It's best to get a unique identifier, which no other user has used. For example a 10 digit user id code. Check that this code doesn't exist, for it to be unique.

UPDATE:

Easily use the UNIQUE SQL tag to resolve this issue.

CREATE TABLE X (
    ID INT UNIQUE
)

Example:

SELECT id, firstname, lastname FROM MyGuests WHERE id=ryan9273__2

Update a specific field

Now that we have fixed the issue we can easily

UPDATE x SET y=z WHERE id=b

Lets fix your code:

UPDATE nearly_inactive SET EmailSent = 'Sudah Kirim Email' WHERE EmailSent = 'Belum Kirim Email'

Lets make it more dynamic

UPDATE nearly_inactive SET :email = :emailaddr WHERE EmailSent = :id

final code:

    $query = $con->prepare("UPDATE nearly_inactive SET :email = :emailaddr WHERE EmailSent = :id");
    $query->bindParam(':email', $email, PDO::PARAM_STR);
    $query->bindParam(':emailaddr', $emailaddr, PDO::PARAM_STR);
    $query->bindParam(':id', $id, PDO::PARAM_STR);
    $update->execute();

Security Matters

You are using PDO, so use bindParam aswell. Secret code enthusiast answer isn't as secure as the current code i provided!

Practice Makes Perfect

Please don't copy my code right away. learn from it and code it again ! Make it better. Also check the official PHP documentation for more info on these topics

Stay safe !

Regards,

Ryan


问:
ElasticSearch - combining search queries not working
I would like to have an intersection of 2 queries
I got 3 documents in the index:

```<code>"_id": "68c220aa-ea51-4f84-b880-29af3302cae9",
"_id": "b6c1c3c5-e959-480f-a145-f5598fafea66",
"_id": "2d30de72-0a2b-465c-8770-970ad9760d47",
</code>```

Query1:

```<code>{
    "from": 0,
    "query": {
        "nested": {
            "path": "attributes",
            "query": {
                "bool": {
                    "must": [
                        {
                            "bool": {
                                "must": [
                                    {
                                        "match_phrase": {
                                            "attributes.asReference": {
                                                "query": "8670ff39-6a0d-4ae8-e217-08d88efd4771"
                                            }
                                        }
                                    },
                                    {
                                        "match_phrase": {
                                            "attributes.attributeId": {
                                                "query": "f51ca670-4223-4ea2-8007-d111dd38a14f"
                                            }
                                        }
                                    }
                                ]
                            }
                        }
                    ]
                }
            }
        }
    },
    "size": 10,
    "sort": [
        {
            "modified": {
                "order": "asc"
            }
        },
        {
            "created": {
                "order": "asc"
            }
        }
    ]
}
</code>```

returns all 3 documents as it should

```<code>"_id": "68c220aa-ea51-4f84-b880-29af3302cae9",
"_id": "b6c1c3c5-e959-480f-a145-f5598fafea66",
"_id": "2d30de72-0a2b-465c-8770-970ad9760d47",
</code>```

Then I do query2:

```<code>{
    "from": 0,
    "query": {
        "nested": {
            "path": "attributes",
            "query": {
                "bool": {
                    "must": [
                        {
                            "bool": {
                                "must": [
                                    {
                                        "match_phrase": {
                                            "attributes.asShortString": {
                                                "query": "RA-005"
                                            }
                                        }
                                    },
                                    {
                                        "match_phrase": {
                                            "attributes.attributeId": {
                                                "query": "7ff3dbc1-3586-4475-9162-5430bb06c6d0"
                                            }
                                        }
                                    }
                                ]
                            }
                        }
                    ]
                }
            }
        }
    },
    "size": 10,
    "sort": [
        {
            "modified": {
                "order": "asc"
            }
        },
        {
            "created": {
                "order": "asc"
            }
        }
    ]
}
</code>```

returns 1 document:

```<code>"_id": "b6c1c3c5-e959-480f-a145-f5598fafea66"
</code>```

But when I combine the queries to:

```<code>{
    "from": 0,
    "query": {
        "nested": {
            "path": "attributes",
            "query": {
                "bool": {
                    "must": [
                        {
                            "bool": {
                                "must": [
                                    {
                                        "match_phrase": {
                                            "attributes.asReference": {
                                                "query": "8670ff39-6a0d-4ae8-e217-08d88efd4771"
                                            }
                                        }
                                    },
                                    {
                                        "match_phrase": {
                                            "attributes.attributeId": {
                                                "query": "f51ca670-4223-4ea2-8007-d111dd38a14f"
                                            }
                                        }
                                    }
                                ]
                            }
                        },
                        {
                            "bool": {
                                "must": [
                                    {
                                        "match_phrase": {
                                            "attributes.asShortString": {
                                                "query": "RA-005"
                                            }
                                        }
                                    },
                                    {
                                        "match_phrase": {
                                            "attributes.attributeId": {
                                                "query": "7ff3dbc1-3586-4475-9162-5430bb06c6d0"
                                            }
                                        }
                                    }
                                ]
                            }
                        }
                    ]
                }
            }
        }
    },
    "size": 10,
    "sort": [
        {
            "modified": {
                "order": "asc"
            }
        },
        {
            "created": {
                "order": "asc"
            }
        }
    ]
}
</code>```

Here I do not get any documents

So the subqueries are working but combined it does not work (it produces 0 results)

What am I missing here?

答:
Due to the way nested documents and queries work, you need to have two separate nested queries in your bool/must query, because each will/might match a different nested document of the same parent document:

```<code>{
  "from": 0,
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "attributes",
            "query": {
              "bool": {
                "must": [
                  {
                    "bool": {
                      "must": [
                        {
                          "match_phrase": {
                            "attributes.asReference": {
                              "query": "8670ff39-6a0d-4ae8-e217-08d88efd4771"
                            }
                          }
                        },
                        {
                          "match_phrase": {
                            "attributes.attributeId": {
                              "query": "f51ca670-4223-4ea2-8007-d111dd38a14f"
                            }
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            }
          }
        },
        {
          "nested": {
            "path": "attributes",
            "query": {
              "bool": {
                "must": [
                  {
                    "bool": {
                      "must": [
                        {
                          "match_phrase": {
                            "attributes.asShortString": {
                              "query": "RA-005"
                            }
                          }
                        },
                        {
                          "match_phrase": {
                            "attributes.attributeId": {
                              "query": "7ff3dbc1-3586-4475-9162-5430bb06c6d0"
                            }
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  },
  "size": 10,
  "sort": [
    {
      "modified": {
        "order": "asc"
      }
    },
    {
      "created": {
        "order": "asc"
      }
    }
  ]
}
</code>```

Body:
I would like to have an intersection of 2 queries
I got 3 documents in the index:

"_id": "68c220aa-ea51-4f84-b880-29af3302cae9",
"_id": "b6c1c3c5-e959-480f-a145-f5598fafea66",
"_id": "2d30de72-0a2b-465c-8770-970ad9760d47",

Query1:

{
    "from": 0,
    "query": {
        "nested": {
            "path": "attributes",
            "query": {
                "bool": {
                    "must": [
                        {
                            "bool": {
                                "must": [
                                    {
                                        "match_phrase": {
                                            "attributes.asReference": {
                                                "query": "8670ff39-6a0d-4ae8-e217-08d88efd4771"
                                            }
                                        }
                                    },
                                    {
                                        "match_phrase": {
                                            "attributes.attributeId": {
                                                "query": "f51ca670-4223-4ea2-8007-d111dd38a14f"
                                            }
                                        }
                                    }
                                ]
                            }
                        }
                    ]
                }
            }
        }
    },
    "size": 10,
    "sort": [
        {
            "modified": {
                "order": "asc"
            }
        },
        {
            "created": {
                "order": "asc"
            }
        }
    ]
}

returns all 3 documents as it should

"_id": "68c220aa-ea51-4f84-b880-29af3302cae9",
"_id": "b6c1c3c5-e959-480f-a145-f5598fafea66",
"_id": "2d30de72-0a2b-465c-8770-970ad9760d47",

Then I do query2:

{
    "from": 0,
    "query": {
        "nested": {
            "path": "attributes",
            "query": {
                "bool": {
                    "must": [
                        {
                            "bool": {
                                "must": [
                                    {
                                        "match_phrase": {
                                            "attributes.asShortString": {
                                                "query": "RA-005"
                                            }
                                        }
                                    },
                                    {
                                        "match_phrase": {
                                            "attributes.attributeId": {
                                                "query": "7ff3dbc1-3586-4475-9162-5430bb06c6d0"
                                            }
                                        }
                                    }
                                ]
                            }
                        }
                    ]
                }
            }
        }
    },
    "size": 10,
    "sort": [
        {
            "modified": {
                "order": "asc"
            }
        },
        {
            "created": {
                "order": "asc"
            }
        }
    ]
}

returns 1 document:

"_id": "b6c1c3c5-e959-480f-a145-f5598fafea66"

But when I combine the queries to:

{
    "from": 0,
    "query": {
        "nested": {
            "path": "attributes",
            "query": {
                "bool": {
                    "must": [
                        {
                            "bool": {
                                "must": [
                                    {
                                        "match_phrase": {
                                            "attributes.asReference": {
                                                "query": "8670ff39-6a0d-4ae8-e217-08d88efd4771"
                                            }
                                        }
                                    },
                                    {
                                        "match_phrase": {
                                            "attributes.attributeId": {
                                                "query": "f51ca670-4223-4ea2-8007-d111dd38a14f"
                                            }
                                        }
                                    }
                                ]
                            }
                        },
                        {
                            "bool": {
                                "must": [
                                    {
                                        "match_phrase": {
                                            "attributes.asShortString": {
                                                "query": "RA-005"
                                            }
                                        }
                                    },
                                    {
                                        "match_phrase": {
                                            "attributes.attributeId": {
                                                "query": "7ff3dbc1-3586-4475-9162-5430bb06c6d0"
                                            }
                                        }
                                    }
                                ]
                            }
                        }
                    ]
                }
            }
        }
    },
    "size": 10,
    "sort": [
        {
            "modified": {
                "order": "asc"
            }
        },
        {
            "created": {
                "order": "asc"
            }
        }
    ]
}

Here I do not get any documents

So the subqueries are working but combined it does not work (it produces 0 results)

What am I missing here?

Body:
Due to the way nested documents and queries work, you need to have two separate nested queries in your bool/must query, because each will/might match a different nested document of the same parent document:

{
  "from": 0,
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "attributes",
            "query": {
              "bool": {
                "must": [
                  {
                    "bool": {
                      "must": [
                        {
                          "match_phrase": {
                            "attributes.asReference": {
                              "query": "8670ff39-6a0d-4ae8-e217-08d88efd4771"
                            }
                          }
                        },
                        {
                          "match_phrase": {
                            "attributes.attributeId": {
                              "query": "f51ca670-4223-4ea2-8007-d111dd38a14f"
                            }
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            }
          }
        },
        {
          "nested": {
            "path": "attributes",
            "query": {
              "bool": {
                "must": [
                  {
                    "bool": {
                      "must": [
                        {
                          "match_phrase": {
                            "attributes.asShortString": {
                              "query": "RA-005"
                            }
                          }
                        },
                        {
                          "match_phrase": {
                            "attributes.attributeId": {
                              "query": "7ff3dbc1-3586-4475-9162-5430bb06c6d0"
                            }
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  },
  "size": 10,
  "sort": [
    {
      "modified": {
        "order": "asc"
      }
    },
    {
      "created": {
        "order": "asc"
      }
    }
  ]
}


问:
How to change the color of a icon among multiple icons one at a time using click event in angular
I have an angular application In that I have added 6 icons .My requirement is when I click on any button the particular icon color should changed from gray red color, and when I click on other icon the other icon changed to red color and previous color changed button should changed to gray color.

and my angular code is:

.component.html

```<code><div class="container">
<span class="icon-number"></span><i class="smiley  icon-face-1"></i>
        <span class="icon-number"></span><i class="smiley  icon-face-2"></i>
        <span class="icon-number"></span><i class="smiley  icon-face-3"></i>
        <span class="icon-number"></span><i class="smiley  icon-4"></i>
        <span class="icon-number"></span><i class="smiley icon-face-5"></i>
        <span class="icon-number"></span><i class="smiley icon-face-6"></i>
</div>

</code>```

So Can any one help me how to change the color of particular icon using click event in angular.

答:
In Component.ts File Take on a variable and name it as
currentButton=''

Also, make on function on .ts side will set the current button

```<code>SetCurrentButton(buttonValue:string){
this.currentButton=buttonValue;
}
</code>```

Now From Html In Your Button Code do Below Change

```<code><div class="container">

 <button type="button" class="buttonstyle" (click)="SetCurrentButton(btn1)" [ngStyle]="{'color':currentButton === 'btn1' ? 'red' : '' }">
          BUTTON-1
        </button>
        <button type="button" class="buttonstyle" (click)="SetCurrentButton(btn2)" [ngStyle]="{'color':currentButton === 'btn2' ? 'red' : '' }">
          BUTTON-2
        </button>
        <button type="button" class="buttonstyle" (click)="SetCurrentButton(btn3)" [ngStyle]="{'color':currentButton === 'btn3' ? 'red' : '' }">
          BUTTON-3
        </button>
 <button type="button" class="buttonstyle" (click)="SetCurrentButton(btn4)" [ngStyle]="{'color':currentButton === 'btn4' ? 'red' : '' }">
          BUTTON-4
        </button>
 <button type="button" class="buttonstyle" (click)="SetCurrentButton(btn5)" [ngStyle]="{'color':currentButton === 'btn5' ? 'red' : '' }">
          BUTTON-5
        </button>
<button type="button" class="buttonstyle" (click)="SetCurrentButton(btn6)" [ngStyle]="{'color':currentButton === 'btn6' ? 'red' : '' }">
          BUTTON-6
        </button>
</div>
</code>```

Body:
I have an angular application In that I have added 6 icons .My requirement is when I click on any button the particular icon color should changed from gray red color, and when I click on other icon the other icon changed to red color and previous color changed button should changed to gray color.

and my angular code is:

.component.html

So Can any one help me how to change the color of particular icon using click event in angular.

Body:
In Component.ts File Take on a variable and name it as
currentButton=''

Also, make on function on .ts side will set the current button

SetCurrentButton(buttonValue:string){
this.currentButton=buttonValue;
}

Now From Html In Your Button Code do Below Change

<div class="container">

 <button type="button" class="buttonstyle" (click)="SetCurrentButton(btn1)" [ngStyle]="{'color':currentButton === 'btn1' ? 'red' : '' }">
          BUTTON-1
        </button>
        <button type="button" class="buttonstyle" (click)="SetCurrentButton(btn2)" [ngStyle]="{'color':currentButton === 'btn2' ? 'red' : '' }">
          BUTTON-2
        </button>
        <button type="button" class="buttonstyle" (click)="SetCurrentButton(btn3)" [ngStyle]="{'color':currentButton === 'btn3' ? 'red' : '' }">
          BUTTON-3
        </button>
 <button type="button" class="buttonstyle" (click)="SetCurrentButton(btn4)" [ngStyle]="{'color':currentButton === 'btn4' ? 'red' : '' }">
          BUTTON-4
        </button>
 <button type="button" class="buttonstyle" (click)="SetCurrentButton(btn5)" [ngStyle]="{'color':currentButton === 'btn5' ? 'red' : '' }">
          BUTTON-5
        </button>
<button type="button" class="buttonstyle" (click)="SetCurrentButton(btn6)" [ngStyle]="{'color':currentButton === 'btn6' ? 'red' : '' }">
          BUTTON-6
        </button>
</div>


问:
ASP.NET MVC - Show counts using razor view in foreach
Below is my razor code

```<code>for (int i = 0; i < Model.physicians.Count; i++)
{
    <div>
        @Model.physicians[i].npi -- Count:
    </div>
}
</code>```

I have table npipatients as below:

npiId
Patientname

1
a

1
b

2
c

My output like this in razor view

1 -- Count:2

2 -- Count:1

I need to write ajax call but how to pass npiid to ajax method for foreach and assign result of npi count to label.

```<code>$.ajax({
    type: "POST",
    url: "/mycontroler/GetnpiDetails",
    dataType: "json",
    data: { "npiId": npiId },
    success: function (data) {

   }
});
</code>```

答:
From what I understand based on your question (Please correct me if I'm wrong), looks like you are trying to fire the API with each Npi record for getting the (grouping) count.

In my perspective, it is NOT EFFICIENT, imagine there are 100 records and you will call the API 100 times. This will lead to pulling down your server performance (Handling the same task 100 times) and also database server (Query the same data 100 times).

Instead,

You need to do the data transformation in Controller first by .GroupBy() the npi record and .Count() for each grouped record.

Expected output:

[
  { "npi": 1, "count": 2 },
  { "npi": 2, "count": 1 }
]
```
<p>With 1 single API call saves you the performance from calling <strong>m</strong> time as discussed.</p>
<p>What's you need to do:</p>
<ol>
<li>Model - Design your desired output with the model class.</li>
<li>Controller - Perform data transformation: Grouping by <code>npiId</code>.</li>
<li>View - Bind the value from Controller.</li>
</ol>
<blockquote>
<p>Model</p>
</blockquote>
<pre class="lang-cs prettyprint-override"><code>public class GroupedNpiModel
{
    public int NpiId { get; set; }

    public int Count { get; set; }
}
</code>```

Controller

public ActionResult Index()
{
    var data = new []
    {
        new { NpiId = 1, Patientname = "a" } ,
        new { NpiId = 1, Patientname = "b" } ,
        new { NpiId = 2, Patientname = "c" }
    };

    var groupedNpi = data.GroupBy(x => x.NpiId)
        .Select(g => new GroupedNpiModel
        {
            NpiId = g.Key,
            Count = g.Count()
        })
        .ToList();

    return View(groupedNpi);
}
```
<blockquote>
<p>View</p>
</blockquote>
```@model IEnumerable<HelloWorldMvcApp.GroupedNpiModel>

@foreach (var npi in Model)
{

        @npi.NpiId -- @npi.Count

}
```

Sample program on .NET Fiddle

Body:
Below is my razor code

for (int i = 0; i < Model.physicians.Count; i++)
{

        @Model.physicians[i].npi -- Count:

}

I have table npipatients as below:

npiId
Patientname

1
a

1
b

2
c

My output like this in razor view

1 -- Count:2

2 -- Count:1

I need to write ajax call but how to pass npiid to ajax method for foreach and assign result of npi count to label.

$.ajax({
    type: "POST",
    url: "/mycontroler/GetnpiDetails",
    dataType: "json",
    data: { "npiId": npiId },
    success: function (data) {

   }
});

Body:
From what I understand based on your question (Please correct me if I'm wrong), looks like you are trying to fire the API with each Npi record for getting the (grouping) count.

In my perspective, it is NOT EFFICIENT, imagine there are 100 records and you will call the API 100 times. This will lead to pulling down your server performance (Handling the same task 100 times) and also database server (Query the same data 100 times).

Instead,

You need to do the data transformation in Controller first by .GroupBy() the npi record and .Count() for each grouped record.

Expected output:

[
  { "npi": 1, "count": 2 },
  { "npi": 2, "count": 1 }
]

With 1 single API call saves you the performance from calling m time as discussed.

What's you need to do:

Model - Design your desired output with the model class.

Controller - Perform data transformation: Grouping by npiId.

View - Bind the value from Controller.

Model

public class GroupedNpiModel
{
    public int NpiId { get; set; }

    public int Count { get; set; }
}

Controller

public ActionResult Index()
{
    var data = new []
    {
        new { NpiId = 1, Patientname = "a" } ,
        new { NpiId = 1, Patientname = "b" } ,
        new { NpiId = 2, Patientname = "c" }
    };

    var groupedNpi = data.GroupBy(x => x.NpiId)
        .Select(g => new GroupedNpiModel
        {
            NpiId = g.Key,
            Count = g.Count()
        })
        .ToList();

    return View(groupedNpi);
}

View

@model IEnumerable<HelloWorldMvcApp.GroupedNpiModel>

@foreach (var npi in Model)
{
    <div>
        @npi.NpiId -- @npi.Count
    </div>
}

Sample program on .NET Fiddle


问:
How do I fix this error "remote: Invalid username or password." in git-bash terminal?
When I try to push the code using git push in the git-bash terminal I get the remote: Invalid username or password., but when try pushing the code using Visual studio code or IntelliJ, it prompts me to enter username and password. After entering the u/n and password, it gets successfully pushed. How do I fix this in git-bash? The git-bash doesn't prompt me to enter username and password.

Below is the command:

```<code>$ git push --set-upstream origin fix_sonar
remote: Invalid username or password.
fatal: Authentication failed for 'https://github.dhdjfjfn.com/jdjdjdjd/nvbcf.git/'
</code>```

答: Sometimes git caches credentials even if you mistyped try "cmdkey delet" and the URL of your repository. Then you should also be asked for your login data on the bash.</p>

Body:
When I try to push the code using git push in the git-bash terminal I get the remote: Invalid username or password., but when try pushing the code using Visual studio code or IntelliJ, it prompts me to enter username and password. After entering the u/n and password, it gets successfully pushed. How do I fix this in git-bash? The git-bash doesn't prompt me to enter username and password.

Below is the command:

$ git push --set-upstream origin fix_sonar
remote: Invalid username or password.
fatal: Authentication failed for 'https://github.dhdjfjfn.com/jdjdjdjd/nvbcf.git/'


问:
How can I merge multiple PDFs to Single PDF in google app script?
I have more than 3 PDF files and I want to merge them into a single PDF using Google App Script, How can I do this?</p>

答:
You can achieve this using pdf.co rest API for merge. Following is source code for your reference.

Source code here is using Google Drive folder to retrieve all PDF files inside, and does merging and saves them back to same folder. However, this can be changed as per our requirement.

```<code>/**
 * IMPORTANT: Add Service reference for "Drive". Go to Services > Locate "Drive (drive API)" > Add Reference of it
 */

// Add Your PDF.co API Key here
const pdfCoAPIKey = 'PDFco_API_Key_Here';

// Get the active spreadsheet and the active sheet
ss = SpreadsheetApp.getActiveSpreadsheet();
ssid = ss.getId();

// Look in the same folder the sheet exists in. For example, if this template is in
// My Drive, it will return all of the files in My Drive.
var ssparents = DriveApp.getFileById(ssid).getParents();

// Store File-Ids/PermissionIds used for merging
let filePermissions = [];

/**
 * Note: Here, we're getting current folder where spreadsheet is residing.
 * But we can certainly pick any folder of our like by using Folder related functions.
 * For example:
  var allFolders = DriveApp.getFoldersByName("Folder_Containing_PDF_Files");
  while (allFolders.hasNext()) {
    var folder = allFolders.next();
    Logger.log(folder.getName());
  }
 */
// Loop through all the files and add the values to the spreadsheet.
var folder = ssparents.next();

/**
 * Add PDF.co Menus in Google Spreadsheet
 */
function onOpen() {
  var menuItems = [
    {name: 'Merge All Files From Current Folder', functionName: 'mergePDFDocumentsFromCurrentFolder'}
  ];
  ss.addMenu('PDF.co', menuItems);
}

function mergePDFDocumentsFromCurrentFolder(){
  var allFilesLink = getPDFFilesFromCurFolder(pdfCoAPIKey);
  mergePDFDocuments(allFilesLink, pdfCoAPIKey);
}

/**
 * Get all PDF files from current folder
 */
function getPDFFilesFromCurFolder(pdfCoAPIKey) {
  var files = folder.getFiles();
  var allFileUrls = [];

  while (files.hasNext()) {
    var file = files.next();

    var fileName = file.getName();
    if(fileName.endsWith(".pdf")){
      // Create Pre-Signed URL from PDF.co
      var respPresignedUrl = getPDFcoPreSignedURL(fileName, pdfCoAPIKey)

      if(!respPresignedUrl.error){
        var fileData = file.getBlob();
        if(uploadFileToPresignedURL(respPresignedUrl.presignedUrl, fileData, pdfCoAPIKey)){
          // Add Url
          allFileUrls.push(respPresignedUrl.url);
        }
      }
    }
  }

  return allFileUrls.join(",");
}

/**
 * Merges PDF URLs using PDF.co and Save to drive
 */
function mergePDFDocuments(pdfUrl, pdfCoAPIKey) {

  // Get Cells for Input/Output
  let resultUrlCell =  ss.getRange("A4");

  // Prepare Payload
  var data = {
    "async": false,
    "encrypt": false,
    "inline": true,
    "name": "result",
    "url": pdfUrl
  };

  // Prepare Request Options
  var options = {
    'method' : 'post',
    'contentType': 'application/json',
    'headers': {
      "x-api-key": pdfCoAPIKey
    },
    // Convert the JavaScript object to a JSON string.
    'payload' : JSON.stringify(data)
  };

  // Get Response
  // https://developers.google.com/apps-script/reference/url-fetch
  var pdfCoResponse = UrlFetchApp.fetch('https://api.pdf.co/v1/pdf/merge', options);

  var pdfCoRespContent = pdfCoResponse.getContentText();
  var pdfCoRespJson = JSON.parse(pdfCoRespContent);

  // Display Result
  if(!pdfCoRespJson.error){
    // Upload file to Google Drive
    uploadFile(pdfCoRespJson.url);

    // Update Cell with result URL
    resultUrlCell.setValue(pdfCoRespJson.url);
  }
  else{
    resultUrlCell.setValue(pdfCoRespJson.message);
  }
}

/**
 * Gets PDF.co Presigned URL
 */
function getPDFcoPreSignedURL(fileName, pdfCoAPIKey){
  // Prepare Request Options
  var options = {
    'method' : 'GET',
    'contentType': 'application/json',
    'headers': {
      "x-api-key": pdfCoAPIKey
    }
  };

  var apiUrl = `https://api.pdf.co/v1/file/upload/get-presigned-url?name=${fileName}`;

  // Get Response
  // https://developers.google.com/apps-script/reference/url-fetch
  var pdfCoResponse = UrlFetchApp.fetch(apiUrl, options);

  var pdfCoRespContent = pdfCoResponse.getContentText();
  var pdfCoRespJson = JSON.parse(pdfCoRespContent);

  return pdfCoRespJson;
}

/**
 * Uploads File to PDF.co PreSigned URL
 */
function uploadFileToPresignedURL(presignedUrl, fileContent, pdfCoAPIKey){
  // Prepare Request Options
  var options = {
    'method' : 'PUT',
    'contentType': 'application/octet-stream',
    'headers': {
      "x-api-key": pdfCoAPIKey
    },
    // Convert the JavaScript object to a JSON string.
    'payload' : fileContent
  };

  // Get Response
  // https://developers.google.com/apps-script/reference/url-fetch
  var pdfCoResponse = UrlFetchApp.fetch(presignedUrl, options);

  if(pdfCoResponse.getResponseCode() === 200){
    return true;
  }
  else{
    return false;
  }
}

/**
 * Save file URL to specific location
 */
function uploadFile(fileUrl) {
  var fileContent = UrlFetchApp.fetch(fileUrl).getBlob();
  folder.createFile(fileContent);
}

</code>```

PDF.co API requires API Key specified in header for request authentication. You can get it by signing up at https://app.pdf.co/signup.

Thanks,
Hiren Patel

ContentLicense: CC BY-SA 3.0

Body:
You can achieve this using pdf.co rest API for merge. Following is source code for your reference.

Source code here is using Google Drive folder to retrieve all PDF files inside, and does merging and saves them back to same folder. However, this can be changed as per our requirement.

/**
 * IMPORTANT: Add Service reference for "Drive". Go to Services > Locate "Drive (drive API)" > Add Reference of it
 */

// Add Your PDF.co API Key here
const pdfCoAPIKey = 'PDFco_API_Key_Here';

// Get the active spreadsheet and the active sheet
ss = SpreadsheetApp.getActiveSpreadsheet();
ssid = ss.getId();

// Look in the same folder the sheet exists in. For example, if this template is in
// My Drive, it will return all of the files in My Drive.
var ssparents = DriveApp.getFileById(ssid).getParents();

// Store File-Ids/PermissionIds used for merging
let filePermissions = [];

/**
 * Note: Here, we're getting current folder where spreadsheet is residing.
 * But we can certainly pick any folder of our like by using Folder related functions.
 * For example:
  var allFolders = DriveApp.getFoldersByName("Folder_Containing_PDF_Files");
  while (allFolders.hasNext()) {
    var folder = allFolders.next();
    Logger.log(folder.getName());
  }
 */
// Loop through all the files and add the values to the spreadsheet.
var folder = ssparents.next();

/**
 * Add PDF.co Menus in Google Spreadsheet
 */
function onOpen() {
  var menuItems = [
    {name: 'Merge All Files From Current Folder', functionName: 'mergePDFDocumentsFromCurrentFolder'}
  ];
  ss.addMenu('PDF.co', menuItems);
}

function mergePDFDocumentsFromCurrentFolder(){
  var allFilesLink = getPDFFilesFromCurFolder(pdfCoAPIKey);
  mergePDFDocuments(allFilesLink, pdfCoAPIKey);
}

/**
 * Get all PDF files from current folder
 */
function getPDFFilesFromCurFolder(pdfCoAPIKey) {
  var files = folder.getFiles();
  var allFileUrls = [];

  while (files.hasNext()) {
    var file = files.next();

    var fileName = file.getName();
    if(fileName.endsWith(".pdf")){
      // Create Pre-Signed URL from PDF.co
      var respPresignedUrl = getPDFcoPreSignedURL(fileName, pdfCoAPIKey)

      if(!respPresignedUrl.error){
        var fileData = file.getBlob();
        if(uploadFileToPresignedURL(respPresignedUrl.presignedUrl, fileData, pdfCoAPIKey)){
          // Add Url
          allFileUrls.push(respPresignedUrl.url);
        }
      }
    }
  }

  return allFileUrls.join(",");
}

/**
 * Merges PDF URLs using PDF.co and Save to drive
 */
function mergePDFDocuments(pdfUrl, pdfCoAPIKey) {

  // Get Cells for Input/Output
  let resultUrlCell =  ss.getRange("A4");

  // Prepare Payload
  var data = {
    "async": false,
    "encrypt": false,
    "inline": true,
    "name": "result",
    "url": pdfUrl
  };

  // Prepare Request Options
  var options = {
    'method' : 'post',
    'contentType': 'application/json',
    'headers': {
      "x-api-key": pdfCoAPIKey
    },
    // Convert the JavaScript object to a JSON string.
    'payload' : JSON.stringify(data)
  };

  // Get Response
  // https://developers.google.com/apps-script/reference/url-fetch
  var pdfCoResponse = UrlFetchApp.fetch('https://api.pdf.co/v1/pdf/merge', options);

  var pdfCoRespContent = pdfCoResponse.getContentText();
  var pdfCoRespJson = JSON.parse(pdfCoRespContent);

  // Display Result
  if(!pdfCoRespJson.error){
    // Upload file to Google Drive
    uploadFile(pdfCoRespJson.url);

    // Update Cell with result URL
    resultUrlCell.setValue(pdfCoRespJson.url);
  }
  else{
    resultUrlCell.setValue(pdfCoRespJson.message);
  }
}

/**
 * Gets PDF.co Presigned URL
 */
function getPDFcoPreSignedURL(fileName, pdfCoAPIKey){
  // Prepare Request Options
  var options = {
    'method' : 'GET',
    'contentType': 'application/json',
    'headers': {
      "x-api-key": pdfCoAPIKey
    }
  };

  var apiUrl = `https://api.pdf.co/v1/file/upload/get-presigned-url?name=${fileName}`;

  // Get Response
  // https://developers.google.com/apps-script/reference/url-fetch
  var pdfCoResponse = UrlFetchApp.fetch(apiUrl, options);

  var pdfCoRespContent = pdfCoResponse.getContentText();
  var pdfCoRespJson = JSON.parse(pdfCoRespContent);

  return pdfCoRespJson;
}

/**
 * Uploads File to PDF.co PreSigned URL
 */
function uploadFileToPresignedURL(presignedUrl, fileContent, pdfCoAPIKey){
  // Prepare Request Options
  var options = {
    'method' : 'PUT',
    'contentType': 'application/octet-stream',
    'headers': {
      "x-api-key": pdfCoAPIKey
    },
    // Convert the JavaScript object to a JSON string.
    'payload' : fileContent
  };

  // Get Response
  // https://developers.google.com/apps-script/reference/url-fetch
  var pdfCoResponse = UrlFetchApp.fetch(presignedUrl, options);

  if(pdfCoResponse.getResponseCode() === 200){
    return true;
  }
  else{
    return false;
  }
}

/**
 * Save file URL to specific location
 */
function uploadFile(fileUrl) {
  var fileContent = UrlFetchApp.fetch(fileUrl).getBlob();
  folder.createFile(fileContent);
}

PDF.co API requires API Key specified in header for request authentication. You can get it by signing up at https://app.pdf.co/signup.

Thanks,
Hiren Patel


问:
Hashtables Python put method showing IndexError
Below is my SimpleHashTable class.

The put(self, key) method should determines where the key is placed in the hashtable when a collision occurs (i.e., calculates the next available index position). Linear probing will be used for collision resolution. I am to do the the following steps:
Invoke the get_hash_index(key) to get the original index position.
Use a while loop to get the next available position.
Store the key into the hashtable according to the available index position.

```<code>class SimpleHashTable:
    def __init__(self, size=7):
        self.size = size
        self.slots = [None] * self.size

    def __str__(self):
        return "{}".format(self.slots)

    def get_hash_index(self, key):
        self.key = key
        self.hkey = key % self.size
        return self.hkey

    def new_hash_code(self, index):
        count = 0
        while count < self.size:
            if self.slots[index] == None:
                return index
            index += 1
            count += 1
        return None

    def put(self, key): #issue here
        code = self.get_hash_index(key)
        if self.slots[code] != None:
            code = self.new_hash_code(code)
        self.slots[code] = key

    def __len__(self):
        count = 0
        for item in self.slots:
            if item != None:
                count += 1
        return count
</code>```

Test:

```<code>my_hash_table = SimpleHashTable(13)
my_hash_table.put(12)
my_hash_table.put(24)
my_hash_table.put(36)
my_hash_table.put(48)
my_hash_table.put(31)
my_hash_table.put(77)
my_hash_table.put(43)
</code>```

Output getting:

```<code>***Error***
Traceback (most recent call last):
  File "__tester__.python3", line 87, in <module>
    my_hash_table.put(77)
  File "__tester__.python3", line 26, in put
    code = self.new_hash_code(code)
  File "__tester__.python3", line 17, in new_hash_code
    if self.slots[index] == None:
IndexError: list index out of range
</code>```

答:
if index is 99 and size is 50

index becomes 49

then

count = 0

index = 49

if my_table[index] is not None

index becomes 50, count becomes 1

count is still less than 50, but index is now out of bounds

beyond that ... your hash table wont work right ... since the hash wont align with the buckets...

you will not be able to implement a better hashtable than builtin dictionary, but you can certainly make a working hashtable

Body:
Below is my SimpleHashTable class.

The put(self, key) method should determines where the key is placed in the hashtable when a collision occurs (i.e., calculates the next available index position). Linear probing will be used for collision resolution. I am to do the the following steps:
Invoke the get_hash_index(key) to get the original index position.
Use a while loop to get the next available position.
Store the key into the hashtable according to the available index position.

class SimpleHashTable:
    def __init__(self, size=7):
        self.size = size
        self.slots = [None] * self.size

    def __str__(self):
        return "{}".format(self.slots)

    def get_hash_index(self, key):
        self.key = key
        self.hkey = key % self.size
        return self.hkey

    def new_hash_code(self, index):
        count = 0
        while count < self.size:
            if self.slots[index] == None:
                return index
            index += 1
            count += 1
        return None

    def put(self, key): #issue here
        code = self.get_hash_index(key)
        if self.slots[code] != None:
            code = self.new_hash_code(code)
        self.slots[code] = key

    def __len__(self):
        count = 0
        for item in self.slots:
            if item != None:
                count += 1
        return count

Test:

my_hash_table = SimpleHashTable(13)
my_hash_table.put(12)
my_hash_table.put(24)
my_hash_table.put(36)
my_hash_table.put(48)
my_hash_table.put(31)
my_hash_table.put(77)
my_hash_table.put(43)

Output getting:

***Error***
Traceback (most recent call last):
  File "__tester__.python3", line 87, in <module>
    my_hash_table.put(77)
  File "__tester__.python3", line 26, in put
    code = self.new_hash_code(code)
  File "__tester__.python3", line 17, in new_hash_code
    if self.slots[index] == None:
IndexError: list index out of range


问:
Invalid hooks call - React Native
I'm new to react native and implementing a flat list. Inside render item of flat list I'm rendering a functional component and I want to use state to change an image if the user selects or deselects it.

The issue I'm facing is that is throws invalid hooks call. I'm tried all the tutorials but it shows the exact same way for describing the state.

```<code>const NewsItem = (props, item, onFavouriteSelect, index) => {

const[isFavourite,setFavourite] = useState(false);

return<Text>Random text for stackoverflow</Text>

}
</code>```

Flat List Code:

```<code>render() {
return (
  <View style={styles.container}>
    {this.state.newsList.length > 0 ? (
      <FlatList
        showsVerticalScrollIndicator={false}
        data={this.state.newsList}
        renderItem={({item, index}) =>
          NewsItem(
            this.props,
            item,
            this.onFavouriteSelect.bind(this),
            index,
            this.state.isFavourite,
          )
        }
      />
    ) : (
      <LoadingScreen />
    )}
  </View>
);
}
</code>```

Versions of react, react dom and react native are mentioned below:

```<code>"react": "17.0.2",
"react-dom": "17.0.2",
"react-native": "0.67.2",
</code>```

Error it throws is:

```<code>Invalid hook call. Hooks can only be called inside of the body of a function component.
This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
</code>```

Thank you.

Updated Code:

```<code>class HomeScreen extends Component {
state = {
newsList: [],
IdsList: [],
isFavourite: false,
};

isFavouriteItem(index) {
if (this.state.IdsList.indexOf(index) === -1) {
  return false;
} else {
  return true;
}
}

render(){
return(){

 <FlatList
   showsVerticalScrollIndicator={false}
   data={this.state.newsList}
   renderItem={({item, index}) =>
          NewsCell(
            this.props,
            item,
            this.onFavouriteSelect.bind(this),
            index,
            this.isFavouriteItem(index),
            this.state.isFavourite,
          )
        }
      />

      }}
</code>```

The updated code I've added now works. But is this a good approach?

答:
Instead of calling const[isFavourite,setFavourite] = useState(false); inside NewsItem, call useState in top-level of your function component.

```<code>const NewsItem = (props, item, onFavouriteSelect, index) => {

    const[isFavourite,setFavourite] = useState(false); //remove this line and place in top-level of your function

  return<Text>Random text for stackoverflow</Text>

}
</code>```

Ref : Breaking the Rules of Hooks

Title: Invalid hooks call - React Native

Body:
I'm new to react native and implementing a flat list. Inside render item of flat list I'm rendering a functional component and I want to use state to change an image if the user selects or deselects it.

The issue I'm facing is that is throws invalid hooks call. I'm tried all the tutorials but it shows the exact same way for describing the state.

const NewsItem = (props, item, onFavouriteSelect, index) => {

const[isFavourite,setFavourite] = useState(false);

return<Text>Random text for stackoverflow</Text>

}

Flat List Code:

render() {
return (
  <View style={styles.container}>
    {this.state.newsList.length > 0 ? (
      <FlatList
        showsVerticalScrollIndicator={false}
        data={this.state.newsList}
        renderItem={({item, index}) =>
          NewsItem(
            this.props,
            item,
            this.onFavouriteSelect.bind(this),
            index,
            this.state.isFavourite,
          )
        }
      />
    ) : (
      <LoadingScreen />
    )}
  </View>
);
}

Versions of react, react dom and react native are mentioned below:

"react": "17.0.2",
"react-dom": "17.0.2",
"react-native": "0.67.2",

Error it throws is:

Invalid hook call. Hooks can only be called inside of the body of a function component.
This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

Thank you.

Updated Code:

class HomeScreen extends Component {
state = {
newsList: [],
IdsList: [],
isFavourite: false,
};

isFavouriteItem(index) {
if (this.state.IdsList.indexOf(index) === -1) {
  return false;
} else {
  return true;
}
}

render(){
return(){

 <FlatList
   showsVerticalScrollIndicator={false}
   data={this.state.newsList}
   renderItem={({item, index}) =>
          NewsCell(
            this.props,
            item,
            this.onFavouriteSelect.bind(this),
            index,
            this.isFavouriteItem(index),
            this.state.isFavourite,
          )
        }
      />

      }}

The updated code I've added now works. But is this a good approach?

Body:
Instead of calling const[isFavourite,setFavourite] = useState(false); inside NewsItem, call useState in top-level of your function component.

const NewsItem = (props, item, onFavouriteSelect, index) => {

    const[isFavourite,setFavourite] = useState(false); //remove this line and place in top-level of your function

  return<Text>Random text for stackoverflow</Text>

}

Ref : Breaking the Rules of Hooks


问:
MessageEmbed field values must be non-empty strings. help command
I am trying to make a help command for my discord bot, when i type .help it gives an error

```<code> /app/node_modules/discord.js/src/util/Util.js:416
     if (typeof data !== 'string') throw new error(errorMessage);
                                   ^

 RangeError [EMBED_FIELD_VALUE]: MessageEmbed field values must be non-empty strings.
     at Function.verifyString (/app/node_modules/discord.js/src/util/Util.js:416:41)
     at Function.normalizeField (/app/node_modules/discord.js/src/structures/MessageEmbed.js:544:19)
     at /app/node_modules/discord.js/src/structures/MessageEmbed.js:565:14
     at Array.map (<anonymous>)
     at Function.normalizeFields (/app/node_modules/discord.js/src/structures/MessageEmbed.js:564:8)
     at MessageEmbed.addFields (/app/node_modules/discord.js/src/structures/MessageEmbed.js:328:42)
     at MessageEmbed.addField (/app/node_modules/discord.js/src/structures/MessageEmbed.js:319:17)
     at Object.execute (/app/commands/informational/help.js:12:10)
     at module.exports (/app/events/messageCreate.js:28:18)
     at Client.emit (node:events:390:28) {
   [Symbol(code)]: 'EMBED_FIELD_VALUE'
 }
</code>```

The code : https://pastebin.com/eyKhB2qs

答: When you are adding a field in your embed, it takes at least three values. The first is the title of the field you are adding and the second is the value of the field. The third value is a boolean and it states whether the field is inline or not. You have only passed the title of the field and you need to pass something in as the value as well such as: .addField('title', 'description', true). You can learn more about embeds in Embeds | Discord.js

Body:
I am trying to make a help command for my discord bot, when i type .help it gives an error

 /app/node_modules/discord.js/src/util/Util.js:416
     if (typeof data !== 'string') throw new error(errorMessage);
                                   ^

 RangeError [EMBED_FIELD_VALUE]: MessageEmbed field values must be non-empty strings.
     at Function.verifyString (/app/node_modules/discord.js/src/util/Util.js:416:41)
     at Function.normalizeField (/app/node_modules/discord.js/src/structures/MessageEmbed.js:544:19)
     at /app/node_modules/discord.js/src/structures/MessageEmbed.js:565:14
     at Array.map (<anonymous>)
     at Function.normalizeFields (/app/node_modules/discord.js/src/structures/MessageEmbed.js:564:8)
     at MessageEmbed.addFields (/app/node_modules/discord.js/src/structures/MessageEmbed.js:328:42)
     at MessageEmbed.addField (/app/node_modules/discord.js/src/structures/MessageEmbed.js:319:17)
     at Object.execute (/app/commands/informational/help.js:12:10)
     at module.exports (/app/events/messageCreate.js:28:18)
     at Client.emit (node:events:390:28) {
   [Symbol(code)]: 'EMBED_FIELD_VALUE'
 }

The code : https://pastebin.com/eyKhB2qs


问:
Redux - Unable to get updated state values in COUNTER
I have just started learning Redux, Having some understanding I tried creating a counter app and the state of my app is not working even after dispatching an action with type. Please share your thoughts.

Here is the source code CODESANDBOX LINK

答:
You'd better use react-redux. See Why Use React Redux?

The process of subscribing to the store, checking for updated data, and triggering a re-render can be made more generic and reusable. A UI binding library like React Redux handles the store interaction logic, so you don't have to write that code yourself.

There is no need to subscribe to the store by yourself. The reason why UI doesn't change even if you dispatch the action is because the App component doesn't re-render to get the latest state from the redux store.

Refactor to this: codesandbox


问:
Convert a list to a data frame
I have a nested list of data. Its length is 132 and each item is a list of length 20. Is there a quick way to convert this structure into a data frame that has 132 rows and 20 columns of data?

Here is some sample data to work with:

```<code>l <- replicate(
  132,
  as.list(sample(letters, 20)),
  simplify = FALSE
)
</code>```

答:
From a different perspective;</p>
```<code>install.packages("smotefamily")
library(smotefamily)
library(dplyr)

data_example = sample_generator(5000,ratio = 0.80)
genData = BLSMOTE(data_example[,-3],data_example[,3])
#There are many lists in genData. If we want to convert one of them to dataframe.

sentetic=as.data.frame.array(genData$syn_data)
# as.data.frame.array seems to be working.
</code>```

Title: Convert a list to a data frame

Body:
I have a nested list of data. Its length is 132 and each item is a list of length 20. Is there a quick way to convert this structure into a data frame that has 132 rows and 20 columns of data?

Here is some sample data to work with:

l <- replicate(
  132,
  as.list(sample(letters, 20)),
  simplify = FALSE
)

Body:
From a different perspective;

install.packages("smotefamily")
library(smotefamily)
library(dplyr)

data_example = sample_generator(5000,ratio = 0.80)
genData = BLSMOTE(data_example[,-3],data_example[,3])
#There are many lists in genData. If we want to convert one of them to dataframe.

sentetic=as.data.frame.array(genData$syn_data)
# as.data.frame.array seems to be working.


问:
Eclipse - java.lang.ClassNotFoundException
When trying to start my JUnit-Test out of Eclipse, I get a "ClassNotFoundException". When running "mvn test" from console - everything works fine. Also, there are no problems reported in Eclipse.

My project structure is the following:

parent project (pom-packaging)

Web project (war-packaging - my JUnit-test is in here)

Flex project

Configuration project

edit: How can the class not be found? It's a simple HelloWorld-Application with no special libraries.

Here's my JUnit's run-configuration:
alt text http://www.walkner.biz/_temp/runconfig.png

Testclass (but as I said; it doesn't work with a simple HelloWorld either...):

```<code>import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import biz.prognoserechnung.domain.User;
import biz.prognoserechnung.domain.UserRepository;
import biz.prognoserechnung.domain.hibernate.UserHibernateDao;

public class UserDaoTest {
/**
 * the applicationcontext.
 */
private ApplicationContext ctx = null;

/**
 * the user itself.
 */
private User record = null;

/**
 * Interface for the user.
 */
private UserRepository dao = null;

@Before
public void setUp() throws Exception {
String[] paths = { "WEB-INF/applicationContext.xml" };
ctx = new ClassPathXmlApplicationContext(paths);
dao = (UserHibernateDao) ctx.getBean("userRepository");
}

@After
public void tearDown() throws Exception {
dao = null;
}

@Test
public final void testIsUser() throws Exception {
Assert.assertTrue(dao.isUser("John", "Doe"));
}

@Test
    public final void testIsNoUser() throws Exception {
    Assert.assertFalse(dao.isUser("not", "existing"));
        Assert.assertFalse(dao.isUser(null, null));
        Assert.assertFalse(dao.isUser("", ""));
    }
}
</code>```

答: For Hybris Project, I fixed the issue by applying below changes in Build Path. I selected Project and clicked on Apply and Close.

Body:
When trying to start my JUnit-Test out of Eclipse, I get a "ClassNotFoundException". When running "mvn test" from console - everything works fine. Also, there are no problems reported in Eclipse.

My project structure is the following:

parent project (pom-packaging)

Web project (war-packaging - my JUnit-test is in here)

Flex project

Configuration project

edit: How can the class not be found? It's a simple HelloWorld-Application with no special libraries.

Here's my JUnit's run-configuration:
alt text http://www.walkner.biz/_temp/runconfig.png

Testclass (but as I said; it doesn't work with a simple HelloWorld either...):

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import biz.prognoserechnung.domain.User;
import biz.prognoserechnung.domain.UserRepository;
import biz.prognoserechnung.domain.hibernate.UserHibernateDao;

public class UserDaoTest {
/**
 * the applicationcontext.
 */
private ApplicationContext ctx = null;

/**
 * the user itself.
 */
private User record = null;

/**
 * Interface for the user.
 */
private UserRepository dao = null;

@Before
public void setUp() throws Exception {
String[] paths = { "WEB-INF/applicationContext.xml" };
ctx = new ClassPathXmlApplicationContext(paths);
dao = (UserHibernateDao) ctx.getBean("userRepository");
}

@After
public void tearDown() throws Exception {
dao = null;
}

@Test
public final void testIsUser() throws Exception {
Assert.assertTrue(dao.isUser("John", "Doe"));
}

@Test
    public final void testIsNoUser() throws Exception {
    Assert.assertFalse(dao.isUser("not", "existing"));
        Assert.assertFalse(dao.isUser(null, null));
        Assert.assertFalse(dao.isUser("", ""));
    }
}


问:
Unexpected directories with Environment.GetFolderPath(Environment.SpecialFolder.Personal)
I am using following to get path to 'My Documents' folder in Windows 7 and iterate through its directories:

```<code>Dim diri As New DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Personal))
For Each diri In diri.GetDirectories
 MessageBox.Show(diri.Name)
Next
</code>```

One of the message boxes I get is for a 'My Music' folder. I do not have that folder in the 'My Documents' folder.

Is this the expected behavior?

答:
Yes.  There is a hidden link in the "Documents" folder named "My Music" that links to your "Music" folder.  There are similar ones for "Pictures" and "Videos".  These are used for backwards compatability with poorly produced Windows XP software that hardcoded the paths to these folder rather than use the system defined settings like you are.

To see all of these links, from the command prompt, type:

```<code>Dir /AL %UserProfile%\Documents
</code>```

Body:
I am using following to get path to 'My Documents' folder in Windows 7 and iterate through its directories:

Dim diri As New DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Personal))
For Each diri In diri.GetDirectories
 MessageBox.Show(diri.Name)
Next

One of the message boxes I get is for a 'My Music' folder. I do not have that folder in the 'My Documents' folder.

Is this the expected behavior?

Body:
Yes.  There is a hidden link in the "Documents" folder named "My Music" that links to your "Music" folder.  There are similar ones for "Pictures" and "Videos".  These are used for backwards compatability with poorly produced Windows XP software that hardcoded the paths to these folder rather than use the system defined settings like you are.

To see all of these links, from the command prompt, type:

Dir /AL %UserProfile%\Documents


问:
CSS Container margin bottom issue
Hi for mobile version I need margin bottom (white space from bottom of the screen) to the container, it was not working. I have tried position absolute still it was not working. I don't know what mistake exactly I did in here.

```<code> ****Desktop version CSS****
       #container {
       width: 70%;
       margin: 0 auto;
       display: flex;
       height: 100vh;
       align-items: center;
</code>```

}

```<code>****mobile version CSS****
 `     #container {
       display: block;
       text-align: center;
       margin-bottom:25px;
}
</code>```

答:
Use this :

            test content

```
<p>And use these styles:</p>
<pre class="lang-css prettyprint-override"><code>html, body {
    padding: 0;
    margin: 0;
    height: 100%;
}
body {
    background-color: red;
}
#container {
    background: blue;
    color: white;
    width: 70%;
    margin: 0 auto;
}
@media(min-width:480px) {
    #container {
        height: 100%;
    }
}
@media(max-width:480px) {
    #container {
        height: calc(100% - 30px);
    }
}
</code>```

Title: CSS Container margin bottom issue

Body:
Hi for mobile version I need margin bottom (white space from bottom of the screen) to the container, it was not working. I have tried position absolute still it was not working. I don't know what mistake exactly I did in here.

 ****Desktop version CSS****
       #container {
       width: 70%;
       margin: 0 auto;
       display: flex;
       height: 100vh;
       align-items: center;

}

****mobile version CSS****
 `     #container {
       display: block;
       text-align: center;
       margin-bottom:25px;
}

Body:
Use this :

<html>
    <body>
        <div id="container">
            test content
        </div>
    </body>
</html>

And use these styles:

html, body {
    padding: 0;
    margin: 0;
    height: 100%;
}
body {
    background-color: red;
}
#container {
    background: blue;
    color: white;
    width: 70%;
    margin: 0 auto;
}
@media(min-width:480px) {
    #container {
        height: 100%;
    }
}
@media(max-width:480px) {
    #container {
        height: calc(100% - 30px);
    }
}


问:
How to obtain Telegram chat_id for a specific user?
How to obtain user chat_id in Telegram bot API?
The documentation says:

Integer | Unique identifier for the message recipient — User or GroupChat id

答:
chat_id is nothing but id of user (telegram user account id). You can start a chat with @get_my_chat_id_bot. It will send you back the chat_id (your user_id).
There are following commonly used ids: channel id, group id, bot id, chat id(user id).


问:
How do you properly stop execution of an express.js endpoint?
I have a middleware error handler that is working great but next(err) and return and return next(err) seems to not stop execution when dealing with promises. What is the proper way to stop execution of my code when an error is found?

For reference: err is a standard Error class in this case.

I don't think you need the code in userProvider.fetchFriends to help with this but if that's wrong please let me know.

```<code>  const uid = req.query.steamUserId;

  //Use the userProvider to get steam friend data
  const friendData = await userProvider.fetchFriends(uid)
  .catch(err => {
    return next(err); //Does not stop execution. Why? just next(err) doesn't either.
  });

  //Putting this after every catch works but seems very stupid. How do I avoid this?
  if(res.writableEnded)
    return;

  ...Other code that runs but causes errors
}
</code>```

答:
You've got two problems here.

First: next() is explicitly continuing to the next middleware or endpoint.

To finish dealing with the request, send a response.

```<code>const middleware = (req, res, next) => {
    if (something(req)) {
        next();
    } else {
        res.status(500).json({ ok: false, msg: "some error message" });
    }
}
</code>```

Second: You need to watch your asynchronous logic carefully.

You can't:

trigger something asynchronous

send a response

send a different response when the asynchronous function is complete

You can only send one response to a request.

Either:

Don't call next or res.something in the catch block and just log the error internally or

Don't call next or res.something outside the promise handling and move it to a then handler instead (you might want to switch to using async/await to make your logic easier to follow)

Body:
I have a middleware error handler that is working great but next(err) and return and return next(err) seems to not stop execution when dealing with promises. What is the proper way to stop execution of my code when an error is found?

For reference: err is a standard Error class in this case.

I don't think you need the code in userProvider.fetchFriends to help with this but if that's wrong please let me know.

  const uid = req.query.steamUserId;

  //Use the userProvider to get steam friend data
  const friendData = await userProvider.fetchFriends(uid)
  .catch(err => {
    return next(err); //Does not stop execution. Why? just next(err) doesn't either.
  });

  //Putting this after every catch works but seems very stupid. How do I avoid this?
  if(res.writableEnded)
    return;

  ...Other code that runs but causes errors
}

Body:
You've got two problems here.

First: next() is explicitly continuing to the next middleware or endpoint.

To finish dealing with the request, send a response.

const middleware = (req, res, next) => {
    if (something(req)) {
        next();
    } else {
        res.status(500).json({ ok: false, msg: "some error message" });
    }
}

Second: You need to watch your asynchronous logic carefully.

You can't:

trigger something asynchronous

send a response

send a different response when the asynchronous function is complete

You can only send one response to a request.

Either:

Don't call next or res.something in the catch block and just log the error internally or

Don't call next or res.something outside the promise handling and move it to a then handler instead (you might want to switch to using async/await to make your logic easier to follow)


问:
configuring swoole http-server without nginx in front
how can I configure a swoole http-server without nginx?
my problem is domain routing. where can I configure a specific domain for swoole http-server in laravel octane?
I have configured an nginx on my server that points to my subdomains (api.domain.com, portal.domain.com).
api and portal both use octane to serve requests.
I wanna know how can I drop nginx and use swoole http-server directly?

thanks in advance and sorry for my eng

答:
Using NGINX as the webserver, load balancer, or reverse proxy (your use case) is not a bad idea.
Let your application handle your business, not web server stuff.

But if you want to handle domains or subdomains in your Laravel application, you can use the Laravel router.

Route::domain('{account}.example.com')->group(function () {
    Route::get('user/{id}', function ($account, $id) {
        //
    });
});
```

Laravel documentation:
https://laravel.com/docs/8.x/routing#route-group-subdomain-routing

Body:
Using NGINX as the webserver, load balancer, or reverse proxy (your use case) is not a bad idea.
Let your application handle your business, not web server stuff.

But if you want to handle domains or subdomains in your Laravel application, you can use the Laravel router.

Route::domain('{account}.example.com')->group(function () {
    Route::get('user/{id}', function ($account, $id) {
        //
    });
});

Laravel documentation:
https://laravel.com/docs/8.x/routing#route-group-subdomain-routing


问:
Unexpected exception after update to vaadin 8
I'm getting the below error on the ListSelect component. A few version back in vaadin 8 it's working file. Now I've updated the version to 8.14.2 then I'm getting this:</p>
```<code>java.lang.IllegalStateException: Client tried fetch more rows than allowed. This is denied to prevent denial of service.
    at com.vaadin.data.provider.DataCommunicator.onRequestRows(DataCommunicator.java:311)
    at com.vaadin.data.provider.DataCommunicator$SimpleDataRequestRpc.requestRows(DataCommunicator.java:74)
    at jdk.internal.reflect.GeneratedMethodAccessor370.invoke(Unknown Source)
</code>```

答:
There is a bug on 8.14.x version when scrolling grid
with grid scroll element and grid has lazy data provider and a lot available hieght. Grid client element fetchs more than 500 rows. If I minimize grid no exception thrown. Exception img</p>

Body:
I'm getting the below error on the ListSelect component. A few version back in vaadin 8 it's working file. Now I've updated the version to 8.14.2 then I'm getting this:

java.lang.IllegalStateException: Client tried fetch more rows than allowed. This is denied to prevent denial of service.
    at com.vaadin.data.provider.DataCommunicator.onRequestRows(DataCommunicator.java:311)
    at com.vaadin.data.provider.DataCommunicator$SimpleDataRequestRpc.requestRows(DataCommunicator.java:74)
    at jdk.internal.reflect.GeneratedMethodAccessor370.invoke(Unknown Source)


问:
Error: unable to locate asset entry in pubspec.yaml: "lib/fonts/IndieFlower-Regular.ttf"
Error: unable to locate asset entry in pubspec.yaml: "lib/fonts/IndieFlower-Regular.ttf".

FAILURE: Build failed with an exception.

Where:
Script 'D:\Flutter project\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1070

What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.

Process 'command 'D:\Flutter project\flutter\bin\flutter.bat'' finished with non-zero exit value 1

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 12s
Exception: Gradle task assembleDebug failed with exit code 1

答:
Welcome to Stackoverflow, Mohamed!

You have to create an assets folder outside the lib directory, in the root of your project and then put the fonts folder in it.

After that, in the pubspec.yaml add these lines in the flutter section:

```<code>flutter:

  fonts:
    - family: font_name
      fonts:
        - asset: assets/fonts/font_name.ttf
</code>```

You can read more about fonts in the Flutter from the official documentation.

Body:
Welcome to Stackoverflow, Mohamed!

You have to create an assets folder outside the lib directory, in the root of your project and then put the fonts folder in it.

After that, in the pubspec.yaml add these lines in the flutter section:

flutter:

  fonts:
    - family: font_name
      fonts:
        - asset: assets/fonts/font_name.ttf

You can read more about fonts in the Flutter from the official documentation.


问:
Why can't I overload constructors in PHP?
I have abandoned all hope of ever being able to overload my constructors in PHP, so what I'd really like to know is why.

Is there even a reason for it? Does it create inherently bad code? Is it widely accepted language design to not allow it, or are other languages nicer than PHP?

答:
In this case I recommend using Interfaces:

```<code>interface IExample {

    public function someMethod();

}

class oneParamConstructor implements IExample {

    public function __construct(private int $someNumber) {

    }

    public function someMethod(){

    }
}

class twoParamConstructor implements IExample {

    public function __construct(private int $someNumber, string $someString) {

    }

    public function someMethod(){

    }
}
</code>```

than in your code:

```<code>function doSomething(IExample $example) {

    $example->someMethod();

}

$a = new oneParamConstructor(12);
$b = new twoParamConstructor(45, "foo");

doSomething($a)
doSomething($b)
</code>```

Body:
In this case I recommend using Interfaces:

interface IExample {

    public function someMethod();

}

class oneParamConstructor implements IExample {

    public function __construct(private int $someNumber) {

    }

    public function someMethod(){

    }
}

class twoParamConstructor implements IExample {

    public function __construct(private int $someNumber, string $someString) {

    }

    public function someMethod(){

    }
}

than in your code:

function doSomething(IExample $example) {

    $example->someMethod();

}

$a = new oneParamConstructor(12);
$b = new twoParamConstructor(45, "foo");

doSomething($a)
doSomething($b)


问:
Visual Studio Code "Error while fetching extensions. XHR failed"
This problem started a few weeks ago, when I started using NordVPN on my laptop.
When I try to search for an extension and even when trying to download through the marketplace I get this error:

EDIT: Just noticed another thing that might indicate to what's causing the issue. When I open VSCode and go to developer tools I get this error messege (before even doing anything):

"(node:19368) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.(Use Code --trace-deprecation ... to show where the warning was created)"

The only partial solution I found so far was to manually download and install extensions.

I've checked similar question here and in other places online, but I didn't find a way to fix this. So far I've tried:

Flushing my DNS cache and setting it to google's DNS server.

Disabling the VPN on my laptop and restarting VS Code.

Clearing the Extension search results.

Disabling all the extensions currently running.

I'm using a laptop running Windows 10. Any other possible solutions I haven't tried?

答:
For me , 'XHR failed' error appears when the proxy settings between your PC system and vs code are conflict.

1.Check PC system proxy settings.

2.Open cmd or terminal, type

echo %http_proxy%, if any output, make sure it fits your pc proxy setting. Because if the proxy on vs code not being set, will be inherited from the http_proxy and https_proxy environment variables.

3.If none, open vs code settings.json , add
"http.proxy":"http://proxyname:port" that fits your pc proxy setting ,without a trailing slash.

Try download extensions again.Hope this helps. ^^


问:
Karate | Can we set payload based on status code condition
We have a post request as below
'''
{
Parameter : "name"
col : 1
}
'''

if the status code is 200 then do nothing, if status code is 400, then
set value : "test" in the above payload as below and send again.

'''
{
Parameter : "name"
col : 1
value : "test"
}
'''

答:
Yes.

```<code>* if (responseStatus == 200) karate.abort()
* request { second: 'time' }
* method post
</code>```

If you want more ideas and also why you shouldn't do these kinds of "clever" tests, read this: https://stackoverflow.com/a/50350442/143475

Body:
Yes.

* if (responseStatus == 200) karate.abort()
* request { second: 'time' }
* method post

If you want more ideas and also why you shouldn't do these kinds of "clever" tests, read this: https://stackoverflow.com/a/50350442/143475