问:
How to manually query posts title, content and image attachment thumbnail?
I am trying to manually query from an external php file the wordpress database and I want to extract the last 3 posts with: title, content, last (or first) image, and for that image, from wp_postmeta I want to get the thumbnail url.

I managed to get the title, content, image id, but I couldn't figure it out how to add another join for getting image thumbnail. This is what I have:

```<code>SELECT a.post_title title, max(c.guid) img_url, a.ID id
FROM wp_posts a

LEFT JOIN
(select post_parent, max(post_date_gmt) as latest_image_date from wp_posts
where post_type='attachment' GROUP BY post_parent) b
on a.id=b.post_parent

LEFT JOIN wp_posts c
on c.post_parent=a.id
and c.post_type='attachment'
and b.latest_image_date = c.post_date_gmt where c.guid IS NOT NULL

GROUP BY a.post_title ORDER BY a.ID
</code>```

The image thumbnail is in wp_postmeta (meta_id, post_id, meta_key, meta_value) table, looking like this: 58435, 6711, _wp_attachment_metadata, a:6:{s:5:"width";s:4:"1024";s:6:"height";s:3:"683"...

I could see I get the image id in c.id and all it needs is another JOIN to also get data from wp_postmeta for the field where meta_key="_wp_attachment_metadata" and post_id=c.id.

Can anyone help me with completing the query? Thanks!

答:
I know this is an old post, but here to help future answer seekers

Update the query as needed. This current query will select post that have attachments. It returns the attachment ID and guid, the post ID and title along with the category name and term_id.

```<code>SELECT DISTINCT p.ID,p.post_title, a.ID as attach_id, a.guid, t.name, t.term_id FROM $wpdb->posts as a
LEFT JOIN $wpdb->posts as p on p.ID = a.post_parent
AND a.post_type = 'attachment' AND a.post_mime_type = 'image/png'

JOIN $wpdb->term_relationships as tr on tr.object_id = p.ID
JOIN $wpdb->terms as t on t.term_id = tr.term_taxonomy_id
JOIN $wpdb->term_taxonomy as tt on tt.term_id = t.term_id
AND tt.taxonomy = 'category'

AND p.post_type = 'post'
AND p.post_status = 'publish';
</code>```

Body:
I am trying to manually query from an external php file the wordpress database and I want to extract the last 3 posts with: title, content, last (or first) image, and for that image, from wp_postmeta I want to get the thumbnail url.

I managed to get the title, content, image id, but I couldn't figure it out how to add another join for getting image thumbnail. This is what I have:

SELECT a.post_title title, max(c.guid) img_url, a.ID id
FROM wp_posts a

LEFT JOIN
(select post_parent, max(post_date_gmt) as latest_image_date from wp_posts
where post_type='attachment' GROUP BY post_parent) b
on a.id=b.post_parent

LEFT JOIN wp_posts c
on c.post_parent=a.id
and c.post_type='attachment'
and b.latest_image_date = c.post_date_gmt where c.guid IS NOT NULL

GROUP BY a.post_title ORDER BY a.ID

The image thumbnail is in wp_postmeta (meta_id, post_id, meta_key, meta_value) table, looking like this: 58435, 6711, _wp_attachment_metadata, a:6:{s:5:"width";s:4:"1024";s:6:"height";s:3:"683"...

I could see I get the image id in c.id and all it needs is another JOIN to also get data from wp_postmeta for the field where meta_key="_wp_attachment_metadata" and post_id=c.id.

Can anyone help me with completing the query? Thanks!

Body:
I know this is an old post, but here to help future answer seekers

Update the query as needed. This current query will select post that have attachments. It returns the attachment ID and guid, the post ID and title along with the category name and term_id.

SELECT DISTINCT p.ID,p.post_title, a.ID as attach_id, a.guid, t.name, t.term_id FROM $wpdb->posts as a
LEFT JOIN $wpdb->posts as p on p.ID = a.post_parent
AND a.post_type = 'attachment' AND a.post_mime_type = 'image/png'

JOIN $wpdb->term_relationships as tr on tr.object_id = p.ID
JOIN $wpdb->terms as t on t.term_id = tr.term_taxonomy_id
JOIN $wpdb->term_taxonomy as tt on tt.term_id = t.term_id
AND tt.taxonomy = 'category'

AND p.post_type = 'post'
AND p.post_status = 'publish';


来源: stackexchange

问:
How to parse attributes which contains dots with --format for docker events output?
I am trying to parse docker events output and format it using the --format argument.
It works for basic attributes, however I can't manage to use attributes containing dots, like those from Docker Swarm.

Here is an example:

$ docker events --since=5m --until=1s --filter type=container --format '{{ json . }}'
```

<pre class="lang-json prettyprint-override"><code>{
  "status": "oom",
  "id": "23916078dbf062b02edf36ae1de3cdd6d439d11cad29acc72daffcc1ac8981b9",
  "from": "(redacted)",
  "Type": "container",
  "Action": "oom",
  "Actor": {
    "ID": "23916078dbf062b02edf36ae1de3cdd6d439d11cad29acc72daffcc1ac8981b9",
    "Attributes": {
      "com.docker.stack.namespace": "beta-client",
      "com.docker.swarm.node.id": "woxyp548c8yat5nizwzmar6ia",
      "com.docker.swarm.service.id": "5j72edfv4sda554gqu0paaxu2",
      "com.docker.swarm.service.name": "beta-client_task",
      "com.docker.swarm.task": "",
      "com.docker.swarm.task.id": "ib57fy6em8hz1cfbrua518r2i",
      "com.docker.swarm.task.name": "beta-client_task.1.ib57fy6em8hz1cfbrua518r2i",
      "image": "(redacted)",
      "name": "beta-client_task.1.ib57fy6em8hz1cfbrua518r2i"
    }
  },
  "scope": "local",
  "time": 1559032467,
  "timeNano": 1559032467083181300
}
</code>```

I would like to fetch the com.docker.stack.namespace attribute, in Actor.Attributes (without using an external tool like jq).

But the dots in the attribute name prevents me from accessing this attribute, and quoting it doesn't seem to work:

$ docker events --since=5m --until=1s --filter type=container --format '{{ .Actor.Attributes."com.docker.stack.namespace" }}'
```

<pre class="lang-bash prettyprint-override"><code>Error parsing format: template: :1: bad character U+0022 '"'
</code>```

Thank you for your help!

答:
You can not use . if parameter name also have . in it. Try index, something like follows:

```<code>--format '{{ index .Actor.Attributes "com.docker.stack.namespace" }}'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to parse docker events output and format it using the --format argument.
It works for basic attributes, however I can't manage to use attributes containing dots, like those from Docker Swarm.

Here is an example:

$ docker events --since=5m --until=1s --filter type=container --format '{{ json . }}'

{
  "status": "oom",
  "id": "23916078dbf062b02edf36ae1de3cdd6d439d11cad29acc72daffcc1ac8981b9",
  "from": "(redacted)",
  "Type": "container",
  "Action": "oom",
  "Actor": {
    "ID": "23916078dbf062b02edf36ae1de3cdd6d439d11cad29acc72daffcc1ac8981b9",
    "Attributes": {
      "com.docker.stack.namespace": "beta-client",
      "com.docker.swarm.node.id": "woxyp548c8yat5nizwzmar6ia",
      "com.docker.swarm.service.id": "5j72edfv4sda554gqu0paaxu2",
      "com.docker.swarm.service.name": "beta-client_task",
      "com.docker.swarm.task": "",
      "com.docker.swarm.task.id": "ib57fy6em8hz1cfbrua518r2i",
      "com.docker.swarm.task.name": "beta-client_task.1.ib57fy6em8hz1cfbrua518r2i",
      "image": "(redacted)",
      "name": "beta-client_task.1.ib57fy6em8hz1cfbrua518r2i"
    }
  },
  "scope": "local",
  "time": 1559032467,
  "timeNano": 1559032467083181300
}

I would like to fetch the com.docker.stack.namespace attribute, in Actor.Attributes (without using an external tool like jq).

But the dots in the attribute name prevents me from accessing this attribute, and quoting it doesn't seem to work:

$ docker events --since=5m --until=1s --filter type=container --format '{{ .Actor.Attributes."com.docker.stack.namespace" }}'

Error parsing format: template: :1: bad character U+0022 '"'

Thank you for your help!

Body:
You can not use . if parameter name also have . in it. Try index, something like follows:

--format '{{ index .Actor.Attributes "com.docker.stack.namespace" }}'


问:
Pygame.error: Video system not initialized, python.display.update error
I have a simple pygame text print code.
When it is run, it opens the pygame window and then crashes.

I have checked multiple times if i haven't missed anything, but I can't find anything which is incorrect.

The code

import pygame
from pygame.locals import *

def draw():
    pygame.init();
    screen=pygame.display.set_mode((1600, 900))
    pygame.display.set_caption("Damn")
    font = pygame.font.Font('freesansbold.ttf', 32)
    text = font.render('0', True, (0, 0, 0))
    textRect=text.get_rect()
    textRect.center=(800, 450)

    while True:
        screen.fill((255, 255, 255))
        screen.blit(text, textRect)
        for event in pygame.event.get():
            if event.type -- pygame.QUIT:
                pygame.quit()
            pygame.display.update()

if __name__=="__main__":
    draw();

```

<p><strong>The error</strong></p>

```
Traceback (most recent call last):
  File "C:/Users/Ienovo/PycharmProjects/untitled/Base.py", line 23, in <module>
    draw();
  File "C:/Users/Ienovo/PycharmProjects/untitled/Base.py", line 20, in draw
    pygame.display.update()
pygame.error: video system not initialized

```

The expected result should be the '0' being print at the center.

答:
The condition:

```<code>if event.type -- pygame.QUIT:
    pygame.quit()
</code>```

evaluates always True.

It has to be:

if event.type == pygame.QUIT:
    pygame.quit()
```

<p>The equality operator is <code>==</code>. See Operators.<br>
The meaning of  <code>event.type -- pygame.QUIT</code> is <code>event.type</code> minus <code>-pygame.QUIT</code>.</p>

<p><code>pygame.quit()</code> uninitializes all pygame modules and causes the code to crashes at the next instruction which tries to access a pygame module.</p>

<hr>

<p>The update of the display <code>pygame.display.update()</code> should be done once in the scope of the main loop rather than the event loop:</p>

<pre class="lang-py prettyprint-override"><code>def draw():

    # [...]

    run = True
    while True:
        screen.fill((255, 255, 255))
        screen.blit(text, textRect)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

        # <---
        pygame.display.update()

    pygame.quit()
</code>```

Body:
I have a simple pygame text print code.
When it is run, it opens the pygame window and then crashes.

I have checked multiple times if i haven't missed anything, but I can't find anything which is incorrect.

The code

import pygame
from pygame.locals import *

def draw():
    pygame.init();
    screen=pygame.display.set_mode((1600, 900))
    pygame.display.set_caption("Damn")
    font = pygame.font.Font('freesansbold.ttf', 32)
    text = font.render('0', True, (0, 0, 0))
    textRect=text.get_rect()
    textRect.center=(800, 450)

    while True:
        screen.fill((255, 255, 255))
        screen.blit(text, textRect)
        for event in pygame.event.get():
            if event.type -- pygame.QUIT:
                pygame.quit()
            pygame.display.update()

if __name__=="__main__":
    draw();

The error

Traceback (most recent call last):
  File "C:/Users/Ienovo/PycharmProjects/untitled/Base.py", line 23, in <module>
    draw();
  File "C:/Users/Ienovo/PycharmProjects/untitled/Base.py", line 20, in draw
    pygame.display.update()
pygame.error: video system not initialized

The expected result should be the '0' being print at the center.

Body:
The condition:

if event.type -- pygame.QUIT:
    pygame.quit()

evaluates always True.

It has to be:

if event.type == pygame.QUIT:
    pygame.quit()

The equality operator is ==. See Operators.

The meaning of  event.type -- pygame.QUIT is event.type minus -pygame.QUIT.

pygame.quit() uninitializes all pygame modules and causes the code to crashes at the next instruction which tries to access a pygame module.

The update of the display pygame.display.update() should be done once in the scope of the main loop rather than the event loop:

def draw():

    # [...]

    run = True
    while True:
        screen.fill((255, 255, 255))
        screen.blit(text, textRect)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

        # <---
        pygame.display.update()

    pygame.quit()


问:
how to make bouncing ball application
I have been following http://www.bit-101.com/blog/?p=1798 tutorial to make bouncing ball app.
But what i want to do is make 20-30 balls which can be dragged anywhere in the iphone screen on user touch and also can be dropped anywhere in the screen.So please can anyone suggest me on this -- how to do this in i phone not using cocos2d please help me out or give me some links or useful information any help will be appreciated.....</p>

答:
As you are working in mentioned code, you can write touchesMoved method where you will handle the position of ballView.

```<code>- (void)touchesMoved: (NSSet *)touches withEvent:(UIEvent *)event {
   UITouch *anyTouch = [touches anyObject];
   [self setCenter:[anyTouch locationInView:[self superView]];
}
</code>```

try this.

or this updated one

```<code>- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{

    if ([touches count] == 1) {
        UITouch *newTouch = [[touches anyObject] locationInView:[self superview]];
        UITouch *lastTouch = [[touches anyObject] previousLocationInView: [self superview]];
        NSLog(@"xxxxxggdfgdfgfdgdfg%f",newTouch.x);
        NSLog(@"yyyyyyggdfgdfgfdgdfg%f",newTouch.y);
        xDif = newTouch.x - lastTouch.x;
        yDif = newTouch.y - lastTouch.y;

        }
        CGAffineTransform translate = CGAffineTransformMakeTranslation(xDif, yDif);
        [self setTransform: CGAffineTransformConcat([self transform], translate)];
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: how to make bouncing ball application

Body:
As you are working in mentioned code, you can write touchesMoved method where you will handle the position of ballView.

- (void)touchesMoved: (NSSet *)touches withEvent:(UIEvent *)event {
   UITouch *anyTouch = [touches anyObject];
   [self setCenter:[anyTouch locationInView:[self superView]];
}

try this.

or this updated one

- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{

    if ([touches count] == 1) {
        UITouch *newTouch = [[touches anyObject] locationInView:[self superview]];
        UITouch *lastTouch = [[touches anyObject] previousLocationInView: [self superview]];
        NSLog(@"xxxxxggdfgdfgfdgdfg%f",newTouch.x);
        NSLog(@"yyyyyyggdfgdfgfdgdfg%f",newTouch.y);
        xDif = newTouch.x - lastTouch.x;
        yDif = newTouch.y - lastTouch.y;

        }
        CGAffineTransform translate = CGAffineTransformMakeTranslation(xDif, yDif);
        [self setTransform: CGAffineTransformConcat([self transform], translate)];
    }


问:
A non-null String must be provided to a Text widget
I'm trying to add the option for the quantity to be adjusted but I get an error saying "A non-null String must be provided to a Text widget"
How do I provide this, to this code?

```<code> trailing: Container(
        height: 60,
        width: 60,
        padding: EdgeInsets.only(left: 10),
        child: Column(
          children: <Widget>[
            new GestureDetector(child: Icon(Icons.arrow_drop_up), onTap: () {}),
            new Text(cart_prod_qty),
            new GestureDetector(child: Icon(Icons.arrow_drop_down), onTap: () {})
          ],
        ),
</code>```

答:
You should check null safe</p>

```<code>Text(cart_prod_qty??'default value'),
</code>```

Body:
I'm trying to add the option for the quantity to be adjusted but I get an error saying "A non-null String must be provided to a Text widget"
How do I provide this, to this code?

 trailing: Container(
        height: 60,
        width: 60,
        padding: EdgeInsets.only(left: 10),
        child: Column(
          children: <Widget>[
            new GestureDetector(child: Icon(Icons.arrow_drop_up), onTap: () {}),
            new Text(cart_prod_qty),
            new GestureDetector(child: Icon(Icons.arrow_drop_down), onTap: () {})
          ],
        ),

Body:
You should check null safe

Text(cart_prod_qty??'default value'),


问:
Looping through an array based on the first index
I have two arrays and I am wanting to loop through a second array to only return arrays whose first element is equal to an element from another array.

```<code> a = [10, 11, 12, 13, 14]
 b = [[9, 23, 45, 67, 56, 23, 54], [10, 8, 52, 30, 15, 47, 109], [11, 81,
 152, 54, 112, 78, 167], [13, 82, 84, 63, 24, 26, 78], [18, 182, 25, 63, 96,
 104, 74]]
</code>```

I have two different arrays, a and b. I would like to find a way to look through each of the sub-arrays(?) within b in which
the first value is equal to the values in array a to create a new array, c.

The result I am looking for is:

```<code>  c = [[10, 8, 52, 30, 15, 47, 109],[11, 81, 152, 54, 112, 78, 167],[13, 82, 84, 63, 24, 26, 78]]
</code>```

Does Python have a tool to do this in a way Excel has MATCH()?

I tried looping in a manner such as:

```<code> for i in a:
      if i in b:
          print (b)
</code>```

But because there are other elements within the array, this way is not working. Any help would be greatly appreciated.

Further explanation of the problem:

a = [5, 6, 7, 9, 12]

I read in a excel file using XLRD (b_csv_data):

```<code> Start  Count   Error   Constant    Result1 Result2 Result3 Result4
 5       41       0       45             23      54      66       19
 5.4     44       1       21             52      35       6       50
 6       16       1       42             95      39       1       13
 6.9     50       1       22             71      86      59       97
 7       38       1       43             50      47      83       67
  8      26       1       29             100     63      15       40
 9       46       0       28             85       9      27       81
 12      43       0       21             74      78      20       85
</code>```

Next, I created a look to read in a select number of rows. For simplicity, this file above only has a few rows. My current file has about 100 rows.

```<code>for r in range (1, 7): #skipping headers and only wanting first few rows to start

     b_raw = b_csv_data.row_values(r)
     b = np.array(b_raw) # I created this b numpy array from the line of code above
</code>```

答:
You are doing it reverse. It is better to loop through the elements of b array and check if it is present in a. If yes then print that element of b. See the answer below.

```<code>a = [10, 11, 12, 13, 14]
b = [[9, 23, 45, 67, 56, 23, 54], [10, 8, 52, 30, 15, 47, 109], [11, 81, 152, 54, 112, 78, 167], [13, 82, 84, 63, 24, 26, 78], [18, 182, 25, 63, 96, 104, 74]]

for bb in b:  # if you want to check only the first element of b is in a
    if bb[0] in a:
            print(bb)

for bb in b:   # if you want to check if any element of b is in a
    for bbb in bb:
        if bbb in a:
            print(bb)
</code>```

Output:

```<code>[10, 8, 52, 30, 15, 47, 109]
[11, 81, 152, 54, 112, 78, 167]
[13, 82, 84, 63, 24, 26, 78]
</code>```

Body:
I have two arrays and I am wanting to loop through a second array to only return arrays whose first element is equal to an element from another array.

 a = [10, 11, 12, 13, 14]
 b = [[9, 23, 45, 67, 56, 23, 54], [10, 8, 52, 30, 15, 47, 109], [11, 81,
 152, 54, 112, 78, 167], [13, 82, 84, 63, 24, 26, 78], [18, 182, 25, 63, 96,
 104, 74]]

I have two different arrays, a and b. I would like to find a way to look through each of the sub-arrays(?) within b in which
the first value is equal to the values in array a to create a new array, c.

The result I am looking for is:

  c = [[10, 8, 52, 30, 15, 47, 109],[11, 81, 152, 54, 112, 78, 167],[13, 82, 84, 63, 24, 26, 78]]

Does Python have a tool to do this in a way Excel has MATCH()?

I tried looping in a manner such as:

 for i in a:
      if i in b:
          print (b)

But because there are other elements within the array, this way is not working. Any help would be greatly appreciated.

Further explanation of the problem:

a = [5, 6, 7, 9, 12]

I read in a excel file using XLRD (b_csv_data):

 Start  Count   Error   Constant    Result1 Result2 Result3 Result4
 5       41       0       45             23      54      66       19
 5.4     44       1       21             52      35       6       50
 6       16       1       42             95      39       1       13
 6.9     50       1       22             71      86      59       97
 7       38       1       43             50      47      83       67
  8      26       1       29             100     63      15       40
 9       46       0       28             85       9      27       81
 12      43       0       21             74      78      20       85

Next, I created a look to read in a select number of rows. For simplicity, this file above only has a few rows. My current file has about 100 rows.

for r in range (1, 7): #skipping headers and only wanting first few rows to start

     b_raw = b_csv_data.row_values(r)
     b = np.array(b_raw) # I created this b numpy array from the line of code above

Body:
You are doing it reverse. It is better to loop through the elements of b array and check if it is present in a. If yes then print that element of b. See the answer below.

a = [10, 11, 12, 13, 14]
b = [[9, 23, 45, 67, 56, 23, 54], [10, 8, 52, 30, 15, 47, 109], [11, 81, 152, 54, 112, 78, 167], [13, 82, 84, 63, 24, 26, 78], [18, 182, 25, 63, 96, 104, 74]]

for bb in b:  # if you want to check only the first element of b is in a
    if bb[0] in a:
            print(bb)

for bb in b:   # if you want to check if any element of b is in a
    for bbb in bb:
        if bbb in a:
            print(bb)

Output:

[10, 8, 52, 30, 15, 47, 109]
[11, 81, 152, 54, 112, 78, 167]
[13, 82, 84, 63, 24, 26, 78]


问:
Node.js - Parsing JSON data into PUG templates
I am trying to parse some JSON data into some elements called homeCards. I use Axios to request the JSON data and have a for loop to iterate through it. I store the fields I want in the title and description variables and pass these variables to the homeCards. My issue is that my title and description variables live inside my axios function, and when I try to assign these values to homeCards, which is declared outside its scope, it can't find them. If I move my homeCard declaration in the Axios function, then I won't be able to call the homeCards in the render function at the bottom of the file. How can I fix this problem? Is there a much easier way to do this?

```<code>var express = require('express');
var router = express.Router();
var title = "title"
var description = "description"

const axios = require('axios');

axios({
  url: "https://api-v3.igdb.com/games",
  method: 'GET',
  headers: {
      'Accept': 'application/json',
      'user-key': 'user-key'
  },
  data: "fields name,summary,popularity;sort popularity desc;limit 4;"
})
  .then(response => {
      let r = response.data;
      for (i=0; i<r.length; ++i){
          title = r[i].name;
          description = r[i].summary;
          console.log(title, description);
      }
    })
  .catch(err => {
      console.error(err);
  });

var homeCards = [
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        ]

/* GET home page. */
router.get('/', (req, res, next) => {
  res.render('index', { pageId: 'index',
                        title: 'Homepage',
                        cards: homeCards
    });

});
/*GET consoles page. */
router.get('/consoles', (req, res, next) => {
    res.render('consoles', { pageId:'consoles',
                             title: 'Consoles', });
});
/*GET about page. */
router.get('/about', (req, res, next) => {
    res.render('about', { pageId:'abuot',
                          title: 'About' });
});

module.exports = router;
</code>```

If I move the relevant code in the router.get calls like so:

```<code>    /* GET home page. */
router.get('/', (req, res, next) => {
  res.render('index', { pageId: 'index',
                        title: 'Homepage',
                        cards: homeCards
    });

  const axios = require('axios');

  axios({
    url: "https://api-v3.igdb.com/games",
    method: 'GET',
    headers: {
        'Accept': 'application/json',
        'user-key': 'feaa948461a62d2965098834275aaa2f'
    },
    data: "fields name,summary,popularity;sort popularity desc;limit 4;"
  })
    .then(response => {
        let r = response.data;
        for (i=0; i<r.length; ++i){
            title = r[i].name;
            description = r[i].summary;
            console.log(title, description);
        }
      })
    .catch(err => {
        console.error(err);
    });
    var homeCards = [
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        ]

});
</code>```

I get the following error: index.pug:19 17| div(class="card-deck") 18| if pageId === 'index' > 19| each item in cards 20| +horizontalCard(item.title,item.imgSrc, item.imgAlt, item.link, item.description) Cannot read property 'length' of undefined.
Here is the pug file in question

```<code> //- views/index.pug
extends layout

mixin horizontalCard(title, imgSrc, imgAlt, link, description)
    div(class="card bg-secondary mb-3" style="min-width: 230px; max-width: 540px;")
        img(src=imgSrc class="card-img" alt=imgAlt)
        div(class="card-body")
            h5(class="card-title")= title
            p(class="card-text")= description
            p(class="card-text")
                small(class="text-muted")
                a(rel="noreferrer noopener" href=link target="_blank") Visit Website

block content
    h1= title
    P Most Popular Games
    div(class="card-deck")
        if pageId === 'index'
            each item in cards
                +horizontalCard(item.title,item.imgSrc, item.imgAlt, item.link, item.description)
</code>```

If I move the router.get calls inside the .then(response) block like so:

```<code>    axios({
  url: "https://api-v3.igdb.com/games",
  method: 'GET',
  headers: {
      'Accept': 'application/json',
      'user-key': 'feaa948461a62d2965098834275aaa2f'
  },
  data: "fields name,summary,popularity;sort popularity desc;limit 4;"
})
  .then(response => {
      /* GET home page. */
    router.get('/', (req, res, next) => {
      res.render('index', { pageId: 'index',
                        title: 'Homepage',
                        cards: homeCards
        });

    });
    var homeCards = [
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        ]
    let r = response.data;
    for (i=0; i<r.length; ++i){
        var title = r[i].name;
        var description = r[i].summary;
        console.log(title, description);
      }
    })
  .catch(err => {
      console.error(err);
  });
</code>```

The homecards display nothing

答:
In your code, the axios({...}).then() block is executed after the main code (assignment to homeCards and calls to router.get) are completed. This is how Node.js (and JavaScript in general) asynchronous calls work, by design: axios makes network call, so it returns its result as a promise, which gets resolved after the caller function code is executed.

Moving everything, including router.get calls, into an axios .then handler is one option. Another option, if you target Node.js 8+, is to use async/await pattern to write asynchronous code in a synchronous way. This is essentially the same as putting all logic in the axios .then handler, but looks much better.

async function init() {
  const response = await axios({...});
  homeCards = ...;
  router.get(...);
  ...
}

init().catch(err => {
  console.error(err);
});
```

Body:
I am trying to parse some JSON data into some elements called homeCards. I use Axios to request the JSON data and have a for loop to iterate through it. I store the fields I want in the title and description variables and pass these variables to the homeCards. My issue is that my title and description variables live inside my axios function, and when I try to assign these values to homeCards, which is declared outside its scope, it can't find them. If I move my homeCard declaration in the Axios function, then I won't be able to call the homeCards in the render function at the bottom of the file. How can I fix this problem? Is there a much easier way to do this?

var express = require('express');
var router = express.Router();
var title = "title"
var description = "description"

const axios = require('axios');

axios({
  url: "https://api-v3.igdb.com/games",
  method: 'GET',
  headers: {
      'Accept': 'application/json',
      'user-key': 'user-key'
  },
  data: "fields name,summary,popularity;sort popularity desc;limit 4;"
})
  .then(response => {
      let r = response.data;
      for (i=0; i<r.length; ++i){
          title = r[i].name;
          description = r[i].summary;
          console.log(title, description);
      }
    })
  .catch(err => {
      console.error(err);
  });

var homeCards = [
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        ]

/* GET home page. */
router.get('/', (req, res, next) => {
  res.render('index', { pageId: 'index',
                        title: 'Homepage',
                        cards: homeCards
    });

});
/*GET consoles page. */
router.get('/consoles', (req, res, next) => {
    res.render('consoles', { pageId:'consoles',
                             title: 'Consoles', });
});
/*GET about page. */
router.get('/about', (req, res, next) => {
    res.render('about', { pageId:'abuot',
                          title: 'About' });
});

module.exports = router;

If I move the relevant code in the router.get calls like so:

    /* GET home page. */
router.get('/', (req, res, next) => {
  res.render('index', { pageId: 'index',
                        title: 'Homepage',
                        cards: homeCards
    });

  const axios = require('axios');

  axios({
    url: "https://api-v3.igdb.com/games",
    method: 'GET',
    headers: {
        'Accept': 'application/json',
        'user-key': 'feaa948461a62d2965098834275aaa2f'
    },
    data: "fields name,summary,popularity;sort popularity desc;limit 4;"
  })
    .then(response => {
        let r = response.data;
        for (i=0; i<r.length; ++i){
            title = r[i].name;
            description = r[i].summary;
            console.log(title, description);
        }
      })
    .catch(err => {
        console.error(err);
    });
    var homeCards = [
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        ]

});

I get the following error: index.pug:19 17| div(class="card-deck") 18| if pageId === 'index' > 19| each item in cards 20| +horizontalCard(item.title,item.imgSrc, item.imgAlt, item.link, item.description) Cannot read property 'length' of undefined.
Here is the pug file in question

 //- views/index.pug
extends layout

mixin horizontalCard(title, imgSrc, imgAlt, link, description)
    div(class="card bg-secondary mb-3" style="min-width: 230px; max-width: 540px;")
        img(src=imgSrc class="card-img" alt=imgAlt)
        div(class="card-body")
            h5(class="card-title")= title
            p(class="card-text")= description
            p(class="card-text")
                small(class="text-muted")
                a(rel="noreferrer noopener" href=link target="_blank") Visit Website

block content
    h1= title
    P Most Popular Games
    div(class="card-deck")
        if pageId === 'index'
            each item in cards
                +horizontalCard(item.title,item.imgSrc, item.imgAlt, item.link, item.description)

If I move the router.get calls inside the .then(response) block like so:

    axios({
  url: "https://api-v3.igdb.com/games",
  method: 'GET',
  headers: {
      'Accept': 'application/json',
      'user-key': 'feaa948461a62d2965098834275aaa2f'
  },
  data: "fields name,summary,popularity;sort popularity desc;limit 4;"
})
  .then(response => {
      /* GET home page. */
    router.get('/', (req, res, next) => {
      res.render('index', { pageId: 'index',
                        title: 'Homepage',
                        cards: homeCards
        });

    });
    var homeCards = [
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        {
          title: title,
          description: description,
        },
        ]
    let r = response.data;
    for (i=0; i<r.length; ++i){
        var title = r[i].name;
        var description = r[i].summary;
        console.log(title, description);
      }
    })
  .catch(err => {
      console.error(err);
  });

The homecards display nothing


问:
Redeclaration of variable
When I run Setup() I expect to see a 't' in my console, followed by multiple 'x' characters. However it returns just multiple 't' chars. It's like my retrn never gets overwrited. Please see codesample below:

```<code>class Returner
{
    public:
        Returner(){}

        char test()
        {
        }
};

class TReturner: public Returner
{
    public:
        TReturner(){}

        char test()
        {
            return 't';
        }
};

class XReturner: public Returner
{
    public:
        XReturner(){}

        char test()
        {
            return 'x';
        }
};

void setup()
{
    Serial.begin(9600);

    TReturner t = TReturner();
    Returner * retrn = &t;

    while(1)
    {
        Serial.print( retrn.test());

        XReturner x = XReturner();
        retrn = &x;

        _delay_ms(500);
    }
}
</code>```

答:
setup() will be called once by the bootloader. (do not create an infinite loop inside of it)

You should define a loop() function, it too will be called by the bootloader an 'infinite' number of times.

Title: Redeclaration of variable

Body:
When I run Setup() I expect to see a 't' in my console, followed by multiple 'x' characters. However it returns just multiple 't' chars. It's like my retrn never gets overwrited. Please see codesample below:

class Returner
{
    public:
        Returner(){}

        char test()
        {
        }
};

class TReturner: public Returner
{
    public:
        TReturner(){}

        char test()
        {
            return 't';
        }
};

class XReturner: public Returner
{
    public:
        XReturner(){}

        char test()
        {
            return 'x';
        }
};

void setup()
{
    Serial.begin(9600);

    TReturner t = TReturner();
    Returner * retrn = &t;

    while(1)
    {
        Serial.print( retrn.test());

        XReturner x = XReturner();
        retrn = &x;

        _delay_ms(500);
    }
}


问:
Controlling dynamic vertex attributes using networkDynamic and/or ndtv
I am looking at how government agencies change over time. The plan is to use the ndtv package to visualise changes. I have an nodelist that lists vertex ids, agency name, node onset and node terminus:

```<code>nodelist <- read.csv("https://github.com/aterhorst/data/raw/master/nodelist.csv", header=T, stringsAsFactors = F)
</code>```

and an edgelist showing onset, terminus of edges:

```<code>edgelist <- read.csv("https://github.com/aterhorst/data/raw/master/edgelist.csv", header=T, stringsAsFactors = F)
</code>```

I can create a network object pretty easily:

```<code>nw <- network(edgelist,
              vertex.attr = nodelist[,c(1,2)],
              vertex.attrnames = c("vertex.id", "agency"),
              directed = F)

nd <-networkDynamic(nw,
                    edge.spells = edgelist[,c(3,4,2,1)],
                    vertex.spells=nodelist[,c(3,4,1)])
</code>```

I can animate the network in terms of edges, vertices no problem:

```<code>reconcile.vertex.activity(nd, mode = "match.to.edges")

filmstrip(nd,
          displaylabels = FALSE,
          frames = 5,
          slice.par = list(start = 2014, end = 2019, interval = 1, aggregate.dur = 1, rule = 'any'))

render.d3movie(nd,
               filename = "~/owncloud/longspine/data/animation.html",
               displaylabels = FALSE,
               # This slice function makes the labels work
               vertex.tooltip = function(slice) {paste("<b>Agency:</b>", (slice %v% "agency"))})
</code>```

Essentially this shows how edges and vertices come and go over time. Next, I want to size vertices by agency budget. This changes from year to year. How should I do this? The online tutorials are a bit hard to intepret. In my example we have 217 agencies in total. Each would have an annual budget (if they exist as per onset, terminus in nodelist). Any tips or advice would be appreciated.

答:
to set up dynamic vertex attributes you can use the activate.vertex.attribute() function to define which vertices should have what values for what duration. For example, to create a dynamic attribute on vertex 1 named 'budget' with value 10000 from 2014-2015:

```<code>    nd <-activate.vertex.attribute(nd,'budget',
                                  value=10000,
                                  onset=2014,
                                  terminus=2015,
                                  v=1)
</code>```

Likely you would want to do this all at once when creating the object.  If you set up your nodelist so that it has one row per vertex per year, you should be able to use the create.TEAs option of the networkDynamic() constructor to initialize the object with the attribute activity spells you need. So if your nodelist looks like:

```<code>
      vertex.id        agency portfolio      onset   terminus  budget
    1         1   AAF Company     FALSE 2014-07-01 2015-07-01   10000
    2         1   AAF Company     FALSE 2015-07-01 2016-07-01   10500
    ...
</code>```

then

```<code>    nd <-networkDynamic(nw,
                    edge.spells = edgelist[,c(3,4,2,1)],
                    vertex.spells=nodelist[,c(3,4,1)],
                    create.TEAs=TRUE,
                    vertex.TEA.names='budget')
</code>```

The section in the networkDynamic package vignette on "Activating TEA Attributes" should have more helpful info https://cran.r-project.org/web/packages/networkDynamic/vignettes/networkDynamic.pdf

You should then be able to map the dynamic vertex attribute to an animation plot property in ndtv (ndtv will manage the conversion from dynamic to static attribute at each time point as it renders)

```<code>render.d3movie(nd,vertex.cex='budget')
</code>```

Unless these organizations have unusually modest budgets, I'm guessing you'd want to use the log() of the budget or some other way to transform the raw budget numbers or the nodes will be unimaginably big.

There is also a tutorial that covers this in more depth, as there is some necessary subtlety in how the aggregation of values in time windows work: http://statnet.csde.washington.edu/workshops/SUNBELT/current/ndtv/ndtv_workshop.html#controlling-plot-properties-using-dynamic-attributes-teas

Body:
I am looking at how government agencies change over time. The plan is to use the ndtv package to visualise changes. I have an nodelist that lists vertex ids, agency name, node onset and node terminus:

nodelist <- read.csv("https://github.com/aterhorst/data/raw/master/nodelist.csv", header=T, stringsAsFactors = F)

and an edgelist showing onset, terminus of edges:

edgelist <- read.csv("https://github.com/aterhorst/data/raw/master/edgelist.csv", header=T, stringsAsFactors = F)

I can create a network object pretty easily:

nw <- network(edgelist,
              vertex.attr = nodelist[,c(1,2)],
              vertex.attrnames = c("vertex.id", "agency"),
              directed = F)

nd <-networkDynamic(nw,
                    edge.spells = edgelist[,c(3,4,2,1)],
                    vertex.spells=nodelist[,c(3,4,1)])

I can animate the network in terms of edges, vertices no problem:

reconcile.vertex.activity(nd, mode = "match.to.edges")

filmstrip(nd,
          displaylabels = FALSE,
          frames = 5,
          slice.par = list(start = 2014, end = 2019, interval = 1, aggregate.dur = 1, rule = 'any'))

render.d3movie(nd,
               filename = "~/owncloud/longspine/data/animation.html",
               displaylabels = FALSE,
               # This slice function makes the labels work
               vertex.tooltip = function(slice) {paste("Agency:", (slice %v% "agency"))})

Essentially this shows how edges and vertices come and go over time. Next, I want to size vertices by agency budget. This changes from year to year. How should I do this? The online tutorials are a bit hard to intepret. In my example we have 217 agencies in total. Each would have an annual budget (if they exist as per onset, terminus in nodelist). Any tips or advice would be appreciated.

Body:
to set up dynamic vertex attributes you can use the activate.vertex.attribute() function to define which vertices should have what values for what duration. For example, to create a dynamic attribute on vertex 1 named 'budget' with value 10000 from 2014-2015:

    nd <-activate.vertex.attribute(nd,'budget',
                                  value=10000,
                                  onset=2014,
                                  terminus=2015,
                                  v=1)

Likely you would want to do this all at once when creating the object.  If you set up your nodelist so that it has one row per vertex per year, you should be able to use the create.TEAs option of the networkDynamic() constructor to initialize the object with the attribute activity spells you need. So if your nodelist looks like:

      vertex.id        agency portfolio      onset   terminus  budget
    1         1   AAF Company     FALSE 2014-07-01 2015-07-01   10000
    2         1   AAF Company     FALSE 2015-07-01 2016-07-01   10500
    ...

then

    nd <-networkDynamic(nw,
                    edge.spells = edgelist[,c(3,4,2,1)],
                    vertex.spells=nodelist[,c(3,4,1)],
                    create.TEAs=TRUE,
                    vertex.TEA.names='budget')

The section in the networkDynamic package vignette on "Activating TEA Attributes" should have more helpful info https://cran.r-project.org/web/packages/networkDynamic/vignettes/networkDynamic.pdf

You should then be able to map the dynamic vertex attribute to an animation plot property in ndtv (ndtv will manage the conversion from dynamic to static attribute at each time point as it renders)

render.d3movie(nd,vertex.cex='budget')

Unless these organizations have unusually modest budgets, I'm guessing you'd want to use the log() of the budget or some other way to transform the raw budget numbers or the nodes will be unimaginably big.

There is also a tutorial that covers this in more depth, as there is some necessary subtlety in how the aggregation of values in time windows work: http://statnet.csde.washington.edu/workshops/SUNBELT/current/ndtv/ndtv_workshop.html#controlling-plot-properties-using-dynamic-attributes-teas


问:
Laravel Validation Rules for Set minimum to 1 when default is 0
I have request array like this

```<code>{
    "amenity_rates": [
        {
            "initial_hour": 1,
            "initial_hour_rate": 0,
            "succeeding_hours": 0,
            "is_default": 0,
            "default_rate": 0
        },
        {

            "initial_hour": 1,
            "initial_hour_rate": 0,
            "succeeding_hours": 0,
            "is_default": 0,
            "default_rate": 0
        }
    ]
}
</code>```

Now this if the rules of my request

```<code>$rules =[
    'amenity_rates'                     => 'required|array',
    'amenity_rates.*.initial_hour'      => 'required_if:amenity_rates.*.is_default,0|numeric',
    'amenity_rates.*.initial_hour_rate' => 'required_if:amenity_rates.*.is_default,0|numeric',
    'amenity_rates.*.succeeding_hours'  => 'required_if:amenity_rates.*.is_default,0|numeric',
    'amenity_rates.*.is_default'        => 'required|in:0,1',
    'amenity_rates.*.default_rate'      => 'required_if:amenity_rates.*.is_default,1|numeric'
];
</code>```

Question is I want to set a minimum of this field('initial_hour','initial_hour_rate','succeeding_hours') if the is_default is 0 when I set min:1 they throw an error if either is_default is 0 or 1.

答:
You can use custom validation rule

first run this in your command line

php artisan make:rule MinIfDefaultIsZero

You will find a file called MinIfDefaultIsZero.php in app/Rules folder

You need to create a constructor that will pass the is_default and then validate it in passes()

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class MinIfDefaultIsZero implements Rule
{
    private $is_default;

    public function __constructor($is_default){
      $this->is_default = $is_default;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        if($this->is_default == 0) {
            return $value > 1;
        }

        return true;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must be more than 1.';
    }
}
```

Body:
I have request array like this

{
    "amenity_rates": [
        {
            "initial_hour": 1,
            "initial_hour_rate": 0,
            "succeeding_hours": 0,
            "is_default": 0,
            "default_rate": 0
        },
        {

            "initial_hour": 1,
            "initial_hour_rate": 0,
            "succeeding_hours": 0,
            "is_default": 0,
            "default_rate": 0
        }
    ]
}

Now this if the rules of my request

$rules =[
    'amenity_rates'                     => 'required|array',
    'amenity_rates.*.initial_hour'      => 'required_if:amenity_rates.*.is_default,0|numeric',
    'amenity_rates.*.initial_hour_rate' => 'required_if:amenity_rates.*.is_default,0|numeric',
    'amenity_rates.*.succeeding_hours'  => 'required_if:amenity_rates.*.is_default,0|numeric',
    'amenity_rates.*.is_default'        => 'required|in:0,1',
    'amenity_rates.*.default_rate'      => 'required_if:amenity_rates.*.is_default,1|numeric'
];

Question is I want to set a minimum of this field('initial_hour','initial_hour_rate','succeeding_hours') if the is_default is 0 when I set min:1 they throw an error if either is_default is 0 or 1.


问:
Is the 'Click to chat' not working anymore on whatssap?
I cannot create a redirect link in whatssap anymore. It seems to no redirect to chat. In my whatssap, this link does not start a new chat with preflilled text.</p>

```<code>    https://web.whatsapp.com/send?phone=5512 98183-2011&text=oi
</code>```

答: I am not sure if it's down or officially removed as a feature, but it's not working for me either. The Click to Chat feature is still listed in the FAQ though.</p>

Body:
I cannot create a redirect link in whatssap anymore. It seems to no redirect to chat. In my whatssap, this link does not start a new chat with preflilled text.

    https://web.whatsapp.com/send?phone=5512 98183-2011&text=oi


问:
ORA-01843: not a valid month ORA-06512: at line 5 and ORA-01861: literal does not match format string ORA-06512: at line 5
procedure created accurately but execution time getting error mentioned in title.</p>

```<code>DECLARE
     var NUMBER;
     var1 NUMBER;
BEGIN
     sale_procedure(outletid => 809,itemcod => 128169,start_date => '2018-1-1',end_date => '2019-1-1'
     ,amount => var,quantity => var1);

     dbms_output.enable;
     dbms_output.put_line(var);
End;
/
</code>```

答:
pass DATE literal, i.e. just add the  word date before your dates, it should work, provided the arguments start_date and end_date  are defined as dates.

```<code> sale_procedure(
      outletid  => 809,
      itemcod   => 128169
    ,start_date => DATE '2018-01-01'
     ,end_date  => DATE '2019-01-01'
     ,amount    => var,
     quantity   => var1
 );
</code>```

Body:
procedure created accurately but execution time getting error mentioned in title.

DECLARE
     var NUMBER;
     var1 NUMBER;
BEGIN
     sale_procedure(outletid => 809,itemcod => 128169,start_date => '2018-1-1',end_date => '2019-1-1'
     ,amount => var,quantity => var1);

     dbms_output.enable;
     dbms_output.put_line(var);
End;
/

Body:
pass DATE literal, i.e. just add the  word date before your dates, it should work, provided the arguments start_date and end_date  are defined as dates.

 sale_procedure(
      outletid  => 809,
      itemcod   => 128169
    ,start_date => DATE '2018-01-01'
     ,end_date  => DATE '2019-01-01'
     ,amount    => var,
     quantity   => var1
 );


答:
I can't 100% explain that behaviour - I'd expect you wouldn't get any characters printed as it'd be using Returner::test - but if you're overriding a function in C++ you need to declare it virtual in the base class:

```<code>class Returner
{
  public:
    Returner(){}
    virtual char test()
    {
    }
};
</code>```

Without test being virtual, the line

```<code>Serial.print( retrn.test() );
</code>```

(don't you mean retrn->test()?) will just pick one implementation of test and use it always. As above I'd expect this to be the empty Returner::test(). You may also either need to make Returner::test abstract

```<code>    virtual char test() = 0;
</code>```

or return some value if you're leaving it with a function body.

Title: Redeclaration of variable

Body:
I can't 100% explain that behaviour - I'd expect you wouldn't get any characters printed as it'd be using Returner::test - but if you're overriding a function in C++ you need to declare it virtual in the base class:

class Returner
{
  public:
    Returner(){}
    virtual char test()
    {
    }
};

Without test being virtual, the line

Serial.print( retrn.test() );

(don't you mean retrn->test()?) will just pick one implementation of test and use it always. As above I'd expect this to be the empty Returner::test(). You may also either need to make Returner::test abstract

    virtual char test() = 0;

or return some value if you're leaving it with a function body.


问:
Gitlab SSH: Permission Denied, Despite correct key setup
I'm trying to use Gitlab for the first time, and have been trying to set up my account to automatically ssh in. I've followed instructions and tried many different times, but no matter what, I can't ssh to gitlab properly.

I've tried deleting my id_rsa and id_rsa.pub files and regenerating keys, using the command line to copy the contents of id_rsa.pub to my Gitlab user settings (both with a newline and no newline at the end of the paste). I added my key using ssh-add. I'm running ssh -vvvv git@gitlab.com for verbosity and I just cannot connect succesfully for the life of me.

```<code>OpenSSH_7.2p2 Ubuntu-4ubuntu2.8, OpenSSL 1.0.2g  1 Mar 2016
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: resolving "gitlab.com" port 22
debug2: ssh_connect_direct: needpriv 0
debug1: Connecting to gitlab.com [35.231.145.151] port 22.
debug1: Connection established.
debug1: identity file /home/jihan/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /home/jihan/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/jihan/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/jihan/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/jihan/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/jihan/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/jihan/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/jihan/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.8
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.2p2 Ubuntu-4ubuntu2.8
debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.8 pat OpenSSH* compat 0x04000000
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to gitlab.com:22 as 'git'
debug3: hostkeys_foreach: reading file "/home/jihan/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/jihan/.ssh/known_hosts:3
debug3: load_hostkeys: loaded 1 keys from gitlab.com
debug3: order_hostkeyalgs: prefer hostkeyalgs: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
debug3: send packet: type 20
debug1: SSH2_MSG_KEXINIT sent
debug3: receive packet: type 20
debug1: SSH2_MSG_KEXINIT received
debug2: local client KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,ext-info-c
debug2: host key algorithms: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsa
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc,3des-cbc
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc,3des-cbc
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com,zlib
debug2: compression stoc: none,zlib@openssh.com,zlib
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug2: peer server KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1
debug2: host key algorithms: ssh-rsa,rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ssh-ed25519
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com
debug2: compression stoc: none,zlib@openssh.com
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug3: send packet: type 30
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug3: receive packet: type 31
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:HbW3g8zUjNSksFbqTiUWPWg2Bq1x8xdGUrliXFzSnUw
debug3: hostkeys_foreach: reading file "/home/jihan/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/jihan/.ssh/known_hosts:3
debug3: load_hostkeys: loaded 1 keys from gitlab.com
debug3: hostkeys_foreach: reading file "/home/jihan/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/jihan/.ssh/known_hosts:4
debug3: load_hostkeys: loaded 1 keys from 35.231.145.151
debug1: Host 'gitlab.com' is known and matches the ECDSA host key.
debug1: Found key in /home/jihan/.ssh/known_hosts:3
debug3: send packet: type 21
debug2: set_newkeys: mode 1
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug3: receive packet: type 21
debug1: SSH2_MSG_NEWKEYS received
debug2: set_newkeys: mode 0
debug1: rekey after 134217728 blocks
debug2: key: /home/jihan/.ssh/id_rsa (0x55e032d43000), agent
debug2: key: jihany@nvidia.com (0x55e032d363a0), agent
debug2: key: /home/jihan/.ssh/id_dsa ((nil))
debug2: key: /home/jihan/.ssh/id_ecdsa ((nil))
debug2: key: /home/jihan/.ssh/id_ed25519 ((nil))
debug3: send packet: type 5
debug3: receive packet: type 7
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<rsa-sha2-256,rsa-sha2-512>
debug3: receive packet: type 6
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug3: send packet: type 50
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug3: start over, passed a different list publickey
debug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/jihan/.ssh/id_rsa
debug3: send_pubkey_test
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug1: Offering RSA public key: jihany@nvidia.com
debug3: send_pubkey_test
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug1: Trying private key: /home/jihan/.ssh/id_dsa
debug3: no such identity: /home/jihan/.ssh/id_dsa: No such file or directory
debug1: Trying private key: /home/jihan/.ssh/id_ecdsa
debug3: no such identity: /home/jihan/.ssh/id_ecdsa: No such file or directory
debug1: Trying private key: /home/jihan/.ssh/id_ed25519
debug3: no such identity: /home/jihan/.ssh/id_ed25519: No such file or directory
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
Permission denied (publickey).
</code>```

It has to be some small dumb mistake somewhere, but I just can't figure it out. If it helps, when I do ssh-add -l, my fingerprints look like a hash for some reason.

答:
Do check that:

when you copy the public key in your GitLab settings profile, it is copied as one line

when you generate your RSA SSH key, you use the old legacy profile (in case the new OPENSSH one with 70 chars per line is not well interpreted)

That is

```<code>ssh-keygen -m PEM -t rsa -P "
</code>```

Body:
I'm trying to use Gitlab for the first time, and have been trying to set up my account to automatically ssh in. I've followed instructions and tried many different times, but no matter what, I can't ssh to gitlab properly.

I've tried deleting my id_rsa and id_rsa.pub files and regenerating keys, using the command line to copy the contents of id_rsa.pub to my Gitlab user settings (both with a newline and no newline at the end of the paste). I added my key using ssh-add. I'm running ssh -vvvv git@gitlab.com for verbosity and I just cannot connect succesfully for the life of me.

OpenSSH_7.2p2 Ubuntu-4ubuntu2.8, OpenSSL 1.0.2g  1 Mar 2016
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: resolving "gitlab.com" port 22
debug2: ssh_connect_direct: needpriv 0
debug1: Connecting to gitlab.com [35.231.145.151] port 22.
debug1: Connection established.
debug1: identity file /home/jihan/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /home/jihan/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/jihan/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/jihan/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/jihan/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/jihan/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/jihan/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/jihan/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.8
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.2p2 Ubuntu-4ubuntu2.8
debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.8 pat OpenSSH* compat 0x04000000
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to gitlab.com:22 as 'git'
debug3: hostkeys_foreach: reading file "/home/jihan/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/jihan/.ssh/known_hosts:3
debug3: load_hostkeys: loaded 1 keys from gitlab.com
debug3: order_hostkeyalgs: prefer hostkeyalgs: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
debug3: send packet: type 20
debug1: SSH2_MSG_KEXINIT sent
debug3: receive packet: type 20
debug1: SSH2_MSG_KEXINIT received
debug2: local client KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,ext-info-c
debug2: host key algorithms: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsa
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc,3des-cbc
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc,3des-cbc
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com,zlib
debug2: compression stoc: none,zlib@openssh.com,zlib
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug2: peer server KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1
debug2: host key algorithms: ssh-rsa,rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ssh-ed25519
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com
debug2: compression stoc: none,zlib@openssh.com
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug3: send packet: type 30
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug3: receive packet: type 31
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:HbW3g8zUjNSksFbqTiUWPWg2Bq1x8xdGUrliXFzSnUw
debug3: hostkeys_foreach: reading file "/home/jihan/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/jihan/.ssh/known_hosts:3
debug3: load_hostkeys: loaded 1 keys from gitlab.com
debug3: hostkeys_foreach: reading file "/home/jihan/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/jihan/.ssh/known_hosts:4
debug3: load_hostkeys: loaded 1 keys from 35.231.145.151
debug1: Host 'gitlab.com' is known and matches the ECDSA host key.
debug1: Found key in /home/jihan/.ssh/known_hosts:3
debug3: send packet: type 21
debug2: set_newkeys: mode 1
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug3: receive packet: type 21
debug1: SSH2_MSG_NEWKEYS received
debug2: set_newkeys: mode 0
debug1: rekey after 134217728 blocks
debug2: key: /home/jihan/.ssh/id_rsa (0x55e032d43000), agent
debug2: key: jihany@nvidia.com (0x55e032d363a0), agent
debug2: key: /home/jihan/.ssh/id_dsa ((nil))
debug2: key: /home/jihan/.ssh/id_ecdsa ((nil))
debug2: key: /home/jihan/.ssh/id_ed25519 ((nil))
debug3: send packet: type 5
debug3: receive packet: type 7
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<rsa-sha2-256,rsa-sha2-512>
debug3: receive packet: type 6
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug3: send packet: type 50
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug3: start over, passed a different list publickey
debug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/jihan/.ssh/id_rsa
debug3: send_pubkey_test
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug1: Offering RSA public key: jihany@nvidia.com
debug3: send_pubkey_test
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug1: Trying private key: /home/jihan/.ssh/id_dsa
debug3: no such identity: /home/jihan/.ssh/id_dsa: No such file or directory
debug1: Trying private key: /home/jihan/.ssh/id_ecdsa
debug3: no such identity: /home/jihan/.ssh/id_ecdsa: No such file or directory
debug1: Trying private key: /home/jihan/.ssh/id_ed25519
debug3: no such identity: /home/jihan/.ssh/id_ed25519: No such file or directory
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
Permission denied (publickey).

It has to be some small dumb mistake somewhere, but I just can't figure it out. If it helps, when I do ssh-add -l, my fingerprints look like a hash for some reason.

Body:
Do check that:

when you copy the public key in your GitLab settings profile, it is copied as one line

when you generate your RSA SSH key, you use the old legacy profile (in case the new OPENSSH one with 70 chars per line is not well interpreted)

That is

ssh-keygen -m PEM -t rsa -P "


问:
Parsing JsonObject into kotlin Data class
I am fairly new to Kotlin and I am trying to parse the JsonObject that I get from my HTTPRequest into data class. But I cannot get the Instance from the data class.

```<code>val jsonObjectRequest = JsonObjectRequest(Request.Method.GET, url, null,
    Response.Listener { response ->
        val text = "Response: %s".format(response.toString())
        print(text)
    },
    Response.ErrorListener { error ->
        // TODO: Handle error
    }

)

@Throws(AuthFailureError::class)
@Override
fun getHeaders(): Map<String, String> {
    var params = HashMap<String, String>()
    if (params == null) params = HashMap()
    val basicAuth = "Basic " + Base64.encodeToString("username:password".toByteArray(), Base64.NO_WRAP);
    params["Authorization"] = basicAuth
    //..add other headers
    return params
}

TempJsonObject.instance?.addToRequestQueue(jsonObjectRequest)
</code>```

Data Class

```<code>data class TempJsonObject(
    val content: List<Content>) {
data class Content(
        val kioskId: Int,
        val location: Location,
        val stats: Stats,
        val settings: Settings,
        val modules: String,
        val visibility: String
) {
    data class Stats(
            val allLockers: Int,
            val emptyLockers: Int,
            val malfunctionLockers: Int,
            val forCustomer: Int,
            val forCourier: Int,
            val bySize: BySize,
            val incoming: Any
    ) {
        data class BySize(
                val XXSMALL: Xxsmall,
                val XSMALL: Xsmall,
                val SMALL: Small,
                val MEDIUM: Medium,
                val LARGE: Large,
                val XLARGE: Xlarge
        ) {
            data class Xxsmall(
                    val empty: Int,
                    val hasContent: Int
            )
        ...
</code>```

Is the way I am trying to do it the right approach and what am I doing wrong?

答:
Looking at instance?.addToRequestQueue, it's really puzzling me. I don't know any Kotlin API like this for parsing JSONs. I thought that you use some library that adds such API, but you also wrote in the comment that the code doesn't compile because of lack of instance field. It looks like it exposes some singleton instance of the data class. Could you point me to any working example using such API, or any other source that you used?

If the above turns out to be incorrect, I would just use some Kotlin or Java library to parse the JSON into an instance of the data class. One option is the Kotlin library Klaxon: https://github.com/cbeust/klaxon. Quoting one of its examples that should fit your use case:

```<code>val result = Klaxon().parse<Person>(""" { "name": "John Smith", } """)

assert(result?.name == "John Smith")
assert(result.age == 23)
</code>```

Body:
I am fairly new to Kotlin and I am trying to parse the JsonObject that I get from my HTTPRequest into data class. But I cannot get the Instance from the data class.

val jsonObjectRequest = JsonObjectRequest(Request.Method.GET, url, null,
    Response.Listener { response ->
        val text = "Response: %s".format(response.toString())
        print(text)
    },
    Response.ErrorListener { error ->
        // TODO: Handle error
    }

)

@Throws(AuthFailureError::class)
@Override
fun getHeaders(): Map<String, String> {
    var params = HashMap<String, String>()
    if (params == null) params = HashMap()
    val basicAuth = "Basic " + Base64.encodeToString("username:password".toByteArray(), Base64.NO_WRAP);
    params["Authorization"] = basicAuth
    //..add other headers
    return params
}

TempJsonObject.instance?.addToRequestQueue(jsonObjectRequest)

Data Class

data class TempJsonObject(
    val content: List<Content>) {
data class Content(
        val kioskId: Int,
        val location: Location,
        val stats: Stats,
        val settings: Settings,
        val modules: String,
        val visibility: String
) {
    data class Stats(
            val allLockers: Int,
            val emptyLockers: Int,
            val malfunctionLockers: Int,
            val forCustomer: Int,
            val forCourier: Int,
            val bySize: BySize,
            val incoming: Any
    ) {
        data class BySize(
                val XXSMALL: Xxsmall,
                val XSMALL: Xsmall,
                val SMALL: Small,
                val MEDIUM: Medium,
                val LARGE: Large,
                val XLARGE: Xlarge
        ) {
            data class Xxsmall(
                    val empty: Int,
                    val hasContent: Int
            )
        ...

Is the way I am trying to do it the right approach and what am I doing wrong?

Body:
Looking at instance?.addToRequestQueue, it's really puzzling me. I don't know any Kotlin API like this for parsing JSONs. I thought that you use some library that adds such API, but you also wrote in the comment that the code doesn't compile because of lack of instance field. It looks like it exposes some singleton instance of the data class. Could you point me to any working example using such API, or any other source that you used?

If the above turns out to be incorrect, I would just use some Kotlin or Java library to parse the JSON into an instance of the data class. One option is the Kotlin library Klaxon: https://github.com/cbeust/klaxon. Quoting one of its examples that should fit your use case:

val result = Klaxon().parse<Person>(""" { "name": "John Smith", } """)

assert(result?.name == "John Smith")
assert(result.age == 23)


问:
Why doesn't observable list always notice changes?
I have some code which I don't understand the result :

```<code>ObservableList<Integer> li = FXCollections.observableArrayList();
        li.add(1);
        li.add(2);
        IntegerProperty intProp = new SimpleIntegerProperty(5);

        li.add(intProp.getValue());

        li.add(li.get(0) + li.get(2));
        System.out.println(li);
        li.addListener((ListChangeListener<Integer>) change -> {
            li.set(3, li.get(0) + li.get(2));
        });
        intProp.setValue(3);
        System.out.println(intProp.get());
        System.out.println(li.get(2));
        System.out.println(li);
</code>```

I don't understand why the changing value of intProp doesn't affect affect the observableList, I mean the int in the position 2 should be the value of the property so the second and third sysout must me the same, and the first must be different from the last, but it isn't the case, and it gives me :

```<code>[1, 2, 5, 6]
3
5
[1, 2, 5, 6]
</code>```

I tried to do some changes by writing this :

```<code>        ObservableList<Integer> li = FXCollections.observableArrayList();
        li.add(1);
        li.add(2);

        li.add(5);

        li.add(li.get(0) + li.get(2));
        System.out.println(li);
        li.addListener((ListChangeListener<Integer>) change -> {
            li.set(3, li.get(0) + li.get(2));
        });
        li.set(2, 3);
        System.out.println(li);
</code>```

it apparently works, but it gives me many errors which I don't understand.

Thanks !

答:
At a fundamental level, you seem to be expecting the following:

```<code>IntegerProperty property = new SimpleIntegerProperty(5);
int i = property.get();
property.set(10);
System.out.println(i);
</code>```

To print out 10 instead of 5. This cannot happen in Java because Java is always pass-by-value. The same is true when adding the value to an ObservableList; all you've done is taken the value of the property at the time and added it to the list. After that, the property and the list are completely separate entities.

There's no fundamental way to observe variables for changes in Java. In order to be notified of changes there has to be code that implements that behavior. An IntegerProperty is basically just a wrapper around an int that intercepts code changing the value and notifying observers of the change. Something like:

```<code>public void set(int newValue) {
    this.value = newValue;
    notifyObservers();
}
</code>```

Note: The actual implementation of IntegerProperty is more complicated than that.

The same is true of ObservableList. All the core implementations are simply wrappers around a regular List and the ObservableList simply intercepts calls and notifies observers of a change. This is why, if you wrap your own List using FXCollections.observableList(List), you can't modify the List directly anymore because that bypasses the wrapping ObservableList and thus no change events will be fired.

If you want the ObservableList to update when the IntegerProperty changes, you'd have to add a listener to the IntegerProperty which updates the ObservableList appropriately. If you want to be aware of changes to contained elements via the ObservableList, you need to use an extractor—see this answer.

it apparently works, but it gives me many errors which I don't understand.

Ignoring the contradiction between "apparently works" and "gives me many errors", you don't actually provide the errors you get. Without the errors it's difficult to know what is going wrong. However, you have the following (which may or may not be related to your errors):

```<code>li.addListener((ListChangeListener<Integer>) change -> {
    li.set(3, li.get(0) + li.get(2));
});
</code>```

This is modifying the the ObservableList that fired the change event. You must not do this:

Warning: This class directly accesses the source list to acquire information about the changes.

  This effectively makes the Change object invalid when another change occurs on the list.

  For this reason it is not safe to use this class on a different thread.

  It also means the source list cannot be modified inside the listener since that would invalidate this Change object for all subsequent listeners.

Body:
I have some code which I don't understand the result :

ObservableList<Integer> li = FXCollections.observableArrayList();
        li.add(1);
        li.add(2);
        IntegerProperty intProp = new SimpleIntegerProperty(5);

        li.add(intProp.getValue());

        li.add(li.get(0) + li.get(2));
        System.out.println(li);
        li.addListener((ListChangeListener<Integer>) change -> {
            li.set(3, li.get(0) + li.get(2));
        });
        intProp.setValue(3);
        System.out.println(intProp.get());
        System.out.println(li.get(2));
        System.out.println(li);

I don't understand why the changing value of intProp doesn't affect affect the observableList, I mean the int in the position 2 should be the value of the property so the second and third sysout must me the same, and the first must be different from the last, but it isn't the case, and it gives me :

[1, 2, 5, 6]
3
5
[1, 2, 5, 6]

I tried to do some changes by writing this :

        ObservableList<Integer> li = FXCollections.observableArrayList();
        li.add(1);
        li.add(2);

        li.add(5);

        li.add(li.get(0) + li.get(2));
        System.out.println(li);
        li.addListener((ListChangeListener<Integer>) change -> {
            li.set(3, li.get(0) + li.get(2));
        });
        li.set(2, 3);
        System.out.println(li);

it apparently works, but it gives me many errors which I don't understand.

Thanks !

Body:
At a fundamental level, you seem to be expecting the following:

IntegerProperty property = new SimpleIntegerProperty(5);
int i = property.get();
property.set(10);
System.out.println(i);

To print out 10 instead of 5. This cannot happen in Java because Java is always pass-by-value. The same is true when adding the value to an ObservableList; all you've done is taken the value of the property at the time and added it to the list. After that, the property and the list are completely separate entities.

There's no fundamental way to observe variables for changes in Java. In order to be notified of changes there has to be code that implements that behavior. An IntegerProperty is basically just a wrapper around an int that intercepts code changing the value and notifying observers of the change. Something like:

public void set(int newValue) {
    this.value = newValue;
    notifyObservers();
}

Note: The actual implementation of IntegerProperty is more complicated than that.

The same is true of ObservableList. All the core implementations are simply wrappers around a regular List and the ObservableList simply intercepts calls and notifies observers of a change. This is why, if you wrap your own List using FXCollections.observableList(List), you can't modify the List directly anymore because that bypasses the wrapping ObservableList and thus no change events will be fired.

If you want the ObservableList to update when the IntegerProperty changes, you'd have to add a listener to the IntegerProperty which updates the ObservableList appropriately. If you want to be aware of changes to contained elements via the ObservableList, you need to use an extractor—see this answer.

it apparently works, but it gives me many errors which I don't understand.

Ignoring the contradiction between "apparently works" and "gives me many errors", you don't actually provide the errors you get. Without the errors it's difficult to know what is going wrong. However, you have the following (which may or may not be related to your errors):

li.addListener((ListChangeListener<Integer>) change -> {
    li.set(3, li.get(0) + li.get(2));
});

This is modifying the the ObservableList that fired the change event. You must not do this:

Warning: This class directly accesses the source list to acquire information about the changes.

  This effectively makes the Change object invalid when another change occurs on the list.

  For this reason it is not safe to use this class on a different thread.

  It also means the source list cannot be modified inside the listener since that would invalidate this Change object for all subsequent listeners.


问:
How to resize Icons in Tizen (Wearable)
I am trying to make a simple app for my Galaxy Watch which runs on Tizen. All I want to do for now is to display a white screen with two circular buttons on the top and bottom (plus and minus buttons). I seem to have the white screen part settled. But, when I try to display the icon, the icon fills the whole window. I need help, please.

(PS: I have some knowledge on Android app development. But, Tizen is a completely different ball game. I know C & C++ to a certain extent)

```<code>    Evas_Object *bg = elm_bg_add(ad->win);
    elm_bg_color_set(bg, 255, 233, 26);
    evas_object_size_hint_weight_set(bg, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
    elm_win_resize_object_add(ad->win, bg);
    evas_object_show(bg);

    /* Plus Icon */
    Evas_Object *plusIcon = elm_icon_add(bg);
    elm_image_file_set(plusIcon, "/opt/usr/apps/org.example.basicui/res/images/plus.png", NULL);
    elm_object_content_set(bg, plusIcon);
</code>```

The Tizen documentation is really confusing and lacklustre (unlike Android's). Also, I can't find any wholesome tutorial regarding Tizen Native Wearable App Development. If you know of any such tutorial, please share it with me.

Thanks again.

答:
"/opt/usr/apps/org.example.basicui/res/images/plus.png"

is there plus.png file in this path?

```<code>if(!elm_image_file_set(plusIcon,...
  elm_bg_color_set(bg, 255, 0, 0);
</code>```

If there is no file, the background will be red.

If you want to create a clickable widget, you can use elm_button.
Make the button's style "circle". Then create elm_image and set it to elm_object_content_set().
However, this style may vary depending on your tizen version.

So I recommend the following way.

```<code>/*BG - box(container) - image(clicked event)
                        image(clicked event)*/

Evas_Object *bg, box, *image;
// Make BG
bg = elm_bg_add(parent);
elm_bg_color_set(bg, 255, 233, 26);
evas_object_size_hint_weight_set(bg, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
evas_object_show(bg);

// Make container
box = elm_box_add(bg);
evas_object_size_hint_weight_set(box, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
evas_object_size_hint_align_set(box, EVAS_HINT_FILL, EVAS_HINT_FILL);
evas_object_show(box);

// Make image
image = elm_image_add(box);
if(!elm_image_file_set(image, /* Image path*/, NULL))
  return;
evas_object_size_hint_min_set(image, 100, 100);  // minimum size
evas_object_show(image);
evas_object_smart_callback_add(image, "clicked",  /* event callback function */, NULL);
elm_box_pack_end(box, image);

image = elm_image_add(box);
if(!elm_image_file_set(image, /* Image path*/, NULL))
  return;
evas_object_size_hint_min_set(image, 100, 100); // minimum size
evas_object_smart_callback_add(image, "clicked", /* event callback function */, NULL);
evas_object_show(image);
elm_box_pack_end(box, image);

elm_object_content_set(bg, box);

elm_win_resize_object_add(ad->win, bg);
</code>```

elm_box
https://developer.tizen.org/ko/development/guides/native-application/user-interface/efl/building-ui-layouts/box

elm_image
https://developer.tizen.org/ko/development/guides/native-application/user-interface/efl/ui-components/wearable-ui-components/image

Title: How to resize Icons in Tizen (Wearable)

Body:
I am trying to make a simple app for my Galaxy Watch which runs on Tizen. All I want to do for now is to display a white screen with two circular buttons on the top and bottom (plus and minus buttons). I seem to have the white screen part settled. But, when I try to display the icon, the icon fills the whole window. I need help, please.

(PS: I have some knowledge on Android app development. But, Tizen is a completely different ball game. I know C & C++ to a certain extent)

    Evas_Object *bg = elm_bg_add(ad->win);
    elm_bg_color_set(bg, 255, 233, 26);
    evas_object_size_hint_weight_set(bg, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
    elm_win_resize_object_add(ad->win, bg);
    evas_object_show(bg);

    /* Plus Icon */
    Evas_Object *plusIcon = elm_icon_add(bg);
    elm_image_file_set(plusIcon, "/opt/usr/apps/org.example.basicui/res/images/plus.png", NULL);
    elm_object_content_set(bg, plusIcon);

The Tizen documentation is really confusing and lacklustre (unlike Android's). Also, I can't find any wholesome tutorial regarding Tizen Native Wearable App Development. If you know of any such tutorial, please share it with me.

Thanks again.

Body:
"/opt/usr/apps/org.example.basicui/res/images/plus.png"

is there plus.png file in this path?

if(!elm_image_file_set(plusIcon,...
  elm_bg_color_set(bg, 255, 0, 0);

If there is no file, the background will be red.

If you want to create a clickable widget, you can use elm_button.
Make the button's style "circle". Then create elm_image and set it to elm_object_content_set().
However, this style may vary depending on your tizen version.

So I recommend the following way.

/*BG - box(container) - image(clicked event)
                        image(clicked event)*/

Evas_Object *bg, box, *image;
// Make BG
bg = elm_bg_add(parent);
elm_bg_color_set(bg, 255, 233, 26);
evas_object_size_hint_weight_set(bg, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
evas_object_show(bg);

// Make container
box = elm_box_add(bg);
evas_object_size_hint_weight_set(box, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
evas_object_size_hint_align_set(box, EVAS_HINT_FILL, EVAS_HINT_FILL);
evas_object_show(box);

// Make image
image = elm_image_add(box);
if(!elm_image_file_set(image, /* Image path*/, NULL))
  return;
evas_object_size_hint_min_set(image, 100, 100);  // minimum size
evas_object_show(image);
evas_object_smart_callback_add(image, "clicked",  /* event callback function */, NULL);
elm_box_pack_end(box, image);

image = elm_image_add(box);
if(!elm_image_file_set(image, /* Image path*/, NULL))
  return;
evas_object_size_hint_min_set(image, 100, 100); // minimum size
evas_object_smart_callback_add(image, "clicked", /* event callback function */, NULL);
evas_object_show(image);
elm_box_pack_end(box, image);

elm_object_content_set(bg, box);

elm_win_resize_object_add(ad->win, bg);

elm_box
https://developer.tizen.org/ko/development/guides/native-application/user-interface/efl/building-ui-layouts/box

elm_image
https://developer.tizen.org/ko/development/guides/native-application/user-interface/efl/ui-components/wearable-ui-components/image


问:
Datatable row : manually update field
I have a datatable. I get a set of selected rows.
When i loop through, and update the value of a field remark,
I can't do it.

how do i manually update the value of a specific field in a row?

```<code>var table = $('#bankReconDataListing').DataTable();
$.map(table.rows('.selectedrow').data(), function (item) {
    item.remarks = 'updated values';
    console.log('-----------------1>',item);
});
</code>```

答:
```<code>    <table id="bankReconDataListing">
        <thead>
            <tr>
                <td>head</td>
                <td>gender</td>
            </tr>
        </thead>
        <tbody>
            <tr><td>one</td><td>boy</td></tr>
            <tr class="selectedrow"><td>two</td><td>boys</td></tr>
            <tr><td>three</td>
            <td>boys</td></tr>
        </tbody>
    </table>

    var table = $('#bankReconDataListing').DataTable();
    var temp = table.row(2).data();
    alert("value before update = " + temp[0]);
    temp[0] = "six";
    table.row(2).data(temp).draw();
    alert("value after update = " + temp[0]);
</code>```

Title: Datatable row : manually update field

Body:
I have a datatable. I get a set of selected rows.
When i loop through, and update the value of a field remark,
I can't do it.

how do i manually update the value of a specific field in a row?

var table = $('#bankReconDataListing').DataTable();
$.map(table.rows('.selectedrow').data(), function (item) {
    item.remarks = 'updated values';
    console.log('-----------------1>',item);
});


问:
How do I implement a switch-case of different functions in python?
How do I implement a switch-case of different functions in python? The function arguments are different in each case. </p>

答:
Like this:

```<code>if case1:
   function1()
elif case2:
   function2(arg1, arg2)
elif case3:
   function3(arg3)
</code>```

etc.

Body:
Like this:

if case1:
   function1()
elif case2:
   function2(arg1, arg2)
elif case3:
   function3(arg3)

etc.


问:
Increase Gatling requests in load test via increase in users?
```<code>class myTest extends Simulation {
  val headers = Map("Authorization" -> "longAuthHeader")

  val httpProtocol = http
    .baseUrl("http://baseurl.com:8000")
    .headers(headers)

  val scn = scenario("Scenario Name")
    .exec(http("request")
    .get("/data/url/"))

   setUp(scn.inject(constantUsersPerSec(40) during (2 minutes)))
    .protocols(httpProtocol)
    .throttle(jumpToRps(40), holdFor(2 minutes))
}
</code>```

Using the above, I am creating a test using gatling which performs 40 RPS to baseurl.com:8000/data/url and maintains this for 2 minutes.

The problem with above approach is that only one user (as identified by the auth header) is performing the test.

What steps do I need to take to change this test to perform a request with, say, 40 users (40 different auth headers) that perform 1RPS each? So I will have 40 RPS distributed over 40 users rather than 40 RPS from one user.

This is important because my application performs slightly different behaviour based on the user context (different auth headers = different behaviour).

答:
the gatling advanced tutorial describes how to do exactly this

gatling.io/docs/current/advanced_tutorial#advanced-tutorial You're interested the sections on configuring virtual users and feeders –

Body:
class myTest extends Simulation {
  val headers = Map("Authorization" -> "longAuthHeader")

  val httpProtocol = http
    .baseUrl("http://baseurl.com:8000")
    .headers(headers)

  val scn = scenario("Scenario Name")
    .exec(http("request")
    .get("/data/url/"))

   setUp(scn.inject(constantUsersPerSec(40) during (2 minutes)))
    .protocols(httpProtocol)
    .throttle(jumpToRps(40), holdFor(2 minutes))
}

Using the above, I am creating a test using gatling which performs 40 RPS to baseurl.com:8000/data/url and maintains this for 2 minutes.

The problem with above approach is that only one user (as identified by the auth header) is performing the test.

What steps do I need to take to change this test to perform a request with, say, 40 users (40 different auth headers) that perform 1RPS each? So I will have 40 RPS distributed over 40 users rather than 40 RPS from one user.

This is important because my application performs slightly different behaviour based on the user context (different auth headers = different behaviour).