问:
Checking the axis of array for zero values
I know that numpy.all() checks if all elements of an array are non-zero other wise (along specified axis). So,

```<code>A = np.arange(27).reshape(3,3,3)
A
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],

       [[18, 19, 20],
        [21, 22, 23],
        [24, 25, 26]]])

A.all(axis=0)
array([[False,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True]])
</code>```

Suppose I'm interested in checking the last elements of the array only, not whole axis, like:

```<code>B = np.array([[[ 1,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],

       [[18, 19, 20],
        [21, 22, 23],
        [0, 0, 0]]])
</code>```

How do I do this?

答:
A simple way is to just use the -1 index (negative indices index backwards from the end of the sequence like object).

B = np.array([[[ 1,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],

       [[18, 19, 20],
        [21, 22, 23],
        [0, 0, 0]]])

print(B[-1, -1])
print(np.any(B[-1, -1]))
print(np.all(B[-1, -1]))
```

<p>Gives</p>

```[0 0 0]
False
False
```

From there you can use whatever method you want to determine truthiness or falsiness.

Body:
I know that numpy.all() checks if all elements of an array are non-zero other wise (along specified axis). So,

A = np.arange(27).reshape(3,3,3)
A
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],

       [[18, 19, 20],
        [21, 22, 23],
        [24, 25, 26]]])

A.all(axis=0)
array([[False,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True]])

Suppose I'm interested in checking the last elements of the array only, not whole axis, like:

B = np.array([[[ 1,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],

       [[18, 19, 20],
        [21, 22, 23],
        [0, 0, 0]]])

How do I do this?

Body:
A simple way is to just use the -1 index (negative indices index backwards from the end of the sequence like object).

B = np.array([[[ 1,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],

       [[18, 19, 20],
        [21, 22, 23],
        [0, 0, 0]]])

print(B[-1, -1])
print(np.any(B[-1, -1]))
print(np.all(B[-1, -1]))

Gives

[0 0 0]
False
False

From there you can use whatever method you want to determine truthiness or falsiness.


来源: stackexchange

问:
Angular @Input() value is not changed when the value is same
When I run this program, initially I get the output as false, 5, 500 as I have initialized them in the child component like that, but when I try to click on update button, I am not able to revert to the previous values. I am expecting the output to be true, 10, 1000, but I am getting it as false, 5, 1000. Only the number which was different got changed.

How can I solve this issue so that I can get the values whatever I set in the parent component?

Link to stackblitz.

app-component.html

```<code><span (click)="clickme()">Update data</span>
</code>```

app-component.ts

```<code>export class AppComponent  {
  public parentBool: boolean;
  public parentNum: number;
  public p2: number;

  public ngOnInit(): void {
    this.parentBool = true;
    this.parentNum = 10;
    this.p2 = 100;
  }

  public clickme(): void {
    this.parentBool = true;
    this.parentNum = 10;
    this.p2 = 1000;
  }
}
</code>```

hello.component.ts

```<code>@Component({
  selector: 'hello-comp',
  template: `
    <div>
     Boolean value is - {{boolChild}} <br/>
     Number value is - {{numChild}} <br />
     Second number is - {{numChild2}}
    </div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent {
  @Input() boolChild: boolean;
  @Input() numChild: number;
  @Input() numChild2: number;

  public ngOnInit(): void {
    this.boolChild = false;
    this.numChild = 5;
    this.numChild2 = 500;
  }
  constructor(private _cd: ChangeDetectorRef){}

    public ngOnChanges(changes: {}): void {
      // this._cd.detectChanges();
      console.log(changes);
    }
}
</code>```

答:
Well your problem is when everything is initialized

Parent value is True and Child Value is False

You are clicking on parent span. This sets the parentBool value to True. This is not a change when it comes to Parent Component. Hence the Change detection does not fire.

I forked this https://stackblitz.com/edit/angular-rgdgd6
from  your link below
https://stackblitz.com/edit/angular-jv3sjz

You can try 2 different approachs

Capture ViewChildren and update within Parent https://stackblitz.com/edit/angular-4fqlqg

Have a service to maintain intermediate state and children will listen to that state. (if required use ngrx or else a simple service will suffice) (Prefer this a bit better as this is more scaleable)

ContentLicense: CC BY-SA 4.0

Body:
When I run this program, initially I get the output as false, 5, 500 as I have initialized them in the child component like that, but when I try to click on update button, I am not able to revert to the previous values. I am expecting the output to be true, 10, 1000, but I am getting it as false, 5, 1000. Only the number which was different got changed.

How can I solve this issue so that I can get the values whatever I set in the parent component?

Link to stackblitz.

app-component.html

Update data

app-component.ts

export class AppComponent  {
  public parentBool: boolean;
  public parentNum: number;
  public p2: number;

  public ngOnInit(): void {
    this.parentBool = true;
    this.parentNum = 10;
    this.p2 = 100;
  }

  public clickme(): void {
    this.parentBool = true;
    this.parentNum = 10;
    this.p2 = 1000;
  }
}

hello.component.ts

@Component({
  selector: 'hello-comp',
  template: `

     Boolean value is - {{boolChild}}

     Number value is - {{numChild}}

     Second number is - {{numChild2}}

  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent {
  @Input() boolChild: boolean;
  @Input() numChild: number;
  @Input() numChild2: number;

  public ngOnInit(): void {
    this.boolChild = false;
    this.numChild = 5;
    this.numChild2 = 500;
  }
  constructor(private _cd: ChangeDetectorRef){}

    public ngOnChanges(changes: {}): void {
      // this._cd.detectChanges();
      console.log(changes);
    }
}


问:
"Failed: There was an error while trying to create this media item."
I'm trying to upload a photo on Google Photos, with google api, but i always get this error:

```<code>"status":{"code":3,"message":"Failed: There was an error while trying to create this media item."}}
</code>```

I think that the problem is in the way i take the binary data of photo.

In this code i follow google photo api developers documentation, and it says, after take authorization, to:
1- Upload the raw bytes to a Google Server: to take upload-token
2- Use the upload token to create the media item.

This my node js code:

```<code>const photo = fs.readFileSync("fbimages/"+req.session.id_client+"/Prague/2020-05-30T17:29:14+0000_0.png", {
            'encoding': 'binary',
            'flag' : 'r'
        });

 var url= 'https://photoslibrary.googleapis.com/v1/uploads';
 var headers= {
     'Authorization': 'Bearer '+token,
     'Content-type': 'application/octet-stream',
     'X-Goog-Upload-Content-Type': 'image/png',
     'X-Goog-Upload-Protocol': 'raw',
     'X-Goog-Upload-File-Name': "2020-05-30T17:29:14+0000_0.png",
 };
 var body= photo

 request({
      url: url,
      method:'POST',
      headers: headers,
      rejectUnauthorized: false,
      body: JSON.stringify(body)
  }, function(error, response, body1){
      if(error)
      {
        console.log(error);
      }
      else
      {
         var upToken = body1.toString();

         console.log(upToken);

         var url= 'https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate';
         var headers= {
             'Authorization' : 'Bearer '+token,
             'Content-type': 'application/json',
         };
         var body= {
             'newMediaItems': [
                 {
                   'description': 'Prague',
                   'simpleMediaItem': {
                         'fileName': 'prova',
                         'uploadToken': upToken,
                    }
                 }
             ]
         };
         request({
             url: url,
             method: 'POST',
             headers: headers,
             rejectUnauthorized: false,
             body: JSON.stringify(body),

           }, function(error, response, body){
              if(error)
              {
                 console.log(error);
               }
               else
               {
                  res.send(JSON.parse(body));
                }
          });
   }});
</code>```

Please help me, if anyone has any idea!!

答:
How about this modification?

Modification points:

I think that encoding: "binary" is not required.

In this case, ``const photo = fs.readFileSync("fig1.png", { flag: "r" });andconst photo = fs.readFileSync("fig1.png");` can be used.

Please modify body: JSON.stringify(body) to photo of const photo = fs.readFileSync("fig1.png", { flag: "r" });.

When above points are reflected to your script, it becomes as follows.

Modified script:

From:

```<code>const photo = fs.readFileSync("fbimages/"+req.session.id_client+"/Prague/2020-05-30T17:29:14+0000_0.png", {
            'encoding': 'binary',
            'flag' : 'r'
        });

 var url= 'https://photoslibrary.googleapis.com/v1/uploads';
 var headers= {
     'Authorization': 'Bearer '+token,
     'Content-type': 'application/octet-stream',
     'X-Goog-Upload-Content-Type': 'image/png',
     'X-Goog-Upload-Protocol': 'raw',
     'X-Goog-Upload-File-Name': "2020-05-30T17:29:14+0000_0.png",
 };
 var body= { 'media-binary-data': photo }

 request({
      url: url,
      method:'POST',
      headers: headers,
      rejectUnauthorized: false,
      body: JSON.stringify(body)
  }, function(error, response, body1){
</code>```

To:

```<code>const photo = fs.readFileSync("fbimages/"+req.session.id_client+"/Prague/2020-05-30T17:29:14+0000_0.png", { flag: "r" });

var url = "https://photoslibrary.googleapis.com/v1/uploads";
var headers = {
  Authorization: "Bearer " + token,
  "Content-type": "application/octet-stream",
  "X-Goog-Upload-Content-Type": "image/png",
  "X-Goog-Upload-Protocol": "raw",
  "X-Goog-Upload-File-Name": "2020-05-30T17:29:14+0000_0.png",
};

request(
  {
    url: url,
    method: "POST",
    headers: headers,
    rejectUnauthorized: false,
    body: photo,
  },
  function (error, response, body1) {
</code>```

Note:

In this modification, it supposes that your token can be used for this API. Please be careful this.

When you want to directly put the uploaded image to an alubmn, please include albumId for requesting to https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate.

Reference:

Upload media

Body:
I'm trying to upload a photo on Google Photos, with google api, but i always get this error:

"status":{"code":3,"message":"Failed: There was an error while trying to create this media item."}}

I think that the problem is in the way i take the binary data of photo.

In this code i follow google photo api developers documentation, and it says, after take authorization, to:
1- Upload the raw bytes to a Google Server: to take upload-token
2- Use the upload token to create the media item.

This my node js code:

const photo = fs.readFileSync("fbimages/"+req.session.id_client+"/Prague/2020-05-30T17:29:14+0000_0.png", {
            'encoding': 'binary',
            'flag' : 'r'
        });

 var url= 'https://photoslibrary.googleapis.com/v1/uploads';
 var headers= {
     'Authorization': 'Bearer '+token,
     'Content-type': 'application/octet-stream',
     'X-Goog-Upload-Content-Type': 'image/png',
     'X-Goog-Upload-Protocol': 'raw',
     'X-Goog-Upload-File-Name': "2020-05-30T17:29:14+0000_0.png",
 };
 var body= photo

 request({
      url: url,
      method:'POST',
      headers: headers,
      rejectUnauthorized: false,
      body: JSON.stringify(body)
  }, function(error, response, body1){
      if(error)
      {
        console.log(error);
      }
      else
      {
         var upToken = body1.toString();

         console.log(upToken);

         var url= 'https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate';
         var headers= {
             'Authorization' : 'Bearer '+token,
             'Content-type': 'application/json',
         };
         var body= {
             'newMediaItems': [
                 {
                   'description': 'Prague',
                   'simpleMediaItem': {
                         'fileName': 'prova',
                         'uploadToken': upToken,
                    }
                 }
             ]
         };
         request({
             url: url,
             method: 'POST',
             headers: headers,
             rejectUnauthorized: false,
             body: JSON.stringify(body),

           }, function(error, response, body){
              if(error)
              {
                 console.log(error);
               }
               else
               {
                  res.send(JSON.parse(body));
                }
          });
   }});

Please help me, if anyone has any idea!!

Body:
How about this modification?

Modification points:

I think that encoding: "binary" is not required.

In this case, ``const photo = fs.readFileSync("fig1.png", { flag: "r" });andconst photo = fs.readFileSync("fig1.png");` can be used.

Please modify body: JSON.stringify(body) to photo of const photo = fs.readFileSync("fig1.png", { flag: "r" });.

When above points are reflected to your script, it becomes as follows.

Modified script:

From:

const photo = fs.readFileSync("fbimages/"+req.session.id_client+"/Prague/2020-05-30T17:29:14+0000_0.png", {
            'encoding': 'binary',
            'flag' : 'r'
        });

 var url= 'https://photoslibrary.googleapis.com/v1/uploads';
 var headers= {
     'Authorization': 'Bearer '+token,
     'Content-type': 'application/octet-stream',
     'X-Goog-Upload-Content-Type': 'image/png',
     'X-Goog-Upload-Protocol': 'raw',
     'X-Goog-Upload-File-Name': "2020-05-30T17:29:14+0000_0.png",
 };
 var body= { 'media-binary-data': photo }

 request({
      url: url,
      method:'POST',
      headers: headers,
      rejectUnauthorized: false,
      body: JSON.stringify(body)
  }, function(error, response, body1){

To:

const photo = fs.readFileSync("fbimages/"+req.session.id_client+"/Prague/2020-05-30T17:29:14+0000_0.png", { flag: "r" });

var url = "https://photoslibrary.googleapis.com/v1/uploads";
var headers = {
  Authorization: "Bearer " + token,
  "Content-type": "application/octet-stream",
  "X-Goog-Upload-Content-Type": "image/png",
  "X-Goog-Upload-Protocol": "raw",
  "X-Goog-Upload-File-Name": "2020-05-30T17:29:14+0000_0.png",
};

request(
  {
    url: url,
    method: "POST",
    headers: headers,
    rejectUnauthorized: false,
    body: photo,
  },
  function (error, response, body1) {

Note:

In this modification, it supposes that your token can be used for this API. Please be careful this.

When you want to directly put the uploaded image to an alubmn, please include albumId for requesting to https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate.

Reference:

Upload media


问:
NetBeans 8.0.2 Java "Project Folder already exists and is not empty"
I've been getting this error message when I want to create a new project in NetBeans. There are two old answers for this question, Project Folder already exists and is not empty- Error in netbeans and Netbeans error: Project Folder already exists and is not empty. Not only they are addressed for NetBeans 7, but also they didn't work.

I tried:

deleting project directory,

deleting userdir under C:\Users..\AppData\Roaming\NetBeans,

deleting cache under C:\Users..\AppData\Local\NetBeans,

uninstalling and installing 8.0.2

updating JDK to 8.40

but none of them worked!

I really appreciate if you'd suggest a solution. Thanks already!

SOLVED: I uninstalled NetBeans from C directory and installed it to the D directory. Then while creating a new project I choose a directory under D. It works fine now!

答:
I had the same problem when i was messing around with some templates, after undoing the edits and saving the error message stopped occurring.

When netbeans says project folder already exists, it isn't a total error. It still creates the project, it just ran into an error while re-creating one of the template files. If you have the original tab still open, all you have to do is undo to the point before you ruined some template.

Uninstalling and re-installing will fix the problem but i hope this knowledge helps.

ContentLicense: CC BY-SA 3.0


问:
Google Client Invalid JWT: Token must be a short-lived token
I am using Google's php api client.  I am running through the quickstart guide for service accounts.  I followed the steps perfectly (as far as I can tell).  I am running into the following error:

```<code>{
   "error": "invalid_grant",
   "error_description": "Invalid JWT: Token must be a short-lived token (60 minutes) and in a reasonable timeframe. Check your iat and exp values and use a clock with skew to account for clock differences between systems."
}
</code>```

From what I have read the most common problem with this error is if the system time is wrong.  I have triple checked that my timezone and date and time are synced with the atomic clock.  I used php set timezone function to set my timezone to match my computer, but I continue to get the error.  I am looking into the other part of the message that mentions the iat and exp settings, and haven't gotten anywhere yet.

Does anyone have any ideas of how I can get past this?

答: For my case, I just need to restart my machine. (Faced the issue on vagrant VM). It's working again.</p>

Body:
I am using Google's php api client.  I am running through the quickstart guide for service accounts.  I followed the steps perfectly (as far as I can tell).  I am running into the following error:

{
   "error": "invalid_grant",
   "error_description": "Invalid JWT: Token must be a short-lived token (60 minutes) and in a reasonable timeframe. Check your iat and exp values and use a clock with skew to account for clock differences between systems."
}

From what I have read the most common problem with this error is if the system time is wrong.  I have triple checked that my timezone and date and time are synced with the atomic clock.  I used php set timezone function to set my timezone to match my computer, but I continue to get the error.  I am looking into the other part of the message that mentions the iat and exp settings, and haven't gotten anywhere yet.

Does anyone have any ideas of how I can get past this?


问:
Magento invoice email: ordered items not visible
The invoice-email doesn't show the ordered items table (no problems in invoice PDF). My template contains this code:

```<code>{{layout area="frontend" handle="sales_email_order_invoice_items" invoice=$invoice order=$order}}
</code>```

However, this part is missing in the email. I tried to find the code that should generate the HTML, I think sales.xml tells me to look at the "email/order/invoice/items.phtml"-template file. But changing its content doesn't seem to have any effect.

Where should I start to fix this problem?

This is the part in sales.xml:

```<code>    <sales_email_order_invoice_items>
        <block type="sales/order_email_invoice_items" name="items" template="email/order/invoice/items.phtml">
            <action method="addItemRender"><type>default</type><block>sales/order_email_items_default</block><template>email/order/items/invoice/default.phtml</template></action>
            <action method="addItemRender"><type>grouped</type><block>sales/order_email_items_order_grouped</block><template>email/order/items/invoice/default.phtml</template></action>
            <block type="sales/order_invoice_totals" name="invoice_totals" template="sales/order/totals.phtml">
                <action method="setLabelProperties"><value>colspan="3" align="right" style="padding:3px 9px"</value></action>
                <action method="setValueProperties"><value>align="right" style="padding:3px 9px"</value></action>
                <block type="tax/sales_order_tax" name="tax" template="tax/order/tax.phtml"/>
            </block>
        </block>
        <block type="core/text_list" name="additional.product.info" />
    </sales_email_order_invoice_items>
</code>```

答:
If you are using Magento 2.3.4, 2.3.5 the temporary fix for this problem is to update an email template with ordered items with is_legacy = 1. For example:

```<code> update email_template set is_legacy = 1 where orig_template_code = 'sales_email_order_template';
</code>```

Body:
The invoice-email doesn't show the ordered items table (no problems in invoice PDF). My template contains this code:

{{layout area="frontend" handle="sales_email_order_invoice_items" invoice=$invoice order=$order}}

However, this part is missing in the email. I tried to find the code that should generate the HTML, I think sales.xml tells me to look at the "email/order/invoice/items.phtml"-template file. But changing its content doesn't seem to have any effect.

Where should I start to fix this problem?

This is the part in sales.xml:

    <sales_email_order_invoice_items>
        <block type="sales/order_email_invoice_items" name="items" template="email/order/invoice/items.phtml">
            <action method="addItemRender"><type>default</type><block>sales/order_email_items_default</block><template>email/order/items/invoice/default.phtml</template></action>
            <action method="addItemRender"><type>grouped</type><block>sales/order_email_items_order_grouped</block><template>email/order/items/invoice/default.phtml</template></action>
            <block type="sales/order_invoice_totals" name="invoice_totals" template="sales/order/totals.phtml">
                <action method="setLabelProperties"><value>colspan="3" align="right" style="padding:3px 9px"</value></action>
                <action method="setValueProperties"><value>align="right" style="padding:3px 9px"</value></action>
                <block type="tax/sales_order_tax" name="tax" template="tax/order/tax.phtml"/>
            </block>
        </block>
        <block type="core/text_list" name="additional.product.info" />
    </sales_email_order_invoice_items>

Body:
If you are using Magento 2.3.4, 2.3.5 the temporary fix for this problem is to update an email template with ordered items with is_legacy = 1. For example:

 update email_template set is_legacy = 1 where orig_template_code = 'sales_email_order_template';


问:
Cannot Understand The Exception
This is the code :

```<code>import java.awt.*;
import javax.swing.*;

class tester {
JFrame fr;
JPanel p;
Graphics g;

tester() {
 buildGUI();
}

public void buildGUI() {
 fr=new JFrame();
 p=new JPanel();
 p.setBackground(Color.red);
 g.setColor(Color.black);
 g.drawOval(18,45,78,39);
 g.fillOval(18,45,78,39);
 fr.add(p);
 fr.setVisible(true);
 fr.setSize(500,500);
}

 public static void main(String args[]) {
  new tester();
 }
}
</code>```

These are the exceptions produced when i try to run the code :

Exception in thread "main" java.lang.NullPointerException
        at tester.buildGUI(tester.java:17)
        at tester.<init>(tester.java:10)
        at tester.main(tester.java:26)

Why do i get these exceptions?
How can i solve it.

答:
You never created object g - you just declared it.

Until you create an object and assign it to the variable holding a reference to it, the value of that variable is null.

That's why you are getting NullPointerException here.

For example:

```<code>//created a variable holding a reference to an object of type JPanel
JPanel p;
//now the value of p is null. It's not pointing to anything

//created an object of type JPanel and assigned it to p
p=new JPanel();
//now p is not null anymore, it's pointing to an instance of JPanel
</code>```

Well, you didn't do that for Graphic object g.

Title: Cannot Understand The Exception

Body:
This is the code :

import java.awt.*;
import javax.swing.*;

class tester {
JFrame fr;
JPanel p;
Graphics g;

tester() {
 buildGUI();
}

public void buildGUI() {
 fr=new JFrame();
 p=new JPanel();
 p.setBackground(Color.red);
 g.setColor(Color.black);
 g.drawOval(18,45,78,39);
 g.fillOval(18,45,78,39);
 fr.add(p);
 fr.setVisible(true);
 fr.setSize(500,500);
}

 public static void main(String args[]) {
  new tester();
 }
}

These are the exceptions produced when i try to run the code :

Exception in thread "main" java.lang.NullPointerException
        at tester.buildGUI(tester.java:17)
        at tester.<init>(tester.java:10)
        at tester.main(tester.java:26)

Why do i get these exceptions?
How can i solve it.

Body:
You never created object g - you just declared it.

Until you create an object and assign it to the variable holding a reference to it, the value of that variable is null.

That's why you are getting NullPointerException here.

For example:

//created a variable holding a reference to an object of type JPanel
JPanel p;
//now the value of p is null. It's not pointing to anything

//created an object of type JPanel and assigned it to p
p=new JPanel();
//now p is not null anymore, it's pointing to an instance of JPanel

Well, you didn't do that for Graphic object g.


问:
JQL to find epics that are not linked to a theme
I can't find any examples of how to do this.

I want to filter all epics that are not linked to any issues of type "theme".

Is this possible?

答: Not with JQL that I know of. I think that I would use Jira python to get the issue link information and filter out the unwanted epics</p>


问:
Sort titles with localCompare
Using Eleventy as static site generator am unable to figure out how to sort titles in certain alphabet (in my case, Latvian, lv). Documentation related sorting

So far script below works for English.

```<code>  eleventyConfig.addCollection("postsDescending", (collection) =>
    collection.getFilteredByGlob("src/posts/*.md").sort((a, b) => {
      if (a.data.title > b.data.title) return 1;
      else if (a.data.title < b.data.title) return -1;
      else return 0;
    })
  );
</code>```

In my take I try the localeCompare, but getting error collection.getFilteredByGlob(...).from is not a function

```<code>const alphabet = ['a','ā','b','c','č','d','e','ē','f','g','ģ','h','i','ī','j','k','ķ','l','ļ','m','n','ņ','o','p','r','s','š','t','u','ū','v','z','ž'];
    eleventyConfig.addCollection("postsDescending", function(collection) {
        return collection.getFilteredByGlob("src/posts/*.md").from(alphabet).sort(function(a, b) {
           return a.localeCompare(b, 'lv', { sensitivity: 'base' });
        });
    });
</code>```

Needless to say am beginner in Javascript ... Any help much appreciated!

答:
Turns out I am able solve this by myself.</p>

```<code>  eleventyConfig.addCollection("postsDescending", (collection) =>
    collection.getFilteredByGlob("src/posts/*.md").sort((a, b) => {
return a.data.title.localeCompare(b.data.title, 'lv', { sensitivity: 'base' });
    })
  );
</code>```

Title: Sort titles with localCompare

Body:
Using Eleventy as static site generator am unable to figure out how to sort titles in certain alphabet (in my case, Latvian, lv). Documentation related sorting

So far script below works for English.

  eleventyConfig.addCollection("postsDescending", (collection) =>
    collection.getFilteredByGlob("src/posts/*.md").sort((a, b) => {
      if (a.data.title > b.data.title) return 1;
      else if (a.data.title < b.data.title) return -1;
      else return 0;
    })
  );

In my take I try the localeCompare, but getting error collection.getFilteredByGlob(...).from is not a function

const alphabet = ['a','ā','b','c','č','d','e','ē','f','g','ģ','h','i','ī','j','k','ķ','l','ļ','m','n','ņ','o','p','r','s','š','t','u','ū','v','z','ž'];
    eleventyConfig.addCollection("postsDescending", function(collection) {
        return collection.getFilteredByGlob("src/posts/*.md").from(alphabet).sort(function(a, b) {
           return a.localeCompare(b, 'lv', { sensitivity: 'base' });
        });
    });

Needless to say am beginner in Javascript ... Any help much appreciated!

Body:
Turns out I am able solve this by myself.

  eleventyConfig.addCollection("postsDescending", (collection) =>
    collection.getFilteredByGlob("src/posts/*.md").sort((a, b) => {
return a.data.title.localeCompare(b.data.title, 'lv', { sensitivity: 'base' });
    })
  );


问:
Discord.js bot commands not working. How to solve?
I'm trying to create a bot with discord.js. It shows there are no errors, and goes online and runs perfectly. However, when I try to run a command, the bot doesn't say anything, not even an error message. My code is here:

const discord = require('discord.js');
var cheerio = require('cheerio');
var request = require('request');
const bot = new discord.Client();
const PREFIX = "//";

bot.on('ready', () => {
  console.log('CherryBot is online!');

})

bot.on("message", (message) => {
  if (message.author.equals(bot.user)) return;

  if (!message.content.startsWith(PREFIX)) return;

  var args = message.content.substring(PREFIX.length).split("");

  switch (args[0].toLowerCase()) {
    case "ping":

      message.channel.sendMessage("Pong!")
      break;

    case "cherry":
      image(message);

      break;
  }
});

function image(message) {

  var options = {
    url: "http://results.dogpile.com/serp?qc=images&q=" + "cherry fruit"
    , method: "GET",
    headers: {
      "Accept": "text/html",
      "User-Agent": "Chrome"
    }
  };

  request(options, function (error, response, responseBody) {
    if (error) {
      return;
    }

    $ = cheerio.load(responseBody);

    var links = $(".image a.link");

    var urls = new Array(links.length).fill(0).map((v, i) => links.eq(i).attr("href"));

    console.log(urls);

    if (!urls.length) {

      return;
    }

    // Send result
    message.channel.send(urls[Math.floor(Math.random() * urls.length)]);
  });
}
```

答:
First of all, you defined args wrong, you need to split() using spaces, slice() the prefix and trim() whitespaces like so:

const args = message.content
          .slice(PREFIX.length) // gets rid of the prefix
          .trim() // removes whitespaces
          .split(/ +/g) // splits using spaces
```

<p>Then you need to use <code>send()</code> instead of <code>sendMessage()</code> since it's deprecated.</p>

<pre class="lang-js prettyprint-override"><code>case "ping":
    message.channel.send("Pong!")
break;
</code>```

Body:
First of all, you defined args wrong, you need to split() using spaces, slice() the prefix and trim() whitespaces like so:

const args = message.content
          .slice(PREFIX.length) // gets rid of the prefix
          .trim() // removes whitespaces
          .split(/ +/g) // splits using spaces

Then you need to use send() instead of sendMessage() since it's deprecated.

case "ping":
    message.channel.send("Pong!")
break;


问:
It is possible to push a docker image inside a docker container?
I have a docker-in-docker container, which we'll call "dind". And a large image, which we'll call "LI".

Dind is responsible for make some docker runs calls. I need to run LI inside Dind. Normally, I push LI to a registry and pull it inside Dind. But I have a bad internet network. it takes a whole life to do this...

So, I was thinking if it is possible to push a docker image inside a docker container.

答:
You should not need to go over the network for this.

First, save LI to a local tarball

Then, in DIND use docker import.

Or alternatively, when you run DIND mount the LI tarball directly


问:
How do I pass a JSONObject from Android application to a PHP file?
I want to send a simple JSON object to PHP server, but when I try to retrieve that object on the server side, there is nothing I mean my $_POST variable is empty. The server side is PHP 5.2 and I'm using android emulator 10... Could someone have a look on my code and tell me what is going wrong?
Thanks a lot

```<code>public void uploadJSon() throws ClientProtocolException, IOException, JSONException{
       HttpClient httpclient = new DefaultHttpClient();
       String url = "http://so-dev-deb.niv2.com/suivi_activite/test.php";
       HttpPost httppost = new HttpPost(url);
       JSONObject json = new JSONObject();

       json.put("username", "bob");
       json.put("email", "test@testsite.com");
       List <NameValuePair> nvps = new ArrayList <NameValuePair>();

       nvps.add(new BasicNameValuePair("value", json.toString()));
       httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

       URL test_url = new URL(url);
       URLConnection connection = test_url.openConnection();
       connection.setDoOutput(true);

       HttpResponse response;
       response = httpclient.execute(httppost);
       Log.i("NVPS",nvps.get(0).toString());
       Log.i("JSON",json.toString());
       Log.i("response", response.getEntity().getContent().toString());
       Log.i("response status",response.getStatusLine().toString());

       BufferedReader in = new BufferedReader(
             new InputStreamReader(
             connection.getInputStream()));

       String decodedString;

       while ((decodedString = in.readLine()) != null) {
          //System.out.println(decodedString);
          Log.i("info 10",decodedString);
       }
       in.close();

    }
</code>```

The server side test.php is :

```<code><?php
    $tmp = json_decode($_POST['value']);
    var_dump($tmp);
?>
</code>```

答:
```<code>public static String login(Context context, String email, String pwd) {

    HttpClient client = new DefaultHttpClient();

    HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
    // Limit
    HttpResponse response;
    JSONObject json = new JSONObject();
    try {

        Log.d("Debug","Login Url:" + context.getResources().getString(
                R.string.url) + context.getResources().getString(
                        R.string.login));

        HttpPost post = new HttpPost(context.getResources().getString(
                R.string.url) + context.getResources().getString(
                        R.string.login));

        post.setHeader("Accept", "application/json");
        post.setHeader("Content-type", "application/json");

        json.put("email", email);
        json.put("password", pwd);

        StringEntity se = new StringEntity("{\"User\":" + json.toString()
                + "}");
        post.setEntity(se);
        response = client.execute(post);

        if (response != null) {
            json = getResult(response);

            if(statusOK(json)){
                return new String(json.getString("token"));
            }
        }
    } catch (Exception e) {
        Log.e("Error", "Error Login", e);
    }
    //  printJSON(json);

    return "ERROR";
}
</code>```

<p>Note I wrap the JSON in the User as the server required this for my case.  </p>

Body:
I want to send a simple JSON object to PHP server, but when I try to retrieve that object on the server side, there is nothing I mean my $_POST variable is empty. The server side is PHP 5.2 and I'm using android emulator 10... Could someone have a look on my code and tell me what is going wrong?
Thanks a lot

public void uploadJSon() throws ClientProtocolException, IOException, JSONException{
       HttpClient httpclient = new DefaultHttpClient();
       String url = "http://so-dev-deb.niv2.com/suivi_activite/test.php";
       HttpPost httppost = new HttpPost(url);
       JSONObject json = new JSONObject();

       json.put("username", "bob");
       json.put("email", "test@testsite.com");
       List <NameValuePair> nvps = new ArrayList <NameValuePair>();

       nvps.add(new BasicNameValuePair("value", json.toString()));
       httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

       URL test_url = new URL(url);
       URLConnection connection = test_url.openConnection();
       connection.setDoOutput(true);

       HttpResponse response;
       response = httpclient.execute(httppost);
       Log.i("NVPS",nvps.get(0).toString());
       Log.i("JSON",json.toString());
       Log.i("response", response.getEntity().getContent().toString());
       Log.i("response status",response.getStatusLine().toString());

       BufferedReader in = new BufferedReader(
             new InputStreamReader(
             connection.getInputStream()));

       String decodedString;

       while ((decodedString = in.readLine()) != null) {
          //System.out.println(decodedString);
          Log.i("info 10",decodedString);
       }
       in.close();

    }

The server side test.php is :

<?php
    $tmp = json_decode($_POST['value']);
    var_dump($tmp);
?>

Body:
public static String login(Context context, String email, String pwd) {

    HttpClient client = new DefaultHttpClient();

    HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
    // Limit
    HttpResponse response;
    JSONObject json = new JSONObject();
    try {

        Log.d("Debug","Login Url:" + context.getResources().getString(
                R.string.url) + context.getResources().getString(
                        R.string.login));

        HttpPost post = new HttpPost(context.getResources().getString(
                R.string.url) + context.getResources().getString(
                        R.string.login));

        post.setHeader("Accept", "application/json");
        post.setHeader("Content-type", "application/json");

        json.put("email", email);
        json.put("password", pwd);

        StringEntity se = new StringEntity("{\"User\":" + json.toString()
                + "}");
        post.setEntity(se);
        response = client.execute(post);

        if (response != null) {
            json = getResult(response);

            if(statusOK(json)){
                return new String(json.getString("token"));
            }
        }
    } catch (Exception e) {
        Log.e("Error", "Error Login", e);
    }
    //  printJSON(json);

    return "ERROR";
}

Note I wrap the JSON in the User as the server required this for my case.


问:
2 player tictactoe pygame
I want to distinguish 2 players in a tictactoe game in pygame. The "click" function is an (x,y) co-ordinate of where the user clicked and in they clicked in a certain place i'd update the shape. Also the "current game" is just an array that holds the state of the current game.

The logic seems correct, but the code will not run, and just bugs when the GUI opens.

```<code>        i=1
        while i<10:
            if p1==True and p2 == False:
                #1st row
                if  click[0]<=250 and click[0]>=100 and click[1]<=250 and click[1]>=100:
                    current_game[0][0] = "X"
                    i+=1
                    p2=True
                    p1=False

                if  click[0]<=550 and click[0]>=250 and click[1]<=250 and click[1]>=100:
                    current_game[0][1] = "X"
                    i += 1
                    p2=True
                    p1 = False

                if  click[0]<=700 and click[0]>=550 and click[1]<=250 and click[1]>=100:
                    current_game[0][2] = "X"
                    i += 1
                    p2=True
                    p1 = False

                #2nd row
                if  click[0]<=250 and click[0]>=100 and click[1]<= 550and click[1]>=250:
                    current_game[1][0] = "X"
                    i += 1
                    p2=True
                    p1 = False

                if  click[0]<=550 and click[0]>=250 and click[1]<=550 and click[1]>=250:
                    current_game[1][1] = "X"
                    i += 1
                    p2=True
                    p1 = False

                if  click[0] <= 700 and click[0] >= 550 and click[1] <= 550 and click[1] >= 250:
                    current_game[1][2] = "X"
                    i += 1
                    p2=True
                    p1 = False

                #3rd row
                if click[0]<=250 and click[0]>=100 and click[1]<= 700and click[1]>=550:
                    current_game[2][0] = "X"
                    i += 1
                    p2=True
                    p1 = False

                if  click[0] <= 550 and click[0] >= 250 and click[1] <= 700 and click[1] >= 550:
                    current_game[2][1] = "X"
                    i += 1
                    p2=True
                    p1 = False

                if  click[0] <= 700 and click[0] >= 550 and click[1] <= 700 and click[1] >= 550:
                    current_game[2][2] = "X"
                    i += 1
                    p2=True
                    p1 = False

            if p2==True and p1==False:
                # 1st row
                if  click[0] <= 250 and click[0] >= 100 and click[1] <= 250 and click[1] >= 100:
                    current_game[0][0] = "o"
                    i += 1
                    p1 = True
                    p2 = False

                if  click[0] <= 550 and click[0] >= 250 and click[1] <= 250 and click[1] >= 100:
                    current_game[0][1] = "o"
                    i += 1
                    p1 = True
                    p2 = False

                if  click[0] <= 700 and click[0] >= 550 and click[1] <= 250 and click[1] >= 100:
                    current_game[0][2] = "o"
                    i += 1
                    p1 = True
                    p2 = False

                # 2nd row
                if  click[0] <= 250 and click[0] >= 100 and click[1] <= 550 and click[1] >= 250:
                    current_game[1][0] = "o"
                    i += 1
                    p1 = True
                    p2 = False
                if  click[0] <= 550 and click[0] >= 250 and click[1] <= 550 and click[1] >= 250:
                    current_game[1][1] = "o"
                    i += 1
                    p1 = True
                    p2 = False

                if  click[0] <= 700 and click[0] >= 550 and click[1] <= 550 and click[1] >= 250:
                    current_game[1][2] = "o"
                    i += 1
                    p1 = True
                    p2 = False

                # 3rd row
                if click[0] <= 250 and click[0] >= 100 and click[1] <= 700 and click[1] >= 550:
                    current_game[2][0] = "o"
                    i += 1
                    p1 = True
                    p2 = False

                if  click[0] <= 550 and click[0] >= 250 and click[1] <= 700 and click[1] >= 550:
                    current_game[2][1] = "o"
                    i += 1
                    p1 = True
                    p2 = False

                if  click[0] <= 700 and click[0] >= 550 and click[1] <= 700 and click[1] >= 550:
                    current_game[2][2] = "o"
                    i += 1
                    p1 = True
                    p2 = False
</code>```

答:
If you didn't omit code within the while loop, then you can start with:

```<code>while i<10:
    # this line seems to be missing
    click = somefunction_that_waits_for_click_and_returns_coordinates()
    ...
</code>```

your current code never updates the values of click. Therfore clickp[0] and click[1] will never change values

Title: 2 player tictactoe pygame

Body:
I want to distinguish 2 players in a tictactoe game in pygame. The "click" function is an (x,y) co-ordinate of where the user clicked and in they clicked in a certain place i'd update the shape. Also the "current game" is just an array that holds the state of the current game.

The logic seems correct, but the code will not run, and just bugs when the GUI opens.

        i=1
        while i<10:
            if p1==True and p2 == False:
                #1st row
                if  click[0]<=250 and click[0]>=100 and click[1]<=250 and click[1]>=100:
                    current_game[0][0] = "X"
                    i+=1
                    p2=True
                    p1=False

                if  click[0]<=550 and click[0]>=250 and click[1]<=250 and click[1]>=100:
                    current_game[0][1] = "X"
                    i += 1
                    p2=True
                    p1 = False

                if  click[0]<=700 and click[0]>=550 and click[1]<=250 and click[1]>=100:
                    current_game[0][2] = "X"
                    i += 1
                    p2=True
                    p1 = False

                #2nd row
                if  click[0]<=250 and click[0]>=100 and click[1]<= 550and click[1]>=250:
                    current_game[1][0] = "X"
                    i += 1
                    p2=True
                    p1 = False

                if  click[0]<=550 and click[0]>=250 and click[1]<=550 and click[1]>=250:
                    current_game[1][1] = "X"
                    i += 1
                    p2=True
                    p1 = False

                if  click[0] <= 700 and click[0] >= 550 and click[1] <= 550 and click[1] >= 250:
                    current_game[1][2] = "X"
                    i += 1
                    p2=True
                    p1 = False

                #3rd row
                if click[0]<=250 and click[0]>=100 and click[1]<= 700and click[1]>=550:
                    current_game[2][0] = "X"
                    i += 1
                    p2=True
                    p1 = False

                if  click[0] <= 550 and click[0] >= 250 and click[1] <= 700 and click[1] >= 550:
                    current_game[2][1] = "X"
                    i += 1
                    p2=True
                    p1 = False

                if  click[0] <= 700 and click[0] >= 550 and click[1] <= 700 and click[1] >= 550:
                    current_game[2][2] = "X"
                    i += 1
                    p2=True
                    p1 = False

            if p2==True and p1==False:
                # 1st row
                if  click[0] <= 250 and click[0] >= 100 and click[1] <= 250 and click[1] >= 100:
                    current_game[0][0] = "o"
                    i += 1
                    p1 = True
                    p2 = False

                if  click[0] <= 550 and click[0] >= 250 and click[1] <= 250 and click[1] >= 100:
                    current_game[0][1] = "o"
                    i += 1
                    p1 = True
                    p2 = False

                if  click[0] <= 700 and click[0] >= 550 and click[1] <= 250 and click[1] >= 100:
                    current_game[0][2] = "o"
                    i += 1
                    p1 = True
                    p2 = False

                # 2nd row
                if  click[0] <= 250 and click[0] >= 100 and click[1] <= 550 and click[1] >= 250:
                    current_game[1][0] = "o"
                    i += 1
                    p1 = True
                    p2 = False
                if  click[0] <= 550 and click[0] >= 250 and click[1] <= 550 and click[1] >= 250:
                    current_game[1][1] = "o"
                    i += 1
                    p1 = True
                    p2 = False

                if  click[0] <= 700 and click[0] >= 550 and click[1] <= 550 and click[1] >= 250:
                    current_game[1][2] = "o"
                    i += 1
                    p1 = True
                    p2 = False

                # 3rd row
                if click[0] <= 250 and click[0] >= 100 and click[1] <= 700 and click[1] >= 550:
                    current_game[2][0] = "o"
                    i += 1
                    p1 = True
                    p2 = False

                if  click[0] <= 550 and click[0] >= 250 and click[1] <= 700 and click[1] >= 550:
                    current_game[2][1] = "o"
                    i += 1
                    p1 = True
                    p2 = False

                if  click[0] <= 700 and click[0] >= 550 and click[1] <= 700 and click[1] >= 550:
                    current_game[2][2] = "o"
                    i += 1
                    p1 = True
                    p2 = False

Body:
If you didn't omit code within the while loop, then you can start with:

while i<10:
    # this line seems to be missing
    click = somefunction_that_waits_for_click_and_returns_coordinates()
    ...

your current code never updates the values of click. Therfore clickp[0] and click[1] will never change values


问:
Mysql UNION way to differ from which table result row is
Lets say I have below query.

```<code>SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
</code>```

Lest say there is one same city NY in both tables witch will give me:

```<code>| City     |
| -------- |
| NY       |
| NY       |
</code>```

I am fetching this in a HTML table, is there a way to differ from witch MySQL table result row is from, other then making another column in tables itself, for example column type.

Maybe is possible to append something to result set itself in query?

答:
Append an extra column with the literal string value as the table name along with the existing query. This will help you to distinguish the rows.

```<code>SELECT 'Customers' as Type, City FROM Customers
UNION ALL
SELECT 'Suppliers' as Type, City FROM Suppliers
ORDER BY City;
</code>```

Update:
UNION removes the duplicate rows. So, if your tables have same values in the City column, it will return the unique rows. You have to use UNION ALL. This will return all rows and appending the string literal as the type column will help you to distinguish between the rows.

Thanks @Gordon for pointing it out.

Body:
Lets say I have below query.

SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;

Lest say there is one same city NY in both tables witch will give me:

| City     |
| -------- |
| NY       |
| NY       |

I am fetching this in a HTML table, is there a way to differ from witch MySQL table result row is from, other then making another column in tables itself, for example column type.

Maybe is possible to append something to result set itself in query?

Body:
Append an extra column with the literal string value as the table name along with the existing query. This will help you to distinguish the rows.

SELECT 'Customers' as Type, City FROM Customers
UNION ALL
SELECT 'Suppliers' as Type, City FROM Suppliers
ORDER BY City;

Update:
UNION removes the duplicate rows. So, if your tables have same values in the City column, it will return the unique rows. You have to use UNION ALL. This will return all rows and appending the string literal as the type column will help you to distinguish between the rows.

Thanks @Gordon for pointing it out.


问:
JUnit 5 test in Netbeans
I have troubles using JUnit 5.52 , when I add the test class and try running it I get the next message:

The <classpath> or <modulepath> for <junit> must include junit.jar if not in Ant's own classpath BUILD FAILED (total time: 0 seconds)

I'm running Apache NetBeans IDE 11.3 and I solved it by deleting JUnit 5 and using JUnit 4.12 but I might use 5.52 because of university requirements.

Any idea how to solve it, still using JUnit 5.52 or any JUnit 5 library?

Thanks in advance.

答: It seems there is no answer available, down grading to Junit 4.12 is the only solution. You could also try re-installing the jar library manually (which I tried also).</p>

Title: JUnit 5 test in Netbeans


问:
Filtering JSON according to some rules
I'm stuck conceptually on this problem. I have some data:

```<code>const measurements = [
  {
    value: 162000,
    properties: [
      {
        name: "Selection Status",
        value: "Most recent value chosen",
      },
      {
        name: "Measurement Method",
        value: "Method of Disks, Single Plane",
      },
      {
        name: "Image Mode",
        value: "2D mode",
      },
      {
        name: "Image View",
        value: "Apical two chamber",
      },
    ],
  },
  {
    value: 171000,
    properties: [
      {
        name: "Selection Status",
        value: "Most recent value chosen",
      },
      {
        name: "Measurement Method",
        value: "Method of Disks, Single Plane",
      },
      {
        name: "Image Mode",
        value: "2D mode",
      },
      {
        name: "Image View",
        value: "Apical four chamber",
      },
    ],
  },
  {
    value: 173000,
    properties: [
      {
        name: "Measurement Method",
        value: "Method of Disks, Biplane",
      },
      {
        name: "Image Mode",
        value: "2D mode",
      },
    ],
  },
  {
    value: 157000,
    properties: [
      {
        name: "Measurement Method",
        value: "Cube Method",
      },
      {
        name: "Image Mode",
        value: "2D mode",
      },
    ],
  },
  {
    value: 141000,
    properties: [
      {
        name: "Measurement Method",
        value: "Teichholz",
      },
      {
        name: "Image Mode",
        value: "2D mode",
      },
    ],
  },
];
</code>```

My goal is to choose the measurement according to some greedy rules. They might look a little like this:

```<code>function findMeasurement(
  measurements: Measurement[],
  filter: MeasurementFilter,
): Measurement | undefined {
  return undefined
}
</code>```

where a MeasurementFilter might look a little like this:

```<code>const MATCH_ANYTHING = /.+/;

{
  'Image Mode': [/2D mode/, MATCH_ANYTHING],
  'Image View': [/Apical four chamber/, /Apical two chamber/, MATCH_ANYTHING],
  'Measurement Method': [
    /Method of Disks, Biplane/,
    /Method of Disks, Single Plane/,
    /Teichholz/,
    MATCH_ANYTHING,
  ],
  'Selection Status': [/Mean value chosen/, MATCH_ANYTHING],
}
</code>```

This filter should look for measurements that match from most specific to least specific. So I want to iterate through the data array, and find the measurement that matches most closely. So it would be measurement 2 with value 171000, as it has Apical four chamber, 2D mode. I want to match top to bottom in my filter.

Does this make sense? Are there any flaws I am missing? Can anyone get me started on a function implementation/pseudo code?

答:
I dont know a trivial way to achieve this although there should be implementations for this usecase, I dont know them. Two solution approaches:

1) You could try to use existing fuzzy search libraries/solutions like elastic search (available for i.e. MongoDB), store your searchable fields in a search string and try to teach fuzzy search how to split the parts as you need them. Probably feasible if you want fuzzy matching in your query too and dont care too much about exact results.

2) Implement your own matching. Start by implementing a similarity measure and iteratively calculate that measure over the dataset. A very simple measure would be to simply add one to the similarity score for every matching field. Assign the score to the document and sort by score after iterating over the whole collection. Now you have a sorted collection by relevance to your query.

I dont see why it should make any difference whether you match top to bottom vs bottom to top.

Title: Filtering JSON according to some rules

Body:
I'm stuck conceptually on this problem. I have some data:

const measurements = [
  {
    value: 162000,
    properties: [
      {
        name: "Selection Status",
        value: "Most recent value chosen",
      },
      {
        name: "Measurement Method",
        value: "Method of Disks, Single Plane",
      },
      {
        name: "Image Mode",
        value: "2D mode",
      },
      {
        name: "Image View",
        value: "Apical two chamber",
      },
    ],
  },
  {
    value: 171000,
    properties: [
      {
        name: "Selection Status",
        value: "Most recent value chosen",
      },
      {
        name: "Measurement Method",
        value: "Method of Disks, Single Plane",
      },
      {
        name: "Image Mode",
        value: "2D mode",
      },
      {
        name: "Image View",
        value: "Apical four chamber",
      },
    ],
  },
  {
    value: 173000,
    properties: [
      {
        name: "Measurement Method",
        value: "Method of Disks, Biplane",
      },
      {
        name: "Image Mode",
        value: "2D mode",
      },
    ],
  },
  {
    value: 157000,
    properties: [
      {
        name: "Measurement Method",
        value: "Cube Method",
      },
      {
        name: "Image Mode",
        value: "2D mode",
      },
    ],
  },
  {
    value: 141000,
    properties: [
      {
        name: "Measurement Method",
        value: "Teichholz",
      },
      {
        name: "Image Mode",
        value: "2D mode",
      },
    ],
  },
];

My goal is to choose the measurement according to some greedy rules. They might look a little like this:

function findMeasurement(
  measurements: Measurement[],
  filter: MeasurementFilter,
): Measurement | undefined {
  return undefined
}

where a MeasurementFilter might look a little like this:

const MATCH_ANYTHING = /.+/;

{
  'Image Mode': [/2D mode/, MATCH_ANYTHING],
  'Image View': [/Apical four chamber/, /Apical two chamber/, MATCH_ANYTHING],
  'Measurement Method': [
    /Method of Disks, Biplane/,
    /Method of Disks, Single Plane/,
    /Teichholz/,
    MATCH_ANYTHING,
  ],
  'Selection Status': [/Mean value chosen/, MATCH_ANYTHING],
}

This filter should look for measurements that match from most specific to least specific. So I want to iterate through the data array, and find the measurement that matches most closely. So it would be measurement 2 with value 171000, as it has Apical four chamber, 2D mode. I want to match top to bottom in my filter.

Does this make sense? Are there any flaws I am missing? Can anyone get me started on a function implementation/pseudo code?


问:
How can I troubleshoot the delete row function
I am attempting to delete a row like this:

data <- data[-1645,]

However, after running the code, the row is still there. I can tell because there is an outlier in that row that is showing up on all my graphs, and when I view the data I can sort a column to easily find the offending outlier. I have had no trouble deleting rows in the past- has anyone run into anything similar? I do understand the limitations of outlier removal and I don't typically remove them however for a number of reasons I would like to see what the data look like without this one (in this case, all other values in the response variable are between -1 and 0, and in this row the value is 10^4).

答:
After playing around with the data, I think the best explanation is that the indexing is off. This is in line with what dcarlson was saying- that it could be removing the 1,645th row, it just isn't labelled as such. I think the best solution is to use subset:

data <- subset(data, Yield.Decline < 100)

This is a more robust solution than trying to remove any given row based on its value (the line can be accidentally run multiple times without erroneously removing additional lines).


问:
list of regular expressions
I'm looking for a concise list of all the regular expression syntax (sort of like a cheatsheet) and I found this tool: http://erik.eae.net/playground/regexp/regexp.html

in which if you click on the question mark on the top right corner it will display some sort of dictionary of regular expressions...

my question is....is this list comprehensive or is it missing something?

if anyone knows a better list, please let me know as well

答: regular-expressions.info is a quite good reference for regular expression. They also have a comparison of syntax components available in the various regular expression flavors.</p>

Title: list of regular expressions


问:
Column value return null
I have a problem with my code, my value in form has always return null.

Here's my code:

```<code>update = async() => {
    const { navigation } = this.props;
    try{
        await fetch('http://0872b1689xxx.ngrok.io/api/xxx/update/' + this.state.id, {
            method:'PUT',
            headers:{
                'Accept'       : 'application/json',
                'Authorization': 'Bearer ' + await AsyncStorage.getItem('api_token'),
            },
            body: JSON.stringify({
                "nip"     : this.state.nip,
                "name"    : this.state.name,
                "email"   : this.state.email,
                "password": this.state.password
            })
        }).then(res => res.text())
        .then(resData => {
            alert(resData);

        });
    }catch(e){
        alert("");
    }
}
</code>```

When I alert(this.state.nip) it works its not null but when I send in my api its say nip null but only my password has value

Here's my API code:

```<code>public function validator($request)
{
    $rules = [
        'nip'           => ['required', 'string'],
        'name'          => ['required', 'string'],
        'email'         => ['required', 'string'],
        'password'      => ['required'],
    ];

    return Validator::make($request->all(), $rules);
}

public function update(Request $request, User $user)
{
    $validator = $this->validator($request);

        $data = [
            'nip'       => $request->nip,
            'name'      => $request->name,
            'role_id'   => Auth::user()->role_id,
            'email'     => $request->email,
            'password'  => Hash::make($request->password),
        ];
        $update = $user->update($data);

        return response()->json("b", 200);
}
</code>```

I hope you can help me

答:
It seems like you're doing nothing with the result of the validation.

To validate a request with no special handling you are usually using $request->validate() which fails with a ValidationException.

From the docs:

[...] if validation fails, an exception will be thrown and the proper
  error response will automatically be sent back to the user. In the
  case of a traditional HTTP request, a redirect response will be
  generated, while a JSON response will be sent for AJAX requests.

```<code>public function update(Request $request, User $user)
{
    // If this fails, it throws an ValidationException which gets handled by your exception handler.
    $request->validate([
        'nip'           => ['required', 'string'],
        'name'          => ['required', 'string'],
        'email'         => ['required', 'string'],
        'password'      => ['required'],
    ]);

    // The data here has been validated and will be suficcient for your query.
    $data = [
        'nip'       => $request->nip,
        'name'      => $request->name,
        'role_id'   => Auth::user()->role_id,
        'email'     => $request->email,
        'password'  => Hash::make($request->password),
    ];
    $update = $user->update($data);

    return response()->json("b", 200);
}
</code>```

If you need to have the rules in another method to reuse them for example, you would need to use the result of your validator function and handle the error yourself.

```<code>public function update(Request $request, User $user)
{
    $validation = $this->validator($request);

    // Abort if the validator fails and send your custom error response.
    if ($validation->fails()) {
        return response()->json(['success' => false, 'errors' => $validation->errors()]);
    }

    // The data here has been validated and will be suficcient for your query.
    $data = [
        'nip'       => $request->nip,
        'name'      => $request->name,
        'role_id'   => Auth::user()->role_id,
        'email'     => $request->email,
        'password'  => Hash::make($request->password),
    ];

    $update = $user->update($data);

    return response()->json("b", 200);
}
</code>```

Title: Column value return null

Body:
I have a problem with my code, my value in form has always return null.

Here's my code:

update = async() => {
    const { navigation } = this.props;
    try{
        await fetch('http://0872b1689xxx.ngrok.io/api/xxx/update/' + this.state.id, {
            method:'PUT',
            headers:{
                'Accept'       : 'application/json',
                'Authorization': 'Bearer ' + await AsyncStorage.getItem('api_token'),
            },
            body: JSON.stringify({
                "nip"     : this.state.nip,
                "name"    : this.state.name,
                "email"   : this.state.email,
                "password": this.state.password
            })
        }).then(res => res.text())
        .then(resData => {
            alert(resData);

        });
    }catch(e){
        alert("");
    }
}

When I alert(this.state.nip) it works its not null but when I send in my api its say nip null but only my password has value

Here's my API code:

public function validator($request)
{
    $rules = [
        'nip'           => ['required', 'string'],
        'name'          => ['required', 'string'],
        'email'         => ['required', 'string'],
        'password'      => ['required'],
    ];

    return Validator::make($request->all(), $rules);
}

public function update(Request $request, User $user)
{
    $validator = $this->validator($request);

        $data = [
            'nip'       => $request->nip,
            'name'      => $request->name,
            'role_id'   => Auth::user()->role_id,
            'email'     => $request->email,
            'password'  => Hash::make($request->password),
        ];
        $update = $user->update($data);

        return response()->json("b", 200);
}

I hope you can help me

Body:
It seems like you're doing nothing with the result of the validation.

To validate a request with no special handling you are usually using $request->validate() which fails with a ValidationException.

From the docs:

[...] if validation fails, an exception will be thrown and the proper
  error response will automatically be sent back to the user. In the
  case of a traditional HTTP request, a redirect response will be
  generated, while a JSON response will be sent for AJAX requests.

public function update(Request $request, User $user)
{
    // If this fails, it throws an ValidationException which gets handled by your exception handler.
    $request->validate([
        'nip'           => ['required', 'string'],
        'name'          => ['required', 'string'],
        'email'         => ['required', 'string'],
        'password'      => ['required'],
    ]);

    // The data here has been validated and will be suficcient for your query.
    $data = [
        'nip'       => $request->nip,
        'name'      => $request->name,
        'role_id'   => Auth::user()->role_id,
        'email'     => $request->email,
        'password'  => Hash::make($request->password),
    ];
    $update = $user->update($data);

    return response()->json("b", 200);
}

If you need to have the rules in another method to reuse them for example, you would need to use the result of your validator function and handle the error yourself.

public function update(Request $request, User $user)
{
    $validation = $this->validator($request);

    // Abort if the validator fails and send your custom error response.
    if ($validation->fails()) {
        return response()->json(['success' => false, 'errors' => $validation->errors()]);
    }

    // The data here has been validated and will be suficcient for your query.
    $data = [
        'nip'       => $request->nip,
        'name'      => $request->name,
        'role_id'   => Auth::user()->role_id,
        'email'     => $request->email,
        'password'  => Hash::make($request->password),
    ];

    $update = $user->update($data);

    return response()->json("b", 200);
}


问:
Problem with node-sass on create-react-app
Before I post this question, I have tried all of the solution offered down below :
ERROR in Cannot find module 'node-sass'

I use create-react-app to create project1 on Windows 10.

My node version :
node -v
-> v12.16.3

Install node-sass :
    npm install node-sass@latest

App.js :

```<code>import React from 'react';

import "assets/scss/style.scss";

function App() {
  return (
     <div>Hi World</div>
  );
}

export default App;
</code>```

npm start

Error on the browser :
./src/App.js
Module not found: Can't resolve 'assets/scss/style.scss' in 'F:\project1\src'

I'm just wondering why isn't there a simpler and guarentee-to-work way to get this node-sass installed and run. After I searched up for solution on google, it turns out that a lot of people (not only me) are having the same problem.

答:
You just need to flow three steps:

npm install node-sass

change file extension ( .css to .scss )

change any import to .scss

provide proper path for style.scss file( May I know your style.scss path? )

Body:
Before I post this question, I have tried all of the solution offered down below :
ERROR in Cannot find module 'node-sass'

I use create-react-app to create project1 on Windows 10.

My node version :
node -v
-> v12.16.3

Install node-sass :
    npm install node-sass@latest

App.js :

import React from 'react';

import "assets/scss/style.scss";

function App() {
  return (

Hi World

  );
}

export default App;

npm start

Error on the browser :
./src/App.js
Module not found: Can't resolve 'assets/scss/style.scss' in 'F:\project1\src'

I'm just wondering why isn't there a simpler and guarentee-to-work way to get this node-sass installed and run. After I searched up for solution on google, it turns out that a lot of people (not only me) are having the same problem.


问:
SliverPersistentHeader in CustomScrollView becomes under the other slivers when scrolling (shown in .gif image). What is wrong and how to fix it?
I have a SliverPersistentHeader widget inside a CustomScrollView.
When I scroll it, it becomes under the other slivers.

```<code>[...]
child: Scaffold(
            body: CustomScrollView(
              scrollDirection: Axis.vertical,
              shrinkWrap: true,
              slivers: [
                SliverPersistentHeader(
                  delegate: SliverAppBar(expandedHeight: 200),
  pinned: true,
                  );
                _activeScreen(), // This returns a SliverList that contains a Form
              ],
            ),
            bottomNavigationBar: [...]

class SliverAppBar extends SliverPersistentHeaderDelegate {
  final double expandedHeight;

  SliverAppBar({@required this.expandedHeight});

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Stack(
      fit: StackFit.expand,
      overflow: Overflow.visible,
      children: [
        Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [
                Colors.black,
                primaryColor,
              ],
            ),
            boxShadow: [
              BoxShadow(
                  color: Colors.black26,
                  offset: Offset(0, 0),
                  blurRadius: 5.0,
                  spreadRadius: 5.0),
            ],
          ),
        ),
        Center(
          child: Text(
            "Sort By Your Taste",
            style: TextStyle(
              fontFamily: 'Modak',
              letterSpacing: 1,
              color: Colors.white,
              fontWeight: FontWeight.w100,
              fontSize: (MediaQuery.of(context).size.width / 10) -
                  ((shrinkOffset < expandedHeight - 50
                          ? shrinkOffset
                          : expandedHeight - 50) /
                      10),
            ),
          ),
        ),
        Positioned(
            [...] // Code for that (c) detail
        ),
      ],
    );
  }
</code>```

```<code>
</code>```

What is wrong with it? I think it might have something to do with the Stack widget, but I didn't find any property in it that could fix it.

Please help me, how to fix it?

答:
All the problem was because of the shrinkWrap property that was set to true.

```<code>[...]
child: Scaffold(
            body: CustomScrollView(
              scrollDirection: Axis.vertical,
              shrinkWrap: true, // <-- Here
[...]
</code>```

I don't remember why I set it to true... But that was the problem, and it has taken so long to me to notice that that was the problem.

Body:
I have a SliverPersistentHeader widget inside a CustomScrollView.
When I scroll it, it becomes under the other slivers.

[...]
child: Scaffold(
            body: CustomScrollView(
              scrollDirection: Axis.vertical,
              shrinkWrap: true,
              slivers: [
                SliverPersistentHeader(
                  delegate: SliverAppBar(expandedHeight: 200),
  pinned: true,
                  );
                _activeScreen(), // This returns a SliverList that contains a Form
              ],
            ),
            bottomNavigationBar: [...]

class SliverAppBar extends SliverPersistentHeaderDelegate {
  final double expandedHeight;

  SliverAppBar({@required this.expandedHeight});

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Stack(
      fit: StackFit.expand,
      overflow: Overflow.visible,
      children: [
        Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [
                Colors.black,
                primaryColor,
              ],
            ),
            boxShadow: [
              BoxShadow(
                  color: Colors.black26,
                  offset: Offset(0, 0),
                  blurRadius: 5.0,
                  spreadRadius: 5.0),
            ],
          ),
        ),
        Center(
          child: Text(
            "Sort By Your Taste",
            style: TextStyle(
              fontFamily: 'Modak',
              letterSpacing: 1,
              color: Colors.white,
              fontWeight: FontWeight.w100,
              fontSize: (MediaQuery.of(context).size.width / 10) -
                  ((shrinkOffset < expandedHeight - 50
                          ? shrinkOffset
                          : expandedHeight - 50) /
                      10),
            ),
          ),
        ),
        Positioned(
            [...] // Code for that (c) detail
        ),
      ],
    );
  }

What is wrong with it? I think it might have something to do with the Stack widget, but I didn't find any property in it that could fix it.

Please help me, how to fix it?

Body:
All the problem was because of the shrinkWrap property that was set to true.

[...]
child: Scaffold(
            body: CustomScrollView(
              scrollDirection: Axis.vertical,
              shrinkWrap: true, // <-- Here
[...]

I don't remember why I set it to true... But that was the problem, and it has taken so long to me to notice that that was the problem.


问:
How do I fix this intelliJ issue?
In trying to change the intelliJ font from 13 to 12, I accident plugged in 1312, and instead of giving an error, IntelliJ actually made the font 1312 and it's freezing. I was not able to open preferences to change the font to 12. I deleted the application and re-downloaded it, still having problems. its still freezing and not even letting me access the preferences to change the font, I also thought the factory setting would be in place since I am redownloading it. not sure what to do...I have a project due tomorrow so im stressed. </p>

答:
If you mean the IDE UI font and not the editor font covered in the answer from Matt, look inside CONFIG/options/other.xml file instead for the lines like these:

```<code>  <component name="NotRoamableUiSettings">
    <option name="fontFace" value="Tahoma" />
    <option name="fontScale" value="1.0" />
    <option name="fontSize" value="13" />
  </component>
</code>```

Title: How do I fix this intelliJ issue?

Body:
If you mean the IDE UI font and not the editor font covered in the answer from Matt, look inside CONFIG/options/other.xml file instead for the lines like these:

  <component name="NotRoamableUiSettings">
    <option name="fontFace" value="Tahoma" />
    <option name="fontScale" value="1.0" />
    <option name="fontSize" value="13" />
  </component>


问:
Question about Java synchronized
The Java documentation says that "it is not possible for two invocations of synchronized methods on the same object to interleave".  What I need to know is whether synchronized will also prevent a synchronized method in two different instances of the same class from interleaving.

E.g. class Worker has method called process().  We have several instances of Worker running in their own threads.  We want to prevent more than one instance running the process() method simultaneously.  Will synchronized do this?

Thanks.

答:
No, the method synchronized locks on the specific object (the 'this'), so 2 instances of the same class would lock on different objects.

If you want to synchronize across all instances of a class, you need to use a synchronized block IN the method, locking on a static final object.

Title: Question about Java synchronized


问:
Can I make component parameter required when building a custom Blazor component?
When I try to build a Blazor component I can define parameters for it like this:

```<code>@code {

   [Parameter]
   public string MyString { get; set; }

}
</code>```

My question is can I make this parameter required so that, when component is used, the project will not build unless I provide the specified parameter? Is this something I should even be worried about? I suppose I could handle any invalid values in component initialization by maybe throwing an exception if the value is not provided like this:

```<code>protected override void OnInitialized()
{
    base.OnInitialized();
    if (string.IsNullOrWhiteSpace(MyString)) {
       // throw an exception here...
    }
}
</code>```

but is that the right way to handle this?

答:
.NET 6 and newer

This can be accomplished with the [EditorRequired] attribute. Example:

```<code>[Parameter, EditorRequired]
public string Name { get; set; }
</code>```

This will give an IDE warning to consumers of components that parameters are missing if their parameters are not supplied.

Before .NET 6

Currently, you’ll have to do exactly as you said.

Body:
When I try to build a Blazor component I can define parameters for it like this:

@code {

   [Parameter]
   public string MyString { get; set; }

}

My question is can I make this parameter required so that, when component is used, the project will not build unless I provide the specified parameter? Is this something I should even be worried about? I suppose I could handle any invalid values in component initialization by maybe throwing an exception if the value is not provided like this:

protected override void OnInitialized()
{
    base.OnInitialized();
    if (string.IsNullOrWhiteSpace(MyString)) {
       // throw an exception here...
    }
}

but is that the right way to handle this?

Body:
.NET 6 and newer

This can be accomplished with the [EditorRequired] attribute. Example:

[Parameter, EditorRequired]
public string Name { get; set; }

This will give an IDE warning to consumers of components that parameters are missing if their parameters are not supplied.

Before .NET 6

Currently, you’ll have to do exactly as you said.


问:
How do I create a code that prints randomly picked letters until it can spell the word I want
What I want to with this code is to be able to randomly pick a letter from the list i've created until it spells out the word coffee. Here is what I have so far.

```<code>import random
def repeat():
    items = ["c", "o", "f", "e"]
    coffee_choice = random.choice(items)

items = ["c", "o", "f", "e"]

coffee_choice = random.choice (items)

print(coffee_choice)
</code>```

UPDATE: I've just realized how the things i said didn't make sense at all so i'll explain it better this time, thanks to those who provided working code unfortunately not what im after. If possible could you provide some explanation in each part of the code on how it works. (trying to learn it!)

Step 1: I need to be able to choose a random letter (done this)

Step 2: Choose letters util the word COFFEE can be spelled out.

Step 3: Display the letters that have been chosen and then state the amount of times/attempts were needed to get all of the letters.

答:
You are free to choose))

```<code>import random
def repeat():
    items = ["c", "o", "f", "e"]
    return random.choice(items)

isNotSpelled = True;
letters_spelled = ""
while isNotSpelled:
    letters_spelled+=repeat()
    length = len(letters_spelled)
    if length>=6:
        if(letters_spelled[length-6:length])=="coffee":
            isNotSpelled = False;
print(len(letters_spelled))
</code>```

The output is the number of spelled letters (attempts) until "coffee" appears

```<code>1434
</code>```

Body:
What I want to with this code is to be able to randomly pick a letter from the list i've created until it spells out the word coffee. Here is what I have so far.

import random
def repeat():
    items = ["c", "o", "f", "e"]
    coffee_choice = random.choice(items)

items = ["c", "o", "f", "e"]

coffee_choice = random.choice (items)

print(coffee_choice)

UPDATE: I've just realized how the things i said didn't make sense at all so i'll explain it better this time, thanks to those who provided working code unfortunately not what im after. If possible could you provide some explanation in each part of the code on how it works. (trying to learn it!)

Step 1: I need to be able to choose a random letter (done this)

Step 2: Choose letters util the word COFFEE can be spelled out.

Step 3: Display the letters that have been chosen and then state the amount of times/attempts were needed to get all of the letters.

Body:
You are free to choose))

import random
def repeat():
    items = ["c", "o", "f", "e"]
    return random.choice(items)

isNotSpelled = True;
letters_spelled = ""
while isNotSpelled:
    letters_spelled+=repeat()
    length = len(letters_spelled)
    if length>=6:
        if(letters_spelled[length-6:length])=="coffee":
            isNotSpelled = False;
print(len(letters_spelled))

The output is the number of spelled letters (attempts) until "coffee" appears

1434


问:
Delete item for todo app in with $emit 2 level up or 1 level up?
I have 3 .vue here: App.vue (default), Todos.vue and Todoitem.vue. I am following the tutorial from https://www.youtube.com/watch?v=Wy9q22isx3U&t=2458. May I know why the author in TodoItem.vue emit id two level up to App.vue to perform the method to delete? Is it best practice or better coding style? Is it easier to just go up one level for Todos.vue to do the same? Below is my one level up approach for any comment.

Below is my TodoItem.vue code

<template>

      <input type="checkbox" v-on:change="markComplete" />
      {{todoObj.title}}
      <button @click="$emit('del-todo',todoObj.id)" class="del">x</button>

</template>

```
</div>
</div>
</p>

<p>Below is my <code>Todo.vue</code> code</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><template>
  <div>
    <h1>Todo List2</h1>
    <!-- :key= and v-bind:key= are exactly the same. -->
    <!-- v-bind. Shorthand: : -->
    <div v-for="todo in ptodos" :key="todo.id">
      <!-- Define todoObj here which to be used in the child component, TodoItem -->
      <MyTodoItem v-bind:todoObj="todo" v-on:del-todo="deleteTodo" />
      <!-- del-todo is from the child. child goes up to parent and then to grandparent (App.vue) -->
    </div>
  </div>
</template>

<script>
import MyTodoItem from "./TodoItem.vue";

export default {
  name: "Todos",
  components: {
    MyTodoItem
  },
  props: ["ptodos"],

  methods: {
    deleteTodo(id) {
      this.ptodos = this.ptodos.filter(todo => todo.id !== id);
    }
  }
};
</script>

<style scoped>
</style></code>```

Below is my App.vue code

<template>
  <MyToDos v-bind:ptodos="todos" />
</template>

```

答:
If you can do it with one level up it's better. To have multiple props on each child can be a bad practice called prop drilling.

Vuex is a good alternative to avoid to get props nested.

Body:
I have 3 .vue here: App.vue (default), Todos.vue and Todoitem.vue. I am following the tutorial from https://www.youtube.com/watch?v=Wy9q22isx3U&t=2458. May I know why the author in TodoItem.vue emit id two level up to App.vue to perform the method to delete? Is it best practice or better coding style? Is it easier to just go up one level for Todos.vue to do the same? Below is my one level up approach for any comment.

Below is my TodoItem.vue code

<template>

      <input type="checkbox" v-on:change="markComplete" />
      {{todoObj.title}}
      <button @click="$emit('del-todo',todoObj.id)" class="del">x</button>

</template>

Below is my Todo.vue code

<template>

Todo List2

      <MyTodoItem v-bind:todoObj="todo" v-on:del-todo="deleteTodo" />

</template>

Below is my App.vue code

<template>
  <MyToDos v-bind:ptodos="todos" />
</template>


问:
Map a nested DTO object to a single item list using mapstruct
I have a DTO that with a nested object that I need to convert into a list.

Here's the general idea (in Kotlin):

DTO (source):

class PersonDto {
    var name: NameDto,
    var otherField: String
}
```

<p>Target:</p>

<pre class="lang-kotlin prettyprint-override"><code>class Person {
    var name: List<Name>,
    var otherField: String
}
</code>```

Where name in target should have just one item: the converted NameDto.

I know I can do something like this:

```<code>fun nameDtoToNameList(nameDto: NameDto) : List<Name> {
     // a bunch of manual code to do the conversion
}
</code>```

but I would love to know if it's possible to do the conversion automatically.

Ideally there would be a solution that could use a nameDtoToName function that would be implemented in a NameMapper interface.

I've been trying to figure out how to do this for hours and haven't gotten anywhere. Any help would be much appreciated.

答:
you can specify @Mapping on the field and set the mapping to name.get(0).

refer this link for syntax : https://mapstruct.org/documentation/dev/reference/html/#basic-mappings

Body:
I have a DTO that with a nested object that I need to convert into a list.

Here's the general idea (in Kotlin):

DTO (source):

class PersonDto {
    var name: NameDto,
    var otherField: String
}

Target:

class Person {
    var name: List<Name>,
    var otherField: String
}

Where name in target should have just one item: the converted NameDto.

I know I can do something like this:

fun nameDtoToNameList(nameDto: NameDto) : List<Name> {
     // a bunch of manual code to do the conversion
}

but I would love to know if it's possible to do the conversion automatically.

Ideally there would be a solution that could use a nameDtoToName function that would be implemented in a NameMapper interface.

I've been trying to figure out how to do this for hours and haven't gotten anywhere. Any help would be much appreciated.


问:
flex-direction column not responsive
I am facing a problem with flex-direction: column on responsive mode. When I write flex-direction: column  to .container its not wrapping to responsive like flex-direction: row, it's going outside of the layout. How to fix that?

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

       <div class="box">First Name Man</div>
              <div class="box">First Name Man</div>
       <div class="box">First Name Man</div>
       <div class="box">First Name Man</div>

     </div>
   </div>
</code>```

```<code>.content {
  width: 100%;
  min-height: 800px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  flex-wrap: wrap;
  background-color: whitesmoke;
}

.container {
  width: 100%;
  min-height: 500px;
   display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  flex-wrap: wrap;

}

.box {
  width:700px;
  margin: 10px;
  color:white;
  min-height: 70px;

  display: flex;
  align-items: center;
  box-shadow: inset 0 2px 4px 0 rgba(0, 0, 0, 0.06);

  justify-content: space-around;
  background-color: indigo;
  flex-direction: column;
  flex-wrap: wrap;
}
</code>```

答: You have a fixed width setting for .box (700px). Change that to width: calc(100% - 20px) (i.e. full width minus 20px for the margin left and right) in a media query, then it will work as desired.

Title: flex-direction column not responsive

Body:
I am facing a problem with flex-direction: column on responsive mode. When I write flex-direction: column  to .container its not wrapping to responsive like flex-direction: row, it's going outside of the layout. How to fix that?

First Name Man

First Name Man

First Name Man

First Name Man

.content {
  width: 100%;
  min-height: 800px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  flex-wrap: wrap;
  background-color: whitesmoke;
}

.container {
  width: 100%;
  min-height: 500px;
   display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  flex-wrap: wrap;

}

.box {
  width:700px;
  margin: 10px;
  color:white;
  min-height: 70px;

  display: flex;
  align-items: center;
  box-shadow: inset 0 2px 4px 0 rgba(0, 0, 0, 0.06);

  justify-content: space-around;
  background-color: indigo;
  flex-direction: column;
  flex-wrap: wrap;
}


问:
Searchfield to search for specific planets
I tried adding a search field to search for planets.
Can someone help me to fix this please?

The error I get is this:
    TypeError: Cannot read property 'state' of undefined
    handleChange
    C:/Users/charl/Desktop/IRONHACK/Paperbox/paperbox/src/pages/Home.js:29
      26 |    }
      27 |
      28 |    handleChange(e){ // eslint-disable-next-line

29 |        const planetssearchlist = this.state.planets.filter(planet => {
           | ^  30 |             if(planet.name){
        31 |                if(planet.name.toLowerCase().includes(e.target.value.toLowerCase())){
        32 |                    return true

```<code>import React, { PureComponent } from 'react'
import axios from "axios";

class Home extends PureComponent {
    constructor(props) {
        super(props)

        this.state = {
            planets: []
        }
    }

    componentDidMount(){
        axios({
            method: "GET",
            url: "https://swapi.dev/api/planets/"
        })
        .then(response => {
            console.log(response)
            let planetslist = response.data.results;
            this.setState({planets: planetslist})
        })
        .catch(error => {
            console.log("You've made an error with the planets load charles: ",error)
        })
    }

    handleChange(e){ // eslint-disable-next-line
        const planetssearchlist = this.state.planets.filter(planet => {
             if(planet.name){
                if(planet.name.toLowerCase().includes(e.target.value.toLowerCase())){
                    return true
                }
            }
            this.setState({
                planets:planetssearchlist
            })
        })
    }

    render() {
        return (

        <div>
            <h1>Star Wars Planets</h1>

            <form>
                <input placeholder="searchbar" type="text" onChange={this.handleChange}></input>
            </form>

            {
                this.state.planets.map((planet,i) => (
                        <p key={i}>{planet.name}</p>
                ))
            }

        </div>

        )
    }
}

export default Home
</code>```

答:
It is related to closure and this keyword in javascript, you define handleChange in Home component but you pass it as a callback for onClick, it is actually not called in Home ==> this is not context of Home any more.
There is 4 way you can solve this.
Using arrow function to define the function (I like this way):

```<code>handleChange = (event) => {}
</code>```

Using array function in render:

// other code
<form>
   <input placeholder="searchbar" type="text" onChange={(event) => this.handleChange(event)}></input>
</form>
// other code```
</div>
</div>
</p>

<p>Bind the function in constructor</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// Other code
constructor(props) {
        super(props)

        this.state = {
            planets: []
        }
        this.handleChange = this.handleChange.bind(this)
    }
// Other code</code>```

Binding function in render:

// other code
<form>
   <input placeholder="searchbar" type="text" onChange={this.handleChange(this)}></input>
</form>
// other code```
</div>
</div>
</p>

<p>Actually there is one more way that using <code>React.createClass</code>, but I'll not mentioned here because it is not JSX way.</p>

<p>ReferenceError: Cannot access 'planetssearchlist' before initialization: Because you are using it inside of this.state.planets.filter where the planetssearchlist have not done initialised yet , bring it outside</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>handleChange(e){ // eslint-disable-next-line
    const planetssearchlist = this.state.planets.filter(planet => {
         if(planet.name){
            if(planet.name.toLowerCase().includes(e.target.value.toLowerCase())){
                return true
            }
        }})
    // This is need to be outside of this.state.planets.filter
    this.setState({
      planets:planetssearchlist
    })
  }</code>```

Body:
I tried adding a search field to search for planets.
Can someone help me to fix this please?

The error I get is this:
    TypeError: Cannot read property 'state' of undefined
    handleChange
    C:/Users/charl/Desktop/IRONHACK/Paperbox/paperbox/src/pages/Home.js:29
      26 |    }
      27 |
      28 |    handleChange(e){ // eslint-disable-next-line

29 |        const planetssearchlist = this.state.planets.filter(planet => {
           | ^  30 |             if(planet.name){
        31 |                if(planet.name.toLowerCase().includes(e.target.value.toLowerCase())){
        32 |                    return true

import React, { PureComponent } from 'react'
import axios from "axios";

class Home extends PureComponent {
    constructor(props) {
        super(props)

        this.state = {
            planets: []
        }
    }

    componentDidMount(){
        axios({
            method: "GET",
            url: "https://swapi.dev/api/planets/"
        })
        .then(response => {
            console.log(response)
            let planetslist = response.data.results;
            this.setState({planets: planetslist})
        })
        .catch(error => {
            console.log("You've made an error with the planets load charles: ",error)
        })
    }

    handleChange(e){ // eslint-disable-next-line
        const planetssearchlist = this.state.planets.filter(planet => {
             if(planet.name){
                if(planet.name.toLowerCase().includes(e.target.value.toLowerCase())){
                    return true
                }
            }
            this.setState({
                planets:planetssearchlist
            })
        })
    }

    render() {
        return (

Star Wars Planets

            <form>
                <input placeholder="searchbar" type="text" onChange={this.handleChange}></input>
            </form>

            {
                this.state.planets.map((planet,i) => (

{planet.name}

                ))
            }

        )
    }
}

export default Home

Body:
It is related to closure and this keyword in javascript, you define handleChange in Home component but you pass it as a callback for onClick, it is actually not called in Home ==> this is not context of Home any more.
There is 4 way you can solve this.
Using arrow function to define the function (I like this way):

handleChange = (event) => {}

Using array function in render:

// other code
<form>
   <input placeholder="searchbar" type="text" onChange={(event) => this.handleChange(event)}></input>
</form>
// other code

Bind the function in constructor

// Other code
constructor(props) {
        super(props)

        this.state = {
            planets: []
        }
        this.handleChange = this.handleChange.bind(this)
    }
// Other code

Binding function in render:

// other code
<form>
   <input placeholder="searchbar" type="text" onChange={this.handleChange(this)}></input>
</form>
// other code

Actually there is one more way that using React.createClass, but I'll not mentioned here because it is not JSX way.

ReferenceError: Cannot access 'planetssearchlist' before initialization: Because you are using it inside of this.state.planets.filter where the planetssearchlist have not done initialised yet , bring it outside

handleChange(e){ // eslint-disable-next-line
    const planetssearchlist = this.state.planets.filter(planet => {
         if(planet.name){
            if(planet.name.toLowerCase().includes(e.target.value.toLowerCase())){
                return true
            }
        }})
    // This is need to be outside of this.state.planets.filter
    this.setState({
      planets:planetssearchlist
    })
  }