问:
Sort by day of the week from Monday to Sunday
If I write

```<code>select ename, to_char(hiredate,'fmDay') as "Day" order by "Day";
</code>```

Then it sorts the result based on Day like; from Friday, then Monday and last Wednesday,
like sorting by characters.

But I want to sort it by day of the week; from Monday to Sunday.

答:
This is my solution.

```<code>select ename, to_char(hiredate,'fmDay') "Day"
from employees
order by DECODE(to_number(to_char(hiredate ,'D'))-1,
                                                0, 7,
                to_number(to_char(hiredate ,'D'))-1);
</code>```

Basically converts day to a number by using 'D' format from to_char function.

```<code>to_number(to_char(hire_date ,'D')
</code>```

But that causes Sunday to be 1 and Monday to be 2 and so on so I subtract 1 to make Monday 1.

```<code>(to_number(to_char(hire_date ,'D') - 1
</code>```

Then I use DECODE function to basically say if 0, then 7, else original number. That just makes Sunday be 7 instead of 0 and everything else is in its proper place(Monday is 1, Tuesday is 2...so on).

```<code>DECODE(to_number(to_char(hire_date ,'D'))-1,
                                                0, 7,
                to_number(to_char(hire_date ,'D'))-1);
</code>```

Body:
If I write

select ename, to_char(hiredate,'fmDay') as "Day" order by "Day";

Then it sorts the result based on Day like; from Friday, then Monday and last Wednesday,
like sorting by characters.

But I want to sort it by day of the week; from Monday to Sunday.

Body:
This is my solution.

select ename, to_char(hiredate,'fmDay') "Day"
from employees
order by DECODE(to_number(to_char(hiredate ,'D'))-1,
                                                0, 7,
                to_number(to_char(hiredate ,'D'))-1);

Basically converts day to a number by using 'D' format from to_char function.

to_number(to_char(hire_date ,'D')

But that causes Sunday to be 1 and Monday to be 2 and so on so I subtract 1 to make Monday 1.

(to_number(to_char(hire_date ,'D') - 1

Then I use DECODE function to basically say if 0, then 7, else original number. That just makes Sunday be 7 instead of 0 and everything else is in its proper place(Monday is 1, Tuesday is 2...so on).

DECODE(to_number(to_char(hire_date ,'D'))-1,
                                                0, 7,
                to_number(to_char(hire_date ,'D'))-1);


来源: stackexchange

问:
how to resolve minikube start error : This computer doesn't have VT-X/AMD-v enabled. Enabling it in the BIOS is mandatory

minikube v1.25.1 on Microsoft Windows 10 Home Single Language 10.0.19043 Build 19043

MINIKUBE_HOME=C:\os\minikube\Minikube

Automatically selected the virtualbox driver

Starting control plane node minikube in cluster minikube

Creating virtualbox VM (CPUs=2, Memory=4000MB, Disk=20000MB) ...
! StartHost failed, but will try again: creating host: create: precreate: This computer doesn't have VT-X/AMD-v enabled. Enabling it in the BIOS is mandatory

Creating virtualbox VM (CPUs=2, Memory=4000MB, Disk=20000MB) ...

Failed to start virtualbox VM. Running "minikube delete" may fix it: creating host: create: precreate: This computer doesn't have VT-X/AMD-v enabled. Enabling it in the BIOS is mandatory

X Exiting due to HOST_VIRT_UNAVAILABLE: Failed to start host: creating host: create: precreate: This computer doesn't have VT-X/AMD-v enabled. Enabling it in the BIOS is mandatory

Suggestion: Virtualization support is disabled on your computer. If you are running minikube within a VM, try '--driver=docker'. Otherwise, consult your systems BIOS manual for how to enable virtualization.

Related issues:

https://github.com/kubernetes/minikube/issues/3900

https://github.com/kubernetes/minikube/issues/4730

答:
Try this command - It will work. I faced the similar issue on my Laptop.
Tried multiple ways to resolve this issue however nothing has worked for me.
Also, the error message states that VT-X/AMD-V should be enabled in BIOS which is mandatory but this cannot be found in my BIOS settings.
I tried the below command to resolve this issue and the minikube started normally.

minikube start --no-vtx-check

Refer this thread:
https://www.virtualbox.org/ticket/4032

ContentLicense: CC BY-SA 4.0


问:
Can I run a list of Robo Scripts?
Is there a way to run a list of Robo Scripts (locally or to Firebase Test Lab) instead of running them one by one?

The way to run Robo Scripts locally one at a time is the following:

java -jar crawl_launcher.jar --apk-file your_app.apk --app-package-name your.app.package.name --android-sdk path/to/android/sdk -—robo-script-file generated_script.json

Moreover, is it possible to stop the App Crawler when the Robo Script is completed? (e.g. with a command in the script). Now, when the App Crawler completes the steps of the script proceeds to explore the app as usual with random actions.

答:
You can add

```<code>{
  "eventType": "TERMINATE_CRAWL"
}
</code>```

as the last action in your Roboscript. It will stop Robo when Roboscript finishes.

Title: Can I run a list of Robo Scripts?

Body:
You can add

{
  "eventType": "TERMINATE_CRAWL"
}

as the last action in your Roboscript. It will stop Robo when Roboscript finishes.


问:
How to pass html textbox value to a javascript function
I have a HTML textbox where user will input some string which i want to pass to a JavaScript function:

```<code><input type="text" id="ad_search_query" style="width:295px">
<input type="button" value="<s:text name="button.search"/>" class="p-userButton"
 onClick="ADSEARCHGF.showTable('');"/>
</code>```

Please suggest how can i do it.

答:
```<code><script>
function showTable(obj){
alert(obj.value)
}
</script>

<input type="text" id="ad_search_query" style="width:295px">
<input type="button" value="search" class="p-userButton" onClick="showTable(document.getElementById('ad_search_query'));"/>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a HTML textbox where user will input some string which i want to pass to a JavaScript function:

<input type="text" id="ad_search_query" style="width:295px">
<input type="button" value="<s:text name="button.search"/>" class="p-userButton"
 onClick="ADSEARCHGF.showTable('');"/>

Please suggest how can i do it.

Body:
<script>
function showTable(obj){
alert(obj.value)
}
</script>

<input type="text" id="ad_search_query" style="width:295px">&nbsp;
<input type="button" value="search" class="p-userButton" onClick="showTable(document.getElementById('ad_search_query'));"/>


问:
global vairable did not initialize correctly between running multiple test cases in c++
I am still actively learning c++ with a strong background in python3, the point of this question is not seeking any help with solving the problem Decode Variations on leetcode or pramp, but to understand the compilation or syntax related issue in c++.

The following code using dfs runs well if I run it case by case, however on pramp, it failed in RUN TESTS! Very surprising! It seems like in test case #2  int n=0; was not initialized and used the output of n in test case #1 as its value rather than 0, see the console in the attached screenshot at the end.

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

using namespace std;

int n=0;

void dfs(const string& s, int i){
  if (i==s.size()){
    n++;
    return;
  }
  if ( 0<s[i]-'0' && s[i]-'0'<10)
    dfs(s, i+1);
  if (i+1<s.size() && 10<=stoi(s.substr(i,2)) && stoi(s.substr(i,2))<=26)
    dfs(s, i+2);
}

int decodeVariations(const string& s)
{

  dfs(s,0);
  cout<<n<<endl;
  return n;
}

int main()
{

    return 0;
}
</code>```

Here is the code to run test case #2:

```<code>int main()
{
  const string s = "26";
  dfs(s,0);
  cout<<n<<endl;
    return 0;
}
</code>```

If I added another initialization of n=0; to int decodeVariations(const string& s), then everything works fine. I try to become a programmer with a clear mind, please educate me.

答:
Yes, non-const global variable is evil. Even though I don't know how leetcode and pramp (especially, the main function is empty) run a number of test cases, but I get a hunch it runs test case in the main function, which only compile and run the code once. Thus the global did not get reinitialized.

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

using namespace std;

int n=0;

void dfs(const string& s, int i){
    if (i==s.size()){
        n++;
        return;
    }
    if ( 0<s[i]-'0' && s[i]-'0'<10)
        dfs(s, i+1);
    if (i+1<s.size() && 10<=stoi(s.substr(i,2)) && stoi(s.substr(i,2))<=26)
        dfs(s, i+2);
}

int decodeVariations(const string& s)
{

    dfs(s,0);
    return n;
}

int main(int argc, char **argv){
    for (int i=1;i<argc;i++)
        cout<<decodeVariations(argv[i])<<endl;
}
</code>```

run with ./test 26 26 26
output:

```<code>2

4

6
</code>```

Quick fix is to get rid of global variable

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

using namespace std;

//int n=0;
int dfs(const string& s, int i){
  int ans = 0;
  if (i==s.size()){
    return 1;
  }
  if ( 0<s[i]-'0' && s[i]-'0'<10)
     ans += dfs(s, i+1);
  if (i+1<s.size() && 10<=stoi(s.substr(i,2)) && stoi(s.substr(i,2))<=26)
     ans += dfs(s, i+2);
  return ans;
}

int decodeVariations(const string& s)
{
    // your code goes here
  int n;
  n = dfs(s,0);
  cout<<n<<endl;
  return n;
}

</code>```

Body:
I am still actively learning c++ with a strong background in python3, the point of this question is not seeking any help with solving the problem Decode Variations on leetcode or pramp, but to understand the compilation or syntax related issue in c++.

The following code using dfs runs well if I run it case by case, however on pramp, it failed in RUN TESTS! Very surprising! It seems like in test case #2  int n=0; was not initialized and used the output of n in test case #1 as its value rather than 0, see the console in the attached screenshot at the end.

#include <iostream>
#include <string>

using namespace std;

int n=0;

void dfs(const string& s, int i){
  if (i==s.size()){
    n++;
    return;
  }
  if ( 0<s[i]-'0' && s[i]-'0'<10)
    dfs(s, i+1);
  if (i+1<s.size() && 10<=stoi(s.substr(i,2)) && stoi(s.substr(i,2))<=26)
    dfs(s, i+2);
}

int decodeVariations(const string& s)
{

  dfs(s,0);
  cout<<n<<endl;
  return n;
}

int main()
{

    return 0;
}

Here is the code to run test case #2:

int main()
{
  const string s = "26";
  dfs(s,0);
  cout<<n<<endl;
    return 0;
}

If I added another initialization of n=0; to int decodeVariations(const string& s), then everything works fine. I try to become a programmer with a clear mind, please educate me.

Body:
Yes, non-const global variable is evil. Even though I don't know how leetcode and pramp (especially, the main function is empty) run a number of test cases, but I get a hunch it runs test case in the main function, which only compile and run the code once. Thus the global did not get reinitialized.

#include <iostream>
#include <string>

using namespace std;

int n=0;

void dfs(const string& s, int i){
    if (i==s.size()){
        n++;
        return;
    }
    if ( 0<s[i]-'0' && s[i]-'0'<10)
        dfs(s, i+1);
    if (i+1<s.size() && 10<=stoi(s.substr(i,2)) && stoi(s.substr(i,2))<=26)
        dfs(s, i+2);
}

int decodeVariations(const string& s)
{

    dfs(s,0);
    return n;
}

int main(int argc, char **argv){
    for (int i=1;i<argc;i++)
        cout<<decodeVariations(argv[i])<<endl;
}

run with ./test 26 26 26
output:

2

4

6

Quick fix is to get rid of global variable

#include <iostream>
#include <string>

using namespace std;

//int n=0;
int dfs(const string& s, int i){
  int ans = 0;
  if (i==s.size()){
    return 1;
  }
  if ( 0<s[i]-'0' && s[i]-'0'<10)
     ans += dfs(s, i+1);
  if (i+1<s.size() && 10<=stoi(s.substr(i,2)) && stoi(s.substr(i,2))<=26)
     ans += dfs(s, i+2);
  return ans;
}

int decodeVariations(const string& s)
{
    // your code goes here
  int n;
  n = dfs(s,0);
  cout<<n<<endl;
  return n;
}


问:
Not all of my constructors are being imported?
I'm making a heap class to be importable with heap.h and my constructors including bool types do not work, yet every other constructor and function imported works.

Here is what's in heap.h:

```<code>#ifndef __HEAP_INCLUDED__
#define __HEAP_INCLUDED__

#include <iostream>
#include <vector>

using namespace std;

class heap{
int capacity;
bool isMinHeap;  //1 is min heap -- ascending order
vector<int> * content;
public:
heap();
heap(bool t);
heap(vector<int> * input);
heap(vector<int> * input, bool t);

void print();
void prettyPrint();
int parent(int i);
int leftChild(int i);
int rightChild(int i);
int size();
int getMax();
void insert(int data);
void heapifyDown(int index);
void heapifyUp(int index);
int invalidChild(int index);
int deleteMax();
int deleteMin();
bool minDir();
int at(int index);
};

vector<int> * heapSort(vector<int> * input);

void swap(vector<int> * vec, int a, int b);

#endif
</code>```

Here are the defined constructors in heap.cpp. Note, all constructors work fine when I add a main to this file to test stuff:

```<code>class heap{
    vector<int> * content;
    int capacity = 256;
    bool isMinHeap;  //1 is min heap -- ascending order

    public:
    heap(){
        content = new vector<int>;
        isMinHeap = 0;
    }
    heap(bool t){
        content = new vector<int>;
        isMinHeap = t;
    }
    heap(vector<int> * input){
        content = input;
        isMinHeap = true;
        for(int i = content->size()/2; i >= 0; i--){
            heapifyDown(i);
        }
    }
    heap(vector<int> * input, bool t){
        content = input;
        isMinHeap = t;
        for(int i = content->size()/2; i >= 0; i--){
            heapifyDown(i);
        }
    }
//other functions below
}
</code>```

The constructors with bool do not work in main.cpp, which has #include "heap.h" at the top. The files are all in the same directory and I am compiling with this command: g++ heap.cpp main.cpp -o main. Why do two of my constructors not work?

The error I see is

```<code>/usr/bin/ld: /tmp/ccwomODk.o: in function `main':
main.cpp:(.text+0x4e2): undefined reference to `heap::heap(bool)'
collect2: error: ld returned 1 exit status
</code>```

-Wall does not elaborate on the issue. I'm pretty sure the issue is with my linking somewhere because the constructors work inside of heap.cpp when I use them in there.

答:
When you declare a program element such as a class, function, or
variable, its name can only be "seen" and used in certain parts of
your program. The context in which a name is visible is called its
scope. For example, if you declare a variable x within a function, x
is only visible within that function body.

It seems you broke ODR rule so bad. Your class members including constructors has no body declared in the source file(heap.cpp).
Use '::' to make class members have a body:

```<code>//heap.cpp
"heap.h"
heap::heap()
{
}
heap:heap(vector<int> * input, bool t)
{
}
int heap::parent(int i)
{
    return i;
}
// this is how you create a body for function that are class members
// the same should be done for all other functions
</code>```

Body:
I'm making a heap class to be importable with heap.h and my constructors including bool types do not work, yet every other constructor and function imported works.

Here is what's in heap.h:

#ifndef __HEAP_INCLUDED__
#define __HEAP_INCLUDED__

#include <iostream>
#include <vector>

using namespace std;

class heap{
int capacity;
bool isMinHeap;  //1 is min heap -- ascending order
vector<int> * content;
public:
heap();
heap(bool t);
heap(vector<int> * input);
heap(vector<int> * input, bool t);

void print();
void prettyPrint();
int parent(int i);
int leftChild(int i);
int rightChild(int i);
int size();
int getMax();
void insert(int data);
void heapifyDown(int index);
void heapifyUp(int index);
int invalidChild(int index);
int deleteMax();
int deleteMin();
bool minDir();
int at(int index);
};

vector<int> * heapSort(vector<int> * input);

void swap(vector<int> * vec, int a, int b);

#endif

Here are the defined constructors in heap.cpp. Note, all constructors work fine when I add a main to this file to test stuff:

class heap{
    vector<int> * content;
    int capacity = 256;
    bool isMinHeap;  //1 is min heap -- ascending order

    public:
    heap(){
        content = new vector<int>;
        isMinHeap = 0;
    }
    heap(bool t){
        content = new vector<int>;
        isMinHeap = t;
    }
    heap(vector<int> * input){
        content = input;
        isMinHeap = true;
        for(int i = content->size()/2; i >= 0; i--){
            heapifyDown(i);
        }
    }
    heap(vector<int> * input, bool t){
        content = input;
        isMinHeap = t;
        for(int i = content->size()/2; i >= 0; i--){
            heapifyDown(i);
        }
    }
//other functions below
}

The constructors with bool do not work in main.cpp, which has #include "heap.h" at the top. The files are all in the same directory and I am compiling with this command: g++ heap.cpp main.cpp -o main. Why do two of my constructors not work?

The error I see is

/usr/bin/ld: /tmp/ccwomODk.o: in function `main':
main.cpp:(.text+0x4e2): undefined reference to `heap::heap(bool)'
collect2: error: ld returned 1 exit status

-Wall does not elaborate on the issue. I'm pretty sure the issue is with my linking somewhere because the constructors work inside of heap.cpp when I use them in there.

Body:
When you declare a program element such as a class, function, or
variable, its name can only be "seen" and used in certain parts of
your program. The context in which a name is visible is called its
scope. For example, if you declare a variable x within a function, x
is only visible within that function body.

It seems you broke ODR rule so bad. Your class members including constructors has no body declared in the source file(heap.cpp).
Use '::' to make class members have a body:

//heap.cpp
"heap.h"
heap::heap()
{
}
heap:heap(vector<int> * input, bool t)
{
}
int heap::parent(int i)
{
    return i;
}
// this is how you create a body for function that are class members
// the same should be done for all other functions


问:
Regex string split with multiple conditions
(Javascript older version of Node.js)

Edit I have to clear up what I want.

I have multiple lines like these

```<code>var name1;

CONST    name2

   Let  nam;

leT     nam

  VAr n1  ;
</code>```

My desired outputs are

```<code>name1

name2

nam

nam

n1
</code>```

So I am trying codes like this.

```<code>/[^;]*/
</code>```

But I need help because I have multiple patterns. Some may have semicolons/space/null after the variable names, I need to omit those.

答:
use /(?<=(var\s+)|(let\s+)|(const\s+))(\w+)/gim

let data = `
var name1;

CONST    name2

   Let  nam;

leT     nam

  VAr n1  ;
`;
data = data.match(/(?<=(var\s+)|(let\s+)|(const\s+))(\w+)/gim);
console.log(data); // [ 'name1', 'name2', 'nam', 'nam', 'n1' ]```

Body:
(Javascript older version of Node.js)

Edit I have to clear up what I want.

I have multiple lines like these

var name1;

CONST    name2

   Let  nam;

leT     nam

  VAr n1  ;

My desired outputs are

name1

name2

nam

nam

n1

So I am trying codes like this.

/[^;]*/

But I need help because I have multiple patterns. Some may have semicolons/space/null after the variable names, I need to omit those.


问:
How to do the correct request signature for amazon spapi with aws4?
I make an integration with amazon spapi, but I couldn't get restricted token from api. I couldn't sign the request. My signed request doesn't match the api's one. Here is my signature code with js. The code make an Autharization sentence and I try the sentence with Postman.
The Postman's result is here.

```<code>    {
    "errors": [
        {
            "message": "The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.

The Canonical String for this request should have been
'POST
/tokens/2021-03-01/restrictedDataToken

host:sandbox.sellingpartnerapi-eu.amazon.com
user-agent:PostmanRuntime/7.28.2
x-amz-access-token:Atza|*****

host;user-agent;x-amz-access-token
2328dd129c329e308cb990d33878a6d5ffd2a8c96e62d13b873dc62d5a7ff20b'

The String-to-Sign should have been
'AWS4-HMAC-SHA256
20210805T134800Z
20210805/eu-west-1/execute-api/aws4_request
c2f03a5e26f63dfae25fcf4cb1490c88fcbdcb78760d357f9234b5d46ac0f824'
",
     "code": "InvalidSignature"
        }
    ]
}
</code>```

Where is my fault?

signer.html

```<code><html>

<head>
    <style>
        table {
            width: 80%
        }

        input {
            width: 100%;
        }

        textarea {
            width:100%;
            height: 200px;
        }
    </style>
</head>

<body>
    <table>
        <tr>
            <td width="10%">Access Key Id</td>
            <td>
                <input type="text" id="accessKeyId" name="accessKeyId" value="AKIAZIX*******" />
            </td>
        </tr>
        <tr>
            <td>Secret Access Key</td>
            <td>
                <input type="text" id="secretAccessKey" name="secretAccessKey" value="3nwTlA06******" />
            </td>
        </tr>
        <tr>
            <td>Access Token</td>
            <td>
                <input type="text" id="token" name="token" value="" />
            </td>
        </tr>
        <tr>
            <td>Region</td>
            <td>
                <input type="text" id="region" name="region" value="eu-west-1" />
            </td>
        </tr>
        <tr>
            <td>Service</td>
            <td>
                <input type="text" id="service" name="service" value="execute-api" />
            </td>
        </tr>
        <tr>
            <td>Method</td>
            <td>
                <input type="text" id="method" name="method" value="POST" />
            </td>
        </tr>
        <tr>
            <td>Host</td>
            <td>
                <input type="text" id="host" name="host" value="sandbox.sellingpartnerapi-eu.amazon.com" />
            </td>
        </tr>
        <tr>
            <td>URI</td>
            <td>
                <input type="text" id="uri" name="uri" value="/tokens/2021-03-01/restrictedDataToken" />
            </td>
        </tr>
        <tr>
            <td>Query</td>
            <td>
                <input type="text" id="query" name="query" value="" />
            </td>
        </tr>
        <tr>
            <td>Data</td>
            <td>
                <input type="text" id="data" name="data" value='{"restrictedResources":[{"method":"GET","path":"/catalog/2020-12-01/items"}]}' />
            </td>
        </tr>
        <tr>
            <td>Header</td>
            <td><textarea id="header"></textarea></td>
        </tr>
        <tr>
            <td></td>
            <td><button id="send">Send</button></td>
        </tr>
    </table>

    <script src="script/crypto-js.min.js"></script>
    <script src="script/sha256.min.js"></script>
    <script src="script/hmac-sha256.min.js"></script>
    <script src="script/enc-base64.min.js"></script>
    <script src="script/bundle.js"></script>

    <script type="text/javascript">
        document.getElementById('send').onclick = function () {
            var crd = new Credentials(
                document.getElementById('accessKeyId').value,
                document.getElementById('secretAccessKey').value,
                document.getElementById('token').value,
                document.getElementById('region').value,
                document.getElementById('service').value
            );

            var req = new Requests(
                document.getElementById('method').value,
                document.getElementById('host').value,
                document.getElementById('uri').value,
                document.getElementById('query').value,
                document.getElementById('data').value
                );

            var signer = new Signer(crd,req);

            document.getElementById('header').value = signer.execute();
        }
    </script>
</body>

</html>
</code>```

bundle.js

```<code>class Credentials {
  constructor(accessKeyId, secretAccessKey, token, region, service) {
    this.accessKeyId = accessKeyId;
    this.secretAccessKey = secretAccessKey;
    this.token = token;
    this.region = region;
    this.service = service;
  }
}

class Requests {
  constructor(method, host, uri, query, data) {
    this.method = method;
    this.host = host;
    this.uri = uri;
    this.query = query;
    this.data = data;
  }
}

class Signer {
  private
  date = new Date();
  termStr = "aws4_request";
  algo = "AWS4-HMAC-SHA256";
  signedHeaders = "host;user-agent;x-amz-access-token";
  userAgent = "PostmanRuntime/7.28.2";

  canonicalHeaders = function () {
    var a = new Array(
      "host:" + this.request.host,
      "user-agent:" + this.userAgent,
      "x-amz-access-token:" + this.credentials.token
    );

    return a.join("\n");
  };

  canonicalRequest = function () {
    var result = '';

    var a = new Array(
      this.request.method.toUpperCase(),
      this.request.uri,
      this.queryParameters(this.request.query),
      this.canonicalHeaders() + "\n",
      this.signedHeaders,
      this.hash(this.request.data)
    );

    result = a.join("\n");
    console.log("canonicalRequest : \n"+result);

    return result;
  };

  credentialScope = function () {
    var a = new Array(
      this.amzShortDate(),
      this.credentials.region,
      this.credentials.service,
      this.termStr
    );

    return a.join("/");
  };

  requestToSign = function () {
    var result = '';

    var a = new Array(
      this.algo,
      this.amzLongDate(),
      this.credentialScope(),
      this.hash(this.canonicalRequest())
    );

    result = a.join("\n");
    console.log("requestToSign : \n"+result);

    return result;
  };

  signature = function () {
    var result = "";

    result = this.hmac(
      "AWS4" + this.credentials.secretAccessKey,
      this.amzShortDate()
    );
    result = this.hmac(result, this.credentials.region);
    result = this.hmac(result, this.service);
    result = this.hmac(result, this.termStr);
    result = this.hmac(result, this.requestToSign()).toString();

    return result;
  };

  authorizationHeader = function () {
    var a = new Array(
      "Credential=" + this.credentials.accessKeyId + "/" + this.credentialScope(),
      "SignedHeaders=" + this.signedHeaders,
      "Signature=" + this.signature()
    );

    return this.algo + " " + a.join(",");
  };

  requestHeader = function () {
    var a = new Array(
      "Authorization: " + this.authorizationHeader(),
      "x-amz-access-token: " + this.credentials.token,
      "x-amz-date: " + this.amzLongDate()
    );

    return a.join("\n");
  };

  queryParameters = function (queryParameterObj) {
    var pieces = [];
    if (queryParameterObj) {
      Object.keys(queryParameterObj)
        .sort()
        .forEach(function (k) {
          return pieces.push(
            k + "=" + encodeURIComponent(queryParameterObj[k])
          );
        });
    }
    return pieces.length > 0 ? pieces.join("&") : "";
  };

  hash = function (str) {
    return CryptoJS.SHA256(str).toString();
  };

  hmac = function (key, data) {
    return CryptoJS.HmacSHA256(data, key);
  };

  amzShortDate = function () {
    return this.amzLongDate().substr(0, 8);
  };

  amzLongDate = function () {
    return this.date
      .toISOString()
      .replace(/[:\-]|\.\d{3}/g, "")
      .substr(0, 13)+'00Z';
  };

  public
  constructor(credentials, request) {
    this.credentials = credentials;
    this.request = request;
  }

  execute = function () {
    return this.requestHeader();
  };
}
</code>```

答: So much easier to just use amazon-sp-api. This package wraps all available API operations and handles all the signing for you.</p>

Body:
I make an integration with amazon spapi, but I couldn't get restricted token from api. I couldn't sign the request. My signed request doesn't match the api's one. Here is my signature code with js. The code make an Autharization sentence and I try the sentence with Postman.
The Postman's result is here.

    {
    "errors": [
        {
            "message": "The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.

The Canonical String for this request should have been
'POST
/tokens/2021-03-01/restrictedDataToken

host:sandbox.sellingpartnerapi-eu.amazon.com
user-agent:PostmanRuntime/7.28.2
x-amz-access-token:Atza|*****

host;user-agent;x-amz-access-token
2328dd129c329e308cb990d33878a6d5ffd2a8c96e62d13b873dc62d5a7ff20b'

The String-to-Sign should have been
'AWS4-HMAC-SHA256
20210805T134800Z
20210805/eu-west-1/execute-api/aws4_request
c2f03a5e26f63dfae25fcf4cb1490c88fcbdcb78760d357f9234b5d46ac0f824'
",
     "code": "InvalidSignature"
        }
    ]
}

Where is my fault?

signer.html

            Access Key Id

                <input type="text" id="accessKeyId" name="accessKeyId" value="AKIAZIX*******" />

            Secret Access Key

                <input type="text" id="secretAccessKey" name="secretAccessKey" value="3nwTlA06******" />

            Access Token

                <input type="text" id="token" name="token" value="" />

            Region

                <input type="text" id="region" name="region" value="eu-west-1" />

            Service

                <input type="text" id="service" name="service" value="execute-api" />

            Method

                <input type="text" id="method" name="method" value="POST" />

            Host

                <input type="text" id="host" name="host" value="sandbox.sellingpartnerapi-eu.amazon.com" />

            URI

                <input type="text" id="uri" name="uri" value="/tokens/2021-03-01/restrictedDataToken" />

            Query

                <input type="text" id="query" name="query" value="" />

            Data

                <input type="text" id="data" name="data" value='{"restrictedResources":[{"method":"GET","path":"/catalog/2020-12-01/items"}]}' />

            Header
            <textarea id="header"></textarea>

            <button id="send">Send</button>

bundle.js

class Credentials {
  constructor(accessKeyId, secretAccessKey, token, region, service) {
    this.accessKeyId = accessKeyId;
    this.secretAccessKey = secretAccessKey;
    this.token = token;
    this.region = region;
    this.service = service;
  }
}

class Requests {
  constructor(method, host, uri, query, data) {
    this.method = method;
    this.host = host;
    this.uri = uri;
    this.query = query;
    this.data = data;
  }
}

class Signer {
  private
  date = new Date();
  termStr = "aws4_request";
  algo = "AWS4-HMAC-SHA256";
  signedHeaders = "host;user-agent;x-amz-access-token";
  userAgent = "PostmanRuntime/7.28.2";

  canonicalHeaders = function () {
    var a = new Array(
      "host:" + this.request.host,
      "user-agent:" + this.userAgent,
      "x-amz-access-token:" + this.credentials.token
    );

    return a.join("\n");
  };

  canonicalRequest = function () {
    var result = '';

    var a = new Array(
      this.request.method.toUpperCase(),
      this.request.uri,
      this.queryParameters(this.request.query),
      this.canonicalHeaders() + "\n",
      this.signedHeaders,
      this.hash(this.request.data)
    );

    result = a.join("\n");
    console.log("canonicalRequest : \n"+result);

    return result;
  };

  credentialScope = function () {
    var a = new Array(
      this.amzShortDate(),
      this.credentials.region,
      this.credentials.service,
      this.termStr
    );

    return a.join("/");
  };

  requestToSign = function () {
    var result = '';

    var a = new Array(
      this.algo,
      this.amzLongDate(),
      this.credentialScope(),
      this.hash(this.canonicalRequest())
    );

    result = a.join("\n");
    console.log("requestToSign : \n"+result);

    return result;
  };

  signature = function () {
    var result = "";

    result = this.hmac(
      "AWS4" + this.credentials.secretAccessKey,
      this.amzShortDate()
    );
    result = this.hmac(result, this.credentials.region);
    result = this.hmac(result, this.service);
    result = this.hmac(result, this.termStr);
    result = this.hmac(result, this.requestToSign()).toString();

    return result;
  };

  authorizationHeader = function () {
    var a = new Array(
      "Credential=" + this.credentials.accessKeyId + "/" + this.credentialScope(),
      "SignedHeaders=" + this.signedHeaders,
      "Signature=" + this.signature()
    );

    return this.algo + " " + a.join(",");
  };

  requestHeader = function () {
    var a = new Array(
      "Authorization: " + this.authorizationHeader(),
      "x-amz-access-token: " + this.credentials.token,
      "x-amz-date: " + this.amzLongDate()
    );

    return a.join("\n");
  };

  queryParameters = function (queryParameterObj) {
    var pieces = [];
    if (queryParameterObj) {
      Object.keys(queryParameterObj)
        .sort()
        .forEach(function (k) {
          return pieces.push(
            k + "=" + encodeURIComponent(queryParameterObj[k])
          );
        });
    }
    return pieces.length > 0 ? pieces.join("&") : "";
  };

  hash = function (str) {
    return CryptoJS.SHA256(str).toString();
  };

  hmac = function (key, data) {
    return CryptoJS.HmacSHA256(data, key);
  };

  amzShortDate = function () {
    return this.amzLongDate().substr(0, 8);
  };

  amzLongDate = function () {
    return this.date
      .toISOString()
      .replace(/[:\-]|\.\d{3}/g, "")
      .substr(0, 13)+'00Z';
  };

  public
  constructor(credentials, request) {
    this.credentials = credentials;
    this.request = request;
  }

  execute = function () {
    return this.requestHeader();
  };
}


问:
Vue-Router: Protecting private routes with authentication the right way
I have a /profile route that should only be accessible by an authenticated user. From research, the recommended approach is to use vue-router's navigation guard:

Here is the route object:

```<code>  {
    path: '/profile',
    name: 'MyProfile',
    component: () => import('@/views/Profile.vue'),
    meta: { requiresAuth: true }
  },
</code>```

And here is the router's navigation guard:

```<code>router.beforeEach((to, from, next) => {
  if (to.matched.some((record) => record.meta.requiresAuth)) {
    if (isAuthenticated()) {
      next()
    }
    else {
      alert('Auth required!')
      next('/login')
    }
  }
})
</code>```

The isAuthenticated() function above sends a jwt token (stored in cookie) to the /jwt/validate endpoint which validates the token and returns a 200 OK response:

```<code>export function isAuthenticated() {
  axios.post(`${baseUrl}/token/validate`, {}, { withCredentials: true })
    .then(resp => resp.statusText == 'OK')
    .catch(err => false)
}
</code>```

With this approach, every time we visit the /profile route, we are making a POST request to the /token/validate endpoint. And this works quite well. However, is it too excessive to make this request every time?

My Solutions

I wonder if there is some way to store the data locally in memory. I thought of two possible solutions:

Option 1: Storing the data on vuex store, however I have learned that the vuex store object is accessible via the browser's console. This means that anyone can modify the access logic to gain access to protected routes.

Option 2: Store it inside a custom Vue.prototype.$user object, however this is similarly accessible via console and therefore has the same security risk as option 1.

Essentially, my question is: is there an option to access a protected route without having to validate the jwt token on the server-side every time?

答:
You should query the server for if the token is valid once when the user initially loads the application. After that, there is usually no reason to check again. If the session expires on the server, then any other API calls you do should return a 401 response (or any other way that you choose to return an error) and your application can act on that.and your application can act on that.

If your profile route is getting data from the server to display and the server is properly validating the user for that request, then it doesn't matter if the user tries to manipulate the Vuex store or Vue state because they won't be able to load the data.

Doing authentication in the vue router is really more for convenience than for actual security.

Don't waste time trying to prevent a malicious user from exploring the Vue application - that is guaranteed to be a losing battle since all of the code is loaded into the browser.

If you really insist on some kind of protection, you can split the application using webpack chunks that are loaded dynamically and configure your web server to only serve those chunks to properly authenticated and authorize users. That said, I would expect such configuration to be difficult and error prone, and I don't recommend it.

Body:
I have a /profile route that should only be accessible by an authenticated user. From research, the recommended approach is to use vue-router's navigation guard:

Here is the route object:

  {
    path: '/profile',
    name: 'MyProfile',
    component: () => import('@/views/Profile.vue'),
    meta: { requiresAuth: true }
  },

And here is the router's navigation guard:

router.beforeEach((to, from, next) => {
  if (to.matched.some((record) => record.meta.requiresAuth)) {
    if (isAuthenticated()) {
      next()
    }
    else {
      alert('Auth required!')
      next('/login')
    }
  }
})

The isAuthenticated() function above sends a jwt token (stored in cookie) to the /jwt/validate endpoint which validates the token and returns a 200 OK response:

export function isAuthenticated() {
  axios.post(`${baseUrl}/token/validate`, {}, { withCredentials: true })
    .then(resp => resp.statusText == 'OK')
    .catch(err => false)
}

With this approach, every time we visit the /profile route, we are making a POST request to the /token/validate endpoint. And this works quite well. However, is it too excessive to make this request every time?

My Solutions

I wonder if there is some way to store the data locally in memory. I thought of two possible solutions:

Option 1: Storing the data on vuex store, however I have learned that the vuex store object is accessible via the browser's console. This means that anyone can modify the access logic to gain access to protected routes.

Option 2: Store it inside a custom Vue.prototype.$user object, however this is similarly accessible via console and therefore has the same security risk as option 1.

Essentially, my question is: is there an option to access a protected route without having to validate the jwt token on the server-side every time?


问:
Conversion not working properly using dicom2nifti
I have a series of dicom files (.dcm) for each patient that I want to convert to nii.gz files, but nothing happens (even error info) with the following conversion...

```<code>import dicom2nifti
dicom2nifti.settings.set_gdcmconv_path('C:/Program Files/GDCM 3.0/bin/gdcmconv.exe')
dicom2nifti.convert_directory('M0_1', 'M0_1.nii.gz')
</code>```

The error occurs when trying other methods....

```<code>import dicom2nifti
dicom2nifti.settings.set_gdcmconv_path('C:/Program Files/GDCM 3.0/bin/gdcmconv.exe')
dicom2nifti.dicom_series_to_nifti('M0_1', 'M0_1.nii.gz')
</code>```

Error Log:

```<code>Traceback (most recent call last):
  File ".\test.py", line 5, in <module>
    dicom2nifti.dicom_series_to_nifti('M0_1', 'M0_1.nii.gz')
  File "D:\Anaconda3\envs\pydicom\lib\site-packages\dicom2nifti\convert_dicom.py", line 78, in dicom_series_to_nifti
    return dicom_array_to_nifti(dicom_input, output_file, reorient_nifti)
  File "D:\Anaconda3\envs\pydicom\lib\site-packages\dicom2nifti\convert_dicom.py", line 112, in dicom_array_to_nifti
    if not are_imaging_dicoms(dicom_list):
  File "D:\Anaconda3\envs\pydicom\lib\site-packages\dicom2nifti\convert_dicom.py", line 151, in are_imaging_dicoms
    if common.is_philips(dicom_input):
  File "D:\Anaconda3\envs\pydicom\lib\site-packages\dicom2nifti\common.py", line 102, in is_philips
    header = dicom_input[0]
IndexError: list index out of range
</code>```

File structure:

```<code>M0_1
   |----IM-0001-0001.dcm
   |----IM-0001-0002.dcm
   ........
   |----IM-0001-000299.dcm
   |----IM-0001-000300.dcm
</code>```

Environment:
windows10, python: 3.6, dicom2nifti2.3.0

Where am I doing wrong?

Or is there any other way to convert it?

Thanks in advance!

答:
I haven't used dicom2nifti, but you can convert DICOM to Nifti using SimpleITK.

Here's the code that ought to do the job:

```<code>import SimpleITK as sitk

reader = sitk.ImageSeriesReader()
dicom_names = reader.GetGDCMSeriesFileNames('M0_1')
reader.SetFileNames(dicom_names)
image = reader.Execute()

# Added a call to PermuteAxes to change the axes of the data
image = sitk.PermuteAxes(image, [2, 1, 0])

sitk.WriteImage(image, 'M0_1.nii.gz')
</code>```

You can learn more about SimpleITK here: https://simpleitk.readthedocs.io/

UPDATE: I added a call to SimpleITK's PermuteAxes to change the axis order from X-Y-Z to Z-Y-X.

Body:
I have a series of dicom files (.dcm) for each patient that I want to convert to nii.gz files, but nothing happens (even error info) with the following conversion...

import dicom2nifti
dicom2nifti.settings.set_gdcmconv_path('C:/Program Files/GDCM 3.0/bin/gdcmconv.exe')
dicom2nifti.convert_directory('M0_1', 'M0_1.nii.gz')

The error occurs when trying other methods....

import dicom2nifti
dicom2nifti.settings.set_gdcmconv_path('C:/Program Files/GDCM 3.0/bin/gdcmconv.exe')
dicom2nifti.dicom_series_to_nifti('M0_1', 'M0_1.nii.gz')

Error Log:

Traceback (most recent call last):
  File ".\test.py", line 5, in <module>
    dicom2nifti.dicom_series_to_nifti('M0_1', 'M0_1.nii.gz')
  File "D:\Anaconda3\envs\pydicom\lib\site-packages\dicom2nifti\convert_dicom.py", line 78, in dicom_series_to_nifti
    return dicom_array_to_nifti(dicom_input, output_file, reorient_nifti)
  File "D:\Anaconda3\envs\pydicom\lib\site-packages\dicom2nifti\convert_dicom.py", line 112, in dicom_array_to_nifti
    if not are_imaging_dicoms(dicom_list):
  File "D:\Anaconda3\envs\pydicom\lib\site-packages\dicom2nifti\convert_dicom.py", line 151, in are_imaging_dicoms
    if common.is_philips(dicom_input):
  File "D:\Anaconda3\envs\pydicom\lib\site-packages\dicom2nifti\common.py", line 102, in is_philips
    header = dicom_input[0]
IndexError: list index out of range

File structure:

M0_1
   |----IM-0001-0001.dcm
   |----IM-0001-0002.dcm
   ........
   |----IM-0001-000299.dcm
   |----IM-0001-000300.dcm

Environment:
windows10, python: 3.6, dicom2nifti2.3.0

Where am I doing wrong?

Or is there any other way to convert it?

Thanks in advance!

Body:
I haven't used dicom2nifti, but you can convert DICOM to Nifti using SimpleITK.

Here's the code that ought to do the job:

import SimpleITK as sitk

reader = sitk.ImageSeriesReader()
dicom_names = reader.GetGDCMSeriesFileNames('M0_1')
reader.SetFileNames(dicom_names)
image = reader.Execute()

# Added a call to PermuteAxes to change the axes of the data
image = sitk.PermuteAxes(image, [2, 1, 0])

sitk.WriteImage(image, 'M0_1.nii.gz')

You can learn more about SimpleITK here: https://simpleitk.readthedocs.io/

UPDATE: I added a call to SimpleITK's PermuteAxes to change the axis order from X-Y-Z to Z-Y-X.


问:
How to make overflow: auto container follow list-item iteratation
I have a div container set to overflow:auto which contains many
's.  I wrote a simple function to change the highlighted list-item when the user clicks a button or presses the up or down arrows.

The only problem is when the user clicks the iteration button the highlighted list-item iterates without the container scrollbar following it.  I'm looking for a way to force the container scrollbar to scroll with the iteration

here is an example of what I'm trying to do:
http://jsfiddle.net/sadmicrowave/rwfUr/

Remember - up and down arrows make the container scroll (as long as the container has focus) but the iteration button does not.

Important - I am looking for an alternative to .scrollTo()

答: What about .scrollIntoView() ?</p>

Body: What about .scrollIntoView() ?


问:
WINUI 3.0 - Reunion 0.5 window size///
I just start learning WinUI 3.0 and can't find any information in google or books like Learn WinUI 3.0 how to set default window size of application. I know in UWP it can be like

ApplicationView.PreferredLaunchViewSize = new Size(480, 800);
ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.PreferredLaunchViewSize;
```

But actually it doesn't work in WinUI

答:
I can't comment on answers yet but to add to Jonas' answer, you can put his answer in the class constructor (where this.InitializeComponent() is) of your main window code-behind or in the OnLaunched method of App.cs. I'm sure that seems obvious to a lot of people but to those coming from other languages/platforms it might not be. Example:</p>
```<code>    public MainWindow()
    {
        this.InitializeComponent();

        IntPtr hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this); // m_window in App.cs
        WindowId windowId = Win32Interop.GetWindowIdFromWindow(hWnd);
        AppWindow appWindow = AppWindow.GetFromWindowId(windowId);

        var size = new Windows.Graphics.SizeInt32();
        size.Width = 480;
        size.Height = 800;

        appWindow.Resize(size);
    // or like Jonas said:
    // appWindow.Resize(new Windows.Graphics.SizeInt32 { Width = 480, Height = 800 });
    }
</code>```

Title: WINUI 3.0 - Reunion 0.5 window size///

Body:
I just start learning WinUI 3.0 and can't find any information in google or books like Learn WinUI 3.0 how to set default window size of application. I know in UWP it can be like

ApplicationView.PreferredLaunchViewSize = new Size(480, 800);
ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.PreferredLaunchViewSize;

But actually it doesn't work in WinUI

Body:
I can't comment on answers yet but to add to Jonas' answer, you can put his answer in the class constructor (where this.InitializeComponent() is) of your main window code-behind or in the OnLaunched method of App.cs. I'm sure that seems obvious to a lot of people but to those coming from other languages/platforms it might not be. Example:

    public MainWindow()
    {
        this.InitializeComponent();

        IntPtr hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this); // m_window in App.cs
        WindowId windowId = Win32Interop.GetWindowIdFromWindow(hWnd);
        AppWindow appWindow = AppWindow.GetFromWindowId(windowId);

        var size = new Windows.Graphics.SizeInt32();
        size.Width = 480;
        size.Height = 800;

        appWindow.Resize(size);
    // or like Jonas said:
    // appWindow.Resize(new Windows.Graphics.SizeInt32 { Width = 480, Height = 800 });
    }


问:
How to store info from an Array to an Array Object?
I have a Java class which uses BufferedReader to obtain information from a text file, then store the information into an Array called newData . I want to store a certain part of the information to the VegTypes[f] = new VegType(); but I not sure what code should I write here to obtain that part of information.

Without completing this part, I am not able to continue working on another Array Object which is Vegs[i] = new Veg(newData[0], newData[1], newData[2],); for storing information together with VegTypes Array Object.

Below is my code of the Java class:

```<code>public class theVegetable {

    private Veg[] Vegs;
    private VegType[] VegTypes;

    public theVegetable() {
        int quantity;
        int vegQuantity;
        String vegLine;

        try {

            BufferedReader br = new BufferedReader(new FileReader("vegetableInfo.txt"));
            quantity = Integer.parseInt(vegLine.readLine());

            Vegs = new Veg[quantity];

            for (int i = 0; i < quantity; i++) {
               vegLine = br.readLine();
                String[] newData = vegLine.split(";");

                vegQuantity = Integer.parseInt(newData[3]);

                //For loop to store information into VegTypes
                for (int f = 0; j < vegQuantity; f++) {

                    VegTypes[f] = new VegType();

                }

                //Vegs Array Object to store information plus VegTypes
                Vegs[i] = new Veg(newData[0], newData[1], newData[2],);

            }

            br.close();

        } catch (FileNotFoundException e) {
            System.out.println("File not found.");
        }
    }
}
</code>```

Below is my vegetableInfo.txt text file:

```<code>3
Tomato;class1;Malaysia Tomato;2;MT100A;MT1;200;90;MT20A;MT2;600;80;Malaysia product
Avocado;class2;Europe Avocado;4;EA100A;EA1;300;90;EA14A;EA2;90;80;EA230A;EA3;43;50.9;EA470A;EA4;400;76;Europe product
Cabbage;class3;Malaysia Cabbage;3;MC100A;MC1;500;20;MC49A;MC2;500;50;MC800A;MC3;600;10.3;Malaysia product
</code>```

The number 3 at the top of the text file is for the int quantity; variable to store the amount.
The kind of information I want the VegTypes[f] = new VegType(); to store are MT100A;MT1;200;90;MT20A;MT2;600;80;, the number 2 besides the Malaysia Tomato are for int vegQuantity; variable. Same thing goes for other vegetables in the text file.

Constructor of my private VegType[] VegTypes; Array Object:

```<code>private String vegCode;
private String vegBatch;
private int vegBatchQuantity;
private double vegGrade;

    public VegType(String inVegCode, String inVegBatch, int inVegBatchQuantity, double inVegGrade) {
        vegCode = inVegCode;
        vegBatch = inVegBatch;
        vegBatchQuantity = inVegBatchQuantity;
        vegGrade = inVegGrade;
    }
</code>```

My Veg Class:

```<code>public class Veg {

    private String vegetableName;
    private String classLevel;
    private String productionCountry;
    private VegType[] VegTypes;
    private String productType;

    //Constructor
    public Veg(String inVegetableName, String inClassLevel, String inProductionCountry, VegType[] inVegTypes, String inProductType) {
        vegetableName = inVegetableName;
        classLevel = inClassLevel;
        productionCountry = inProductionCountry;
        vegType = inVegTypes;

        productType = inProductType;
    }

    public String getVegetableName() {
        return vegetableName;
    }

    public String getClassLevel() {
        return classLevel;
    }

    public String getProductionCountry() {
        return productionCountry;
    }

    public String getProductType() {
        return productType;
    }
}
</code>```

答:
```<code>class VegType {
    private String vegCode;
    private String vegBatch;
    private int vegBatchQuantity;
    private double vegGrade;

    public VegType(String inVegCode, String inVegBatch, int inVegBatchQuantity, double inVegGrade) {
        vegCode = inVegCode;
        vegBatch = inVegBatch;
        vegBatchQuantity = inVegBatchQuantity;
        vegGrade = inVegGrade;
    }

    @Override
    public String toString() {
        return vegCode+" "+vegBatch+" "+vegBatchQuantity+" "+vegGrade;
    }
}

class Veg {
    private String vegetableName;
    private String classLevel;
    private String productionCountry;
    private VegType[] VegTypes;
    private String productType;

    //Constructor
    public Veg(String inVegetableName, String inClassLevel, String inProductionCountry, VegType[] inVegTypes, String inProductType) {
        vegetableName = inVegetableName;
        classLevel = inClassLevel;
        productionCountry = inProductionCountry;
        VegTypes = inVegTypes;
        productType = inProductType;
    }

    @Override
    public String toString() {
        return vegetableName+" "+classLevel+" "+productionCountry+" "+VegTypes+" "+productType;
    }

    public String getVegetableName() {
        return vegetableName;
    }

    public String getClassLevel() {
        return classLevel;
    }

    public String getProductionCountry() {
        return productionCountry;
    }

    public String getProductType() {
        return productType;
    }
}

class TheVegetable {
    private Veg[] Vegs;
    private VegType[] VegTypes;

    public TheVegetable() throws IOException {
        int quantity;
        int vegQuantity;
        String vegLine;

        try {

            BufferedReader br = new BufferedReader(new FileReader("vegetableInfo.txt"));
            quantity = Integer.parseInt(br.readLine());

            Vegs = new Veg[quantity];

            for (int i=0; i<quantity; i++) {
                vegLine = br.readLine();
                String[] newData = vegLine.split(";");

                vegQuantity = Integer.parseInt(newData[3]);
                VegTypes=new VegType[vegQuantity];
                for(int j=4, k=0; j<newData.length-1; j+=4, k++) {
                    VegTypes[k] = new VegType(newData[j], newData[j+1], Integer.parseInt(newData[j+2]), Double.parseDouble(newData[j+3]));
                }
                Vegs[i]=new Veg(newData[0], newData[1], newData[2], VegTypes, newData[newData.length-1]);
            }

            br.close();

        } catch (FileNotFoundException e) {
            System.out.println("File not found.");
        }
    }
}
</code>```

Body:
I have a Java class which uses BufferedReader to obtain information from a text file, then store the information into an Array called newData . I want to store a certain part of the information to the VegTypes[f] = new VegType(); but I not sure what code should I write here to obtain that part of information.

Without completing this part, I am not able to continue working on another Array Object which is Vegs[i] = new Veg(newData[0], newData[1], newData[2],); for storing information together with VegTypes Array Object.

Below is my code of the Java class:

public class theVegetable {

    private Veg[] Vegs;
    private VegType[] VegTypes;

    public theVegetable() {
        int quantity;
        int vegQuantity;
        String vegLine;

        try {

            BufferedReader br = new BufferedReader(new FileReader("vegetableInfo.txt"));
            quantity = Integer.parseInt(vegLine.readLine());

            Vegs = new Veg[quantity];

            for (int i = 0; i < quantity; i++) {
               vegLine = br.readLine();
                String[] newData = vegLine.split(";");

                vegQuantity = Integer.parseInt(newData[3]);

                //For loop to store information into VegTypes
                for (int f = 0; j < vegQuantity; f++) {

                    VegTypes[f] = new VegType();

                }

                //Vegs Array Object to store information plus VegTypes
                Vegs[i] = new Veg(newData[0], newData[1], newData[2],);

            }

            br.close();

        } catch (FileNotFoundException e) {
            System.out.println("File not found.");
        }
    }
}

Below is my vegetableInfo.txt text file:

3
Tomato;class1;Malaysia Tomato;2;MT100A;MT1;200;90;MT20A;MT2;600;80;Malaysia product
Avocado;class2;Europe Avocado;4;EA100A;EA1;300;90;EA14A;EA2;90;80;EA230A;EA3;43;50.9;EA470A;EA4;400;76;Europe product
Cabbage;class3;Malaysia Cabbage;3;MC100A;MC1;500;20;MC49A;MC2;500;50;MC800A;MC3;600;10.3;Malaysia product

The number 3 at the top of the text file is for the int quantity; variable to store the amount.
The kind of information I want the VegTypes[f] = new VegType(); to store are MT100A;MT1;200;90;MT20A;MT2;600;80;, the number 2 besides the Malaysia Tomato are for int vegQuantity; variable. Same thing goes for other vegetables in the text file.

Constructor of my private VegType[] VegTypes; Array Object:

private String vegCode;
private String vegBatch;
private int vegBatchQuantity;
private double vegGrade;

    public VegType(String inVegCode, String inVegBatch, int inVegBatchQuantity, double inVegGrade) {
        vegCode = inVegCode;
        vegBatch = inVegBatch;
        vegBatchQuantity = inVegBatchQuantity;
        vegGrade = inVegGrade;
    }

My Veg Class:

public class Veg {

    private String vegetableName;
    private String classLevel;
    private String productionCountry;
    private VegType[] VegTypes;
    private String productType;

    //Constructor
    public Veg(String inVegetableName, String inClassLevel, String inProductionCountry, VegType[] inVegTypes, String inProductType) {
        vegetableName = inVegetableName;
        classLevel = inClassLevel;
        productionCountry = inProductionCountry;
        vegType = inVegTypes;

        productType = inProductType;
    }

    public String getVegetableName() {
        return vegetableName;
    }

    public String getClassLevel() {
        return classLevel;
    }

    public String getProductionCountry() {
        return productionCountry;
    }

    public String getProductType() {
        return productType;
    }
}


问:
_CrtMemDumpAllObjectsSince not returning expected results
I'm using _CrtMemCheckpoint and _CrtMemDumpAllObjectsSince to track possible memory leaks in my dll.

In DllMain when DLL_PROCESS_ATTACH is detected an init function is called which calls _CrtMemCheckpoint(&startState) on the global _CrtMemState variable startState.  When DLL_PROCESS_DETACH is detected an exit function is called that calls _CrtMemDumpAllObjectsSince(&startState).  This returns

```<code>ExitInstance()Dumping objects ->
{8706} normal block at 0x07088200, 8 bytes long.
 Data: <p v     > 70 FF 76 07 01 01 CD CD
{8705} normal block at 0x07084D28, 40 bytes long.
 Data: <                > 00 00 00 10 FF FF FF FF FF FF FF FF 00 00 00 00
{4577} normal block at 0x070845F0, 40 bytes long.
 Data: <dbV             > 64 62 56 0F 01 00 00 00 FF FF FF FF FF FF FF FF
{166} normal block at 0x028DD4B8, 40 bytes long.
 Data: <dbV             > 64 62 56 0F 01 00 00 00 FF FF FF FF FF FF FF FF
{87} normal block at 0x02889BA8, 12 bytes long.
 Data: < P          > DC 50 90 02 00 00 00 00 01 00 00 00
</code>```

So far so good, except the last three entries (4577, 166 and 87) are also in startState.  I.E.  If I run _CrtDumpMemoryLeaks() in my Init function and in my Exit function those entries are in both lists.

The documentation says this:

_CrtMemDumpAllObjectsSince uses the value of the state parameter to determine where to initiate the dump operation. To begin dumping from
  a specified heap state, the state parameter must be a pointer to a
  _CrtMemState structure that has been filled in by _CrtMemCheckpoint before _CrtMemDumpAllObjectsSince was called.

Which makes me believe that items tracked in startState would be excluded from the output.  At the end of the Init function where _CrtMemCheckpoint is called there have been about 4700 allocation calls.  Shouldn't _CrtMemDumpAllObjectsSince only dump objects allocated after that checkpoint call?

What have I missed?

答:
Short

This is apparently strange only, but it does the job (in part), however in an overzealous mode.

These functions are decades old, so not buggy but not completely well designed.

Truth is there is something in the "old" state that change after your "since" state.

So the question is "yes it does reflect a change since, but is it a lethal leak?"

This frequent and amplified with delayed init for DLL.

Also by a lot of complex objects like map/string/array/list which does delay allocation of internal buffer.

Bad news being that nearly all complex object declared as "static" are in fact inited on first use.

So theses change ought to be shown in _CrtMemDumpAllObjectsSince because they changed their memory alloc.

Unfortunately the display is so crude and unfiltered that it also show too many irrelevant blocks (not modified).

Typical biggest culprit is use of "realloc" that change state of old alloc

This may even look stranger as they may disappear,

For example when a genuine malloc is made after stat snapshoot, because this one will do a kind of 'reset' of the low water marker used for dump, setting it to a higher level. And this magically make a bunch of your "extra display" to disappear.

Behavior is even more erratic if you are doing Multithreading, as it becomes easily non repetitive.

Note:

The fact that it doesn't show a file name and line number is a sign that it's dealing here with a preinit.

So culprits are most likely static complex objetc inited BEFORE main() (or InitInstance();)

Long:

_CrtMemDumpAllObjectsSince is painful!

And in fact, can be so clutter of non-useful info that it defies the purpose for a day/day simple use of _CrtMemDumpAllObjectsSince.
(In the good essence it inspires)

Workaround

None simple!

You may try to do a malloc then free AFTER you do your "since" state snapshoot, in order to tease this marker.

But to be safer and more in control, unfortunetaly I did saw way around writting my own _MyCrtMemDumpAllObjectsSince that dump from the original MS structure.
This was inspired by static void __cdecl dump_all_object_since_nolock(_CrtMemState const* const state) throw()

( see "debug_heap.cpp") Copyright Microsoft!

Code available "as is" more for inspiration.

But before some explanation on the way _CrtMemState works:

A _CrtMemState state does have a pointer 'pBlockHeader' which is usually a link of a double linked list of '_CrtMemBlockHeader*'

This list is in fact more than a snapshoot at a time it is build, but a selection (unclear how) of all the memory blocks in use, arranged in such a way that the "current state" is directly pointed to by 'pBlockHeader'

So that going

-> _block_header_prev allows the exploration of older blocks

-> _block_header_next allows the exploration of newer blocks (the Juice you look for in the concept "Since" but very dangerous as there is no end marker)

The TRICKY part:

MS maintain a vital internal static _CrtMemBlockHeader* called __acrt_first_block
This __acrt_first_block continuously changes during alloc and realloc

However, _MyCrtMemDumpAllObjectsSince dump does start from this __acrt_first_block and go forward (use _block_header_next) until finding a NULL ptr

The first block handled is decided by this __acrt_first_block, and the 'state' you sent is not more than a STOP of the dump.

Otherwise said _CrtMemDumpAllObjectsSince doesn't really dump the "since" state

But dump from __acrt_first_block as it is to your "since" state.

The 'for' loop is overkilling by showing blocks from a 'start'(since) to an 'end'(oldest modified since).

This makes sense but this does also encompass dumping blocks that have NOT been modified. Showing things we don't care about.

MS structure is clever and can be used directly, while it is not guaranteed that Microsoft will maintain the same vital structure _CrtMemBlockHeader in future

But over the last 15 years I haven't seen a bit of change in it (nor do I foresee any reason they would change a strategical and critical structure.)

I dislike copy/paste of MS code and resolve linker with my piggyback code

So the workaround I used is based on the capability to intercept text message sent to "Output" windows, decoding and storing ALL information in my own bank

Structurally below gives an idea of the intercepts using a static struct under lock to store all infos

```<code>_CrtSetReportHook2(_CRT_RPTHOOK_INSTALL,MyReportHookDumpFilter);
_CrtMemDumpAllObjectsSince(state);  // CONTRARY to what it says, this thing seems to dump everything until old_state
_CrtSetReportHook2(_CRT_RPTHOOK_REMOVE,MyReportHookDumpFilter);
_MyReportHookDumpFilterCommand(_CUST_SORT,NULL);
_MyReportHookDumpFilterCommand(_CUST_DUMP,NULL);
</code>```

The `_MyReportHookDumpFilterCommand` does check the preexistence of blocks that are NOT modified at all and avoids displaying those during it's Dump phase

Take it as inspiration of code to ease display.

If anybody have simpler way to use it, please share!

Body:
I'm using _CrtMemCheckpoint and _CrtMemDumpAllObjectsSince to track possible memory leaks in my dll.

In DllMain when DLL_PROCESS_ATTACH is detected an init function is called which calls _CrtMemCheckpoint(&startState) on the global _CrtMemState variable startState.  When DLL_PROCESS_DETACH is detected an exit function is called that calls _CrtMemDumpAllObjectsSince(&startState).  This returns

ExitInstance()Dumping objects ->
{8706} normal block at 0x07088200, 8 bytes long.
 Data:
 70 FF 76 07 01 01 CD CD
{8705} normal block at 0x07084D28, 40 bytes long.
 Data: <                > 00 00 00 10 FF FF FF FF FF FF FF FF 00 00 00 00
{4577} normal block at 0x070845F0, 40 bytes long.
 Data: <dbV             > 64 62 56 0F 01 00 00 00 FF FF FF FF FF FF FF FF
{166} normal block at 0x028DD4B8, 40 bytes long.
 Data: <dbV             > 64 62 56 0F 01 00 00 00 FF FF FF FF FF FF FF FF
{87} normal block at 0x02889BA8, 12 bytes long.
 Data:
 DC 50 90 02 00 00 00 00 01 00 00 00

So far so good, except the last three entries (4577, 166 and 87) are also in startState.  I.E.  If I run _CrtDumpMemoryLeaks() in my Init function and in my Exit function those entries are in both lists.

The documentation says this:

_CrtMemDumpAllObjectsSince uses the value of the state parameter to determine where to initiate the dump operation. To begin dumping from
  a specified heap state, the state parameter must be a pointer to a
  _CrtMemState structure that has been filled in by _CrtMemCheckpoint before _CrtMemDumpAllObjectsSince was called.

Which makes me believe that items tracked in startState would be excluded from the output.  At the end of the Init function where _CrtMemCheckpoint is called there have been about 4700 allocation calls.  Shouldn't _CrtMemDumpAllObjectsSince only dump objects allocated after that checkpoint call?

What have I missed?

Body:
Short

This is apparently strange only, but it does the job (in part), however in an overzealous mode.

These functions are decades old, so not buggy but not completely well designed.

Truth is there is something in the "old" state that change after your "since" state.

So the question is "yes it does reflect a change since, but is it a lethal leak?"

This frequent and amplified with delayed init for DLL.

Also by a lot of complex objects like map/string/array/list which does delay allocation of internal buffer.

Bad news being that nearly all complex object declared as "static" are in fact inited on first use.

So theses change ought to be shown in _CrtMemDumpAllObjectsSince because they changed their memory alloc.

Unfortunately the display is so crude and unfiltered that it also show too many irrelevant blocks (not modified).

Typical biggest culprit is use of "realloc" that change state of old alloc

This may even look stranger as they may disappear,

For example when a genuine malloc is made after stat snapshoot, because this one will do a kind of 'reset' of the low water marker used for dump, setting it to a higher level. And this magically make a bunch of your "extra display" to disappear.

Behavior is even more erratic if you are doing Multithreading, as it becomes easily non repetitive.

Note:

The fact that it doesn't show a file name and line number is a sign that it's dealing here with a preinit.

So culprits are most likely static complex objetc inited BEFORE main() (or InitInstance();)

Long:

_CrtMemDumpAllObjectsSince is painful!

And in fact, can be so clutter of non-useful info that it defies the purpose for a day/day simple use of _CrtMemDumpAllObjectsSince.
(In the good essence it inspires)

Workaround

None simple!

You may try to do a malloc then free AFTER you do your "since" state snapshoot, in order to tease this marker.

But to be safer and more in control, unfortunetaly I did saw way around writting my own _MyCrtMemDumpAllObjectsSince that dump from the original MS structure.
This was inspired by static void __cdecl dump_all_object_since_nolock(_CrtMemState const* const state) throw()

( see "debug_heap.cpp") Copyright Microsoft!

Code available "as is" more for inspiration.

But before some explanation on the way _CrtMemState works:

A _CrtMemState state does have a pointer 'pBlockHeader' which is usually a link of a double linked list of '_CrtMemBlockHeader*'

This list is in fact more than a snapshoot at a time it is build, but a selection (unclear how) of all the memory blocks in use, arranged in such a way that the "current state" is directly pointed to by 'pBlockHeader'

So that going

-> _block_header_prev allows the exploration of older blocks

-> _block_header_next allows the exploration of newer blocks (the Juice you look for in the concept "Since" but very dangerous as there is no end marker)

The TRICKY part:

MS maintain a vital internal static _CrtMemBlockHeader* called __acrt_first_block
This __acrt_first_block continuously changes during alloc and realloc

However, _MyCrtMemDumpAllObjectsSince dump does start from this __acrt_first_block and go forward (use _block_header_next) until finding a NULL ptr

The first block handled is decided by this __acrt_first_block, and the 'state' you sent is not more than a STOP of the dump.

Otherwise said _CrtMemDumpAllObjectsSince doesn't really dump the "since" state

But dump from __acrt_first_block as it is to your "since" state.

The 'for' loop is overkilling by showing blocks from a 'start'(since) to an 'end'(oldest modified since).

This makes sense but this does also encompass dumping blocks that have NOT been modified. Showing things we don't care about.

MS structure is clever and can be used directly, while it is not guaranteed that Microsoft will maintain the same vital structure _CrtMemBlockHeader in future

But over the last 15 years I haven't seen a bit of change in it (nor do I foresee any reason they would change a strategical and critical structure.)

I dislike copy/paste of MS code and resolve linker with my piggyback code

So the workaround I used is based on the capability to intercept text message sent to "Output" windows, decoding and storing ALL information in my own bank

Structurally below gives an idea of the intercepts using a static struct under lock to store all infos

_CrtSetReportHook2(_CRT_RPTHOOK_INSTALL,MyReportHookDumpFilter);
_CrtMemDumpAllObjectsSince(state);  // CONTRARY to what it says, this thing seems to dump everything until old_state
_CrtSetReportHook2(_CRT_RPTHOOK_REMOVE,MyReportHookDumpFilter);
_MyReportHookDumpFilterCommand(_CUST_SORT,NULL);
_MyReportHookDumpFilterCommand(_CUST_DUMP,NULL);

The `_MyReportHookDumpFilterCommand` does check the preexistence of blocks that are NOT modified at all and avoids displaying those during it's Dump phase

Take it as inspiration of code to ease display.

If anybody have simpler way to use it, please share!


问:
How to read Kafka record ingestion timestamp in Apache Beam
I am new to Apache Beam and struggling with this problem for a while.
I am using KafkaIO as a source of my pipeline in Apache Beam Java .
I  want to fetch Kafka record ingestion timestamp along with every record and write that as an additional column to my output. The timestamp at which the record was ingested in Kafka and not the event time.

I am not able to figure out how to use kafkaIOReader without using the function withoutMetadata() . As far as I understand the Kafka record ingestion timestamp should be part of the metadata for each record ?

答: I you specify the timestamp policy, you should be able to access the timestamp of the resulting elements in your DoFn regardless of whether you're reading metadata.  You can then do with this as you like (e.g. sticking it into a field of a POJO).</p>


问:
Check if series of numbers is between two columns in pandas dataframe
I am trying to classify genomic locations, and I have DataFrame like the following, with all locations and their respective classification types. The Type column does not have unique classifications, but each row will have a unique combination of Chr, Low, High.

```<code>pd.DataFrame({
    'Chr':[1,1,3],
    'Low':[100,200,300],
    'High':[150,250,350],
    'Type':['Foo','Bar','Foo']
})
</code>```

I then have my sample set that needs to be classified like the DataFrame below.

```<code>pd.DataFrame({
    'Chr':[1,1,5],
    'Loc':[125,325,325]
})
</code>```

To classify the data, for each location in the sample set, the Chromosome position found within the Chr column must match a Chr value found within the reference DataFrame and the Loc value must be >= the Low value and <= the High value. If this happens, that row should then be labeled with the respective Type in the reference DataFrame. In the example I provide, the sample set should be labeled like the following.

```<code>pd.DataFrame({
    'Chr':[1,1,5],
    'Loc':[125,325,325],
    'Type':['Foo','None','None']
})
</code>```

which looks like:

```<code>   Chr  Loc  Type
0    1  125   Foo
1    1  325  None
2    5  325  None
</code>```

答:
I'm not clear on the requirements for your question, as noted in a comment on the question above. However, if the currently accepted solution that only checks the conditions you specified row-to-row, then I think this is a better solution:

```<code>df1 = pd.DataFrame({
    'Chr':[1,1,3],
    'Low':[100,200,300],
    'High':[150,250,350],
    'Type':['Foo','Bar','Foo']
})
df2 = pd.DataFrame({
    'Chr':[1,1,5],
    'Loc':[125,325,325]
})
mask = (df2['Chr']==df1['Chr'])&(df2['Loc']>=df1['Low'])&(df2['Loc']<=df1['High'])
df2.loc[mask, 'Type'] = df1.loc[mask, 'Type']
</code>```

Output:

If the requirement is to check each value of 'Chr' in the sample dataframe with ALL rows in the classification dataframe, df1, that match the 'Chr' value, then this is a bit more complicated and I can update this answer accordingly, but I think @enke's solution handles this case correctly.

Body:
I am trying to classify genomic locations, and I have DataFrame like the following, with all locations and their respective classification types. The Type column does not have unique classifications, but each row will have a unique combination of Chr, Low, High.

pd.DataFrame({
    'Chr':[1,1,3],
    'Low':[100,200,300],
    'High':[150,250,350],
    'Type':['Foo','Bar','Foo']
})

I then have my sample set that needs to be classified like the DataFrame below.

pd.DataFrame({
    'Chr':[1,1,5],
    'Loc':[125,325,325]
})

To classify the data, for each location in the sample set, the Chromosome position found within the Chr column must match a Chr value found within the reference DataFrame and the Loc value must be >= the Low value and <= the High value. If this happens, that row should then be labeled with the respective Type in the reference DataFrame. In the example I provide, the sample set should be labeled like the following.

pd.DataFrame({
    'Chr':[1,1,5],
    'Loc':[125,325,325],
    'Type':['Foo','None','None']
})

which looks like:

   Chr  Loc  Type
0    1  125   Foo
1    1  325  None
2    5  325  None

Body:
I'm not clear on the requirements for your question, as noted in a comment on the question above. However, if the currently accepted solution that only checks the conditions you specified row-to-row, then I think this is a better solution:

df1 = pd.DataFrame({
    'Chr':[1,1,3],
    'Low':[100,200,300],
    'High':[150,250,350],
    'Type':['Foo','Bar','Foo']
})
df2 = pd.DataFrame({
    'Chr':[1,1,5],
    'Loc':[125,325,325]
})
mask = (df2['Chr']==df1['Chr'])&(df2['Loc']>=df1['Low'])&(df2['Loc']<=df1['High'])
df2.loc[mask, 'Type'] = df1.loc[mask, 'Type']

Output:

If the requirement is to check each value of 'Chr' in the sample dataframe with ALL rows in the classification dataframe, df1, that match the 'Chr' value, then this is a bit more complicated and I can update this answer accordingly, but I think @enke's solution handles this case correctly.


问:
Can't Import Python3 Requests Module
I am using VS Code using Python 3.9.1.

I have setup a venv called env. Folder structure is:

```<code>env
  - Include
  - Lib
      - requests
  - Scripts
  - pyvenv.cfg
  - scrape.py
</code>```

In my script, scrape.py I have:

```<code>import requests

URL = "https://etherscan.io/token/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d"
page = requests.get(URL)

print(page.text)
</code>```

I get the following error:
Import "requests" could not be resolved from source Pylance(reportMIssingModuleSource)

I have installed requests as you can see from the directory structure. A pip list gives the following which also shows requests is installed:

答:
Use the command select python interpreter, setting it to your venv.

Make sure you Activate your venv in the console.

I think it'll add the string (venv) to your prompt. After running activate, pip and python now

There's additional guides here:
https://code.visualstudio.com/docs/python/environments#_where-the-extension-looks-for-environments

Title: Can't Import Python3 Requests Module

Body:
I am using VS Code using Python 3.9.1.

I have setup a venv called env. Folder structure is:

env
  - Include
  - Lib
      - requests
  - Scripts
  - pyvenv.cfg
  - scrape.py

In my script, scrape.py I have:

import requests

URL = "https://etherscan.io/token/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d"
page = requests.get(URL)

print(page.text)

I get the following error:
Import "requests" could not be resolved from source Pylance(reportMIssingModuleSource)

I have installed requests as you can see from the directory structure. A pip list gives the following which also shows requests is installed:


问:
Fill NULL based on conditions python
I have a dataset, and needs to create a new column to deal with the NULL based on the conditions. Here is the sample data:

```<code>id1 id2 col1 col2
1   1   2     3
2   2   2     NULL
3   3   NULL  3
4   4   NULL  3
5   5   10    11
</code>```

The expect output is

```<code>id1 id2 col1 col2  combine
1   1   2     3     2,3
2   2   2     NULL  2,3
3   3   NULL  3     2,3
4   4   NULL  3     2,3
5   5   10    11    10,11
</code>```

for example,If any col1 and col2 has 2 or 3, the new column need to contain both values.Not sure how to capture if col1 or col2 has NULLs.

答:
You can use ffill to fill NaNs convert to int, then str, then join on axis:

```<code>df['combine'] = df[['col1','col2']].ffill().astype(int).astype(str).apply(','.join, axis=1)
</code>```

Output:

```<code>   id1  id2  col1  col2 combine
0    1    1   2.0   3.0     2,3
1    2    2   2.0   NaN     2,3
2    3    3   NaN   3.0     2,3
3    4    4  10.0  11.0   10,11
</code>```

Title: Fill NULL based on conditions python

Body:
I have a dataset, and needs to create a new column to deal with the NULL based on the conditions. Here is the sample data:

id1 id2 col1 col2
1   1   2     3
2   2   2     NULL
3   3   NULL  3
4   4   NULL  3
5   5   10    11

The expect output is

id1 id2 col1 col2  combine
1   1   2     3     2,3
2   2   2     NULL  2,3
3   3   NULL  3     2,3
4   4   NULL  3     2,3
5   5   10    11    10,11

for example,If any col1 and col2 has 2 or 3, the new column need to contain both values.Not sure how to capture if col1 or col2 has NULLs.

Body:
You can use ffill to fill NaNs convert to int, then str, then join on axis:

df['combine'] = df[['col1','col2']].ffill().astype(int).astype(str).apply(','.join, axis=1)

Output:

   id1  id2  col1  col2 combine
0    1    1   2.0   3.0     2,3
1    2    2   2.0   NaN     2,3
2    3    3   NaN   3.0     2,3
3    4    4  10.0  11.0   10,11


问:
Google Sheet Auto Add / Update Value
I'm using Google Forms to collect a data. So, there was one question in the Google Form that I considered as a primary key when using the VLOOKUP function. However, there is a possibility that some data will collect zero (0) for the answer since they do not have an official ID number yet. I'm wondering if there is a way for me to automatically add or update a value when the value is zero (0). I'm thinking of using an temporary ID which letters and numbers. Ex: ID000001

答:
I believe your goal is as follows.

You want to convert 0 to ID000001. And, when the multiple 0 values are existing, you want to convert to ID000001, ID000002,,,.

In this case, how about the following sample script?

Sample script:

function myFunction() {
  const sheetName = "Sheet1"; // Please set the sheet name.

  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
  const range = sheet.getRange("A2:A" + sheet.getLastRow());
  let c = 1;
  const values = range.getValues().map(([a]) => [a === 0 ? `ID${(c++).toString().padStart(6, '0')}` : a]);
  range.setValues(values);
}
```
<ul>
<li>In this script, it supposes that the column of "STUDENT ID" is the column "A" because I cannot know the column information from your sample image.</li>
</ul>
<h3>References:</h3>
<ul>
<li>map()</li>
<li>padStart()</li>
</ul>
<h2>Added:</h2>
<p>From your following additional question,</p>
<blockquote>
<p>Wait. If I run again the script, the output is starting again with ID000001. Is there a way for me to just continue the number?</p>
</blockquote>
<p>In this case, how about using PropertiesServices as follows?</p>
<h3>Sample script:</h3>
<pre class="lang-js prettyprint-override"><code>function myFunction() {
  const sheetName = "Sheet1"; // Please set the sheet name.

  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
  const range = sheet.getRange("A2:A" + sheet.getLastRow());
  const p = PropertiesService.getScriptProperties();
  const count = p.getProperty("count");
  let c = count ? Number(count) : 1; // If you want to set the initial count, please modify 1 to other.
  const values = range.getValues().map(([a]) => [a === 0 ? `ID${(c++).toString().padStart(6, '0')}` : a]);
  range.setValues(values);
  p.setProperty("count", c);
}

// When you want to reset the count, please run this function.
function reset() {
  PropertiesService.getScriptProperties().deleteProperty("count");
}
</code>```

For example, when all ID###### values are updated every run, you can also use the following sample script.

function myFunction() {
  const sheetName = "Sheet1"; // Please set the sheet name.

  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
  const range = sheet.getRange("A2:A" + sheet.getLastRow());
  range.createTextFinder("^ID[\\d]+$").matchEntireCell(true).useRegularExpression(true).replaceAllWith(0);
  let c = 1;
  const values = range.getValues().map(([a]) => [a === 0 ? `ID${(c++).toString().padStart(6, '0')}` : a]);
  range.setValues(values);
}
```

Title: Google Sheet Auto Add / Update Value

Body:
I believe your goal is as follows.

You want to convert 0 to ID000001. And, when the multiple 0 values are existing, you want to convert to ID000001, ID000002,,,.

In this case, how about the following sample script?

Sample script:

function myFunction() {
  const sheetName = "Sheet1"; // Please set the sheet name.

  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
  const range = sheet.getRange("A2:A" + sheet.getLastRow());
  let c = 1;
  const values = range.getValues().map(([a]) => [a === 0 ? `ID${(c++).toString().padStart(6, '0')}` : a]);
  range.setValues(values);
}

In this script, it supposes that the column of "STUDENT ID" is the column "A" because I cannot know the column information from your sample image.

References:

map()

padStart()

Added:

From your following additional question,

Wait. If I run again the script, the output is starting again with ID000001. Is there a way for me to just continue the number?

In this case, how about using PropertiesServices as follows?

Sample script:

function myFunction() {
  const sheetName = "Sheet1"; // Please set the sheet name.

  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
  const range = sheet.getRange("A2:A" + sheet.getLastRow());
  const p = PropertiesService.getScriptProperties();
  const count = p.getProperty("count");
  let c = count ? Number(count) : 1; // If you want to set the initial count, please modify 1 to other.
  const values = range.getValues().map(([a]) => [a === 0 ? `ID${(c++).toString().padStart(6, '0')}` : a]);
  range.setValues(values);
  p.setProperty("count", c);
}

// When you want to reset the count, please run this function.
function reset() {
  PropertiesService.getScriptProperties().deleteProperty("count");
}

For example, when all ID###### values are updated every run, you can also use the following sample script.

function myFunction() {
  const sheetName = "Sheet1"; // Please set the sheet name.

  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
  const range = sheet.getRange("A2:A" + sheet.getLastRow());
  range.createTextFinder("^ID[\\d]+$").matchEntireCell(true).useRegularExpression(true).replaceAllWith(0);
  let c = 1;
  const values = range.getValues().map(([a]) => [a === 0 ? `ID${(c++).toString().padStart(6, '0')}` : a]);
  range.setValues(values);
}


问:
How to convert time format to a number format (Google Sheets/Data Studio)
I want to convert the numbers in ColA to normal numbers, like the ones I have in ColB. The one in ColA currently are in this format: 00:56:00.000. I initially started out with a time length, that I then converted to seconds (what's currently in ColA). I need to convert them back into a single number to import into Data Studio so it can read it as time. If I try to change the formatting to a number it comes up as a decimal, how can I change the format to a number? Or can I do it in Data Studio?

https://docs.google.com/spreadsheets/d/1xaAfc6hcFJJ1JsPfrx9Ly3usfljuzELT80UsgSxcNM8/edit#gid=0

答: Change format to seconds only.</p>

Body: Change format to seconds only.


问:
Insert multiple records in mysql using node.js fails
I am trying to INSERT multiple records in a MySQL Table, but whatever I do, it inserts only one row.

Here is the node.js code:

```<code>let orderID = 15; //It is a foreign key. Noted it from the table.
itemParams = [
        [ orderID, 'd', 34.6, '12', '123.jpeg' ],
        [ orderID, 'd', 30.6, '2', '456.jpeg' ]
];

let addOrderItems = await pool.query(`INSERT INTO orderitems (oid, description, weight, quantity, image_url) VALUES (?)`, itemParams);
</code>```

When I console log addOrderItems the affectedRows count is 1, so I also checked my table in Workbench to be sure and only one row was added. (oid is a foreign key). Table does have a primary key which auto increments.

The query I found online didn't have paranthesis around the question mark ? but when I remove the paranthesis, I get the following error:

```<code>Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '19, 'd', 34.6, '12', '123.jpeg'' at line 1
    at Query.Sequence._packetToError (Z:\Jura_SaaS\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
    at Query.ErrorPacket (Z:\Jura_SaaS\node_modules\mysql\lib\protocol\sequences\Query.js:79:18)
    at Protocol._parsePacket (Z:\Jura_SaaS\node_modules\mysql\lib\protocol\Protocol.js:291:23)
    at Parser._parsePacket (Z:\Jura_SaaS\node_modules\mysql\lib\protocol\Parser.js:433:10)
    at Parser.write (Z:\Jura_SaaS\node_modules\mysql\lib\protocol\Parser.js:43:10)
    at Protocol.write (Z:\Jura_SaaS\node_modules\mysql\lib\protocol\Protocol.js:38:16)
    at Socket.<anonymous> (Z:\Jura_SaaS\node_modules\mysql\lib\Connection.js:88:28)
    at Socket.<anonymous> (Z:\Jura_SaaS\node_modules\mysql\lib\Connection.js:526:10)
    at Socket.emit (events.js:315:20)
    at addChunk (_stream_readable.js:309:12)
    --------------------
    at Pool.query (Z:\Jura_SaaS\node_modules\mysql\lib\Pool.js:199:23)
    at internal/util.js:297:30
    at new Promise (<anonymous>)
    at Pool.query (internal/util.js:296:12)
    at Z:\Jura_SaaS\routes\order.js:190:44
    at processTicksAndRejections (internal/process/task_queues.js:93:5) {
  code: 'ER_PARSE_ERROR',
  errno: 1064,
  sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '19, 'd', 34.6, '12', '123.jpeg'' at line 1",
  sqlState: '42000',
  index: 0,
  sql: "INSERT INTO orderitems (oid, description, weight, quantity, image_url) VALUES 19, 'd', 34.6, '12', '123.jpeg';"
}
</code>```

NOTE: I have promisified pool.query that is the reason you don't see the callback format of it.

答:
I had the same issue. Here is an article detailing your case. For your case I would do the following :</p>
```<code>let orderID = 15; //It is a foreign key. Noted it from the table.
itemParams = [
        [ orderID, 'd', 34.6, '12', '123.jpeg' ],
        [ orderID, 'd', 30.6, '2', '456.jpeg' ]
];

let addOrderItems = await pool.query(`INSERT INTO orderitems (oid, description, weight, quantity, image_url) VALUES ?`, [itemParams]);
</code>```

Body:
I am trying to INSERT multiple records in a MySQL Table, but whatever I do, it inserts only one row.

Here is the node.js code:

let orderID = 15; //It is a foreign key. Noted it from the table.
itemParams = [
        [ orderID, 'd', 34.6, '12', '123.jpeg' ],
        [ orderID, 'd', 30.6, '2', '456.jpeg' ]
];

let addOrderItems = await pool.query(`INSERT INTO orderitems (oid, description, weight, quantity, image_url) VALUES (?)`, itemParams);

When I console log addOrderItems the affectedRows count is 1, so I also checked my table in Workbench to be sure and only one row was added. (oid is a foreign key). Table does have a primary key which auto increments.

The query I found online didn't have paranthesis around the question mark ? but when I remove the paranthesis, I get the following error:

Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '19, 'd', 34.6, '12', '123.jpeg'' at line 1
    at Query.Sequence._packetToError (Z:\Jura_SaaS\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
    at Query.ErrorPacket (Z:\Jura_SaaS\node_modules\mysql\lib\protocol\sequences\Query.js:79:18)
    at Protocol._parsePacket (Z:\Jura_SaaS\node_modules\mysql\lib\protocol\Protocol.js:291:23)
    at Parser._parsePacket (Z:\Jura_SaaS\node_modules\mysql\lib\protocol\Parser.js:433:10)
    at Parser.write (Z:\Jura_SaaS\node_modules\mysql\lib\protocol\Parser.js:43:10)
    at Protocol.write (Z:\Jura_SaaS\node_modules\mysql\lib\protocol\Protocol.js:38:16)
    at Socket.<anonymous> (Z:\Jura_SaaS\node_modules\mysql\lib\Connection.js:88:28)
    at Socket.<anonymous> (Z:\Jura_SaaS\node_modules\mysql\lib\Connection.js:526:10)
    at Socket.emit (events.js:315:20)
    at addChunk (_stream_readable.js:309:12)
    --------------------
    at Pool.query (Z:\Jura_SaaS\node_modules\mysql\lib\Pool.js:199:23)
    at internal/util.js:297:30
    at new Promise (<anonymous>)
    at Pool.query (internal/util.js:296:12)
    at Z:\Jura_SaaS\routes\order.js:190:44
    at processTicksAndRejections (internal/process/task_queues.js:93:5) {
  code: 'ER_PARSE_ERROR',
  errno: 1064,
  sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '19, 'd', 34.6, '12', '123.jpeg'' at line 1",
  sqlState: '42000',
  index: 0,
  sql: "INSERT INTO orderitems (oid, description, weight, quantity, image_url) VALUES 19, 'd', 34.6, '12', '123.jpeg';"
}

NOTE: I have promisified pool.query that is the reason you don't see the callback format of it.

Body:
I had the same issue. Here is an article detailing your case. For your case I would do the following :

let orderID = 15; //It is a foreign key. Noted it from the table.
itemParams = [
        [ orderID, 'd', 34.6, '12', '123.jpeg' ],
        [ orderID, 'd', 30.6, '2', '456.jpeg' ]
];

let addOrderItems = await pool.query(`INSERT INTO orderitems (oid, description, weight, quantity, image_url) VALUES ?`, [itemParams]);


问:
How to use both destination_prefix_naming and default_file_naming in Apache Beam WriteToFiles?
I have an Apache Beam pipeline that is writing to files via:

```<code>with beam.Pipeline(options=options) as p:
    my_pipeline = (
        p
        | "ReadTable" >> beam.io.Read(source)
        | "WriteSomeFiles" >>  beam.io.fileio.WriteToFiles(
            path="/path/prefix/to/directory/",
            destination=lambda record: record["filename"],
            file_naming=beam.io.fileio.destination_prefix_naming(),
            sink=JsonSink())
        )
</code>```

This successfully names the files with the "filename" entry in my record. How can I also set the suffix of the file? E.g. with default_file_naming like:

```<code>default_file_naming(prefix="my-prefix", suffix=".json")
</code>```

答: destination_prefix_naming takes an optional parameter suffix that you can pass to set the suffix of the file.

Body:
I have an Apache Beam pipeline that is writing to files via:

with beam.Pipeline(options=options) as p:
    my_pipeline = (
        p
        | "ReadTable" >> beam.io.Read(source)
        | "WriteSomeFiles" >>  beam.io.fileio.WriteToFiles(
            path="/path/prefix/to/directory/",
            destination=lambda record: record["filename"],
            file_naming=beam.io.fileio.destination_prefix_naming(),
            sink=JsonSink())
        )

This successfully names the files with the "filename" entry in my record. How can I also set the suffix of the file? E.g. with default_file_naming like:

default_file_naming(prefix="my-prefix", suffix=".json")


问:
Throttle css animation to only update every N milliseconds
Certain types of css animations are more performant as js due to the fact that they only need to update every ~20+ milliseconds.

For instance, making a gradient that very subtly (slowly) changes its color over minutes.

Is there a way to make css animations only update every N milliseconds if it's a case where the user would never see the difference (but technically there could be one every frame)?

答:
Found it.  There's a steps() timing function that can be used for animations.

animation-timing-function: steps(1000);

.RaceTrack {
  position: relative;
  height: 1px;
  width: 100%;
  background: yellow;
  border-top: 25px solid black;
  border-bottom: 25px solid black;
}

.Snail {
  position: absolute;
  top: -25px;
  left: 0px;

  animation: snail-race;
  animation-duration: 100s;
  animation-timing-function: linear;
  animation-iteration-count: infinite;
}

.Snail.steps {
  top: 0px;
  animation-timing-function: steps(1000);
}

@keyframes snail-race {
  from { left: 0px; }
  to { left: 100%; }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="RaceTrack">
  <div class="Snail"></div>
  <div class="Snail steps"></div>
 </div>

Top snail animates every frame<br>
Bottom snail animates every 100ms</code>```

Body:
Found it.  There's a steps() timing function that can be used for animations.

animation-timing-function: steps(1000);

.RaceTrack {
  position: relative;
  height: 1px;
  width: 100%;
  background: yellow;
  border-top: 25px solid black;
  border-bottom: 25px solid black;
}

.Snail {
  position: absolute;
  top: -25px;
  left: 0px;

  animation: snail-race;
  animation-duration: 100s;
  animation-timing-function: linear;
  animation-iteration-count: infinite;
}

.Snail.steps {
  top: 0px;
  animation-timing-function: steps(1000);
}

@keyframes snail-race {
  from { left: 0px; }
  to { left: 100%; }
}

<div class="RaceTrack">
  <div class="Snail"></div>
  <div class="Snail steps"></div>
 </div>

Top snail animates every frame<br>
Bottom snail animates every 100ms


问:
Second
 tag failing to show up with color
I'm trying to create an animation with 2 div tags, but the child is not appearing in the parent. How do I get the child to show up with background color?

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Rotate</title>

```

答:
The main culprit is the use of a semicolon after the .parent css class declaration. That semicolon causes subsequent declarations (.child in this case) to be ignored:

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Rotate</title>

```

I also removed z-index: 2; from .child since it is not needed in this example.

Title: Second <div> tag failing to show up with color

Body:
The main culprit is the use of a semicolon after the .parent css class declaration. That semicolon causes subsequent declarations (.child in this case) to be ignored:

<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Rotate</title>
  </head>
  <body>
    <style>
      .parent {
        width: 400px;
        height: 400px;
        background-color: hsla(200,100%,20%);
      }     /* <------ Removed semicolon */

      .child {
        width: 50%;
        height: 50%;
        background-color: red;
      }
    </style>
    <div class = "parent">
      <div class = "child"></div>
    </div>
  </body>
</html>

I also removed z-index: 2; from .child since it is not needed in this example.