问:
MongoDB NodeJS always expiring after one minute
I am using the MongoDB npm module in my node app and I have this code to create a new object in the collection with a TTL index:

```<code>var utcDate = new Date();
var emailObj = {email: emailAddress, createdAt: utcDate};
dbo.collection("initialEmail").createIndex({ "createdAt": 1 }, { expireAfterSeconds: 3600 });
dbo.collection("initialEmail").insertOne(emailObj, function(err, response) {
    ...
});
</code>```

However, the entry always deletes after about one minute (instead of the 1 hour I set it to be).

I got from my research that mongo runs its script to delete about every one minute. This makes me think that for some reason my mongo server timezone is off from my node server timezone, therefore making the mongo expiration time of the object created already an hour before the current mongo server time.

For the utcDate variable, I have tried:

new Date( moment.utc().format() );

new Date( moment().valueOf() );

new Date(Date.now() - new Date().getTimezoneOffset() * 60 * 1000);

But there was no effect. All of these make the object delete after about 1 minute.

I have also tried: (for utcDate)

moment().valueOf();

Date.now() - new Date().getTimezoneOffset() * 60 * 1000;

But these cause the type of createdAt when viewing the object as JSON to be an int, and the object never gets deleted, (even after waiting many minutes after expected expiration).

How can I ensure the object inserted will always last at least an hour?

答:
I am using docker-compose, with the official mongo image. I switched back to var utcDate = new Date();, and guessed maybe somehow the docker image saved the index for some reason from when, a long time ago, I set the expireAfterSeconds value to 60. And because it does not "change the value of expireAfterSeconds of an existing index," my value must have still been 60.

I deleted the image and ran docker-compose up again and it worked.

I am not using docker volumes at all, so I thought the mongo image would be a completely fresh build each and every time. I do not fully understand the semi-persistence of data in Docker images, so if you understand why the database collection index properties were saved from one up to another, please comment and educate me.

Body:
I am using the MongoDB npm module in my node app and I have this code to create a new object in the collection with a TTL index:

var utcDate = new Date();
var emailObj = {email: emailAddress, createdAt: utcDate};
dbo.collection("initialEmail").createIndex({ "createdAt": 1 }, { expireAfterSeconds: 3600 });
dbo.collection("initialEmail").insertOne(emailObj, function(err, response) {
    ...
});

However, the entry always deletes after about one minute (instead of the 1 hour I set it to be).

I got from my research that mongo runs its script to delete about every one minute. This makes me think that for some reason my mongo server timezone is off from my node server timezone, therefore making the mongo expiration time of the object created already an hour before the current mongo server time.

For the utcDate variable, I have tried:

new Date( moment.utc().format() );

new Date( moment().valueOf() );

new Date(Date.now() - new Date().getTimezoneOffset() * 60 * 1000);

But there was no effect. All of these make the object delete after about 1 minute.

I have also tried: (for utcDate)

moment().valueOf();

Date.now() - new Date().getTimezoneOffset() * 60 * 1000;

But these cause the type of createdAt when viewing the object as JSON to be an int, and the object never gets deleted, (even after waiting many minutes after expected expiration).

How can I ensure the object inserted will always last at least an hour?


来源: stackexchange

问:
Insert multiple strings into a string without adjusting for index changes
The conundrum I have is as follows: I have an array of the pair of indexes of a string at which one character (the third item in the sub-arrays) must be inserted (note, these pairs can be duplicates), e.g.

let arr = [[0, 6, "7"], [0, 6, "h"], [2, 10, "2"], [12, 17, "j"]];

let my_string = "This is a very important string";

for (let i = 0; i < arr.length; i++) {
  // magic code
}

// => my_string now equals "7hth2is i7hs a 2vejry imjportant string";
```

I can't just insert the character at each index because the next pair of indexes in the array will become out of date, due to the previous pair of indexes changing the string and so causing it to have new indexes for each character.

I've also tried slicing the string based on the index pairs (using them as the start and end indexes) and inserting the characters onto these substrings before merging them all together again, but the issue with this is that if two pairs of indexes overlap, then parts of the original string get duplicated.

NOTE: the array is sorted in order from smallest second index in the pair to largest, as shown above. This can be changed. However, the array will always contain pairs of indexes - i.e. I cannot flatten the array into just indexes because of the third item of the arrays being the character I want to insert.

One other thing I tried was going from the end of the array of index pairs to the start, but again the fact that index pairs can overlap means this does not work.

How would I insert the characters at each index in the array of index pairs?

Thanks in advance for any help.

答:
Instead of looping through the array you can loop through the string.

let arr = [[0, 6, "7"], [0, 6, "h"], [2, 10, "2"], [12, 17, "j"]];

let my_string = "This is a very important string";

let str2 = ''
for (let i = 0; i < my_string.length; i++) {
  str2 += arr.filter(x => x.includes(i))
             .reduce(( total, current) => total + current[2],'') + my_string[i];
}

console.log(str2);```
</div>
</div>
</p>

<p>The <code>filter</code> will keep those elements in <code>arr</code> that contains the current index (<code>i</code>) of the loop. </p>

<p>If the <code>filter</code>'s output is not empty then <code>reduce</code> will concatenate all their 3rd elements. Finally the current <code>my_string</code> element is added at the end. </p>

<p>If the <code>filter</code>'s output is empty, <code>reduce</code> will do nothing, so only the current character in <code>my_string</code> is concatenated to <code>str2</code>.</p>

<p>The result:</p>

```7hTh2is i7hs a 2vejry imjportant string
```

ContentLicense: CC BY-SA 4.0

Body:
The conundrum I have is as follows: I have an array of the pair of indexes of a string at which one character (the third item in the sub-arrays) must be inserted (note, these pairs can be duplicates), e.g.

let arr = [[0, 6, "7"], [0, 6, "h"], [2, 10, "2"], [12, 17, "j"]];

let my_string = "This is a very important string";

for (let i = 0; i < arr.length; i++) {
  // magic code
}

// => my_string now equals "7hth2is i7hs a 2vejry imjportant string";

I can't just insert the character at each index because the next pair of indexes in the array will become out of date, due to the previous pair of indexes changing the string and so causing it to have new indexes for each character.

I've also tried slicing the string based on the index pairs (using them as the start and end indexes) and inserting the characters onto these substrings before merging them all together again, but the issue with this is that if two pairs of indexes overlap, then parts of the original string get duplicated.

NOTE: the array is sorted in order from smallest second index in the pair to largest, as shown above. This can be changed. However, the array will always contain pairs of indexes - i.e. I cannot flatten the array into just indexes because of the third item of the arrays being the character I want to insert.

One other thing I tried was going from the end of the array of index pairs to the start, but again the fact that index pairs can overlap means this does not work.

How would I insert the characters at each index in the array of index pairs?

Thanks in advance for any help.

Body:
Instead of looping through the array you can loop through the string.

let arr = [[0, 6, "7"], [0, 6, "h"], [2, 10, "2"], [12, 17, "j"]];

let my_string = "This is a very important string";

let str2 = ''
for (let i = 0; i < my_string.length; i++) {
  str2 += arr.filter(x => x.includes(i))
             .reduce(( total, current) => total + current[2],'') + my_string[i];
}

console.log(str2);

The filter will keep those elements in arr that contains the current index (i) of the loop.

If the filter's output is not empty then reduce will concatenate all their 3rd elements. Finally the current my_string element is added at the end.

If the filter's output is empty, reduce will do nothing, so only the current character in my_string is concatenated to str2.

The result:

7hTh2is i7hs a 2vejry imjportant string


问:
"The page you are requesting cannot be served because of the extension configuration." error message
I'm getting this error message when trying to run my application. I don't know how to fix it:

HTTP Error 404.3 - Not Found The page
  you are requesting cannot be served
  because of the extension
  configuration. If the page is a
  script, add a handler. If the file
  should be downloaded, add a MIME map.

Here's a screenshot of the error page:

What can I do to fix this error?

答:
If you are trying to view an extensionless file what worked for me was adding a MIME Type: File name extension: . MIME type: text/plain

This might have some MVC implications, especially if your Static File Handler is above the Extensionless... handlers (under IIS / Handler Mappings) but might be a work around when you only need this temporarily, like activating SSL Certs.

OwnerDisplayName: delete

ContentLicense: CC BY-SA 3.0


问:
Data Table Solution In R To Find Group Min/Max
Data

```<code>data=data.frame("student"=c(1,1,1,2,2,2,3,3,3),
                "score"=c(NA,7,6,6,1,4,8,NA,3),
                "min"=c(6,6,6,1,1,1,3,3,3),
                "max"=c(7,7,7,6,6,6,8,8,8))
</code>```

I have columns 'student' and 'score' and wish to use data.table to create 'min' and 'max' which simply put are the minimum and maximum values for each student IGNORING NA Values. If all values are NA then simply list 'NA' as the min/max.

答:
But OP wanted to return NA if all scores for any student were NA. This solution fixes the Inf problem.

```<code>data=data.frame("student"=c(1,1,1,2,2,2,3,3,3),
                "score"=c(NA,NA,NA,6,1,4,8,NA,3))
> dt <- data.table(data); dt
   student score
1:       1    NA
2:       1    NA
3:       1    NA
4:       2     6
5:       2     1
6:       2     4
7:       3     8
8:       3    NA
9:       3     3
</code>```

Create a function to handle the case where all values are NA, to return NA

```<code>min.na = function(x) if (all(is.na(x))) x[NA_integer_] else min(x, na.rm = TRUE)
max.na = function(x) if (all(is.na(x))) x[NA_integer_] else max(x, na.rm = TRUE)

dt[, c("min", "max") := list(min.na(score), max.na(score)), by=student]
dt
   student score min max
1:       1    NA  NA  NA
2:       1    NA  NA  NA
3:       1    NA  NA  NA
4:       2     6   1   6
5:       2     1   1   6
6:       2     4   1   6
7:       3     8   3   8
8:       3    NA   3   8
9:       3     3   3   8
</code>```

Edit: And I'm not sure why you'd want to do this anyway. Combining summary statistics to the original data is bad practice. It results in redundancy/duplication. Surely you just want a separate result for each student:

```<code>dt[, .(min=min.na(score), max=max.na(score)), by=student]
   student min max
1:       1  NA  NA
2:       2   1   6
3:       3   3   8
</code>```

I know this last part is not what was asked, but I always check that what they ask for is what they really wanted. ;)

Body:
Data

data=data.frame("student"=c(1,1,1,2,2,2,3,3,3),
                "score"=c(NA,7,6,6,1,4,8,NA,3),
                "min"=c(6,6,6,1,1,1,3,3,3),
                "max"=c(7,7,7,6,6,6,8,8,8))

I have columns 'student' and 'score' and wish to use data.table to create 'min' and 'max' which simply put are the minimum and maximum values for each student IGNORING NA Values. If all values are NA then simply list 'NA' as the min/max.

Body:
But OP wanted to return NA if all scores for any student were NA. This solution fixes the Inf problem.

data=data.frame("student"=c(1,1,1,2,2,2,3,3,3),
                "score"=c(NA,NA,NA,6,1,4,8,NA,3))
> dt <- data.table(data); dt
   student score
1:       1    NA
2:       1    NA
3:       1    NA
4:       2     6
5:       2     1
6:       2     4
7:       3     8
8:       3    NA
9:       3     3

Create a function to handle the case where all values are NA, to return NA

min.na = function(x) if (all(is.na(x))) x[NA_integer_] else min(x, na.rm = TRUE)
max.na = function(x) if (all(is.na(x))) x[NA_integer_] else max(x, na.rm = TRUE)

dt[, c("min", "max") := list(min.na(score), max.na(score)), by=student]
dt
   student score min max
1:       1    NA  NA  NA
2:       1    NA  NA  NA
3:       1    NA  NA  NA
4:       2     6   1   6
5:       2     1   1   6
6:       2     4   1   6
7:       3     8   3   8
8:       3    NA   3   8
9:       3     3   3   8

Edit: And I'm not sure why you'd want to do this anyway. Combining summary statistics to the original data is bad practice. It results in redundancy/duplication. Surely you just want a separate result for each student:

dt[, .(min=min.na(score), max=max.na(score)), by=student]
   student min max
1:       1  NA  NA
2:       2   1   6
3:       3   3   8

I know this last part is not what was asked, but I always check that what they ask for is what they really wanted. ;)


问:
try-catch blocks with the return type
If I have a method that returns something, like

```<code>public DataTable ReturnSomething()
{
   try
   {
      //logic here
     return ds.Tables[0];
   }
   catch (Exception e)
   {
      ErrorString=e.Message;
   }
}
</code>```

This produces compiler error, obviously because catch{} block does not return anything.

So when I have methods with return values I don't use try-catch block, which is a bad practice. If there is an error, I would like to set error string to that error. But then I need a return value as well. Advice?

答:
i'd assume you can still set the message, then return null or whatever the c# equivalent is</p>

```<code>public DataTable ReturnSomething(){
   try {
        //logic here
        return ds.Tables[0];
   } catch (Exception e) {
        ErrorString=e.Message;
        return null;
   }
}
</code>```

OwnerDisplayName: Julia

LastEditorDisplayName: Daniel L

ContentLicense: CC BY-SA 2.5

Title: try-catch blocks with the return type

Body:
If I have a method that returns something, like

public DataTable ReturnSomething()
{
   try
   {
      //logic here
     return ds.Tables[0];
   }
   catch (Exception e)
   {
      ErrorString=e.Message;
   }
}

This produces compiler error, obviously because catch{} block does not return anything.

So when I have methods with return values I don't use try-catch block, which is a bad practice. If there is an error, I would like to set error string to that error. But then I need a return value as well. Advice?

Body:
i'd assume you can still set the message, then return null or whatever the c# equivalent is

public DataTable ReturnSomething(){
   try {
        //logic here
        return ds.Tables[0];
   } catch (Exception e) {
        ErrorString=e.Message;
        return null;
   }
}

OwnerDisplayName: zaczap


问:
Avoid createElement function if it's inside a
 element (contentEditable)
I'm using this function in order to replace
New Divs
 with
 in break lines on contentEditable divs using Safari and Chrome:

```<code>$("#form_description").live("keypress", function(e){
if (e.which == 13) {
if (window.getSelection) {
  var selection = window.getSelection(),
      range = selection.getRangeAt(0),
      br = document.createElement("br");
  range.deleteContents();
  range.insertNode(br);
  range.setStartAfter(br);
  range.setEndAfter(br);
  range.collapse(false);
  selection.removeAllRanges();
  selection.addRange(range);
  return false;
}
}
});
</code>```

The problem is that when I'm typing inside an

Something

 and I press the "return" key, I don't want to get a
, so I can continue whit the list...

How could I create a condition for that function not to work if I'm inside a LI element?

EDIT WITH MY ANSWER:

Ok, I've managed to do it, but If you have any comment on the code, you're welcome:

```<code>$("#form_description").live("keypress", function(e){
if (e.which == 13) {

  node = document.getSelection().anchorNode;
  nodeName = node.parentNode.nodeName.toLowerCase();

  if ((nodeName != "li") && (nodeName != "blockquote")) {
... etc }
</code>```

答:
First, use keyup as the event name, keypress works only on Firefox.

Second, e.which is not always available. Use e.keyCode primarily, and fall back to e.which:

```<code>var code = e.keyCode || e.which;
if (code == 13) {
  // your code here..
}
</code>```

Third, if you need to cancel default events fired in the key-press, you might want to throw in a preventDefault() inside your event handler routine. Make sure it's the first line.

```<code>function(e){
   e.preventDefault();
 ..
}
</code>```

Title: Avoid createElement function if it's inside a <LI> element (contentEditable)

Body:
I'm using this function in order to replace
New Divs
 with
 in break lines on contentEditable divs using Safari and Chrome:

$("#form_description").live("keypress", function(e){
if (e.which == 13) {
if (window.getSelection) {
  var selection = window.getSelection(),
      range = selection.getRangeAt(0),
      br = document.createElement("br");
  range.deleteContents();
  range.insertNode(br);
  range.setStartAfter(br);
  range.setEndAfter(br);
  range.collapse(false);
  selection.removeAllRanges();
  selection.addRange(range);
  return false;
}
}
});

The problem is that when I'm typing inside an

Something

 and I press the "return" key, I don't want to get a
, so I can continue whit the list...

How could I create a condition for that function not to work if I'm inside a LI element?

EDIT WITH MY ANSWER:

Ok, I've managed to do it, but If you have any comment on the code, you're welcome:

$("#form_description").live("keypress", function(e){
if (e.which == 13) {

  node = document.getSelection().anchorNode;
  nodeName = node.parentNode.nodeName.toLowerCase();

  if ((nodeName != "li") && (nodeName != "blockquote")) {
... etc }

Body:
First, use keyup as the event name, keypress works only on Firefox.

Second, e.which is not always available. Use e.keyCode primarily, and fall back to e.which:

var code = e.keyCode || e.which;
if (code == 13) {
  // your code here..
}

Third, if you need to cancel default events fired in the key-press, you might want to throw in a preventDefault() inside your event handler routine. Make sure it's the first line.

function(e){
   e.preventDefault();
 ..
}


问:
How can I fetch a single file at at a specific commit (by hash) from a remote git repository?
I'd like to fetch a file at a commit from a remote git repository without fetching all objects in the repository. I know git archive doesn't work as it can only fetch the tip of a branch.

With sparse-checkout and using protocol v2 (thanks @bk2204) I can create a work-tree with only the readme at a commit, but git transmits 10s of thousands of objects and 188mb.

```<code>mkdir linux
cd linux
git init
git config core.sparseCheckout true
git config protocol.version 2
git remote add origin git@github.com:torvalds/linux.git
echo "/README" > .git/info/sparse-checkout
git fetch --depth 1 origin ab02b61f24c76b1659086fcc8b00cbeeb6e95ac7
git checkout ab02b61f24c76b1659086fcc8b00cbeeb6e95ac7
</code>```

```<code>remote: Enumerating objects: 71432, done.
remote: Counting objects: 100% (71432/71432), done.
remote: Compressing objects: 100% (66651/66651), done.
remote: Total 71432 (delta 5277), reused 25451 (delta 3920), pack-reused 0
Receiving objects: 100% (71432/71432), 188.85 MiB | 7.71 MiB/s, done.
Resolving deltas: 100% (5277/5277), done.
</code>```

Ideally this operation should fetch 3 objects
 - the commit (the known sha) > the commit's tree > the file in the tree

```<code>$ git cat-file -p ab02b61f24c76b1659086fcc8b00cbeeb6e95ac7 | grep tree
tree f6760b0bf32bd3b9a760d6e895c7fb76cd9c2ef8
$ git cat-file -p f6760b0bf32bd3b9a760d6e895c7fb76cd9c2ef8 | grep README
100644 blob 669ac7c32292798644b21dbb5a0dc657125f444d    README
$ git cat-file -p 669ac7c32292798644b21dbb5a0dc657125f444d
</code>```

答:
A hosting service is supposed to have APIs to download a file of a revision or retrieve its content. For example, Gitlab has GET /projects/:id/repository/files/:file_path/raw, and Github has GET /repos/:owner/:repo/contents/:path, and Gerrit has GET /projects/{project-name}/commits/{commit-id}/files/{file-id}/content.

For a simple self-hosting repository, to fetch a random commit or object by git fetch, you could set uploadpack.allowReachableSHA1InWant=true or uploadpack.allowAnySHA1InWant=true. In most cases, they are false(by default) for safety and performance. For a self-hosting Gerrit, it has similar configuration options. I have no idea about a self-hosting Gitlab.

Body:
I'd like to fetch a file at a commit from a remote git repository without fetching all objects in the repository. I know git archive doesn't work as it can only fetch the tip of a branch.

With sparse-checkout and using protocol v2 (thanks @bk2204) I can create a work-tree with only the readme at a commit, but git transmits 10s of thousands of objects and 188mb.

mkdir linux
cd linux
git init
git config core.sparseCheckout true
git config protocol.version 2
git remote add origin git@github.com:torvalds/linux.git
echo "/README" > .git/info/sparse-checkout
git fetch --depth 1 origin ab02b61f24c76b1659086fcc8b00cbeeb6e95ac7
git checkout ab02b61f24c76b1659086fcc8b00cbeeb6e95ac7

remote: Enumerating objects: 71432, done.
remote: Counting objects: 100% (71432/71432), done.
remote: Compressing objects: 100% (66651/66651), done.
remote: Total 71432 (delta 5277), reused 25451 (delta 3920), pack-reused 0
Receiving objects: 100% (71432/71432), 188.85 MiB | 7.71 MiB/s, done.
Resolving deltas: 100% (5277/5277), done.

Ideally this operation should fetch 3 objects
 - the commit (the known sha) > the commit's tree > the file in the tree

$ git cat-file -p ab02b61f24c76b1659086fcc8b00cbeeb6e95ac7 | grep tree
tree f6760b0bf32bd3b9a760d6e895c7fb76cd9c2ef8
$ git cat-file -p f6760b0bf32bd3b9a760d6e895c7fb76cd9c2ef8 | grep README
100644 blob 669ac7c32292798644b21dbb5a0dc657125f444d    README
$ git cat-file -p 669ac7c32292798644b21dbb5a0dc657125f444d


问:
How can I reconfigure Apache from source code using installing openssl?
In a server linux Centos 5 64bit, I have compile from the source code the webserver Apache version 2.4.6.

Below, the configure instruction that I have used.

```<code>./configure --enable-mods-shared=reallyall --with-suexec-caller=apache --enable-cache --enable-cache-disk --with-ldap --enable-ldap --enable-authnz-ldap
</code>```

Now, I must recompile the webserver Apache to using the new installed version of openssl (1.0.1e-fips).

What is the correct syntax to reconfigure Apache to using the current version of openssl installed on the server?

Many thanks at all.

答:
As you unfortunately didn't mention how you installed OpenSSL 1.0.1e-fips (and where), this can't be answered. Based on 1.0.1e-fips, I see some chances that you used my openssl101e RPM package from EPEL 5 (even more important: openssl101e-devel). If so, run

```<code>export CFLAGS="$CFLAGS -I/usr/include/openssl101e"
export CPPFLAGS="$CPPFLAGS -I/usr/include/openssl101e"
export LDFLAGS="$LDFLAGS -L/usr/include/openssl101e"
</code>```

before ./configure. Otherwise you first need to reveal more details about your OpenSSL 1.0.1e-fips installation/update.

Body:
In a server linux Centos 5 64bit, I have compile from the source code the webserver Apache version 2.4.6.

Below, the configure instruction that I have used.

./configure --enable-mods-shared=reallyall --with-suexec-caller=apache --enable-cache --enable-cache-disk --with-ldap --enable-ldap --enable-authnz-ldap

Now, I must recompile the webserver Apache to using the new installed version of openssl (1.0.1e-fips).

What is the correct syntax to reconfigure Apache to using the current version of openssl installed on the server?

Many thanks at all.

Body:
As you unfortunately didn't mention how you installed OpenSSL 1.0.1e-fips (and where), this can't be answered. Based on 1.0.1e-fips, I see some chances that you used my openssl101e RPM package from EPEL 5 (even more important: openssl101e-devel). If so, run

export CFLAGS="$CFLAGS -I/usr/include/openssl101e"
export CPPFLAGS="$CPPFLAGS -I/usr/include/openssl101e"
export LDFLAGS="$LDFLAGS -L/usr/include/openssl101e"

before ./configure. Otherwise you first need to reveal more details about your OpenSSL 1.0.1e-fips installation/update.


问:
How this code to find difference betwen two array of objects works?
I've tested this code from an answer from SO, it basically returns only the items that exists in array 1 that not exists in array 2. But i can't figure out how this works, can someone explain me?

```<code>const arrayOne = [
  { value: "4a55eff3-1e0d-4a81-9105-3ddd7521d642", display: "Jamsheer" },
  { value: "644838b3-604d-4899-8b78-09e4799f586f", display: "Muhammed" },
  { value: "b6ee537a-375c-45bd-b9d4-4dd84a75041d", display: "Ravi" },
  { value: "e97339e1-939d-47ab-974c-1b68c9cfb536", display: "Ajmal" },
  { value: "a63a6f77-c637-454e-abf2-dfb9b543af6c", display: "Ryan" },
];

const arrayTwo = [
  { value: "4a55eff3-1e0d-4a81-9105-3ddd7521d642", display: "Jamsheer"},
  { value: "644838b3-604d-4899-8b78-09e4799f586f", display: "Muhammed"},
  { value: "b6ee537a-375c-45bd-b9d4-4dd84a75041d", display: "Ravi"},
  { value: "e97339e1-939d-47ab-974c-1b68c9cfb536", display: "Ajmal"},
];

const results = arrayOne.filter(({ value: id1 }) => !arrayTwo.some(({ value: id2 }) => id2 === id1));

console.log(results);
</code>```

I think { value: id1 } is destructuring assignment, but it seems to swap the key and value??? And what relation with  id2 === id1?

答:
{ value: id1 } Assign a property to a variable with another name.

For example:

({ a:id, b } = { a: 10, b: 20 });
console.log(id); // 10
console.log(a); // "Uncaught ReferenceError: a is not defined"```
</div>
</div>

2. After assigning the <code>value</code> to <code>id1</code> & <code>id2</code>, now we can check the <code>id1</code> in <code>arrayOne</code> and <code>id2</code> in <code>arrayTwo</code></p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const arrayOne = [
  { value: "4a55eff3-1e0d-4a81-9105-3ddd7521d642", display: "Jamsheer" },
  { value: "644838b3-604d-4899-8b78-09e4799f586f", display: "Muhammed" },
  { value: "b6ee537a-375c-45bd-b9d4-4dd84a75041d", display: "Ravi" },
  { value: "e97339e1-939d-47ab-974c-1b68c9cfb536", display: "Ajmal" },
  { value: "a63a6f77-c637-454e-abf2-dfb9b543af6c", display: "Ryan" },
];

const arrayTwo = [
  { value: "4a55eff3-1e0d-4a81-9105-3ddd7521d642", display: "Jamsheer"},
  { value: "644838b3-604d-4899-8b78-09e4799f586f", display: "Muhammed"},
  { value: "b6ee537a-375c-45bd-b9d4-4dd84a75041d", display: "Ravi"},
  { value: "e97339e1-939d-47ab-974c-1b68c9cfb536", display: "Ajmal"},
];

const results = arrayOne.filter(
                        ({ value : id1  }) => !arrayTwo.some(
                                            ({ value: id2 }) => id2 === id1)
                );
console.log(results);</code>```

The same solution

```<code>const results = arrayOne.filter(
                        item1 => !arrayTwo.some( item2 => item1.value === item2.value)
                );
console.log(results);
</code>```

const arrayOne = [
  { value: "4a55eff3-1e0d-4a81-9105-3ddd7521d642", display: "Jamsheer" },
  { value: "644838b3-604d-4899-8b78-09e4799f586f", display: "Muhammed" },
  { value: "b6ee537a-375c-45bd-b9d4-4dd84a75041d", display: "Ravi" },
  { value: "e97339e1-939d-47ab-974c-1b68c9cfb536", display: "Ajmal" },
  { value: "a63a6f77-c637-454e-abf2-dfb9b543af6c", display: "Ryan" },
];

const arrayTwo = [
  { value: "4a55eff3-1e0d-4a81-9105-3ddd7521d642", display: "Jamsheer"},
  { value: "644838b3-604d-4899-8b78-09e4799f586f", display: "Muhammed"},
  { value: "b6ee537a-375c-45bd-b9d4-4dd84a75041d", display: "Ravi"},
  { value: "e97339e1-939d-47ab-974c-1b68c9cfb536", display: "Ajmal"},
];

// The same solution
const results = arrayOne.filter(
                        item1 => !arrayTwo.some( item2 => item1.value === item2.value)
                );
console.log(results);```

Body:
I've tested this code from an answer from SO, it basically returns only the items that exists in array 1 that not exists in array 2. But i can't figure out how this works, can someone explain me?

const arrayOne = [
  { value: "4a55eff3-1e0d-4a81-9105-3ddd7521d642", display: "Jamsheer" },
  { value: "644838b3-604d-4899-8b78-09e4799f586f", display: "Muhammed" },
  { value: "b6ee537a-375c-45bd-b9d4-4dd84a75041d", display: "Ravi" },
  { value: "e97339e1-939d-47ab-974c-1b68c9cfb536", display: "Ajmal" },
  { value: "a63a6f77-c637-454e-abf2-dfb9b543af6c", display: "Ryan" },
];

const arrayTwo = [
  { value: "4a55eff3-1e0d-4a81-9105-3ddd7521d642", display: "Jamsheer"},
  { value: "644838b3-604d-4899-8b78-09e4799f586f", display: "Muhammed"},
  { value: "b6ee537a-375c-45bd-b9d4-4dd84a75041d", display: "Ravi"},
  { value: "e97339e1-939d-47ab-974c-1b68c9cfb536", display: "Ajmal"},
];

const results = arrayOne.filter(({ value: id1 }) => !arrayTwo.some(({ value: id2 }) => id2 === id1));

console.log(results);

I think { value: id1 } is destructuring assignment, but it seems to swap the key and value??? And what relation with  id2 === id1?

Body:
{ value: id1 } Assign a property to a variable with another name.

For example:

({ a:id, b } = { a: 10, b: 20 });
console.log(id); // 10
console.log(a); // "Uncaught ReferenceError: a is not defined"

2. After assigning the value to id1 & id2, now we can check the id1 in arrayOne and id2 in arrayTwo

const arrayOne = [
  { value: "4a55eff3-1e0d-4a81-9105-3ddd7521d642", display: "Jamsheer" },
  { value: "644838b3-604d-4899-8b78-09e4799f586f", display: "Muhammed" },
  { value: "b6ee537a-375c-45bd-b9d4-4dd84a75041d", display: "Ravi" },
  { value: "e97339e1-939d-47ab-974c-1b68c9cfb536", display: "Ajmal" },
  { value: "a63a6f77-c637-454e-abf2-dfb9b543af6c", display: "Ryan" },
];

const arrayTwo = [
  { value: "4a55eff3-1e0d-4a81-9105-3ddd7521d642", display: "Jamsheer"},
  { value: "644838b3-604d-4899-8b78-09e4799f586f", display: "Muhammed"},
  { value: "b6ee537a-375c-45bd-b9d4-4dd84a75041d", display: "Ravi"},
  { value: "e97339e1-939d-47ab-974c-1b68c9cfb536", display: "Ajmal"},
];

const results = arrayOne.filter(
                        ({ value : id1  }) => !arrayTwo.some(
                                            ({ value: id2 }) => id2 === id1)
                );
console.log(results);

The same solution

const results = arrayOne.filter(
                        item1 => !arrayTwo.some( item2 => item1.value === item2.value)
                );
console.log(results);

const arrayOne = [
  { value: "4a55eff3-1e0d-4a81-9105-3ddd7521d642", display: "Jamsheer" },
  { value: "644838b3-604d-4899-8b78-09e4799f586f", display: "Muhammed" },
  { value: "b6ee537a-375c-45bd-b9d4-4dd84a75041d", display: "Ravi" },
  { value: "e97339e1-939d-47ab-974c-1b68c9cfb536", display: "Ajmal" },
  { value: "a63a6f77-c637-454e-abf2-dfb9b543af6c", display: "Ryan" },
];

const arrayTwo = [
  { value: "4a55eff3-1e0d-4a81-9105-3ddd7521d642", display: "Jamsheer"},
  { value: "644838b3-604d-4899-8b78-09e4799f586f", display: "Muhammed"},
  { value: "b6ee537a-375c-45bd-b9d4-4dd84a75041d", display: "Ravi"},
  { value: "e97339e1-939d-47ab-974c-1b68c9cfb536", display: "Ajmal"},
];

// The same solution
const results = arrayOne.filter(
                        item1 => !arrayTwo.some( item2 => item1.value === item2.value)
                );
console.log(results);


问:
How do I prevent this infinite loop
When I run the following code, sometimes it will exit successfully and sometimes it will enter an infinite loop if highestNum is equal to 255. I understand that this happens because of rollover when 255 gets incremented and becomes 0. I understand why this is happening but I would like advice on stopping this. Should I put an if statement at the end to check if i is equal to the max number and then break at the end? this seems like bad style and something that is easy to forget to fix if i increased the size of the variables.</p>

```<code>    // delete all the files
    for (unsigned char i = 0; i <= highestNum; i++){
        rc = snprintf(formatString, sizeof(formatString), "x%u", i);
        if (rc < 0){
            perror("snprintf in delete");
        }
        rc = unlinkat(directoryFD, formatString, 0);
        if (rc == 0){
            printf("file unlinked\n");
        }
    }
</code>```

答:
You can use a wider type (such as unsigned int) to do this with a minimal code change. Another option is to use a different loop variations, such as a do..while:

```<code>int highestNum = 255;
{
    unsigned char i = 0;
    do {
        printf("%u\n", i);
        ++i;
    } while (i <= highestNum && i != 0);
}
</code>```

This has similar scoping to your for loop in that i does not "escape" the block it's declared in, and the checking for i against zero catches the wrap-around case (something more difficult in a for loop as it checks the condition at the start of each iteration rather than the end).

Note that there's no check to ensure highestNumber is zero or more, so at least one file will always be deleted. If you want the capability to specify no files (eg, you would set highestNumber to -1 if no files were to be deleted), you could add a simple pre-check:

```<code>int highestNum = 255;
if (highestNumber >= 0) {
    unsigned char i = 0;
    do {
        printf("%u\n", i);
        ++i;
    } while (i <= highestNum && i != 0);
}
</code>```

Title: How do I prevent this infinite loop

Body:
When I run the following code, sometimes it will exit successfully and sometimes it will enter an infinite loop if highestNum is equal to 255. I understand that this happens because of rollover when 255 gets incremented and becomes 0. I understand why this is happening but I would like advice on stopping this. Should I put an if statement at the end to check if i is equal to the max number and then break at the end? this seems like bad style and something that is easy to forget to fix if i increased the size of the variables.

    // delete all the files
    for (unsigned char i = 0; i <= highestNum; i++){
        rc = snprintf(formatString, sizeof(formatString), "x%u", i);
        if (rc < 0){
            perror("snprintf in delete");
        }
        rc = unlinkat(directoryFD, formatString, 0);
        if (rc == 0){
            printf("file unlinked\n");
        }
    }

Body:
You can use a wider type (such as unsigned int) to do this with a minimal code change. Another option is to use a different loop variations, such as a do..while:

int highestNum = 255;
{
    unsigned char i = 0;
    do {
        printf("%u\n", i);
        ++i;
    } while (i <= highestNum && i != 0);
}

This has similar scoping to your for loop in that i does not "escape" the block it's declared in, and the checking for i against zero catches the wrap-around case (something more difficult in a for loop as it checks the condition at the start of each iteration rather than the end).

Note that there's no check to ensure highestNumber is zero or more, so at least one file will always be deleted. If you want the capability to specify no files (eg, you would set highestNumber to -1 if no files were to be deleted), you could add a simple pre-check:

int highestNum = 255;
if (highestNumber >= 0) {
    unsigned char i = 0;
    do {
        printf("%u\n", i);
        ++i;
    } while (i <= highestNum && i != 0);
}


问:
Spring Resttemplate : how to post file and common String data at the same time
I meet a request to upload files with spring resttemplate to upload files
with http header "multipart/form-data", also some other normal parameters need to be posted. how to implements that?</p>

答: I got the error "cannot be cast to java.lang.String" although my code does not have any casting.


问:
Switch Parameter and an If Statement
I am trying to use the value of a switch parameter as the trigger to write to a csv file if the parameter is called with the script from the command line.  However, with my current code the csv file is created whether I include the parameter or not.  What's up with that?

Also, is there a better way to handle my else/if else/if else section?

```<code>[CmdletBinding()]
param (
    [Parameter(Mandatory=$true)]
    [string]$dir,
    [Parameter(Mandatory=$true)]
    [int]$days,
    [switch]$csv=$false
)

Process {
    Clear-Host
    $totSize = 0
    $totFiles = 0
    $modDate = (Get-date).AddDays(-$days).Date
    $modfiles = Get-ChildItem -Path $dir -Recurse -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -ge $modDate }
    If ($csv = $true){
        $modfiles | Select-Object -Property FullName, Length,LastWriteTime | Export-Csv -Path .\modFiles.csv -NoTypeInformation
    }
    foreach ($file in $modfiles){
        $totFiles = $totFiles + 1
        $totSize = $totSize + $file.Length
    }

    If ($totSize -lt 1MB){
        $outSize = $totSize/1KB
        $unit = "KB"
    }
    elseif (($totSize -ge 1MB) -and ($totSize -lt 1GB)){
        $outSize = $totSize/1MB
        $unit = "MB"
    }
    elseif ($totSize -ge 1GB){
        $outSize = $totSize/1GB
        $unit = "GB"
    }

    $outRound = [math]::Round($outSize,2)
    Write-Host $totFiles "Files"
    Write-Host $outRound $unit
}
</code>```

答:
Two problems.

Do not specify a default value for a [switch] parameter.  It will mess you up.  Leave it off, and it will be $true if specified, and $false if
not.

When testing a logical value, such as an If statement, do not use the assignment equals (=), use the comparison equals (-eq).

```<code>If ($csv -eq $true){
    $modfiles | Select-Object -Property FullName, Length,LastWriteTime | Export-Csv -Path .\modFiles.csv -NoTypeInformation
}
</code>```

EDIT (Thanks @Scepticalist): Further, if the variable you are testing already holds a [bool] value, or can be implicitly converted to [bool], you don't even need the -eq $true part of the comparison, so:

```<code>If ($csv){
        $modfiles | Select-Object -Property FullName, Length,LastWriteTime | Export-Csv -Path .\modFiles.csv -NoTypeInformation
    }
</code>```

Title: Switch Parameter and an If Statement

Body:
I am trying to use the value of a switch parameter as the trigger to write to a csv file if the parameter is called with the script from the command line.  However, with my current code the csv file is created whether I include the parameter or not.  What's up with that?

Also, is there a better way to handle my else/if else/if else section?

[CmdletBinding()]
param (
    [Parameter(Mandatory=$true)]
    [string]$dir,
    [Parameter(Mandatory=$true)]
    [int]$days,
    [switch]$csv=$false
)

Process {
    Clear-Host
    $totSize = 0
    $totFiles = 0
    $modDate = (Get-date).AddDays(-$days).Date
    $modfiles = Get-ChildItem -Path $dir -Recurse -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -ge $modDate }
    If ($csv = $true){
        $modfiles | Select-Object -Property FullName, Length,LastWriteTime | Export-Csv -Path .\modFiles.csv -NoTypeInformation
    }
    foreach ($file in $modfiles){
        $totFiles = $totFiles + 1
        $totSize = $totSize + $file.Length
    }

    If ($totSize -lt 1MB){
        $outSize = $totSize/1KB
        $unit = "KB"
    }
    elseif (($totSize -ge 1MB) -and ($totSize -lt 1GB)){
        $outSize = $totSize/1MB
        $unit = "MB"
    }
    elseif ($totSize -ge 1GB){
        $outSize = $totSize/1GB
        $unit = "GB"
    }

    $outRound = [math]::Round($outSize,2)
    Write-Host $totFiles "Files"
    Write-Host $outRound $unit
}

Body:
Two problems.

Do not specify a default value for a [switch] parameter.  It will mess you up.  Leave it off, and it will be $true if specified, and $false if
not.

When testing a logical value, such as an If statement, do not use the assignment equals (=), use the comparison equals (-eq).

If ($csv -eq $true){
    $modfiles | Select-Object -Property FullName, Length,LastWriteTime | Export-Csv -Path .\modFiles.csv -NoTypeInformation
}

EDIT (Thanks @Scepticalist): Further, if the variable you are testing already holds a [bool] value, or can be implicitly converted to [bool], you don't even need the -eq $true part of the comparison, so:

If ($csv){
        $modfiles | Select-Object -Property FullName, Length,LastWriteTime | Export-Csv -Path .\modFiles.csv -NoTypeInformation
    }


问:
What is the difference between Java vararg with direct type vs wildcard generic via extends?
How do following 2 Java method declarations differ:

```<code>public <S extends Item> void withExtra1(S... extra) {
    Collections.addAll(pool, extra);
}
</code>```

and:

```<code>public void withExtra2(Item... extra) {
    Collections.addAll(pool, extra);
}
</code>```

答:
The two signatures are equivalent, assuming the caller does not provide an explicit type witness. Any set of arguments that can be accepted by one signature is accepted by the other:

Any set of arguments that is accepted by the first signature, must consist of expressions that have type equal to or a subtype of S, and since S is equal to or a subtype of Item, all the expressions have type equal to or a subtype of Item, and is accepted by the second signature.

Any set of arguments that is accepted by the second signature, must consist of expressions that have type equal to or a subtype of Item, and can be passed to the first signature if S is inferred to be Item (which it can, since Item is within S's bound of extends Item)

Body:
How do following 2 Java method declarations differ:

public <S extends Item> void withExtra1(S... extra) {
    Collections.addAll(pool, extra);
}

and:

public void withExtra2(Item... extra) {
    Collections.addAll(pool, extra);
}


问:
How to properly read an HTTP Post message segmented into two TCP segments?
When I execute the following Python code on a pcap file:

```<code>if tcp.dport == 80:
   try:
      http=dpkt.http.Request(tcp.data)
   except (dpkt.dpkt.NeedData):
      continue
   except (dpkt.dpkt.UnpackError):
      continue
if http.method == 'POST':
   print('POST Message')
</code>```

Packets such as the following ones create a problem:

These are a single HTTP Post message segmented into two TCP segments and each one is sent in a different packet. However, because the first segment is a TCP only and the second one is recognised as HTTP, it seems that when dpkt.http.Request tries to read the first segment as HTTP it fails.

So far no problem. It is OK to fail as it is not really a full HTTP message. However, the issue is that it does not seem to be reading the second segment at all ("POST Message" is not printed)!!! The second segment is totally ignored as if it does not exist!!! The only possible explanation for that is that dpkt automatically reads the second segment at once as it recognises they both are segments for the same message.

The issue is that, though both TCP segments are read at once (following the above assumption), the resulted tcp.data is not recognised as an HTTP packet, rather it is still recognised as TCP only because the first segment of the message is a TCP only packet.

So what shall I do to read the HTTP header and data of such pcap file?

答: Perhaps a bit late. The points raised by @steffen Ullrich are correct. However, assuming you do not have those issues (i.e no lost, duplicate pkts, etc), you can do some rudimentary reassembly like I did for reassembling TLS frames spread over multiple TLS packets. You can apply similar logic to HTTP traffic. You can find my solution in my SO question I posted for a similar issue related to TLS frame reassembly. BTW, in my solution I was using scapy.</p>

Body:
When I execute the following Python code on a pcap file:

if tcp.dport == 80:
   try:
      http=dpkt.http.Request(tcp.data)
   except (dpkt.dpkt.NeedData):
      continue
   except (dpkt.dpkt.UnpackError):
      continue
if http.method == 'POST':
   print('POST Message')

Packets such as the following ones create a problem:

These are a single HTTP Post message segmented into two TCP segments and each one is sent in a different packet. However, because the first segment is a TCP only and the second one is recognised as HTTP, it seems that when dpkt.http.Request tries to read the first segment as HTTP it fails.

So far no problem. It is OK to fail as it is not really a full HTTP message. However, the issue is that it does not seem to be reading the second segment at all ("POST Message" is not printed)!!! The second segment is totally ignored as if it does not exist!!! The only possible explanation for that is that dpkt automatically reads the second segment at once as it recognises they both are segments for the same message.

The issue is that, though both TCP segments are read at once (following the above assumption), the resulted tcp.data is not recognised as an HTTP packet, rather it is still recognised as TCP only because the first segment of the message is a TCP only packet.

So what shall I do to read the HTTP header and data of such pcap file?


问:
WSO2 Identity Server 5.9.0 oAuth2 type of configuration
I want to use WSO2 as a centralized authentication solution for all my clients.

I'm trying to setup this scenario:
Each client as Dev, QA and Prod Environments.
Some users should be able to log in into different environment.

So far, as with oAuth2 I could setup an app id for each environment, and allow or deny authentication per application.

With WSO2, I've been trying to setup some type of differentiated identity vaults, or specify this type of relationship, but  unfortuantely, documentation hasn't been quite illustrative about how things are done.

Documentation talks about SSO but with SSO you have several IDP, in this scenario I want WSO2 IS 5.9.0 to BE the identity provider for all my infrastructure...

答:
MultiTenancy create an IDP for each tenant automatically.

The only thing needed is to login  with the credentials setup when adding the tenant, and WSO2 would handle the rest.

Yes is THAT simple!


问:
What's the jquery syntax for click function of submit button
my form has a submit button that's been defined this way:

```<code><input type="submit" name="submit-reg" value="Register" class="submit button">
</code>```

What is the syntax to call the button's jquery click() function?
I've tried:

```<code>$('#submit-reg').click(function()...
</code>```

But it's not working.

答:
```<code>$("input[@name='submit-reg']").click(
function()
{
   //Code
});
</code>```

Try this jquery code

And, if you want to stop other click events on the same input button then try this

```<code>$("input[@name='submit-reg']").click(
function(event)
{
   event.stopPropagation();
   //Code
});
</code>```

Body:
my form has a submit button that's been defined this way:

<input type="submit" name="submit-reg" value="Register" class="submit button">

What is the syntax to call the button's jquery click() function?
I've tried:

$('#submit-reg').click(function()...

But it's not working.

Body:
$("input[@name='submit-reg']").click(
function()
{
   //Code
});

Try this jquery code

And, if you want to stop other click events on the same input button then try this

$("input[@name='submit-reg']").click(
function(event)
{
   event.stopPropagation();
   //Code
});


答:
I'd say the best way to understand it is to do a refactoring using some old school vanilla JS:

const results = arrayOne.filter(objectOne => {
  return !arrayTwo.some(objectTwo => {
    return objectOne.value === objectTwo.value;
  })
});
```

Here I didn't use object destructuring nor omitted return keyword, it made things a bit more clear.

Title: How this code to find difference betwen two array of objects works?

Body:
I'd say the best way to understand it is to do a refactoring using some old school vanilla JS:

const results = arrayOne.filter(objectOne => {
  return !arrayTwo.some(objectTwo => {
    return objectOne.value === objectTwo.value;
  })
});

Here I didn't use object destructuring nor omitted return keyword, it made things a bit more clear.


问:
How to make multiple route::put in one controller (Laravel 6)
I want to make two Route::put for my controller, but Im having errors when I do this.
I'm having an error like this:

Facade\Ignition\Exceptions\ViewException
  Route [home.callqueue] not defined. (View:
  C:\xampp\htdocs\dqrs\resources\views\dashboard.blade.php)

This is my Controller

```<code>    public function updatenotif(Request $request)
    {
        $request->validate([
            'text'=>['max:255']

        ]);

        DB::table('notifications')->where('id', '1')->update(['text'=>$request->text]);

        return redirect('admin')->withStatus(__('Notification message updated successfully.'));

    }

    public function callqueue(Request $request)
    {
        $request->validate([
            'called'=>['max:255']

        ]);

        $dept=Auth::user()->department;
        Queue::where('department',$dept)
                       ->whereDate('created_at', Carbon::today())
                       ->orderBy('id', 'desc')
                       ->first()
                       ->update(['called'=>$request->called]);

                       return redirect('admin')->withStatus(__('Queue has been called.'));
    }
</code>```

This is my web routes

```<code>  Route::put('admin',['as'=>'home.callqueue','uses'=>'HomeController@callqueue']);
  Route::put('admin',['as'=>'home.updatenotif','uses'=>'HomeController@updatenotif']);
</code>```

答:
You cannot have two routes with the same path unless they have different methods.
And you are getting this error "Route [home.callqueue] not defined" because the second route is overriding the first one.

```<code> Route::put('admin',['as'=>'home.callqueue','uses'=>'HomeController@callqueue']);
 Route::put('admin',['as'=>'home.updatenotif','uses'=>'HomeController@updatenotif']);
</code>```

What you can do is change the paths of your routes to:

```<code> Route::put('admin/callqueue',['as'=>'home.callqueue','uses'=>'HomeController@callqueue']);
 Route::put('admin/updatenotif',['as'=>'home.updatenotif','uses'=>'HomeController@updatenotif']);
</code>```

Body:
I want to make two Route::put for my controller, but Im having errors when I do this.
I'm having an error like this:

Facade\Ignition\Exceptions\ViewException
  Route [home.callqueue] not defined. (View:
  C:\xampp\htdocs\dqrs\resources\views\dashboard.blade.php)

This is my Controller

    public function updatenotif(Request $request)
    {
        $request->validate([
            'text'=>['max:255']

        ]);

        DB::table('notifications')->where('id', '1')->update(['text'=>$request->text]);

        return redirect('admin')->withStatus(__('Notification message updated successfully.'));

    }

    public function callqueue(Request $request)
    {
        $request->validate([
            'called'=>['max:255']

        ]);

        $dept=Auth::user()->department;
        Queue::where('department',$dept)
                       ->whereDate('created_at', Carbon::today())
                       ->orderBy('id', 'desc')
                       ->first()
                       ->update(['called'=>$request->called]);

                       return redirect('admin')->withStatus(__('Queue has been called.'));
    }

This is my web routes

  Route::put('admin',['as'=>'home.callqueue','uses'=>'HomeController@callqueue']);
  Route::put('admin',['as'=>'home.updatenotif','uses'=>'HomeController@updatenotif']);

Body:
You cannot have two routes with the same path unless they have different methods.
And you are getting this error "Route [home.callqueue] not defined" because the second route is overriding the first one.

 Route::put('admin',['as'=>'home.callqueue','uses'=>'HomeController@callqueue']);
 Route::put('admin',['as'=>'home.updatenotif','uses'=>'HomeController@updatenotif']);

What you can do is change the paths of your routes to:

 Route::put('admin/callqueue',['as'=>'home.callqueue','uses'=>'HomeController@callqueue']);
 Route::put('admin/updatenotif',['as'=>'home.updatenotif','uses'=>'HomeController@updatenotif']);


问:
Why is a join ON false much slower that a join with an ON condition that refers the columns but always evaluates to false in Snowflake?
This two queries have the same result but very different execution times, in both cases the ON clause always evaluate to false. In the first query there is a explicit ON false and the second query the ON t1.c1 = t2.c2 will always evaluate to false as well.

```<code>-- query 1
with t1 as (
  select seq4()*2 as c1 from table(generator(rowcount => 1000000))
)
,t2 as (
  select (seq4()*2)+1 as c2 from table(generator(rowcount => 1000000))
)
select * from t1 FULL JOIN t2 ON false; -- takes 16 minutes on a small warehouse

--query 2
with t1 as (
  select seq4()*2 as c1 from table(generator(rowcount => 1000000))
)
,t2 as (
  select (seq4()*2)+1 as c2 from table(generator(rowcount => 1000000))
)
select * from t1 FULL JOIN t2 ON t1.c1 = t2.c2 -- Instantaneous , same results
;
</code>```

According to the snowflake profiler the only difference is that in query 1 we get a FULL OUTER join node with Additional Join Condition 1=0 and in query 2 we get a FULL OUTER join node with Equality Join Condition SYS_VW.C1_0 = SYS_VW.C2_0.

I guess that query 1 is really doing a CROSS JOIN first (1000000 * 1000000 = 10ˆ12 rows) and then filtering that. While query2 is doing just doing a UNION of sorts evaluating only 1000000+1000000 = 2M rows.

But the question is: why? I mean, it's this behaviour specified / required by SQL in general or it's just a miss from the Snowflake query planner / optimizer ?

答:
This does seem to be a miss by Snowflake's query planner. I don't see any docs specific to this example though. Off the top of my head, based on experience in other dbms, my theory here is that it has to do with sargability.

A quick Google search on "sargable" will do more for you than an answer here. But in short, predicates that can take advantage of an index are considered sargable. Most dbms have some situations where a predicate will obviously not interfere with an index (your case is a good example), but the optimizer won't have that specific situation coded for and will then decide "well I'm not sure if an index can still be used, so I'll assume they can't and do this the long way around"

So I'm wondering if something similar is happening here since Snowflake does some different things under the hood for optimizing and "indexing" than most other systems. In your example I would guess that in case 2, it's able to determine that it has two sorted lists of numbers and just has to run through the two lists in order. Whereas in the first list it decides, "I have two sorted lists of numbers, but that isn't relevant to my join predicate... better compare each row to every other row and check the predicate each time"

I'd recommend sending this in to Snowflake in a support ticket.

Body:
This two queries have the same result but very different execution times, in both cases the ON clause always evaluate to false. In the first query there is a explicit ON false and the second query the ON t1.c1 = t2.c2 will always evaluate to false as well.

-- query 1
with t1 as (
  select seq4()*2 as c1 from table(generator(rowcount => 1000000))
)
,t2 as (
  select (seq4()*2)+1 as c2 from table(generator(rowcount => 1000000))
)
select * from t1 FULL JOIN t2 ON false; -- takes 16 minutes on a small warehouse

--query 2
with t1 as (
  select seq4()*2 as c1 from table(generator(rowcount => 1000000))
)
,t2 as (
  select (seq4()*2)+1 as c2 from table(generator(rowcount => 1000000))
)
select * from t1 FULL JOIN t2 ON t1.c1 = t2.c2 -- Instantaneous , same results
;

According to the snowflake profiler the only difference is that in query 1 we get a FULL OUTER join node with Additional Join Condition 1=0 and in query 2 we get a FULL OUTER join node with Equality Join Condition SYS_VW.C1_0 = SYS_VW.C2_0.

I guess that query 1 is really doing a CROSS JOIN first (1000000 * 1000000 = 10ˆ12 rows) and then filtering that. While query2 is doing just doing a UNION of sorts evaluating only 1000000+1000000 = 2M rows.

But the question is: why? I mean, it's this behaviour specified / required by SQL in general or it's just a miss from the Snowflake query planner / optimizer ?


问:
Proxy in IIS to a private Prismic repo - is it possible?
I have an Angular(8) solution that talks to a public Prismic repo through a reverse proxy on the same IIS that Angular is hosted on.

Now I want to talk to a private Prismic repo instead.

How do I set up the proxy to add headers and whatnot?

Is it even possible or does the authorisation require yet a step?

(I don't get it to work in VSCode-rest-client-plugin either. There is documentation on how to get it to work in Postman - and that is what hints me it is not possible to "simply proxy" a call into a private Prismic repo.)

Addendum:

The private Prismic repo has a secret key that must not make its way on to the client.

I hope to add the secret in the proxy as I am in full control of the proxy.

答:
As I hinted in the comments, I think I've got a bit sidetracked by a reverse proxy thing. Correct me if I'm still way off.

Looking at the documentation, as far as I understand it, the only difference between public and private Prismic repo is an extra layer of security (read: API key) that you have to pass along with every request.

Prismic content is distributed through an API that can be configured as private. In private mode, the API requires the client application to authenticate itself to query, retrieve and display any content stored in a Prismic repository.

To prove my point of no proxy needed, I started off a new private repo in Prismic and put together a quick code pen that makes a simple request using angular-prismico as example. Of note here is the PrismicProvider setup:

    PrismicProvider.setApiEndpoint('https://my-instance.cdn.prismic.io/api/v2');
    PrismicProvider.setAccessToken('my master key');
    PrismicProvider.setClientId('some client id');
    PrismicProvider.setClientSecret('some_secret');
```

(the pen has working credentials but it's a throwaway instance that I opened up for this answer so those will likely expire soon)

This brings us to my first suggestion:

use the Angular client library (either Angular2+ or AngularJs as you didn't specify your version). Only do this if you don't care about the api key leaking to public (it might be an option for internal website for example).

Suppose you want to keep the key secret

and this is probably your case. In this situation, a flow similar to my other SO answer will make sense. In short - you somehow authorise clients of your Angular SPA to your IIS-hosted app, and you use Prismic's .net client library to fulfill the requests from clients.

To answer your specific question: yes, implementing a proxy that calls from SPA to Prismic can be done. You could start with this somewhat official sample and build on.

Body:
As I hinted in the comments, I think I've got a bit sidetracked by a reverse proxy thing. Correct me if I'm still way off.

Looking at the documentation, as far as I understand it, the only difference between public and private Prismic repo is an extra layer of security (read: API key) that you have to pass along with every request.

Prismic content is distributed through an API that can be configured as private. In private mode, the API requires the client application to authenticate itself to query, retrieve and display any content stored in a Prismic repository.

To prove my point of no proxy needed, I started off a new private repo in Prismic and put together a quick code pen that makes a simple request using angular-prismico as example. Of note here is the PrismicProvider setup:

    PrismicProvider.setApiEndpoint('https://my-instance.cdn.prismic.io/api/v2');
    PrismicProvider.setAccessToken('my master key');
    PrismicProvider.setClientId('some client id');
    PrismicProvider.setClientSecret('some_secret');

(the pen has working credentials but it's a throwaway instance that I opened up for this answer so those will likely expire soon)

This brings us to my first suggestion:

use the Angular client library (either Angular2+ or AngularJs as you didn't specify your version). Only do this if you don't care about the api key leaking to public (it might be an option for internal website for example).

Suppose you want to keep the key secret

and this is probably your case. In this situation, a flow similar to my other SO answer will make sense. In short - you somehow authorise clients of your Angular SPA to your IIS-hosted app, and you use Prismic's .net client library to fulfill the requests from clients.

To answer your specific question: yes, implementing a proxy that calls from SPA to Prismic can be done. You could start with this somewhat official sample and build on.


问:
Update specific value from specific row with pandas python3
Inside of my tag_data.csv file I want to change the  column for “Posts”  value from “4532” to “1234”  in the the row that contains “metal “

My csv file looks like this:

```<code>    Tag    Posts
0 plastic   2456
0 paper     3449
0 metal     4532
0 other     8722
</code>```

The output should be the file updated and saved to look like this:

```<code>    Tag    Posts
0 plastic   2456
0 paper     3449
0 metal     1234
0 other     8722
</code>```

This is what I’ve been trying:

```<code>read_csv = pd.read_csv(‘tag_data.csv’)

read_csv.loc[read_csv.Tag == ‘metal’, ‘Posts’], [‘Posts’] = 123.to_csv(‘tag_data.csv’)
</code>```

答:
It looks like you're trying to do too much in one line, this should do the value replacement:

```<code>read_csv.loc[(read_csv["Tag"]=="metal"), "Posts"] = 1234
</code>```

Alternatively, you can use replace with a dictionary of values:

```<code>read_csv["Posts"] = read_csv["Posts"].replace({4532: 1234})
</code>```

Body:
Inside of my tag_data.csv file I want to change the  column for “Posts”  value from “4532” to “1234”  in the the row that contains “metal “

My csv file looks like this:

    Tag    Posts
0 plastic   2456
0 paper     3449
0 metal     4532
0 other     8722

The output should be the file updated and saved to look like this:

    Tag    Posts
0 plastic   2456
0 paper     3449
0 metal     1234
0 other     8722

This is what I’ve been trying:

read_csv = pd.read_csv(‘tag_data.csv’)

read_csv.loc[read_csv.Tag == ‘metal’, ‘Posts’], [‘Posts’] = 123.to_csv(‘tag_data.csv’)

Body:
It looks like you're trying to do too much in one line, this should do the value replacement:

read_csv.loc[(read_csv["Tag"]=="metal"), "Posts"] = 1234

Alternatively, you can use replace with a dictionary of values:

read_csv["Posts"] = read_csv["Posts"].replace({4532: 1234})


问:
What should I do when I change the status to graphql mutation?
there is member schema like following

```<code>type Member {
   is_deleted
}
</code>```

when i change only is_deleted field, what is the best practice change that field

using updateMember mutation that can modify all fields

using another changeDeleteStatus mutation that can only change is_delete status

please give me the insight

答: For performance the two has no significant difference. But for me i would use the current updateMember function so that I wont create a new function just for that one operation.</p>

Body:
there is member schema like following

type Member {
   is_deleted
}

when i change only is_deleted field, what is the best practice change that field

using updateMember mutation that can modify all fields

using another changeDeleteStatus mutation that can only change is_delete status

please give me the insight


问:
Qt FlowLayout example - how to get sizeHint to be called when layout changes?
I want to arrange a bunch of QPushButtons in a layout so they will wrap horizontally (like text). I'm trying to use the Qt example FlowLayout in PySide2.

I've posted a simple example revision 2 here

(This is based on the official example here, which is why I'm so perturbed it doesn't work well.)

Specifically, it works well when the window is large enough:

but doesn't prevent the window from being shrunk down small, whereas a VBoxLayout or GridLayout would:

I think the minimum size should depend on the current width. This should be a minimum size:

and so should this:

How can I get the layout to prevent its parent from being shrunk so small that its contents aren't visible?

sizeHint() and minimumSize() always return the size of a single item, which I thought was the problem. However if I rewrite them to take into account all items at the current layout width, it doesn't matter, because both are only called once, when I create and populate the layout.

My best idea so far is to call update() from heightForWidth(), roughly this:

def heightForWidth(self, width):
    oldWidth = self.geometry().width() - 2 * self.contentsMargins().top()
    oldHeight = self.doLayout(QtCore.QRect(0, 0, oldWidth, 0), True)
    height = self.doLayout(QtCore.QRect(0, 0, width, 0), True)
    print 'heightForWidth', width, oldWidth, height, oldHeight
    if height != oldHeight:
        self.update()
    return height
```

full sample with changes to minimumSize and doLayout is revision 3.
 It works sometimes, but has several problems:

When the layout is first created there are constant calls to update(). I think the call to update() triggers a call to heightForWidth() and for some reason the width passed in is not close to the "oldWidth" that I calculate until I resize the window, even by a single pixel.

As soon as I resize the window, calls to heightForWidth() stop completely, and minimumSize() stops being called, and I can no longer resize my window smaller than the last size calculated. I've no idea why.

(Much less important) self.geometry().width() - 2 * self.contentsMargins().top() does not return the width that was last passed to heightForWidth (even when top/bottom/left/right margins are identical), though I took it from other code in the example. This doesn't usually matter but at certain widths it causes a flurry of calls to update()

I suppose I'm doing it all wrong. Can it be done right?

答: I've ported the original/official example to PySide2 now, and it works without changes. I'm not sure what was preventing it from working before.</p>

Body:
I want to arrange a bunch of QPushButtons in a layout so they will wrap horizontally (like text). I'm trying to use the Qt example FlowLayout in PySide2.

I've posted a simple example revision 2 here

(This is based on the official example here, which is why I'm so perturbed it doesn't work well.)

Specifically, it works well when the window is large enough:

but doesn't prevent the window from being shrunk down small, whereas a VBoxLayout or GridLayout would:

I think the minimum size should depend on the current width. This should be a minimum size:

and so should this:

How can I get the layout to prevent its parent from being shrunk so small that its contents aren't visible?

sizeHint() and minimumSize() always return the size of a single item, which I thought was the problem. However if I rewrite them to take into account all items at the current layout width, it doesn't matter, because both are only called once, when I create and populate the layout.

My best idea so far is to call update() from heightForWidth(), roughly this:

def heightForWidth(self, width):
    oldWidth = self.geometry().width() - 2 * self.contentsMargins().top()
    oldHeight = self.doLayout(QtCore.QRect(0, 0, oldWidth, 0), True)
    height = self.doLayout(QtCore.QRect(0, 0, width, 0), True)
    print 'heightForWidth', width, oldWidth, height, oldHeight
    if height != oldHeight:
        self.update()
    return height

full sample with changes to minimumSize and doLayout is revision 3.
 It works sometimes, but has several problems:

When the layout is first created there are constant calls to update(). I think the call to update() triggers a call to heightForWidth() and for some reason the width passed in is not close to the "oldWidth" that I calculate until I resize the window, even by a single pixel.

As soon as I resize the window, calls to heightForWidth() stop completely, and minimumSize() stops being called, and I can no longer resize my window smaller than the last size calculated. I've no idea why.

(Much less important) self.geometry().width() - 2 * self.contentsMargins().top() does not return the width that was last passed to heightForWidth (even when top/bottom/left/right margins are identical), though I took it from other code in the example. This doesn't usually matter but at certain widths it causes a flurry of calls to update()

I suppose I'm doing it all wrong. Can it be done right?


问:
Starting gitk on OS X displays a GreaseKit error
When I load gitk (git version 1.6.5.1) on OS X (SL) I recieve an error/warning about GreaseKit:

Error loading /Library/Application Support/SIMBL/Plugins/GreaseKit.bundle/Contents/MacOS/GreaseKit:  dlopen(/Library/Application Support/SIMBL/Plugins/GreaseKit.bundle/Contents/MacOS/GreaseKit, 265): no suitable image found.  Did find:
    /Library/Application Support/SIMBL/Plugins/GreaseKit.bundle/Contents/MacOS/GreaseKit: GC capability mismatch

gitk does start and appears to be functional. Has anyone seen this? Any need to be concerned?

Thanks,

Scott

答:
You may want to edit the GreaseKit.bundle on your machine manually to only get included into Safari:

Navigate to /Users//Library/Application Support/SIMBL/Plugins/GreaseKit.bundle in Finder and choose to open the package.

Inside there is a Content folder which contains Info.plist. There you change the SIMBLTargetApplications Lines at the end from:

```<code><key>SIMBLTargetApplications</key>
    <array>
        <dict>
            <key>BundleIdentifier</key>
            <string>*</string>
            <key>MaxBundleVersion</key>
            <string>*</string>
            <key>MinBundleVersion</key>
            <string>*</string>
        </dict>
    </array>
</code>```

to

```<code><key>SIMBLTargetApplications</key>
    <array>
        <dict>
            <key>BundleIdentifier</key>
            <string>com.apple.Safari</string>
            <key>MaxBundleVersion</key>
            <string>*</string>
            <key>MinBundleVersion</key>
            <string>*</string>
        </dict>
    </array>
</code>```

You may add other applications you want to have GreaseKit available for.

Alternatively just execute this in a Terminal Window to get to the file:

```<code>edit ~/Library/Application\ Support/SIMBL/Plugins/GreaseKit.bundle/Contents/Info.plist
</code>```

Body:
You may want to edit the GreaseKit.bundle on your machine manually to only get included into Safari:

Navigate to /Users//Library/Application Support/SIMBL/Plugins/GreaseKit.bundle in Finder and choose to open the package.

Inside there is a Content folder which contains Info.plist. There you change the SIMBLTargetApplications Lines at the end from:

<key>SIMBLTargetApplications</key>
    <array>
        <dict>
            <key>BundleIdentifier</key>
            <string>*</string>
            <key>MaxBundleVersion</key>
            <string>*</string>
            <key>MinBundleVersion</key>
            <string>*</string>
        </dict>
    </array>

to

<key>SIMBLTargetApplications</key>
    <array>
        <dict>
            <key>BundleIdentifier</key>
            <string>com.apple.Safari</string>
            <key>MaxBundleVersion</key>
            <string>*</string>
            <key>MinBundleVersion</key>
            <string>*</string>
        </dict>
    </array>

You may add other applications you want to have GreaseKit available for.

Alternatively just execute this in a Terminal Window to get to the file:

edit ~/Library/Application\ Support/SIMBL/Plugins/GreaseKit.bundle/Contents/Info.plist


问:
index.html:42 Uncaught ReferenceError: function is not defined
I am using a node.js server to serve an index.html file that imports a module which contains something like this:

```<code><script type="text/javascript" src="SomeModule.js"></script>
.
.
.
<input id="plot_graph" type="button" onclick="plotGraph()" class="ghost-button" value="Plot Graph">
</code>```

When I access the webpage and click the button I end up getting the error Uncaught SyntaxError: Cannot use import statement outside a module. I did some reading and realized I need to include the script as a module so I modified the
```

<p>The error goes away when I go to the page but as soon as I click the button I get the error <code>ReferenceError: module is not defined at...</code></p>

<p>Can someone explain why my module can't be imported? How can I import this module?</p>

```SomeModule.js

import * as Chart from './node_modules/chart.js/dist/Chart.js'
function plotGraph()
{
    .
    .
    .
}
module.exports.plotGraph = plotGraph; // Error complains about this line.
```

答:
module.exports is a CommonJS module, you should be using ES6 format.

```<code>...
export plotGraph;
</code>```

and then use the function from a script

```<code><script type="module">
  import { plotGraph } from 'SomeModule';

  document.getElementById('plot_graph').addEventListener('click', plotGraph);
<script>
</code>```

Body:
I am using a node.js server to serve an index.html file that imports a module which contains something like this:

.
.
.
<input id="plot_graph" type="button" onclick="plotGraph()" class="ghost-button" value="Plot Graph">

When I access the webpage and click the button I end up getting the error Uncaught SyntaxError: Cannot use import statement outside a module. I did some reading and realized I need to include the script as a module so I modified the

The error goes away when I go to the page but as soon as I click the button I get the error ReferenceError: module is not defined at...

Can someone explain why my module can't be imported? How can I import this module?

SomeModule.js

import * as Chart from './node_modules/chart.js/dist/Chart.js'
function plotGraph()
{
    .
    .
    .
}
module.exports.plotGraph = plotGraph; // Error complains about this line.

Body:
module.exports is a CommonJS module, you should be using ES6 format.

...
export plotGraph;

and then use the function from a script

<script type="module">
  import { plotGraph } from 'SomeModule';

  document.getElementById('plot_graph').addEventListener('click', plotGraph);
<script>


问:
Update binary files in Node.js
I'm trying to work with binary files using Node.js.

I'm trying to receive a binary file from the client, open the binary file, convert to hexadecimal, replace data and return the new binary file to the client.

```<code>app.use('/read-binary-file',(req,res) => {
    try {
        let content = fs.readFileSync(file_path);
        console.log('content', content)
        res.status(200).send({content})
    }
    catch(err) {
        console.error(err);
    }
})
</code>```

I wrote code that takes an existing file and try to read it. When I print it, I get this in the buffer:

```<code>content <Buffer 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ... >
</code>```

I'm not sure how to convert it to hexadecimal and then try to change it...
When I read the file via online hex editor, I get them in 16 bit each line and this way is very comfortable.

I have some questions:

How can convert from binary to hexadecimal?

How can I replace data in a hexadecimal file and then return to the client?

How can I display them in code as 16 bit?

What is the best way to store them in a database? To store the file and then
in the database store only the path?

Is there any documentation that can help?

答:
You don't need to convert binary data to hexadecimal in order to replace anything in it. If you want to replace data inside a binary file, then it means that you know exactly what you want to replace, which means specific offsets based on some patterns or data structure or byte chunks you'll have to search for.

If you want to create an online hex editor for your clients, then that's a totally different thing and it involves not only backend logic, but also a UI that will let the users upload/edit and download files.

Replacing binary data with binary data on fixed offset using Buffer.copy:

// The first three bytes of data Buffer will be replaced with 0x02 0x03 0x04 bytes
Buffer.alloc(3, new Uint8Array([0x02, 0x03, 0x04])).copy(data, 0, 0, 3);
```
<h3>Using <code>Buffer.indexOf</code> to search for binary data patterns:</h3>
<pre class="lang-js prettyprint-override"><code>// Loading a PNG image
const data = fs.readFileSync('js-logo-16x16.png');

// Search for the PNG signature using Buffer.indexOf
const sigpos = data.indexOf(Buffer.from('PNG'));

if (sigpos >= 0) {
  // If signature pos found (!= -1), replace it with JPG using Buffer.write
  data.write('JPG', sigpos, 3);
}
</code>```

You can use simple loop and string manipulation logic to print hexadecimal data:

// For Node.js using a Buffer
function displayHexData(data) {
  for (let addr = 0; addr <= data.length; addr += 16) {
    const displayAddr = addr.toString(16).toUpperCase().padStart(8, '0');
    const block = data.slice(addr, Math.min(addr + 16, data.length));

    let hexblock = block.toString('hex');

    if (addr + 16 > data.length) {
      hexblock += '  '.repeat(16 - (data.length - addr));
    }

    const charsblock = Array.from(block)
      .map(b => b >= 32 && b <= 126 ? String.fromCharCode(b) : '.')
      .join('');

    console.log(displayAddr, hexblock.split(/(.{2})/).join(' '), charsblock);
  }
}
```
<p>will output something like this:</p>
<p><img src="https://i.stack.imgur.com/kIoBU.png" alt="Node.js binary data hex display" /></p>
<h3>And for web JavaScript:</h3>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// 16 x 16 PNG 8-bit
const base64Data = 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAA3NCSVQICAjb4U/gAAAAMFBMVEUAAADQvhqQghFBOgj/7iAjIAT84x+6qxdqYA3u1x2nlxT//CIxLAZKQwnOuhnZyBvQr3QtAAAACXBIWXMAAAsSAAALEgHS3X78AAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAAAFNJREFUCJljSIMCBlIZKW4ubmBGhkrtdTDD1Yz5rBuI4XOTyQUs4mPdEA4SSfGx3n7gCZDxKfV+24fVQEYBQyED6zQgI39d2qyVIMUpW9Kyt6UBAGorNUfBuVldAAAAAElFTkSuQmCC';

const data = Uint8Array.from(atob(base64Data), c => c.charCodeAt(0));

displayHexData(data);

function displayHexData(data) {
  let result = '';

  for (let addr = 0; addr <= data.length; addr += 16) {
    const displayAddr = addr.toString(16).toUpperCase().padStart(8, '0');
    const block = data.slice(addr, Math.min(addr + 16, data.length));

    let hexblock = Array.from (block)
      .map (b => b.toString(16).toUpperCase().padStart(2, "0"))
      .join('');

    if (addr + 16 > data.length) {
      hexblock += '  '.repeat(16 - (data.length - addr));
    }

    const charsblock = Array.from(block)
      .map(b => b >= 32 && b <= 126 ? String.fromCharCode(b) : '.')
      .join('');

    result += `${displayAddr} ${hexblock.split(/(.{2})/).join(' ')} ${charsblock}\n`;
  }

  document.getElementById('hex').appendChild(document.createTextNode(result));
}</code>```

#hex {
  font-size: small;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><pre id="hex">``````

As for saving binary data to the database, it depends of course on the database type. Most databases support the Binary Large OBject (BLOB) data type, like MySQL and you use it to store binary data. Saving the file to the filesystem and just using a field to save its path is also a pretty good way to go, but you'll have to handle backups/restores, including those directories where the files will be stored.

Title: Update binary files in Node.js

Body:
I'm trying to work with binary files using Node.js.

I'm trying to receive a binary file from the client, open the binary file, convert to hexadecimal, replace data and return the new binary file to the client.

app.use('/read-binary-file',(req,res) => {
    try {
        let content = fs.readFileSync(file_path);
        console.log('content', content)
        res.status(200).send({content})
    }
    catch(err) {
        console.error(err);
    }
})

I wrote code that takes an existing file and try to read it. When I print it, I get this in the buffer:

content <Buffer 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ... >

I'm not sure how to convert it to hexadecimal and then try to change it...
When I read the file via online hex editor, I get them in 16 bit each line and this way is very comfortable.

I have some questions:

How can convert from binary to hexadecimal?

How can I replace data in a hexadecimal file and then return to the client?

How can I display them in code as 16 bit?

What is the best way to store them in a database? To store the file and then
in the database store only the path?

Is there any documentation that can help?

Body:
You don't need to convert binary data to hexadecimal in order to replace anything in it. If you want to replace data inside a binary file, then it means that you know exactly what you want to replace, which means specific offsets based on some patterns or data structure or byte chunks you'll have to search for.

If you want to create an online hex editor for your clients, then that's a totally different thing and it involves not only backend logic, but also a UI that will let the users upload/edit and download files.

Replacing binary data with binary data on fixed offset using Buffer.copy:

// The first three bytes of data Buffer will be replaced with 0x02 0x03 0x04 bytes
Buffer.alloc(3, new Uint8Array([0x02, 0x03, 0x04])).copy(data, 0, 0, 3);

Using Buffer.indexOf to search for binary data patterns:

// Loading a PNG image
const data = fs.readFileSync('js-logo-16x16.png');

// Search for the PNG signature using Buffer.indexOf
const sigpos = data.indexOf(Buffer.from('PNG'));

if (sigpos >= 0) {
  // If signature pos found (!= -1), replace it with JPG using Buffer.write
  data.write('JPG', sigpos, 3);
}

You can use simple loop and string manipulation logic to print hexadecimal data:

// For Node.js using a Buffer
function displayHexData(data) {
  for (let addr = 0; addr <= data.length; addr += 16) {
    const displayAddr = addr.toString(16).toUpperCase().padStart(8, '0');
    const block = data.slice(addr, Math.min(addr + 16, data.length));

    let hexblock = block.toString('hex');

    if (addr + 16 > data.length) {
      hexblock += '  '.repeat(16 - (data.length - addr));
    }

    const charsblock = Array.from(block)
      .map(b => b >= 32 && b <= 126 ? String.fromCharCode(b) : '.')
      .join('');

    console.log(displayAddr, hexblock.split(/(.{2})/).join(' '), charsblock);
  }
}

will output something like this:

And for web JavaScript:

// 16 x 16 PNG 8-bit
const base64Data = 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAA3NCSVQICAjb4U/gAAAAMFBMVEUAAADQvhqQghFBOgj/7iAjIAT84x+6qxdqYA3u1x2nlxT//CIxLAZKQwnOuhnZyBvQr3QtAAAACXBIWXMAAAsSAAALEgHS3X78AAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAAAFNJREFUCJljSIMCBlIZKW4ubmBGhkrtdTDD1Yz5rBuI4XOTyQUs4mPdEA4SSfGx3n7gCZDxKfV+24fVQEYBQyED6zQgI39d2qyVIMUpW9Kyt6UBAGorNUfBuVldAAAAAElFTkSuQmCC';

const data = Uint8Array.from(atob(base64Data), c => c.charCodeAt(0));

displayHexData(data);

function displayHexData(data) {
  let result = '';

  for (let addr = 0; addr <= data.length; addr += 16) {
    const displayAddr = addr.toString(16).toUpperCase().padStart(8, '0');
    const block = data.slice(addr, Math.min(addr + 16, data.length));

    let hexblock = Array.from (block)
      .map (b => b.toString(16).toUpperCase().padStart(2, "0"))
      .join('');

    if (addr + 16 > data.length) {
      hexblock += '  '.repeat(16 - (data.length - addr));
    }

    const charsblock = Array.from(block)
      .map(b => b >= 32 && b <= 126 ? String.fromCharCode(b) : '.')
      .join('');

    result += `${displayAddr} ${hexblock.split(/(.{2})/).join(' ')} ${charsblock}\n`;
  }

  document.getElementById('hex').appendChild(document.createTextNode(result));
}

#hex {
  font-size: small;
}

<pre id="hex"></pre>

As for saving binary data to the database, it depends of course on the database type. Most databases support the Binary Large OBject (BLOB) data type, like MySQL and you use it to store binary data. Saving the file to the filesystem and just using a field to save its path is also a pretty good way to go, but you'll have to handle backups/restores, including those directories where the files will be stored.


问:
how to call getsupportfragmentmanager() from adapter class?
I have ViewPager as the first item inside a RecyclerView.I want to set FragmentStatePagerAdapter to the viewpager inside the onBindViewHolder() method.
But i can't call getsupportfragmentmanager().Please help!!.
Here's my code:

```<code>public class CustomListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private Context context;
    private List<RowItem> rowItemList;
    private final int VIEW_TYPE_CUSTOM = 0;
    private final int VIEW_TYPE_NORMAL = 1;
    NewPagerAdapter mCustomPagerAdapter;

    public CustomListAdapter(Context context, List<RowItem> rowItemList) {
        this.context = context;
        this.rowItemList = rowItemList;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0)
            return VIEW_TYPE_CUSTOM;
        else
            return VIEW_TYPE_NORMAL;
    }

    @Override
    public int getItemCount() {
        return rowItemList.size()+1;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        switch (getItemViewType(position)) {
            case VIEW_TYPE_CUSTOM:
                recViewHolder1 viewHolderSecond = (recViewHolder1) holder;
                    mCustomPagerAdapter = new NewPagerAdapter(getSupportFragmentManager());
                    viewHolderSecond.vPager.setAdapter(mCustomPagerAdapter);
                break;
            case VIEW_TYPE_NORMAL:
                recViewHolder2 viewHolderFirst = (recViewHolder2) holder;
                RowItem rowItem = rowItemList.get(position-1);
                viewHolderFirst.vName.setText(rowItem.getName());
                viewHolderFirst.vImage.setImageResource(rowItem.getImageId());
                break;

        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case VIEW_TYPE_CUSTOM:
                View itemView = LayoutInflater.
                        from(parent.getContext()).
                        inflate(R.layout.pagerlayout, parent, false);
                return new recViewHolder1(itemView);
            case VIEW_TYPE_NORMAL:
                View itemView1 = LayoutInflater.
                        from(parent.getContext()).
                        inflate(R.layout.rowlayout, parent, false);
                return new recViewHolder2(itemView1);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return super.getItemId(position);
    }

    public static class recViewHolder1 extends RecyclerView.ViewHolder {
        protected static ViewPager vPager;

        public recViewHolder1(View v) {
            super(v);
            vPager = (ViewPager) v.findViewById(R.id.vPager);
        }
    }

    public class recViewHolder2 extends RecyclerView.ViewHolder implements View.OnClickListener {
        protected  TextView vName;
        protected  ImageView vImage;

        public recViewHolder2(View v) {
            super(v);
            v.setOnClickListener(this);
            vName = (TextView) v.findViewById(R.id.vName);
            vImage = (ImageView) v.findViewById(R.id.vImage);
        } } }
</code>```

答:
I worked as follows:</p>
```<code>@Override
public void onBindViewHolder(DataAdapter.ViewHolder holder, final int position) {

        holder.txtTitle.setText(list.get(position).getTitle());
        holder.txtMessage.setText(list.get(position).getMessage());

        holder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String title = list.get(position).getTitle();

                if(title.equals("FRECUENTES")){
                    RequestFrequentFragment fragment = new RequestFrequentFragment(); // you fragment
                    FragmentManager fragmentManager = ((FragmentActivity) v.getContext()).getSupportFragmentManager(); // instantiate your view context
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    fragmentTransaction.replace(R.id.nav_host_fragment, fragment);// your container and your fragment
                    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                    fragmentTransaction.addToBackStack(null);
                    fragmentTransaction.commit();

                }

            }
        });
}
</code>```

Body:
I have ViewPager as the first item inside a RecyclerView.I want to set FragmentStatePagerAdapter to the viewpager inside the onBindViewHolder() method.
But i can't call getsupportfragmentmanager().Please help!!.
Here's my code:

public class CustomListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private Context context;
    private List<RowItem> rowItemList;
    private final int VIEW_TYPE_CUSTOM = 0;
    private final int VIEW_TYPE_NORMAL = 1;
    NewPagerAdapter mCustomPagerAdapter;

    public CustomListAdapter(Context context, List<RowItem> rowItemList) {
        this.context = context;
        this.rowItemList = rowItemList;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0)
            return VIEW_TYPE_CUSTOM;
        else
            return VIEW_TYPE_NORMAL;
    }

    @Override
    public int getItemCount() {
        return rowItemList.size()+1;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        switch (getItemViewType(position)) {
            case VIEW_TYPE_CUSTOM:
                recViewHolder1 viewHolderSecond = (recViewHolder1) holder;
                    mCustomPagerAdapter = new NewPagerAdapter(getSupportFragmentManager());
                    viewHolderSecond.vPager.setAdapter(mCustomPagerAdapter);
                break;
            case VIEW_TYPE_NORMAL:
                recViewHolder2 viewHolderFirst = (recViewHolder2) holder;
                RowItem rowItem = rowItemList.get(position-1);
                viewHolderFirst.vName.setText(rowItem.getName());
                viewHolderFirst.vImage.setImageResource(rowItem.getImageId());
                break;

        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case VIEW_TYPE_CUSTOM:
                View itemView = LayoutInflater.
                        from(parent.getContext()).
                        inflate(R.layout.pagerlayout, parent, false);
                return new recViewHolder1(itemView);
            case VIEW_TYPE_NORMAL:
                View itemView1 = LayoutInflater.
                        from(parent.getContext()).
                        inflate(R.layout.rowlayout, parent, false);
                return new recViewHolder2(itemView1);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return super.getItemId(position);
    }

    public static class recViewHolder1 extends RecyclerView.ViewHolder {
        protected static ViewPager vPager;

        public recViewHolder1(View v) {
            super(v);
            vPager = (ViewPager) v.findViewById(R.id.vPager);
        }
    }

    public class recViewHolder2 extends RecyclerView.ViewHolder implements View.OnClickListener {
        protected  TextView vName;
        protected  ImageView vImage;

        public recViewHolder2(View v) {
            super(v);
            v.setOnClickListener(this);
            vName = (TextView) v.findViewById(R.id.vName);
            vImage = (ImageView) v.findViewById(R.id.vImage);
        } } }

Body:
I worked as follows:

@Override
public void onBindViewHolder(DataAdapter.ViewHolder holder, final int position) {

        holder.txtTitle.setText(list.get(position).getTitle());
        holder.txtMessage.setText(list.get(position).getMessage());

        holder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String title = list.get(position).getTitle();

                if(title.equals("FRECUENTES")){
                    RequestFrequentFragment fragment = new RequestFrequentFragment(); // you fragment
                    FragmentManager fragmentManager = ((FragmentActivity) v.getContext()).getSupportFragmentManager(); // instantiate your view context
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    fragmentTransaction.replace(R.id.nav_host_fragment, fragment);// your container and your fragment
                    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                    fragmentTransaction.addToBackStack(null);
                    fragmentTransaction.commit();

                }

            }
        });
}


答:
Node JS has some support for ECMAScript Modules such as import. However require works better . I think I use it in one of my projects No problems with require...

```<code>var Chart = require('chart.js');
var myChart = new Chart(ctx, {...});
</code>```

Just NPM install the module into your working directory and it works perfectly .

Title: index.html:42 Uncaught ReferenceError: function is not defined

Body:
Node JS has some support for ECMAScript Modules such as import. However require works better . I think I use it in one of my projects No problems with require...

var Chart = require('chart.js');
var myChart = new Chart(ctx, {...});

Just NPM install the module into your working directory and it works perfectly .