问:
Why won't my app render when state changes?
I'm building an application that allows for posting community concerns with the ability to upvote those concerns using React, and right now, I am working on the upvote functionality.  One way I'm trying to limit the currently logged in user to a single vote is to disable the button once an upvote has been successfully registered for any given post.

To do this, I created a function that checks if the logged in user's ID matches the ID of the upvote for each post.  If no match is found, this means the user hasn't voted for already and can register the new upvote.  Once this is complete, the button is disabled.  I created state for this and is set to false upon the initial render (not sure if this is what I should be doing).  I also created state for the all of the votes that have been successfully registered.  Both are included below.

```<code>const [alreadyVoted, setAlreadyVoted] = useState(false);
const [userVotes, setUserVotes] = useState(upvotes) // upvotes is being passed via props
</code>```

I'm using the useEffect hook (again, not sure if this is the best way) to check if each button should be enabled or disabled like so:

```<code>useEffect(() => {
  hasVoted()
}, [userVotes])
</code>```

Finally, my hasVoted function checks to see if the user has already voted for the issue before and determines the state.  It looks like:

```<code>function hasVoted() {
  userVotes.forEach(vote => {
    if (vote.issue_id === issue.id) {  // issue here is from props
      setAlreadyVoted(true) // I want this to then disable my button
    }
  })
}
</code>```

Right now, when I click the button to register the upvote, the page doesn't rerender upon clicking.  However, if I refresh the page, the button is successfully disabled as it should be.  It probably goes without saying, I'm still getting the hang of React, but any and all help is appreciated.

答:
This code is meaningless at first place

```<code>userVotes.forEach(vote => {
    if (vote.issue_id === issue.id) {  // issue here is from props
      setAlreadyVoted(true) // I want this to then disable my button
    }
  })
</code>```

, it can be transformed into

```<code>if (userVotes.some(vote => vote.issue_id === issue.id)) setAlreadyVoted(true)
</code>```

but still the logic of it is not clear

Body:
I'm building an application that allows for posting community concerns with the ability to upvote those concerns using React, and right now, I am working on the upvote functionality.  One way I'm trying to limit the currently logged in user to a single vote is to disable the button once an upvote has been successfully registered for any given post.

To do this, I created a function that checks if the logged in user's ID matches the ID of the upvote for each post.  If no match is found, this means the user hasn't voted for already and can register the new upvote.  Once this is complete, the button is disabled.  I created state for this and is set to false upon the initial render (not sure if this is what I should be doing).  I also created state for the all of the votes that have been successfully registered.  Both are included below.

const [alreadyVoted, setAlreadyVoted] = useState(false);
const [userVotes, setUserVotes] = useState(upvotes) // upvotes is being passed via props

I'm using the useEffect hook (again, not sure if this is the best way) to check if each button should be enabled or disabled like so:

useEffect(() => {
  hasVoted()
}, [userVotes])

Finally, my hasVoted function checks to see if the user has already voted for the issue before and determines the state.  It looks like:

function hasVoted() {
  userVotes.forEach(vote => {
    if (vote.issue_id === issue.id) {  // issue here is from props
      setAlreadyVoted(true) // I want this to then disable my button
    }
  })
}

Right now, when I click the button to register the upvote, the page doesn't rerender upon clicking.  However, if I refresh the page, the button is successfully disabled as it should be.  It probably goes without saying, I'm still getting the hang of React, but any and all help is appreciated.

Body:
This code is meaningless at first place

userVotes.forEach(vote => {
    if (vote.issue_id === issue.id) {  // issue here is from props
      setAlreadyVoted(true) // I want this to then disable my button
    }
  })

, it can be transformed into

if (userVotes.some(vote => vote.issue_id === issue.id)) setAlreadyVoted(true)

but still the logic of it is not clear


来源: stackexchange

问:
print value of char array which is loaded with void pointer
I have below code where I am passing address of array of charectors to function "GetStr". GetStr function prototype is fixed.

Here in below code I am passing command line argument where string to function "GetStr" and update the value in the address of variable "str".

PRoblem:
At Print 1, I am getting the value what I passed from command line arguments. A Print 2 in main function, I am unable to print or get the value back. Could you please let me know how to print the value at "Print 2" statement

```<code>int GetStr(void *RetVal, int argc, char **argv)
{
    if(argc != 0){

        if(argv != NULL && argv[1] != '\0'){
            RetVal = argv[1];
        }
        else{
            RetVal = '\0';
        }
        cout<< " RetVal: " << (char *)RetVal <<endl; ->>>  PRINT 1
    }
    else{
        return -1;
    }
    return 0;
}
</code>```

Driver:

```<code>int main(int argc, char **argv)
{
    char str[8];

    GetStr(str,argc,argv);

    cout<<"HH: "<<((char *)(str))<<endl;  ->>>  PRINT 2
  }
</code>```

答:
The parameter RetVal is a local variable of the function GetStr. Changes of it do not influence on the original argument passed to the function. Moreover as the original argument is an array then arrays do not have the assignment operator. You have to copy characters pointed to by argv[1] to the passed array.

So in any case this statement

```<code>RetVal = argv[1];
</code>```

and this

```<code>RetVal = '\0';
</code>```

have no effect relative to the passed array. And it is unclear what you are trying to do in the second statement above. Either you want to set the pointer to NULL. Or you want to set the first pointed byte to the terminating zero character that is invalid because the pointer is not dereferenced and moreover has the type void *.

Also it seems that instead of this expression in the if statement

```<code>argv[1] != '\0'
</code>```

you mean either

```<code>argv[1][0] != '\0'
</code>```

or

```<code>argv[1] != nullptr
</code>```

In any case these two if statements

```<code>if(argc != 0){

    if(argv != NULL && argv[1] != '\0'){
</code>```

can be substituted for one if statement as

```<code>if ( not ( argc < 2 ) )
</code>```

The function can look at least the following way

```<code>int GetStr( void *RetVal, int argc, char **argv )
{
    int error = argc < 2 ? -1 : 0;

    if ( not error )
    {
        strcpy( RetVal, argv[1] );
    }

    return error;
}
</code>```

The function should not output anything except for the debug purpose. It is the caller of the function will decide whether to output a message if any.

Pay attention to that the function is unsafe because the passed array can be less than it is required to copy the string pointed to by argv[1].

ContentLicense: CC BY-SA 4.0

Body:
I have below code where I am passing address of array of charectors to function "GetStr". GetStr function prototype is fixed.

Here in below code I am passing command line argument where string to function "GetStr" and update the value in the address of variable "str".

PRoblem:
At Print 1, I am getting the value what I passed from command line arguments. A Print 2 in main function, I am unable to print or get the value back. Could you please let me know how to print the value at "Print 2" statement

int GetStr(void *RetVal, int argc, char **argv)
{
    if(argc != 0){

        if(argv != NULL && argv[1] != '\0'){
            RetVal = argv[1];
        }
        else{
            RetVal = '\0';
        }
        cout<< " RetVal: " << (char *)RetVal <<endl; ->>>  PRINT 1
    }
    else{
        return -1;
    }
    return 0;
}

Driver:

int main(int argc, char **argv)
{
    char str[8];

    GetStr(str,argc,argv);

    cout<<"HH: "<<((char *)(str))<<endl;  ->>>  PRINT 2
  }

Body:
The parameter RetVal is a local variable of the function GetStr. Changes of it do not influence on the original argument passed to the function. Moreover as the original argument is an array then arrays do not have the assignment operator. You have to copy characters pointed to by argv[1] to the passed array.

So in any case this statement

RetVal = argv[1];

and this

RetVal = '\0';

have no effect relative to the passed array. And it is unclear what you are trying to do in the second statement above. Either you want to set the pointer to NULL. Or you want to set the first pointed byte to the terminating zero character that is invalid because the pointer is not dereferenced and moreover has the type void *.

Also it seems that instead of this expression in the if statement

argv[1] != '\0'

you mean either

argv[1][0] != '\0'

or

argv[1] != nullptr

In any case these two if statements

if(argc != 0){

    if(argv != NULL && argv[1] != '\0'){

can be substituted for one if statement as

if ( not ( argc < 2 ) )

The function can look at least the following way

int GetStr( void *RetVal, int argc, char **argv )
{
    int error = argc < 2 ? -1 : 0;

    if ( not error )
    {
        strcpy( RetVal, argv[1] );
    }

    return error;
}

The function should not output anything except for the debug purpose. It is the caller of the function will decide whether to output a message if any.

Pay attention to that the function is unsafe because the passed array can be less than it is required to copy the string pointed to by argv[1].


问:
strange behaviour of ternary operator in recursion
There is a properly working code:

```<code>#include <iostream>

int sum_odd_digits(int n)
{
  if(n==0) return 0;
  else return (((n%2)!=0)?n%10:0) + sum_odd_digits(n/10);
}

int main(int argc, char ** argv)
{
  std::cout<<sum_odd_digits(25897641)<<std::endl;
  return 0;
}
</code>```

But if to remove the outer parenthesis, i. e. replace

```<code>else return (((n%2)!=0)?n%10:0) + sum_odd_digits(n/10);
</code>```

with

```<code>else return ((n%2)!=0)?n%10:0 + sum_odd_digits(n/10);
</code>```

the program begins giving a wrong output result, i. e. begins working incorrectly.

Why? What is the difference between these 2 lines?

答:
This is due to operator precedence: + has higher precedence than ?:, so your incorrect version resolves to:

```<code>((n%2)!=0) ? n%10 : (0 + sum_odd_digits(n/10));
                    ^                        ^
                  // addition is grouped first
</code>```

which now has obviously different grouping than the first version.

Body:
There is a properly working code:

#include <iostream>

int sum_odd_digits(int n)
{
  if(n==0) return 0;
  else return (((n%2)!=0)?n%10:0) + sum_odd_digits(n/10);
}

int main(int argc, char ** argv)
{
  std::cout<<sum_odd_digits(25897641)<<std::endl;
  return 0;
}

But if to remove the outer parenthesis, i. e. replace

else return (((n%2)!=0)?n%10:0) + sum_odd_digits(n/10);

with

else return ((n%2)!=0)?n%10:0 + sum_odd_digits(n/10);

the program begins giving a wrong output result, i. e. begins working incorrectly.

Why? What is the difference between these 2 lines?

Body:
This is due to operator precedence: + has higher precedence than ?:, so your incorrect version resolves to:

((n%2)!=0) ? n%10 : (0 + sum_odd_digits(n/10));
                    ^                        ^
                  // addition is grouped first

which now has obviously different grouping than the first version.


问:
Using android.support.v7.widget.CardView in my project (Eclipse)
I'd like to use the new CardView widget that was introduced with the new Android L Developer Preview Support Library (As mentioned here), which seems to be part of a new revision of the v7 support library.

I have now updated my SDK version, downloaded the newest Support Library package, but I still cannot find the new CardView widget.

I already searched the web and the official docs, but could not get any hints on where I can get the new support library.

Any help is highly appreciated!

EDIT: I'm using ADT/Eclipse

答:
In the most latest android, we implement card view like this:

build.gradle file:

```<code>dependencies {
    ...
    compile 'com.android.support:cardview-v7:24.0.0'
}
</code>```

and in the xml file its referenced as:

```<code><androidx.cardview.widget.CardView
…>
…
</androidx.cardview.widget.CardView>
</code>```

this means its class has changed to:
androidx.cardview.widget.CardView

ContentLicense: CC BY-SA 3.0

Body:
In the most latest android, we implement card view like this:

build.gradle file:

dependencies {
    ...
    compile 'com.android.support:cardview-v7:24.0.0'
}

and in the xml file its referenced as:

<androidx.cardview.widget.CardView
…>
…
</androidx.cardview.widget.CardView>

this means its class has changed to:
androidx.cardview.widget.CardView


问:
Casting to unsigned without specifying a type
```<code>#include <stdio.h>

int main(){
  ssize_t a= -1;
  size_t b = (unsigned)a;
  return 0;
}
</code>```

a is 8 bytes all set to 1, however b becomes a 4 byte number when casted to unsigned without doing a proper (unsigned size_t), why is that? why doesn't it turn into an 8 byte unsigned variable?

答:
Casting a negative value to unsigned (independently of what type is the unsigned) is Undefined Behaviour.  You can cast only positive signed values to be unsigned.

The result of casting is not defined as a valid operation, and it depends on the architecture and the compiler implementation how it deals with that cast.

Anyway, when you add the unsigned keyword but don't specify the actual integer type you want, you have to think that short, long, long long, are also adjectives to the basic int type (which is the default type to substitute) so, to end, the default type is int.

Body:
#include <stdio.h>

int main(){
  ssize_t a= -1;
  size_t b = (unsigned)a;
  return 0;
}

a is 8 bytes all set to 1, however b becomes a 4 byte number when casted to unsigned without doing a proper (unsigned size_t), why is that? why doesn't it turn into an 8 byte unsigned variable?


问:
Create an array of values between two numbers incremented a specific number of times?
I've found the answer to this question before but I can't for the life of me find the source. The goal is to create an array of values between 9.5 and 10.9, and in total the array needs to be incremented 513 times. The 9.5 and 10.9 are the first and last increment.

It's also important that every value is different, so decimal places should be moved back as far as necessary.

Hope I've explained the goal clear enough, thank you.

答:
I'm not sure what you exactly want but if you just count from 0 to 513 as in

const start = 9.5;
const end = 10.9;
const times = 513;
const array = [];
for (let i = 0; i < times; ++i) {
  const u = i / (times - 1);            // this will go from 0 to 1
  const v = start + (end - start) * u;  // this will go from 9.5 to 10.9
  array.push(v);
}
console.log(array);```


问:
Need some advice to choose the proper container
I'm trying to design a task scheduler to a game engine. A task could be an animation, a trigger controller, etc.

My problem is what container to choose. The idea is: when you insert a new task, the container must reorder and put the task in the proper place. Once executed, task could change and be scheduled again or deleted. This is mainly push and pop.

But, if possible, it would be nice if I could have random access to an element, but not vital. No matter if the container supports one or more elements with the same key.

I think that priority queue fits my needs but I saw that is based on vector implementation, and I think that this container must be somehow  optimized to push and pop.

Opinions?

答:
(source: adrinael.net)

(original source: Liam Devine)


问:
Spring Cloud Config Server encryption issue
We have a Pivotal Cloud Foundry server which is configured with a Spring config server with the encryption key. In the corresponding properties file (via github), we have {cipher} prefixed for some simple properties and we are able to get the values just fine in the application. But the challenge we noticed recently is that when we have a base64 data that need to be encrypted, the spring encryption is truncating the trailing equals sign at the end of base64 data. And when our application reads this data, its failing parsing it since its not a valid base64 as its padding character (equals sign) at the end is missing. We tried escaping the equals sign with a backslash but still no luck. We are just seeing two backslashes, so wondering if there are any suggestions to nail this issue. Thanks!   </p>

答:
The issue here, as far as I can tell, appears to be with the usage of curl. I'm able to replicate the problem you're seeing by running:

```<code>spring decrypt --key @${HOME}/server_rsa_no_eol.key "$(curl -H "Authorization: $(cf oauth-token)" https://config-server.example.com/encrypt -s -d 'VGVzdC0=')"
</code>```

This uses curl to hit the encrypt endpoint and takes the result and immediately decrypts it with spring decrypt. As you've indicated, this returns VGVzdC0.

It seems like this is a curl issue because I can make the same post to https://httpbin.org/post and I get the same result, VGVzdC0 without the =.

```<code>$ curl https://httpbin.org/post --data 'VGVzdC0='
{
  ...
  "form": {
    "VGVzdC0": ""
  },
  ...
</code>```

What works is if I url encode the = character.

```<code>$ curl https://httpbin.org/post --data 'VGVzdC0%3D'
{
  ...
  "form": {
    "VGVzdC0=": ""
  },
  ...
</code>```

You can also make curl do the url encoding by using --data-urlencode but there's a catch. You must prefix the value with a =. So this also works

```<code>$ curl https://httpbin.org/post --data-urlencode '=VGVzdC0='
{
  "args": {},
  "data": "",
  "files": {},
  "form": {
    "VGVzdC0=": ""
  },
...
</code>```

From the curl man page:

```<code>  --data-urlencode <data>
          (HTTP) This posts data, similar to the other -d, --data options with the exception that this performs URL-encoding.

          To be CGI-compliant, the <data> part should begin with a name followed by a separator and a content specification. The <data> part can be passed to curl using one of the following
          syntaxes:

          content
                 This will make curl URL-encode the content and pass that on. Just be careful so that the content doesn't contain any = or @ symbols, as that will then make the syntax match
                 one of the other cases below!

          =content
                 This will make curl URL-encode the content and pass that on. The preceding = symbol is not included in the data.
</code>```

The key is the last part =content. That will make curl url encode the content and the prefixed = is not included.

If I repeat my test above, I get the expected result VGVzdC0=.

```<code>spring decrypt --key @${HOME}/server_rsa_no_eol.key "$(curl -H "Authorization: $(cf oauth-token)" https://config-server.example.com/encrypt -s --data-urlencode '=VGVzdC0=')"
</code>```

As an aside, you can also take the easy option and install the Spring Boot CLI + the Spring Cloud Extension. Then you can just spring encrypt --key @${HOME}/server_rsa_no_eol.key 'VGVzdC0=' and you'll get the right values. That does mean you need a copy of the key on your local machine though, which you may or may not have.

```<code>brew install springboot
spring install org.springframework.cloud:spring-cloud-cli:2.2.1.RELEASE
</code>```

https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/html/spring-boot-cli.html#cli-installation

https://cloud.spring.io/spring-cloud-static/spring-cloud-cli/2.2.1.RELEASE/reference/html/#_installation

Body:
The issue here, as far as I can tell, appears to be with the usage of curl. I'm able to replicate the problem you're seeing by running:

spring decrypt --key @${HOME}/server_rsa_no_eol.key "$(curl -H "Authorization: $(cf oauth-token)" https://config-server.example.com/encrypt -s -d 'VGVzdC0=')"

This uses curl to hit the encrypt endpoint and takes the result and immediately decrypts it with spring decrypt. As you've indicated, this returns VGVzdC0.

It seems like this is a curl issue because I can make the same post to https://httpbin.org/post and I get the same result, VGVzdC0 without the =.

$ curl https://httpbin.org/post --data 'VGVzdC0='
{
  ...
  "form": {
    "VGVzdC0": ""
  },
  ...

What works is if I url encode the = character.

$ curl https://httpbin.org/post --data 'VGVzdC0%3D'
{
  ...
  "form": {
    "VGVzdC0=": ""
  },
  ...

You can also make curl do the url encoding by using --data-urlencode but there's a catch. You must prefix the value with a =. So this also works

$ curl https://httpbin.org/post --data-urlencode '=VGVzdC0='
{
  "args": {},
  "data": "",
  "files": {},
  "form": {
    "VGVzdC0=": ""
  },
...

From the curl man page:

  --data-urlencode <data>
          (HTTP) This posts data, similar to the other -d, --data options with the exception that this performs URL-encoding.

          To be CGI-compliant, the <data> part should begin with a name followed by a separator and a content specification. The <data> part can be passed to curl using one of the following
          syntaxes:

          content
                 This will make curl URL-encode the content and pass that on. Just be careful so that the content doesn't contain any = or @ symbols, as that will then make the syntax match
                 one of the other cases below!

          =content
                 This will make curl URL-encode the content and pass that on. The preceding = symbol is not included in the data.

The key is the last part =content. That will make curl url encode the content and the prefixed = is not included.

If I repeat my test above, I get the expected result VGVzdC0=.

spring decrypt --key @${HOME}/server_rsa_no_eol.key "$(curl -H "Authorization: $(cf oauth-token)" https://config-server.example.com/encrypt -s --data-urlencode '=VGVzdC0=')"

As an aside, you can also take the easy option and install the Spring Boot CLI + the Spring Cloud Extension. Then you can just spring encrypt --key @${HOME}/server_rsa_no_eol.key 'VGVzdC0=' and you'll get the right values. That does mean you need a copy of the key on your local machine though, which you may or may not have.

brew install springboot
spring install org.springframework.cloud:spring-cloud-cli:2.2.1.RELEASE

https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/html/spring-boot-cli.html#cli-installation

https://cloud.spring.io/spring-cloud-static/spring-cloud-cli/2.2.1.RELEASE/reference/html/#_installation


问:
How do I make my flex cell fill up its whole space?
Whenever I hover over the box, the cell's background takes up the full width (thanks to the width: 100%) but when I do the same with height, it doesn't do so. The parent doesn't have any padding, so how can I fix this?

I have looked at links like "https://css-tricks.com/boxes-fill-height-dont-squish/" and tried using flex-grow but it doesn't seem to work for me, but I am probably messing it up.

div {
  display: flex;
  flex-direction: row;
  background-color: lightgray;
  text-align: center;
  justify-content: space-evenly;
}

div p {
  font-size: 20px;
  color: black;
  font-weight: bold;
  width: 100%;
  height: 100%;
}

div p:hover {
  background-color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <p>Header1</p>
  <p>Header2</p>
  <p>Header3</p>
</div></code>```

答:
You can use span tag instead of p and provide padding to it as below;

div {
  display: flex;
  flex-direction: row;
  background-color: lightgray;
  text-align: center;
  justify-content: space-evenly;
}

div span {
  font-size: 20px;
  color: black;
  font-weight: bold;
  width: 100%;
  height: 100%;
  padding: 25px;
}

div span:hover {
  background-color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <span>Header1</span>
  <span>Header2</span>
  <span>Header3</span>
</div></code>```

Body:
Whenever I hover over the box, the cell's background takes up the full width (thanks to the width: 100%) but when I do the same with height, it doesn't do so. The parent doesn't have any padding, so how can I fix this?

I have looked at links like "https://css-tricks.com/boxes-fill-height-dont-squish/" and tried using flex-grow but it doesn't seem to work for me, but I am probably messing it up.

div {
  display: flex;
  flex-direction: row;
  background-color: lightgray;
  text-align: center;
  justify-content: space-evenly;
}

div p {
  font-size: 20px;
  color: black;
  font-weight: bold;
  width: 100%;
  height: 100%;
}

div p:hover {
  background-color: green;
}

Header1

Header2

Header3

Body:
You can use span tag instead of p and provide padding to it as below;

div {
  display: flex;
  flex-direction: row;
  background-color: lightgray;
  text-align: center;
  justify-content: space-evenly;
}

div span {
  font-size: 20px;
  color: black;
  font-weight: bold;
  width: 100%;
  height: 100%;
  padding: 25px;
}

div span:hover {
  background-color: green;
}

<div>
  <span>Header1</span>
  <span>Header2</span>
  <span>Header3</span>
</div>


问:
Sabre cancel itinerary segments error (OTA_CancelRQ)
I am trying to cancel itinerary segment through Sabre API (OTA_CancelRQ).

I followed this answer here and I could reach step number 3 ( OTA_CancelRQ ).

STEP1: SessionCreateRQ

STEP2: GetReservationRQ

STEP3: OTA_CancelRQ

STEP4: EndTransactionRQ

STEP5: SessionCloseRQ

Currently I am stuck at step number 3, it always fail with this below error message

cvc-elt.1: Cannot find the declaration of element 'OTA_CancelRQ'.

Request Data

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <SOAP-ENV:Header>
      <MessageHeader xmlns="http://www.ebxml.org/namespaces/messageHeader">
         <From>
            <PartyId>sample.url.of.sabre.client.com</PartyId>
         </From>
         <To>
            <PartyId>webservices.sabre.com</PartyId>
         </To>
         <CPAId>****</CPAId>
         <ConversationId>convid</ConversationId>
         <Service>OTA_CancelLLSRQ</Service>
         <Action>OTA_CancelLLSRQ</Action>
         <MessageData>
            <MessageId>msgid112</MessageId>
            <Timestamp>2020-04-20T09:25:27Z</Timestamp>
            <TimeToLive>2020-04-20T09:25:27Z</TimeToLive>
         </MessageData>
      </MessageHeader>
      <Security xmlns="http://schemas.xmlsoap.org/ws/2002/12/secext">
         <BinarySecurityToken EncodingType="Base64Binary" valueType="String">Shared/IDL:IceSess\/SessMgr:1\.0.IDL/Common/!ICESMS\/ACPCRTC!ICESMSLB\/CRT.LB!1587378430974!2968!17</BinarySecurityToken>
      </Security>
   </SOAP-ENV:Header>
   <SOAP-ENV:Body>
      <OTA_CancelRQ Version="2.0.2">
         <Segment Type="entire" />
      </OTA_CancelRQ>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

```

<hr>

<h2>Response Data</h2>

<pre class="lang-xml prettyprint-override"><code>
<?xml version="1.0" encoding="UTF-8"?>
<soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
   <soap-env:Header>
      <eb:MessageHeader xmlns:eb="http://www.ebxml.org/namespaces/messageHeader" eb:version="1.0" soap-env:mustUnderstand="1">
         <eb:From>
            <eb:PartyId eb:type="URI">webservices.sabre.com</eb:PartyId>
         </eb:From>
         <eb:To>
            <eb:PartyId eb:type="URI">sample.url.of.sabre.client.com</eb:PartyId>
         </eb:To>
         <eb:CPAId>****</eb:CPAId>
         <eb:ConversationId>convid</eb:ConversationId>
         <eb:Service>OTA_CancelLLSRQ</eb:Service>
         <eb:Action>OTA_CancelLLSRS</eb:Action>
         <eb:MessageData>
            <eb:MessageId>1447971375167810151</eb:MessageId>
            <eb:Timestamp>2020-04-20T10:25:17</eb:Timestamp>
            <eb:RefToMessageId>msgid112</eb:RefToMessageId>
         </eb:MessageData>
      </eb:MessageHeader>
      <wsse:Security xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/12/secext">
         <wsse:BinarySecurityToken valueType="String" EncodingType="wsse:Base64Binary">Shared/IDL:IceSess\/SessMgr:1\.0.IDL/Common/!ICESMS\/ACPCRTC!ICESMSLB\/CRT.LB!1587378313106!6744!9</wsse:BinarySecurityToken>
      </wsse:Security>
   </soap-env:Header>
   <soap-env:Body>
      <soap-env:Fault>
         <faultcode>soap-env:Client.Validation</faultcode>
         <faultstring>ERR.SWS.CLIENT.VALIDATION_FAILED</faultstring>
         <detail>
            <stl:ApplicationResults xmlns:stl="http://services.sabre.com/STL/v01" status="NotProcessed">
               <stl:Error timeStamp="2020-04-20T05:25:17-05:00" type="Validation">
                  <stl:SystemSpecificResults>
                     <stl:Message>cvc-elt.1: Cannot find the declaration of element 'OTA_CancelRQ'.</stl:Message>
                     <stl:ShortText>ERR.SWS.CLIENT.VALIDATION_FAILED</stl:ShortText>
                  </stl:SystemSpecificResults>
               </stl:Error>
            </stl:ApplicationResults>
         </detail>
      </soap-env:Fault>
   </soap-env:Body>
</soap-env:Envelope>

</code>```

答:
Modify the soap request body as following:

```<code> <SOAP-ENV:Body>
<OTA_CancelRQ xmlns="http://webservices.sabre.com/sabreXML/2011/10" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Version="2.0.2">
<Segment Type="entire"/>
</code>```

This should resolve the issue being faced.

Hope it helps!

Thank You!

Body:
I am trying to cancel itinerary segment through Sabre API (OTA_CancelRQ).

I followed this answer here and I could reach step number 3 ( OTA_CancelRQ ).

STEP1: SessionCreateRQ

STEP2: GetReservationRQ

STEP3: OTA_CancelRQ

STEP4: EndTransactionRQ

STEP5: SessionCloseRQ

Currently I am stuck at step number 3, it always fail with this below error message

cvc-elt.1: Cannot find the declaration of element 'OTA_CancelRQ'.

Request Data

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <SOAP-ENV:Header>
      <MessageHeader xmlns="http://www.ebxml.org/namespaces/messageHeader">
         <From>
            <PartyId>sample.url.of.sabre.client.com</PartyId>
         </From>
         <To>
            <PartyId>webservices.sabre.com</PartyId>
         </To>
         <CPAId>****</CPAId>
         <ConversationId>convid</ConversationId>
         <Service>OTA_CancelLLSRQ</Service>
         <Action>OTA_CancelLLSRQ</Action>
         <MessageData>
            <MessageId>msgid112</MessageId>
            <Timestamp>2020-04-20T09:25:27Z</Timestamp>
            <TimeToLive>2020-04-20T09:25:27Z</TimeToLive>
         </MessageData>
      </MessageHeader>
      <Security xmlns="http://schemas.xmlsoap.org/ws/2002/12/secext">
         <BinarySecurityToken EncodingType="Base64Binary" valueType="String">Shared/IDL:IceSess\/SessMgr:1\.0.IDL/Common/!ICESMS\/ACPCRTC!ICESMSLB\/CRT.LB!1587378430974!2968!17</BinarySecurityToken>
      </Security>
   </SOAP-ENV:Header>
   <SOAP-ENV:Body>
      <OTA_CancelRQ Version="2.0.2">
         <Segment Type="entire" />
      </OTA_CancelRQ>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Response Data

<?xml version="1.0" encoding="UTF-8"?>
<soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
   <soap-env:Header>
      <eb:MessageHeader xmlns:eb="http://www.ebxml.org/namespaces/messageHeader" eb:version="1.0" soap-env:mustUnderstand="1">
         <eb:From>
            <eb:PartyId eb:type="URI">webservices.sabre.com</eb:PartyId>
         </eb:From>
         <eb:To>
            <eb:PartyId eb:type="URI">sample.url.of.sabre.client.com</eb:PartyId>
         </eb:To>
         <eb:CPAId>****</eb:CPAId>
         <eb:ConversationId>convid</eb:ConversationId>
         <eb:Service>OTA_CancelLLSRQ</eb:Service>
         <eb:Action>OTA_CancelLLSRS</eb:Action>
         <eb:MessageData>
            <eb:MessageId>1447971375167810151</eb:MessageId>
            <eb:Timestamp>2020-04-20T10:25:17</eb:Timestamp>
            <eb:RefToMessageId>msgid112</eb:RefToMessageId>
         </eb:MessageData>
      </eb:MessageHeader>
      <wsse:Security xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/12/secext">
         <wsse:BinarySecurityToken valueType="String" EncodingType="wsse:Base64Binary">Shared/IDL:IceSess\/SessMgr:1\.0.IDL/Common/!ICESMS\/ACPCRTC!ICESMSLB\/CRT.LB!1587378313106!6744!9</wsse:BinarySecurityToken>
      </wsse:Security>
   </soap-env:Header>
   <soap-env:Body>
      <soap-env:Fault>
         <faultcode>soap-env:Client.Validation</faultcode>
         <faultstring>ERR.SWS.CLIENT.VALIDATION_FAILED</faultstring>
         <detail>
            <stl:ApplicationResults xmlns:stl="http://services.sabre.com/STL/v01" status="NotProcessed">
               <stl:Error timeStamp="2020-04-20T05:25:17-05:00" type="Validation">
                  <stl:SystemSpecificResults>
                     <stl:Message>cvc-elt.1: Cannot find the declaration of element 'OTA_CancelRQ'.</stl:Message>
                     <stl:ShortText>ERR.SWS.CLIENT.VALIDATION_FAILED</stl:ShortText>
                  </stl:SystemSpecificResults>
               </stl:Error>
            </stl:ApplicationResults>
         </detail>
      </soap-env:Fault>
   </soap-env:Body>
</soap-env:Envelope>

Body:
Modify the soap request body as following:

 <SOAP-ENV:Body>
<OTA_CancelRQ xmlns="http://webservices.sabre.com/sabreXML/2011/10" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Version="2.0.2">
<Segment Type="entire"/>

This should resolve the issue being faced.

Hope it helps!

Thank You!


问:
Patch REST API to Partial Update MongoDB in .NET
I have an object

```<code>{
  "_id": "testobject",
  "A": "First line",
  "B": "Second line",
  "C": "Third line"
}
</code>```

I want to send a REST PATCH request to my API to only update one of these properties

```<code>{
  "_id": "testobject",
  "C": "Forth line"
}
</code>```

This gets parsed into a class

```<code>public class SomeObject {
  public string A { get; set; }
  public string B { get; set; }
  public string C { get; set; }
}
</code>```

I now need to update the existing document in MongoDB but only updating the property C.

I could create an update definition just for this one record

```<code>UpdateDefinition<SomeObject> update = Builders<SomeObject>.Update.Set(x => x.C, <value of property C>)
</code>```

Or I could hard code a check on each property to see if it is empty

```<code>IList<UpdateDefinition<SomeObject>> updates = new List<UpdateDefinition<SomeObject>>();
if (!string.IsNullOrEmpty(C)) {
  updates.Add(UpdateDefinition<SomeObject> update = Builders<SomeObject>.Update.Set(x => x.C, <value of property C>));
}
if (!string.IsNullOrEmpty(C)) {
  updates.Add(UpdateDefinition<SomeObject> update = Builders<SomeObject>.Update.Set(x => x.C, <value of property C>));
}
</code>```

However, if I have many properties and many sub properties this could get very large very fast. The other issue is that if I set the value of the property to be intentionally empty then it would not update the record at all due to it looking for the field to non-empty.

How can I dynamically do partial updates to MongoDB documents in .NET so that I have a generic PATCH API call that can take any of the parameters the document has and only update the properties specified?

答:
Not sure anyone is here >= June '20 however I did the following.  I'm using NewtonSoft JObject/JArray and I wanted to create a mongo update parser/function that wouldn't know the incoming schema and would build out nested documents as well.  Another thing I had to get used to (I'm new to Mongo) was the syntax of the keys in the Bson Update document i.e.

```<code>{ "key.full.path.into.nested.document" : "valueToSet" }
</code>```

So, after trying a few ways to manually/recursively account for the nesting/containing path of incoming JSON doc, I finally found and can just use JToken.Path property perfectly for this.

Anyway, hopefully this is something someone will find useful.  It's just an example and makes a few assumptions about the document structure but is pretty useful in its current form.  And, like me, I think it might help a few people that are learning Mongo and their C# driver while also using JSON.Net to wrap the incoming REST requests.

```<code>    public BsonDocument ParseUpdateRequest(JObject req)
    {
        BsonDocument bson = new BsonDocument();
        Parse(req, ref bson);

        BsonDocument parsedBson = new BsonDocument();
        parsedBson["$set"] = bson;
        return parsedBson;
    }
    private void Parse(JObject req, ref BsonDocument bson)
    {
        /**
         * Could use a parent key/node in each recursion call or just use the JToken path
         * string.IsNullOrEmpty(parentNode) ? field.Key : parentNode + "." + field.Key;
         **/
        string key;
        JToken val;
        foreach (var field in req)
        {
            key = field.Value.Path;
            val = field.Value;
            switch (val.Type)
            {
                case JTokenType.String:
                    bson.Add(key, (string)val);
                    break;
                case JTokenType.Integer:
                    bson.Add(key, (int)val);
                    break;
                case JTokenType.Float:
                    bson.Add(key, (float)val);
                    break;
                case JTokenType.Date:
                    DateTime dt = (DateTime)val;
                    bson.Add(key, dt.ToUniversalTime());
                    break;
                case JTokenType.Array:
                    BsonArray bsonArray = ParseArray((JArray)val);
                    bson.Add(key, bsonArray);
                    break;
                case JTokenType.Object:
                    Parse((JObject)val, ref bson);
                    break;
            }
        }
        return;
    }

    private BsonArray ParseArray(JArray source)
    {
        BsonArray bson = new BsonArray();
        foreach (JToken field in source)
        {
            switch (field.Type)
            {
                case JTokenType.String:
                    bson.Add((string)field);
                    break;
                case JTokenType.Date:
                    DateTime dt = (DateTime)field;
                    bson.Add(dt.ToUniversalTime());
                    break;
                case JTokenType.Integer:
                    bson.Add((int)field);
                    break;
                case JTokenType.Float:
                    bson.Add((float)field);
                    break;
                case JTokenType.Object:
                    BsonDocument nestedDoc = new BsonDocument();
                    Parse((JObject)field, ref nestedDoc);
                    bson.Add(nestedDoc);
                    break;
            }
        }
        return bson;
    }
</code>```

And here's some simple test code I wrote:

```<code>            ModelUser user = new ModelUser();
        ControllerApp app = new ControllerApp();
        ControllerApp.Instance.User = user;
        JObject req = new JObject();
        req["first"] = "First";
        req["last"] = "Last";
        req["usertype"] = "parent";
        req["pw"] = "q345n3452345n2345";
        req["array"] = JArray.Parse("[ '1', '2', '3' ]");
        req["dateTest"] = DateTime.UtcNow;
        req["profile"] = new JObject();
        req["profile"]["name"] = new JObject();
        req["profile"]["name"]["first"] = "testUpdateFirst";

        BsonDocument bd;
        bd = user.ParseUpdateRequest(req);
        string s = bd.ToJson();
</code>```

Body:
I have an object

{
  "_id": "testobject",
  "A": "First line",
  "B": "Second line",
  "C": "Third line"
}

I want to send a REST PATCH request to my API to only update one of these properties

{
  "_id": "testobject",
  "C": "Forth line"
}

This gets parsed into a class

public class SomeObject {
  public string A { get; set; }
  public string B { get; set; }
  public string C { get; set; }
}

I now need to update the existing document in MongoDB but only updating the property C.

I could create an update definition just for this one record

UpdateDefinition<SomeObject> update = Builders<SomeObject>.Update.Set(x => x.C, <value of property C>)

Or I could hard code a check on each property to see if it is empty

IList<UpdateDefinition<SomeObject>> updates = new List<UpdateDefinition<SomeObject>>();
if (!string.IsNullOrEmpty(C)) {
  updates.Add(UpdateDefinition<SomeObject> update = Builders<SomeObject>.Update.Set(x => x.C, <value of property C>));
}
if (!string.IsNullOrEmpty(C)) {
  updates.Add(UpdateDefinition<SomeObject> update = Builders<SomeObject>.Update.Set(x => x.C, <value of property C>));
}

However, if I have many properties and many sub properties this could get very large very fast. The other issue is that if I set the value of the property to be intentionally empty then it would not update the record at all due to it looking for the field to non-empty.

How can I dynamically do partial updates to MongoDB documents in .NET so that I have a generic PATCH API call that can take any of the parameters the document has and only update the properties specified?

Body:
Not sure anyone is here >= June '20 however I did the following.  I'm using NewtonSoft JObject/JArray and I wanted to create a mongo update parser/function that wouldn't know the incoming schema and would build out nested documents as well.  Another thing I had to get used to (I'm new to Mongo) was the syntax of the keys in the Bson Update document i.e.

{ "key.full.path.into.nested.document" : "valueToSet" }

So, after trying a few ways to manually/recursively account for the nesting/containing path of incoming JSON doc, I finally found and can just use JToken.Path property perfectly for this.

Anyway, hopefully this is something someone will find useful.  It's just an example and makes a few assumptions about the document structure but is pretty useful in its current form.  And, like me, I think it might help a few people that are learning Mongo and their C# driver while also using JSON.Net to wrap the incoming REST requests.

    public BsonDocument ParseUpdateRequest(JObject req)
    {
        BsonDocument bson = new BsonDocument();
        Parse(req, ref bson);

        BsonDocument parsedBson = new BsonDocument();
        parsedBson["$set"] = bson;
        return parsedBson;
    }
    private void Parse(JObject req, ref BsonDocument bson)
    {
        /**
         * Could use a parent key/node in each recursion call or just use the JToken path
         * string.IsNullOrEmpty(parentNode) ? field.Key : parentNode + "." + field.Key;
         **/
        string key;
        JToken val;
        foreach (var field in req)
        {
            key = field.Value.Path;
            val = field.Value;
            switch (val.Type)
            {
                case JTokenType.String:
                    bson.Add(key, (string)val);
                    break;
                case JTokenType.Integer:
                    bson.Add(key, (int)val);
                    break;
                case JTokenType.Float:
                    bson.Add(key, (float)val);
                    break;
                case JTokenType.Date:
                    DateTime dt = (DateTime)val;
                    bson.Add(key, dt.ToUniversalTime());
                    break;
                case JTokenType.Array:
                    BsonArray bsonArray = ParseArray((JArray)val);
                    bson.Add(key, bsonArray);
                    break;
                case JTokenType.Object:
                    Parse((JObject)val, ref bson);
                    break;
            }
        }
        return;
    }

    private BsonArray ParseArray(JArray source)
    {
        BsonArray bson = new BsonArray();
        foreach (JToken field in source)
        {
            switch (field.Type)
            {
                case JTokenType.String:
                    bson.Add((string)field);
                    break;
                case JTokenType.Date:
                    DateTime dt = (DateTime)field;
                    bson.Add(dt.ToUniversalTime());
                    break;
                case JTokenType.Integer:
                    bson.Add((int)field);
                    break;
                case JTokenType.Float:
                    bson.Add((float)field);
                    break;
                case JTokenType.Object:
                    BsonDocument nestedDoc = new BsonDocument();
                    Parse((JObject)field, ref nestedDoc);
                    bson.Add(nestedDoc);
                    break;
            }
        }
        return bson;
    }

And here's some simple test code I wrote:

            ModelUser user = new ModelUser();
        ControllerApp app = new ControllerApp();
        ControllerApp.Instance.User = user;
        JObject req = new JObject();
        req["first"] = "First";
        req["last"] = "Last";
        req["usertype"] = "parent";
        req["pw"] = "q345n3452345n2345";
        req["array"] = JArray.Parse("[ '1', '2', '3' ]");
        req["dateTest"] = DateTime.UtcNow;
        req["profile"] = new JObject();
        req["profile"]["name"] = new JObject();
        req["profile"]["name"]["first"] = "testUpdateFirst";

        BsonDocument bd;
        bd = user.ParseUpdateRequest(req);
        string s = bd.ToJson();


问:
Use recode function with %like% operator
Is there anyway to use the recode function from dplyr with the %like% operator from DescTools, as well as with an 'other' statement? i.e. what is shown below:

```<code>library(tidyverse)
library(DescTools)

dat <- data.frame(NAME = c("Bill", "Billy", "Wibill", "Chris"))

dat %>%
  mutate(NAME_2 = recode(NAME, "%Bill%" = "Willhelm", "Other"))
</code>```

Desired output is:

```<code>NAME      NAME_2
Bill      Willhelm
Billy     Willhelm
Wibill    Willhelm
Chris     Other
</code>```

答:
Another option with grepl in base R

```<code>dat$NAME_2 <- with(dat, ifelse(grepl("Bill", NAME, ignore.case = TRUE), "Willhelm", "Other"))
</code>```

Body:
Is there anyway to use the recode function from dplyr with the %like% operator from DescTools, as well as with an 'other' statement? i.e. what is shown below:

library(tidyverse)
library(DescTools)

dat <- data.frame(NAME = c("Bill", "Billy", "Wibill", "Chris"))

dat %>%
  mutate(NAME_2 = recode(NAME, "%Bill%" = "Willhelm", "Other"))

Desired output is:

NAME      NAME_2
Bill      Willhelm
Billy     Willhelm
Wibill    Willhelm
Chris     Other

Body:
Another option with grepl in base R

dat$NAME_2 <- with(dat, ifelse(grepl("Bill", NAME, ignore.case = TRUE), "Willhelm", "Other"))


问:
WCF - Inspect the messages being sent/received?
I have 2 solutions:
 - Server Solution
 - Client Solution

The server registers itself to my localhost IIS: http://localhost/MyApp/

The client adds WCF Services (Service References) from the localhost application: http://localhost/MyApp/MyService.svc

When I'm running the client I want to be able to see the messages being passed back and forth. I downloaded Fiddler, but it doesn't seem to want to show me any traffic being sent unless I actually use a web browser. Am I using Fiddler wrong or is there another tool I should be using for this?

To clarify, what I'm looking to do is to see the actual messages being passed in. I don't want to do anything with them except see them visually with my own eyes.

I like the WCF Service Log Utility, but I don't think I have the correct setting on there. I can't see the actual soap message, just that a message was received.

And also to clarify further, I don't care what tool I use as long as I can easily see the messages themselves.

答:
Look at this StackOverflow thread: How to use Fiddler to monitor WCF service

It answers some of your questions. you can also use something like WireShark if you want to examine everything on the wire rather than set up a Proxy, as Fiddler does.


问:
Visual Studio Code : Sort functions by name?
Is it possible to sort functions by name in Visual Studio Code ? I mean, using a keyboard shortcut or even an extension.

Precision: I'm spaeking about sorting the functions in the panel code editor.

答: If you are using TypeScript, take a look at member-ordering rule and alphabetize option in tsLint. for other languages like C#, there are probably extensions out there but I haven't looked them up myself.


问:
Add icon as button in each row of angular material table
I am using angular material version 9.2.4
I have a table in html. The table has been displayed properly. But I want to add an icon as button in each row of the table.
The table datas are coming from a rest api while I want to use same icon(say Delete icon) in each row of the table.

```<code><mat-table [dataSource]="employeeData" class="mat-elevation-z8">
<!-- Position Column -->
<ng-container matColumnDef="name">
  <mat-header-cell *matHeaderCellDef> NAME </mat-header-cell>
  <mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
</ng-container>

<!-- Name Column -->
<ng-container matColumnDef="phoneNumber">
  <mat-header-cell *matHeaderCellDef> PHONE NUMBER </mat-header-cell>
  <mat-cell *matCellDef="let element"> {{element.phoneNumber}} </mat-cell>
</ng-container>

<!-- Weight Column -->
<ng-container matColumnDef="emailId">
  <mat-header-cell *matHeaderCellDef> EMAIL ID </mat-header-cell>
  <mat-cell *matCellDef="let element"> {{element.emailId}} </mat-cell>
</ng-container>

<!-- Symbol Column -->
<ng-container matColumnDef="dateOfBirth">
  <mat-header-cell *matHeaderCellDef> DATE OF BIRTH </mat-header-cell>
  <mat-cell *matCellDef="let element"> {{element.dateOfBirth }} </mat-cell>
</ng-container>

<!-- Delete Column -->
<ng-container matColumnDef="deleteEmployee">
  <mat-cell *matCellDef="let element">
    <!-- <button mat-icon-button aria-label="Example icon button with a vertical three dot icon"> -->
      <mat-icon>delete</mat-icon>
    <!-- </button> -->
  </mat-cell>
</ng-container>

<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</code>```

I am not able to get the delete icon. the table looks like this

I want to display the delete icon after the column date of birth.
What I am missing?

答:
Add the matColumnDef 'deleteEmployee' to displayedColumns's Array in your ts file.

For Example:

```<code>displayedColumns: string[] = ['position', 'name', 'weight', 'symbol', 'deleteEmployee'];
</code>```

and your html file

```<code><!-- Delete Column -->
  <ng-container matColumnDef="deleteEmployee">
    <th mat-header-cell *matHeaderCellDef> Delete </th>
    <td mat-cell *matCellDef="let element">
       <button mat-icon-button color="primary" aria-label="Example icon button with a home icon">
        <mat-icon>delete</mat-icon>
      </button>
    </td>
  </ng-container>
</code>```

Body:
I am using angular material version 9.2.4
I have a table in html. The table has been displayed properly. But I want to add an icon as button in each row of the table.
The table datas are coming from a rest api while I want to use same icon(say Delete icon) in each row of the table.

<mat-table [dataSource]="employeeData" class="mat-elevation-z8">

<ng-container matColumnDef="name">
  <mat-header-cell *matHeaderCellDef> NAME </mat-header-cell>
  <mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
</ng-container>

<ng-container matColumnDef="phoneNumber">
  <mat-header-cell *matHeaderCellDef> PHONE NUMBER </mat-header-cell>
  <mat-cell *matCellDef="let element"> {{element.phoneNumber}} </mat-cell>
</ng-container>

<ng-container matColumnDef="emailId">
  <mat-header-cell *matHeaderCellDef> EMAIL ID </mat-header-cell>
  <mat-cell *matCellDef="let element"> {{element.emailId}} </mat-cell>
</ng-container>

<ng-container matColumnDef="dateOfBirth">
  <mat-header-cell *matHeaderCellDef> DATE OF BIRTH </mat-header-cell>
  <mat-cell *matCellDef="let element"> {{element.dateOfBirth }} </mat-cell>
</ng-container>

<ng-container matColumnDef="deleteEmployee">
  <mat-cell *matCellDef="let element">

      <mat-icon>delete</mat-icon>

  </mat-cell>
</ng-container>

<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>

I am not able to get the delete icon. the table looks like this

I want to display the delete icon after the column date of birth.
What I am missing?

Body:
Add the matColumnDef 'deleteEmployee' to displayedColumns's Array in your ts file.

For Example:

displayedColumns: string[] = ['position', 'name', 'weight', 'symbol', 'deleteEmployee'];

and your html file

<!-- Delete Column -->
  <ng-container matColumnDef="deleteEmployee">
    <th mat-header-cell *matHeaderCellDef> Delete </th>
    <td mat-cell *matCellDef="let element">
       <button mat-icon-button color="primary" aria-label="Example icon button with a home icon">
        <mat-icon>delete</mat-icon>
      </button>
    </td>
  </ng-container>


问:
Running a bash script using a Kubenetes Service
I am not sure how dumb or un-reasonable this question is, but we are trying to see if we can do this in any way.

I have a .bash file. And I want to run this when I invoke a url.

Let's take the url is https://domainname.com/jobapi
When I invoke this on the browser, this should invoke a .bash script on the container.

Is this really possible?
If it is possible, want to know if I need to add this script as a deployment or a job?

答:
What I would try to do is to run the shell script from a php file. Otherwise you are going to need some sort of driver to trigger the script.

So you would have the script as a regular executable, and upon the request php will execute it via shell.

Actually you can make it like an API; domain.com/job1 could execute job1, domain.com/jobn could execute jobn and so on.

Now, the way I'm describing would work only as a Deployment, as you want the server to be always up and ready to get requests.


问:
Mock static getter with jest
I'm trying to mock a logging service that have static getters.

```<code>  static get error(): Function {
    return console.error.bind(console, 'Error: ');
  }
</code>```

Tried with:
    jest.spyOn(ConsoleLoggingService, 'error').mockImplementation(() => 'blah');

but I get TypeError: Cannot set property info of function ConsoleLoggingService() {} which has only a getter

Also tried:
    jest.spyOn(ConsoleLoggingService, 'error', 'get').mockImplementation(() => 'blah');
And get TypeError: console_logging_service_1.ConsoleLoggingService.error is not a function

Any suggestions?

Thanks

答:
jest.spyOn(ConsoleLoggingService, 'error', 'get').mockImplementation(() => ...) mocks get accessor function, so an implementation is expected to return another function, while a string is returned.

It can return another spy for testing purposes:

```<code>jest.spyOn(ConsoleLoggingService, 'error', 'get').mockReturnValue(jest.fn())
...
expect(ConsoleLoggingService.error).toBeCalledWith(...)
</code>```

The use of get is less efficient because the function is bound on every error access. It could be simplified to:

```<code>static error = console.error.bind(console, 'Error: ')
</code>```

And mocked as:

```<code>jest.spyOn(ConsoleLoggingService, 'error').mockImplementation(() => {})
</code>```

Title: Mock static getter with jest

Body:
I'm trying to mock a logging service that have static getters.

  static get error(): Function {
    return console.error.bind(console, 'Error: ');
  }

Tried with:
    jest.spyOn(ConsoleLoggingService, 'error').mockImplementation(() => 'blah');

but I get TypeError: Cannot set property info of function ConsoleLoggingService() {} which has only a getter

Also tried:
    jest.spyOn(ConsoleLoggingService, 'error', 'get').mockImplementation(() => 'blah');
And get TypeError: console_logging_service_1.ConsoleLoggingService.error is not a function

Any suggestions?

Thanks

Body:
jest.spyOn(ConsoleLoggingService, 'error', 'get').mockImplementation(() => ...) mocks get accessor function, so an implementation is expected to return another function, while a string is returned.

It can return another spy for testing purposes:

jest.spyOn(ConsoleLoggingService, 'error', 'get').mockReturnValue(jest.fn())
...
expect(ConsoleLoggingService.error).toBeCalledWith(...)

The use of get is less efficient because the function is bound on every error access. It could be simplified to:

static error = console.error.bind(console, 'Error: ')

And mocked as:

jest.spyOn(ConsoleLoggingService, 'error').mockImplementation(() => {})


问:
How to debug GXT application and how to print error message on browser console for debugging?
I am woring on a project where i have to debug gxt files on UI and want to print few error message on chrome console.  What to write in GXT java file to print messages on console.</p>

答:
Best way to debug a GTX application, like every other GWT application, is using Super Dev Mode (SDM).

See: https://www.youtube.com/watch?v=Wxlh_E8uyq4

To print something on the browser's console, you can use GWT.log("debug message"); or DomGlobal.console.log("debug message");.

Hope that helps.


问:
How to Map values from parent to child component in Angular?
In the parent component (app.component.html):-

```<code><stl-app [filename]="'abc.STL'" [colorname]="'red'" [perspective]="35"></stl-app>
</code>```

In the parent component.ts (app.component.ts):-

```<code>@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
 })
export class AppComponent implements OnInit  {

  title = 'stl-app';
  @ViewChild(ImlStlAppComponent) child:ImlStlAppComponent;

  constructor(){}

  ngOnInit():void{}

  ngAfterViewInit(){
    this.child.mySubmit();
  }
</code>```

In the child component (stl-app.component.html):-

```<code><mat-form-field>
  <mat-label>Name of the file</mat-label>
  <mat-hint> File path of only stl file</mat-hint>
  <input  matInput  [(ngModel)]="filename"  name="filename"  required>
  </mat-form-field>

  <mat-form-field>
  <mat-label>Name of the color</mat-label>
  <mat-hint> Color in string</mat-hint>
  <input  matInput  [(ngModel)]="colorname" name="colorname"  required>
  </mat-form-field>

  <mat-form-field>
    <mat-label>Camera Perspective</mat-label>
    <mat-hint> values in Integer</mat-hint>
    <input  matInput  [(ngModel)]="perspective" name="perspective"  required>
    </mat-form-field>

<button  mat-raised-button (click)="mySubmit()"  color="primary">Submit</button>
</code>```

In child component.ts (stl-app.component.ts):-

```<code>export class ImlStlAppComponent implements OnInit {

@Input()
filename:string;
@Input()
colorname:any;
@Input()
perspective:number;

mySubmit(){

//Something Todo----

}
}
</code>```

When I click on the "Submit" button , the mySubmit() method is not triggered with the values already given in the parent component.html,hence nothing is rendered. How to avoid this problem?

答:
TS code for parent

```<code> @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit { title = 'stl-app';
pFileName = 'somefilename';
pColorName = 'somecolorname';
pPerspective = 'someperspective';

@ViewChild(ImlStlAppComponent) child:ImlStlAppComponent;
 constructor(){} ngOnInit():void{}
 ngAfterViewInit(){ this.child.mySubmit(); }
</code>```

HTML for parent

```<code><stl-app [filename]='pFileName' [colorname]='pColorName' [perspective]='pPerspective'></stl-app>
</code>```

Please let me know if it works for you or not.

Body:
In the parent component (app.component.html):-

<stl-app [filename]="'abc.STL'" [colorname]="'red'" [perspective]="35"></stl-app>

In the parent component.ts (app.component.ts):-

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
 })
export class AppComponent implements OnInit  {

  title = 'stl-app';
  @ViewChild(ImlStlAppComponent) child:ImlStlAppComponent;

  constructor(){}

  ngOnInit():void{}

  ngAfterViewInit(){
    this.child.mySubmit();
  }

In the child component (stl-app.component.html):-

<mat-form-field>
  <mat-label>Name of the file</mat-label>
  <mat-hint> File path of only stl file</mat-hint>
  <input  matInput  [(ngModel)]="filename"  name="filename"  required>
  </mat-form-field>

  <mat-form-field>
  <mat-label>Name of the color</mat-label>
  <mat-hint> Color in string</mat-hint>
  <input  matInput  [(ngModel)]="colorname" name="colorname"  required>
  </mat-form-field>

  <mat-form-field>
    <mat-label>Camera Perspective</mat-label>
    <mat-hint> values in Integer</mat-hint>
    <input  matInput  [(ngModel)]="perspective" name="perspective"  required>
    </mat-form-field>

<button  mat-raised-button (click)="mySubmit()"  color="primary">Submit</button>

In child component.ts (stl-app.component.ts):-

export class ImlStlAppComponent implements OnInit {

@Input()
filename:string;
@Input()
colorname:any;
@Input()
perspective:number;

mySubmit(){

//Something Todo----

}
}

When I click on the "Submit" button , the mySubmit() method is not triggered with the values already given in the parent component.html,hence nothing is rendered. How to avoid this problem?

Body:
TS code for parent

 @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit { title = 'stl-app';
pFileName = 'somefilename';
pColorName = 'somecolorname';
pPerspective = 'someperspective';

@ViewChild(ImlStlAppComponent) child:ImlStlAppComponent;
 constructor(){} ngOnInit():void{}
 ngAfterViewInit(){ this.child.mySubmit(); }

HTML for parent

<stl-app [filename]='pFileName' [colorname]='pColorName' [perspective]='pPerspective'></stl-app>

Please let me know if it works for you or not.


问:
putting a space between the 3rd and 4th characters of postal code in Python
I have a df (data frame) in Python with with a postal_code variable that has Canadian  postal codes. All the postal codes are collected in a row such as k1b6j2. But , for me to use the the 'pgeocode' package i need the postal code in a standard form which is like k1b 6j2 (there must be a space between the 3rd and 4th character)

So, is there a way to replace all the postal codes with the modified ones in the df?

Many Thanks,
Ben

答:
Apply this to all postal codes in the df:</p>

```<code>code_with_space = code_without_space[:3] + " " + code_without_space[3:]
</code>```

Body:
Apply this to all postal codes in the df:

code_with_space = code_without_space[:3] + " " + code_without_space[3:]


问:
Loop through a table valued function
I have a table x which has columns y and z it has 10 rows of data.

I then have a table-valued function getDetails(y,z) which takes values stored in table x in columns y and z to return a table tb with three columns.

I need to write a tsql query that loops values from table x through  function getDetails(y,z)to return one row per set of values y and zfrom table x in this case table tb should have 10 rows.

This is what I have so far which returns one row only each time I run it.

```<code>DECLARE @y NVARCHAR(50);
DECLARE @z NVARCHAR(2);

SELECT @y =y FROM x

SElECT @z =z FROM x

SELECT * from getDetails(@y,@z)
</code>```

This returns

```<code>       col1      col2     col3
       ---------------------
row1   Lorem     Ipsum     Sit
</code>```

//UPDATE
If anyone has an idea how I can use temp tables to achieve this please let me know

答:
If you're open to getting all of the results at once, I would use CROSS APPLY here.

```<code>SELECT
  d.col1,
  d.col2,
  d.col3
FROM x
CROSS APPLY dbo.getDetails (x.y, x.z) AS d;
</code>```

This will return the complete data set all at once. You could also add x.y and x.z to the SELECT clause if you needed/wanted those values in your results.

Title: Loop through a table valued function

Body:
I have a table x which has columns y and z it has 10 rows of data.

I then have a table-valued function getDetails(y,z) which takes values stored in table x in columns y and z to return a table tb with three columns.

I need to write a tsql query that loops values from table x through  function getDetails(y,z)to return one row per set of values y and zfrom table x in this case table tb should have 10 rows.

This is what I have so far which returns one row only each time I run it.

DECLARE @y NVARCHAR(50);
DECLARE @z NVARCHAR(2);

SELECT @y =y FROM x

SElECT @z =z FROM x

SELECT * from getDetails(@y,@z)

This returns

       col1      col2     col3
       ---------------------
row1   Lorem     Ipsum     Sit

//UPDATE
If anyone has an idea how I can use temp tables to achieve this please let me know

Body:
If you're open to getting all of the results at once, I would use CROSS APPLY here.

SELECT
  d.col1,
  d.col2,
  d.col3
FROM x
CROSS APPLY dbo.getDetails (x.y, x.z) AS d;

This will return the complete data set all at once. You could also add x.y and x.z to the SELECT clause if you needed/wanted those values in your results.


问:
button.value is undefined?
While attempting to make a calculator I found an issue that I was unable to solve. In my script, I told the browser that when a button is clicked, it adds the value of that button to the calculator's display. (for example, if the calculator is currently showing "455", and you click the plus button, the text of the display would turn to "455+", because the value of the plus button is "+").

The issue I am having here is that when I click a button, "undefined" adds instead of the value of that button. how come button.value returns undefined instead of the value of the button? What is the problem here?

window.onload = () => {
  const calculator = document.querySelector('form[name = "calculator"]')
  const btns = document.querySelectorAll(`form[name = "calculator"] table tr td`)
  btns.forEach((button) => {
    button.addEventListener('click', () => {
      calculator.display.value += button.value
    })
  })
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
  <html>
    <head></head>
    </body>
      <!-- Page Contents !-->
      <form name = "calculator">
        <table>
          <tr>
            <input type = "text" name = "display" id = "display" disabled>
          </tr>
          <tr>
            <td><input type = "button" name = "one" value = "1"></td>
            <td><input type = "button" name = "two" value = "2"></td>
            <td><input type = "button" name = "three" value = "3"></td>
            <td><input type = "button" name = "plus" value = "+"></td>
          </tr>
        </table>
      </form>
      <script src = "script.js"></script>
    </body>
  </html></code>```

Sorry if I am doing something wrong, or breaking any "rules" set in place, I am a new javascript programmer. Thanks!

答:
You're selecting the , not the <input>. Change your selector to select the buttons.

```<code>const btns = document.querySelectorAll(`form[name="calculator"] table tr td input[type="button"]`)
</code>```

Title: button.value is undefined?

Body:
While attempting to make a calculator I found an issue that I was unable to solve. In my script, I told the browser that when a button is clicked, it adds the value of that button to the calculator's display. (for example, if the calculator is currently showing "455", and you click the plus button, the text of the display would turn to "455+", because the value of the plus button is "+").

The issue I am having here is that when I click a button, "undefined" adds instead of the value of that button. how come button.value returns undefined instead of the value of the button? What is the problem here?

window.onload = () => {
  const calculator = document.querySelector('form[name = "calculator"]')
  const btns = document.querySelectorAll(`form[name = "calculator"] table tr td`)
  btns.forEach((button) => {
    button.addEventListener('click', () => {
      calculator.display.value += button.value
    })
  })
}

<!DOCTYPE html>

      <form name = "calculator">

            <input type = "text" name = "display" id = "display" disabled>

            <input type = "button" name = "one" value = "1">
            <input type = "button" name = "two" value = "2">
            <input type = "button" name = "three" value = "3">
            <input type = "button" name = "plus" value = "+">

      </form>

Sorry if I am doing something wrong, or breaking any "rules" set in place, I am a new javascript programmer. Thanks!

Body:
You're selecting the <td>, not the <input>. Change your selector to select the buttons.

const btns = document.querySelectorAll(`form[name="calculator"] table tr td input[type="button"]`)


问:
haskell state and typeclasses
how can i group getX and putX in a class instance ?
the code below is an answer for this post Class set method in Haskell using State-Monad

```<code>
import Control.Monad.State

data Point = Point { x :: Int, y :: Int } deriving Show

getX :: State Point Int
getX = get >>= return . x

putX :: Int -> State Point ()
putX newVal = do
    pt - get
    put (pt { x = newVal })

increaseX :: State Point ()
increaseX = do
    x - getX
    putX (x + 1)

</code>```

Later I hope I will implement setters and getters for a hierarchy of 2 classes, but for now i just wanna do something like this:

```<code>
class A a where

   putX :: Int -> State Point ()

instance A (State Point) where

    putX newVal = do
        pt - get
            put (pt { x = newVal })
</code> ```

答:
You seem to be conflating multiple concepts here, to the point that I'm not sure exactly what you're aiming to accomplish. A few thoughts on what you might be after:

Field access, i.e., a way to inspect or replace a piece of a larger data structure. This doesn't really lend itself to a type class, because for many combinations of "inner field" and "data structure" there will be more than one accessor possible. Abstractions along these lines are often called "lenses".

Stateful references in some generic fashion. For the most part in a State monad this amounts to combining something like the aforementioned lenses with the standard get and put. In this case you could have a type class for the combination of a particular monad and the accessor data type, but it wouldn't really do that much.

Overloading access to a particular field, so that functions can work on any data type that contains an "x" field. In this case I assume you'd also want "y", as some sort of type class for 2D points. This is entirely separate from the above issues, however.

Perhaps you could clarify your goal?

Title: haskell state and typeclasses

Body:
how can i group getX and putX in a class instance ?
the code below is an answer for this post Class set method in Haskell using State-Monad

import Control.Monad.State

data Point = Point { x :: Int, y :: Int } deriving Show

getX :: State Point Int
getX = get >>= return . x

putX :: Int -> State Point ()
putX newVal = do
    pt - get
    put (pt { x = newVal })

increaseX :: State Point ()
increaseX = do
    x - getX
    putX (x + 1)

Later I hope I will implement setters and getters for a hierarchy of 2 classes, but for now i just wanna do something like this:

class A a where

   putX :: Int -> State Point ()

instance A (State Point) where

    putX newVal = do
        pt - get
            put (pt { x = newVal })


问:
A new table for each user created
I am using Django 3.0 and I was wondering how to create a new database table linked to the creation of each user. In a practical sense: I want an app that lets users add certain stuff to a list but each user to have a different list where they can add their stuff. How should I approach this as I can't seem to find the right documentation... Thanks a lot !!!</p>

答:
This is too long for a comment.

Creating a new table for each user is almost never the right way to solve a problem.  Instead, you just have a userStuff table that maintains the lists.  It would have columns like:

userId

stuffId

And, if you want the stuff for a given user, just use a where clause.

Title: A new table for each user created


问:
ArrayFormula, SumProduct and Google Sheets returning only 1 value
I have two sheets. I'm using SUMPRODUCT to sum a column based on a matching string.

```<code>=SUMPRODUCT(--(skus_campaign!A:A=A2),skus_campaign!D:D)))
</code>```

This works exactly as expected, if I drag the formula to the rows below.

If I attach ARRAYFORMULA and and IF test to see if there's a blank value, it won't work.

```<code>=ARRAYFORMULA(IF(ISBLANK(A2:A), " ", SUMPRODUCT(--(skus_campaign!A:A=A2),skus_campaign!D:D)))
</code>```

Am I missing something here? Is there an easier way to accomplish this while still using ARRAYFORMULA to grow and shrink the column based on the values in column A?

EDIT: Here's the link to the example Google Sheet. Column "D" under the "Data" sheet is the issue.

答:
Try in E1

```<code>={"COGS"; ArrayFormula(if(len(A2:A), vlookup(A2:A, query(skus!A:D, "Select A, sum(D) where A <>'' group by A"), 2, 0),))}
</code>```

and see if that produces the desired result. If it does, clear all values and formulas in column D and enter the formula in D1.

Body:
I have two sheets. I'm using SUMPRODUCT to sum a column based on a matching string.

=SUMPRODUCT(--(skus_campaign!A:A=A2),skus_campaign!D:D)))

This works exactly as expected, if I drag the formula to the rows below.

If I attach ARRAYFORMULA and and IF test to see if there's a blank value, it won't work.

=ARRAYFORMULA(IF(ISBLANK(A2:A), " ", SUMPRODUCT(--(skus_campaign!A:A=A2),skus_campaign!D:D)))

Am I missing something here? Is there an easier way to accomplish this while still using ARRAYFORMULA to grow and shrink the column based on the values in column A?

EDIT: Here's the link to the example Google Sheet. Column "D" under the "Data" sheet is the issue.

Body:
Try in E1

={"COGS"; ArrayFormula(if(len(A2:A), vlookup(A2:A, query(skus!A:D, "Select A, sum(D) where A <>'' group by A"), 2, 0),))}

and see if that produces the desired result. If it does, clear all values and formulas in column D and enter the formula in D1.


问:
NodeJS MySQL, reconnecting on connection loss?
```<code>function Connect() {
    var connection = mysql.createConnection({
        host     : 'hidden',
        user     : 'hidden',
        password : 'hidden',
        database : 'hidden'
    });

    connection.connect(function(err) {
        if (err) {
            console.log('Error connecting to Database'.red);
            setInterval(Connect, 5000);
            connection.end();
            }else{
            console.log('Connected to Database'.green);
        }

    });
}

Connect();
</code>```

I am attempting to make it so my code won't crash if the database loses connection.

It will be connected to a database which is prone to many restarts and updates, meaning that the program will crash upon losing connection.

I tried adding  setInterval(Connect, 5000); so it would attempt to reconnect if it loses connection but to no luck.

Can someone help me out where I am going wrong?

答:
Assuming you're using the mysql npm package you can use connection pooling provided by the library:

https://github.com/mysqljs/mysql#pooling-connections

When a previous connection is retrieved from the pool, a ping packet is sent to the server to check if the connection is still good.

It's rather easy to use, instead of using createConnection you can use createPool

var pool  = mysql.createPool({
  connectionLimit : 2,
  host            : 'example.org',
  user            : 'bob',
  password        : 'secret',
  database        : 'my_db'
});
```

And then use the pool to query the database.

It has many additional benefits as well e.g. load balancing connections.

Body:
function Connect() {
    var connection = mysql.createConnection({
        host     : 'hidden',
        user     : 'hidden',
        password : 'hidden',
        database : 'hidden'
    });

    connection.connect(function(err) {
        if (err) {
            console.log('Error connecting to Database'.red);
            setInterval(Connect, 5000);
            connection.end();
            }else{
            console.log('Connected to Database'.green);
        }

    });
}

Connect();

I am attempting to make it so my code won't crash if the database loses connection.

It will be connected to a database which is prone to many restarts and updates, meaning that the program will crash upon losing connection.

I tried adding  setInterval(Connect, 5000); so it would attempt to reconnect if it loses connection but to no luck.

Can someone help me out where I am going wrong?

Body:
Assuming you're using the mysql npm package you can use connection pooling provided by the library:

https://github.com/mysqljs/mysql#pooling-connections

When a previous connection is retrieved from the pool, a ping packet is sent to the server to check if the connection is still good.

It's rather easy to use, instead of using createConnection you can use createPool

var pool  = mysql.createPool({
  connectionLimit : 2,
  host            : 'example.org',
  user            : 'bob',
  password        : 'secret',
  database        : 'my_db'
});

And then use the pool to query the database.

It has many additional benefits as well e.g. load balancing connections.


问:
what is the shortest way to check for typeof any type?
I found this today to check if something is a boolean:

Instead of:

```<code>typeof a === 'boolean' && //do sth
</code>```

You can use:

```<code>a === !!a && //do sth
</code>```

Are there any other methods like this to check for typeof string/number/obj/arr etc?

I'm not looking for best practices but rather for clever ways to do " typechecking "  .

答:
A clean approach

You can't do it cleanly. Javascript has a few quirks that I see almost always throws people off, even the most experience. And very often you end up with very ugly, not really human readable conditional statements:

if (
    typeof foo !== 'string'
    || (typeof foo !== 'number'
    || (typeof foo === 'number' && !isNaN(chk)))
    || !Array.isArray(chk)
) {

    throw Error("Not valid, but I don't know why.")
}
```
<h2>No other way, just use a very lightweight library</h2>
<p>You should consider using a very small library like Issable. Solves all problems:</p>
<pre class="lang-js prettyprint-override"><code>let integer = 10
let array = []
is(integer).number() // returns true
is(array).number() // throws error
</code>```

If you make it a habit, your code will be much stronger. Typescript solves part of the problem but doesn't work at runtime, which is also important.

function test (string, boolean) {
    // any of these below will throw errors to protect you
    is(string).string()
    is(boolean).boolean()
    // continue with your code.
}
```

Body:
I found this today to check if something is a boolean:

Instead of:

typeof a === 'boolean' && //do sth

You can use:

a === !!a && //do sth

Are there any other methods like this to check for typeof string/number/obj/arr etc?

I'm not looking for best practices but rather for clever ways to do " typechecking "  .

Body:
A clean approach

You can't do it cleanly. Javascript has a few quirks that I see almost always throws people off, even the most experience. And very often you end up with very ugly, not really human readable conditional statements:

if (
    typeof foo !== 'string'
    || (typeof foo !== 'number'
    || (typeof foo === 'number' && !isNaN(chk)))
    || !Array.isArray(chk)
) {

    throw Error("Not valid, but I don't know why.")
}

No other way, just use a very lightweight library

You should consider using a very small library like Issable. Solves all problems:

let integer = 10
let array = []
is(integer).number() // returns true
is(array).number() // throws error

If you make it a habit, your code will be much stronger. Typescript solves part of the problem but doesn't work at runtime, which is also important.

function test (string, boolean) {
    // any of these below will throw errors to protect you
    is(string).string()
    is(boolean).boolean()
    // continue with your code.
}


问:
Why properties of an XMLHttpRequest object are only printable through console.log()?
```<code>var obj = new XMLHttpRequest();
console.log("Object.keys():",Object.keys(obj));
console.log("Object.getOwnPropertyNames():",Object.getOwnPropertyNames(obj))
console.log("Object.entries():",Object.entries(obj))
console.log("JSON.stringify():",JSON.stringify(obj))

console.log("console.log:"); console.log(obj)
</code>```

output:

Object.keys(): []

  Object.getOwnPropertyNames(): []

  Object.entries(): []

  JSON.stringify(): {}

  console.log:

  XMLHttpRequest {onreadystatechange: null, readyState: 0, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}

How can I create such an object in javascript, whose properties are only printed using console.log(obj), but not returned by any of the above functions?

I have already tried to create objects using constructor function, object.create() (with enumerable:false),  Object.assign(), using getters, instatiating from a class, instatiating from an extended class e.t.c

答:
Why properties of an XMLHttpRequest object are only printable through console.log()?

That's not true

var obj = new XMLHttpRequest();
for(var key in obj) console.log(key);
```

<p>Answer on the question from the description</p>

<blockquote>
  <p>How can I create such an object in javascript, whose properties are only printed using</p>
</blockquote>

<pre class="lang-js prettyprint-override"><code>  var obj = Object.create({ foo: "foo", constructor: function() {} });
</code>```

If you want to hide property from for in you should set enumerable attribute to false for desired property:

Object.defineProperty(obj, 'foo', {
  value: 42,
  enumerable: false
});
```

Body:
var obj = new XMLHttpRequest();
console.log("Object.keys():",Object.keys(obj));
console.log("Object.getOwnPropertyNames():",Object.getOwnPropertyNames(obj))
console.log("Object.entries():",Object.entries(obj))
console.log("JSON.stringify():",JSON.stringify(obj))

console.log("console.log:"); console.log(obj)

output:

Object.keys(): []

  Object.getOwnPropertyNames(): []

  Object.entries(): []

  JSON.stringify(): {}

  console.log:

  XMLHttpRequest {onreadystatechange: null, readyState: 0, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}

How can I create such an object in javascript, whose properties are only printed using console.log(obj), but not returned by any of the above functions?

I have already tried to create objects using constructor function, object.create() (with enumerable:false),  Object.assign(), using getters, instatiating from a class, instatiating from an extended class e.t.c

Body:
Why properties of an XMLHttpRequest object are only printable through console.log()?

That's not true

var obj = new XMLHttpRequest();
for(var key in obj) console.log(key);

Answer on the question from the description

How can I create such an object in javascript, whose properties are only printed using

  var obj = Object.create({ foo: "foo", constructor: function() {} });

If you want to hide property from for in you should set enumerable attribute to false for desired property:

Object.defineProperty(obj, 'foo', {
  value: 42,
  enumerable: false
});


问:
How to set processing timeouts in apache beam / Dataflow python batch jobs?
I am currently using the stopit library https://github.com/glenfant/stopit to set per element processing timeouts in batch jobs. These jobs work on the direct runner and I am able to timeout functions that take too long.

What is the beam way of setting a per element process timeout for a batch job?

Is there a way I could set a processing timeout with a trigger for a dataflow batch job?

My use case is extracting named entities from a text. The NER process sometimes takes too long if the document being processed is too long.

It would be nice to get rid of this dependency and move to a beam native solution.

答:
As per my understanding the answer to the question is timely processing which also maintain state.
Lets say you have a function f and get the output for  any batch that will use the function.
So basically we have to mark the batch(update a state) after we receive a batch and we will set timers that will update the output as per the watermark/expiry timing which can be set, if there is any output we will receive it and if we don't any output from the function as per your query, we can surely re-route that batch.

This is not an exact solution, but can be worked out

For better understanding you can read it here:  apache beam documentation


问:
Angular 8 component nested inside the same component event emitter
I have used the component nested inside the same component. when I change the checkbox in the parent component attached function called correctly and Event emitter is working fine but when I change the child checkbox attached function was fired but event emitter not available (as of my knowledge ever matter is not bind with child one). I want to emit the data when I change the checkbox in the child.

If anyone know the answer please help me to solve this problem. And what is the terminology for using component nested inside the same component?

Thanking you

This is stackblitz link https://stackblitz.com/edit/angular-material-normal-tree
(please check the console)

tree.component.ts

```<code>import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-tree',
  templateUrl: './tree.component.html',
  styleUrls: ['./tree.component.css'],
})

export class TreeComponent {
  @Input() treeData: any;
  @Output() toggleEmitter: EventEmitter<any> = new EventEmitter();

  constructor() {}

  toggleChild(node) {
    console.log('from tree start');
    console.log(node);
    console.log('from tree end');
    this.toggleEmitter.emit(node);
    // if ('children' in node && node.children.length) {
    //   node.isExpand = !node.isExpand;
    // }
  }

  test(node, i) {
    node.parentIndex = i;
    console.log(node);
    // this.toggleEmitter.emit(node);
  }

  CBchangeEvent(node) {
    console.log(node);
    this.toggleEmitter.emit(node);
  }

}
</code>```

tree.component.html

```<code><ul *ngIf="treeData">
    <li *ngFor="let node of treeData;let i = index;">
        <button mat-icon-button="" mattreenodetoggle="" class="mat-icon-button" (click)="toggleChild(node)">
        <span class="mat-button-wrapper">
          <mat-icon class="mat-icon material-icons" role="img" aria-hidden="true">
            {{node.isExpand != 0 ? 'expand_more' : 'chevron_right'}}
          </mat-icon>
        </span>
      </button>
        <mat-checkbox class="checklist-leaf-node" (change)="CBchangeEvent(node)">{{node.name}}</mat-checkbox>
        <app-tree *ngIf="node.isExpand" [treeData]="node.children" (toggleEmitter)="test(node,i)"></app-tree>
    </li>
</ul>
</code>```

tree.component.css

```<code>ul {
    list-style-type: none !important;
}
</code>```

tree.module.ts

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TreeComponent } from './tree.component';
import {
  MatIconModule, MatCheckboxModule, MatFormFieldModule, MatButtonModule
} from '@angular/material';

@NgModule({
  imports: [
    CommonModule,
    MatIconModule,
    MatCheckboxModule,
    MatFormFieldModule,
    MatButtonModule
  ],
  declarations: [TreeComponent],
  exports: [TreeComponent]
})
export class TreeModule {
  static forRoot() {
    return {
      ngModule: TreeModule
    }
  }
}
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  myData = [
    {'id':1, 'name':'Main 1','isExpand':false,
     'children':[
       {'id':1, 'name':'Child 1', 'isExpand':false,
       'children':[
         {'id':2, 'name':'Test2','isExpand':false}
       ]
       }
     ]
    },
    {
      'id':2, 'name':'Main 2','isExpand':false
    }
  ]

  test(node) {
    console.log('from app start');
    console.log(node);
    console.log('from app end');
    if ('children' in node && node.children.length) {
      node.isExpand = !node.isExpand;
    }
  }
}
</code>```

app.component.html

```<code><app-tree [treeData]='myData' (toggleEmitter)="test($event)"></app-tree>
</code>```

app.module.ts

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { TreeModule } from './tree/tree.module';
import {
  MdToolbarModule,
  MdTabsModule,
  MdButtonModule,
  MdInputModule,
  MdDatepickerModule,
  MdNativeDateModule,
  MdCheckboxModule,
  MdRadioModule,
  NoConflictStyleCompatibilityMode
} from '@angular/material';

import { AppComponent } from './app.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule, BrowserAnimationsModule, MdToolbarModule, MdTabsModule, MdButtonModule, MdInputModule, MdDatepickerModule, MdNativeDateModule, MdCheckboxModule, MdRadioModule, TreeModule, NoConflictStyleCompatibilityMode ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }
</code>```

答:
instead of biding "test" you should bind "toggleChild" in child component.

change

```<code><app-tree *ngIf="node.isExpand" [treeData]="node.children" (toggleEmitter)="test(node,i)"></app-tree>
</code>```

to

```<code><app-tree *ngIf="node.isExpand" [treeData]="node.children" (toggleEmitter)="toggleChild(node,i)"></app-tree>
</code>```

Body:
I have used the component nested inside the same component. when I change the checkbox in the parent component attached function called correctly and Event emitter is working fine but when I change the child checkbox attached function was fired but event emitter not available (as of my knowledge ever matter is not bind with child one). I want to emit the data when I change the checkbox in the child.

If anyone know the answer please help me to solve this problem. And what is the terminology for using component nested inside the same component?

Thanking you

This is stackblitz link https://stackblitz.com/edit/angular-material-normal-tree
(please check the console)

tree.component.ts

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-tree',
  templateUrl: './tree.component.html',
  styleUrls: ['./tree.component.css'],
})

export class TreeComponent {
  @Input() treeData: any;
  @Output() toggleEmitter: EventEmitter<any> = new EventEmitter();

  constructor() {}

  toggleChild(node) {
    console.log('from tree start');
    console.log(node);
    console.log('from tree end');
    this.toggleEmitter.emit(node);
    // if ('children' in node && node.children.length) {
    //   node.isExpand = !node.isExpand;
    // }
  }

  test(node, i) {
    node.parentIndex = i;
    console.log(node);
    // this.toggleEmitter.emit(node);
  }

  CBchangeEvent(node) {
    console.log(node);
    this.toggleEmitter.emit(node);
  }

}

tree.component.html

        <button mat-icon-button="" mattreenodetoggle="" class="mat-icon-button" (click)="toggleChild(node)">

          <mat-icon class="mat-icon material-icons" role="img" aria-hidden="true">
            {{node.isExpand != 0 ? 'expand_more' : 'chevron_right'}}
          </mat-icon>

      </button>
        <mat-checkbox class="checklist-leaf-node" (change)="CBchangeEvent(node)">{{node.name}}</mat-checkbox>
        <app-tree *ngIf="node.isExpand" [treeData]="node.children" (toggleEmitter)="test(node,i)"></app-tree>

tree.component.css

ul {
    list-style-type: none !important;
}

tree.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TreeComponent } from './tree.component';
import {
  MatIconModule, MatCheckboxModule, MatFormFieldModule, MatButtonModule
} from '@angular/material';

@NgModule({
  imports: [
    CommonModule,
    MatIconModule,
    MatCheckboxModule,
    MatFormFieldModule,
    MatButtonModule
  ],
  declarations: [TreeComponent],
  exports: [TreeComponent]
})
export class TreeModule {
  static forRoot() {
    return {
      ngModule: TreeModule
    }
  }
}

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  myData = [
    {'id':1, 'name':'Main 1','isExpand':false,
     'children':[
       {'id':1, 'name':'Child 1', 'isExpand':false,
       'children':[
         {'id':2, 'name':'Test2','isExpand':false}
       ]
       }
     ]
    },
    {
      'id':2, 'name':'Main 2','isExpand':false
    }
  ]

  test(node) {
    console.log('from app start');
    console.log(node);
    console.log('from app end');
    if ('children' in node && node.children.length) {
      node.isExpand = !node.isExpand;
    }
  }
}

app.component.html

<app-tree [treeData]='myData' (toggleEmitter)="test($event)"></app-tree>

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { TreeModule } from './tree/tree.module';
import {
  MdToolbarModule,
  MdTabsModule,
  MdButtonModule,
  MdInputModule,
  MdDatepickerModule,
  MdNativeDateModule,
  MdCheckboxModule,
  MdRadioModule,
  NoConflictStyleCompatibilityMode
} from '@angular/material';

import { AppComponent } from './app.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule, BrowserAnimationsModule, MdToolbarModule, MdTabsModule, MdButtonModule, MdInputModule, MdDatepickerModule, MdNativeDateModule, MdCheckboxModule, MdRadioModule, TreeModule, NoConflictStyleCompatibilityMode ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Body:
instead of biding "test" you should bind "toggleChild" in child component.

change

<app-tree *ngIf="node.isExpand" [treeData]="node.children" (toggleEmitter)="test(node,i)"></app-tree>

to

<app-tree *ngIf="node.isExpand" [treeData]="node.children" (toggleEmitter)="toggleChild(node,i)"></app-tree>


问:
How to convert text from MySQL database to an image using PHP and GD Library?
I have been up and down the Internet for some simple solution and I am simply not finding it. I even opened questions on Stackoverflow with sample code and I've been told that everything is wrong in the code. Then, I don't know what I am doing and my questions get closed IMMEDIATELY. It doesn't make any sense.

All I want to be able to do is Query MySQL database for a text string and then convert it into an image to display on the web browser using PHP and GD Library.

Query Database

Retrieve a TEXT or a STRING (ALPHANUMERIC like any words in English Language) from a MySQL database.

Create an Image using that text for displaying on the browser.

Very similar to what I found on another question, but their answer doesn't work even though it was chosen as a working answer. GD Library image generation does not work with mySQL query   My issue is that I can't Query my database for text and create an image of that text all at once on the same page. Very simple example would be helpful.

Please, help.

答:
Since I spent 2 whole day trying to find solution to this question, I am going to post my answer and I feel my answer will help others.

If you want to QUERY alphanumeric TEXT from your MySQL Database and then turn it into an Image of your choice like jpg, png, gif, etc using PHP and GD library right after, you must use PHP Data Objects or PDO for your MySQL DataBase Connection and SQL Query. It looks like for somethings, mysql connection and mysqli connection is no longer supported.


问:
How should I make a Discord bot that detects certain words then delete them?
So i've been trying to learn myself Python by making a Discord bot, everything went well until i had this error AttributeError: 'Bot' object has no attribute 'delete'. I was going to make a feature in which if it detects certain words from a dictionary, it will be deleted. I've read  Benjamin Soyka's question asking how to do the same, but with older version of Discord.py

Right now, my code is :

with open("bad_words.txt") as file: # bad-words.txt contains one blacklisted phrase per line
    bad_words = [bad_word.strip().lower() for bad_word in file.readlines()]

@client.event
async def on_message(message):
    print(message.content) #prints messages in console
    for bad_word in bad_words:
        if bad_word in message.content:
            print("bad words detected") #prints when bad word is found
            await client.delete(message) #delete said message
    await client.process_commands(message)
```

I've tried with different ways like making classes or nested functions, but seems like none is working for me. Sorry if this question seems silly, and Thanks for your help!

答:
Use (Rewrite version)

```<code>await message.delete()
</code>```

instead of

```<code>await client.delete(message)
</code>```

Body:
So i've been trying to learn myself Python by making a Discord bot, everything went well until i had this error AttributeError: 'Bot' object has no attribute 'delete'. I was going to make a feature in which if it detects certain words from a dictionary, it will be deleted. I've read  Benjamin Soyka's question asking how to do the same, but with older version of Discord.py

Right now, my code is :

with open("bad_words.txt") as file: # bad-words.txt contains one blacklisted phrase per line
    bad_words = [bad_word.strip().lower() for bad_word in file.readlines()]

@client.event
async def on_message(message):
    print(message.content) #prints messages in console
    for bad_word in bad_words:
        if bad_word in message.content:
            print("bad words detected") #prints when bad word is found
            await client.delete(message) #delete said message
    await client.process_commands(message)

I've tried with different ways like making classes or nested functions, but seems like none is working for me. Sorry if this question seems silly, and Thanks for your help!

Body:
Use (Rewrite version)

await message.delete()

instead of

await client.delete(message)