问:
How to differentiate signin and signup user in firebase using google auth?
I am using firebase to authenticate user. If new user signin using google/facebook provider, it creates a user and automatically sign in. After user signin, how to differentiate between signIn and signUp?</p>

```<code>var provider = new firebase.auth.GoogleAuthProvider();

firebase.auth().signInWithPopup(provider).then(function(result) {
  var token = result.credential.accessToken;
  var user = result.user;
  // if new user i want to redirect to some other page.
  // if user already exist, i want to redirect to home page
}).catch(function(error) {
  // Handle Errors here.
});
</code>```

答:
use getAdditionalUserInfo

```<code>var provider = new firebase.auth.GoogleAuthProvider();

firebase
  .auth()
  .signInWithPopup(provider)
  .then(function (result) {
    var token = result.credential.accessToken;
    var user = result.user;
    const additionalUserInfo = getAdditionalUserInfo(userCredential);
    if (additionalUserInfo.isNewUser) {
      // if new user i want to redirect to some other page.
    } else {
      // if user already exist, i want to redirect to home page
    }
  })
  .catch(function (error) {
    // Handle Errors here.
  });

</code>```

Body:
I am using firebase to authenticate user. If new user signin using google/facebook provider, it creates a user and automatically sign in. After user signin, how to differentiate between signIn and signUp?

var provider = new firebase.auth.GoogleAuthProvider();

firebase.auth().signInWithPopup(provider).then(function(result) {
  var token = result.credential.accessToken;
  var user = result.user;
  // if new user i want to redirect to some other page.
  // if user already exist, i want to redirect to home page
}).catch(function(error) {
  // Handle Errors here.
});

Body:
use getAdditionalUserInfo

var provider = new firebase.auth.GoogleAuthProvider();

firebase
  .auth()
  .signInWithPopup(provider)
  .then(function (result) {
    var token = result.credential.accessToken;
    var user = result.user;
    const additionalUserInfo = getAdditionalUserInfo(userCredential);
    if (additionalUserInfo.isNewUser) {
      // if new user i want to redirect to some other page.
    } else {
      // if user already exist, i want to redirect to home page
    }
  })
  .catch(function (error) {
    // Handle Errors here.
  });


来源: stackexchange

问:
Display Array as a Table
I am trying to print a table using PHP/HTML. Data stored inside array like this:

```<code>Array ( [id] => 1 [first_name] => mike [last_name] => lastname )
</code>```

My code is as follow. It runs and there are no error however the output is not as expected. Here is the PHP/HTML code:

```<code><table>

<tr>
    <th>1</th>
    <th>2</th>
    <th>3</th>
</tr>

<?php foreach ($res as $item): ?>
<tr>
     <td><?php echo $item['id'] ?></td>
     <td><?php echo $item['first_name'] ?></td>
     <td><?php echo $item['last_name'] ?></td>
</tr>
<?php endforeach; ?>

</table>
</code>```

The result I get is the first character of the items:

```<code>1       2      3
1       1      1
m       m      m
l       l      l
</code>```

Not sure what I am doing wrong? I would really appreciate an explanation.

UPDATE:

PHP CODE that has no errors:

```<code><?php
    foreach ($result as $row)
    {
        echo '<tr>';
        echo '<td>' . $row['id'] . '</td>';
        echo '<td>' . $row['first_name'] . '</td>';
        echo '<td>' . $row['last_name'] . '</td>';
        echo '</tr>';
    }
?>
</code>```

And this is my array with only one "row" in it:

Output of $result variable using print_r($result) wrapped with
 tags

```<code>Array
(
    [id] => 3
    [first_name] => Jim
    [last_name] => Dude
)
</code>```

Here is the result I am getting:

Actual Table result:

```<code>ID    First Name  Last Name
3     3           3
J     J           J
D     D           D
</code>```

However if I have 0 in array or more than 1 (meaning 2 or more) it works perfectly. IT JUST DOES NOT WORK WHEN I HAVE ONLY ONE "ROW" OF ELEMENTS INSIDE ARRAY. For example this array, works perfectly:

```<code>  Array
    (
    [0] => Array
        (
            [id] => 3
            [first_name] => Jim
            [last_name] => Dude
        )

    [1] => Array
        (
            [id] => 4
            [first_name] => John
            [last_name] => Dude2
        )
    )
</code>```

I get this result:

```<code>ID      First Name    Last Name
3       Jim         Dude
4       John            Dude2
</code>```

I am not really sure what I am doing wrong. The idea is not knowing how many items is in a Table read it into $result variable and then using this variable print all elements inside HTML table. Table could contain O elements, 1 row of elements, 1 or more rows of elements.

答:
In addition to @Phrank, it was more useful for me when I did it this way

```<code>function  show_array_as_table($array,$key_color='blue',$value_color="black",$fontfamily="arial",$fontsize="12pt") {

    foreach($array as $key => $value) {
        if (is_array($value)) {
    echo "<tr>";
    echo "<td title=\"{$key}\" style='width:150pt; height:25pt; text-align:right; vertical-align:top; background-color:cccccc; color:{$key_color}'><b>{$key}</b></td>";
        show_array_as_table($value,$key_color,$value_color,$fontfamily,$fontsize);
    echo "</tr>";
        } else {
    echo "<td style='width:300pt; height:25pt; text-align:justify; vertical-align:top; color:{$value_color}'>";
        echo "<i>{$value}</i>";
    echo "</td>";
        }
    }
}

echo "<table class='table'>";
echo show_array_as_table($reader);
echo "</table>";
</code>```

ContentLicense: CC BY-SA 3.0

Title: Display Array as a Table

Body:
I am trying to print a table using PHP/HTML. Data stored inside array like this:

Array ( [id] => 1 [first_name] => mike [last_name] => lastname )

My code is as follow. It runs and there are no error however the output is not as expected. Here is the PHP/HTML code:

    1
    2
    3

<?php foreach ($res as $item): ?>

     <?php echo $item['id'] ?>
     <?php echo $item['first_name'] ?>
     <?php echo $item['last_name'] ?>

<?php endforeach; ?>

The result I get is the first character of the items:

1       2      3
1       1      1
m       m      m
l       l      l

Not sure what I am doing wrong? I would really appreciate an explanation.

UPDATE:

PHP CODE that has no errors:

<?php
    foreach ($result as $row)
    {
        echo '
';
        echo '' . $row['id'] . '	';
        echo '' . $row['first_name'] . '	';
        echo '' . $row['last_name'] . '	';
        echo '
';
    }
?>

And this is my array with only one "row" in it:

Output of $result variable using print_r($result) wrapped with
 tags

Array
(
    [id] => 3
    [first_name] => Jim
    [last_name] => Dude
)

Here is the result I am getting:

Actual Table result:

ID    First Name  Last Name
3     3           3
J     J           J
D     D           D

However if I have 0 in array or more than 1 (meaning 2 or more) it works perfectly. IT JUST DOES NOT WORK WHEN I HAVE ONLY ONE "ROW" OF ELEMENTS INSIDE ARRAY. For example this array, works perfectly:

  Array
    (
    [0] => Array
        (
            [id] => 3
            [first_name] => Jim
            [last_name] => Dude
        )

    [1] => Array
        (
            [id] => 4
            [first_name] => John
            [last_name] => Dude2
        )
    )

I get this result:

ID      First Name    Last Name
3       Jim         Dude
4       John            Dude2

I am not really sure what I am doing wrong. The idea is not knowing how many items is in a Table read it into $result variable and then using this variable print all elements inside HTML table. Table could contain O elements, 1 row of elements, 1 or more rows of elements.

Body:
In addition to @Phrank, it was more useful for me when I did it this way

function  show_array_as_table($array,$key_color='blue',$value_color="black",$fontfamily="arial",$fontsize="12pt") {

    foreach($array as $key => $value) {
        if (is_array($value)) {
    echo "<tr>";
    echo "<td title=\"{$key}\" style='width:150pt; height:25pt; text-align:right; vertical-align:top; background-color:cccccc; color:{$key_color}'><b>{$key}</b></td>";
        show_array_as_table($value,$key_color,$value_color,$fontfamily,$fontsize);
    echo "</tr>";
        } else {
    echo "<td style='width:300pt; height:25pt; text-align:justify; vertical-align:top; color:{$value_color}'>";
        echo "<i>{$value}</i>";
    echo "</td>";
        }
    }
}

echo "<table class='table'>";
echo show_array_as_table($reader);
echo "</table>";

ContentLicense: CC BY-SA 4.0


问:
application for mobile devices
there are so many platfroms mac/Andriod/windows. can we make one application which will work on all platform  I don't want make seperate binaries for all platforms. will j2me help us in achieving this?</p>

答: Web application based on HTML 5</p>

Title: application for mobile devices

Body: Web application based on HTML 5


问:
Django TypeError get() argument after ** must be a mapping, not list
I'm creating a serializer for a model with a ManyToManyField (tag_id) that refers to a Tag table.

serializers.py

```<code>class CombinationSerializer(serializers.ModelSerializer):
  # tag_id = serializers.PrimaryKeyRelatedField(queryset=Tag.objects.all(), source='tag', required=False, many=True)
  tag_id = TagWithIdSerializer(many=True, required=False, write_only=False)
  resource_id = serializers.PrimaryKeyRelatedField(queryset=Resource.objects.all(),
                                                   required=True,
                                                   source='resource',
                                                   write_only=False)
  gameround_id = serializers.PrimaryKeyRelatedField(queryset=Gameround.objects.all(),
                                                    required=False,
                                                    source='gameround',
                                                    write_only=False)
  user_id = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all(),
                                               required=False,
                                               source='user',
                                               write_only=False)

  class Meta:
    model = Combination
    depth = 1
    fields = ('id', 'user_id', 'gameround_id', 'resource_id', 'tag_id', 'created', 'score')

  def create(self, validated_data):
    user = None
    request = self.context.get("request")
    if request and hasattr(request, "user"):
      user = request.user

    score = 0

    combination = Combination(
      user=user,
      gameround=validated_data.get("gameround"),
      resource=validated_data.get("resource"),
      created=datetime.now(),
      score=score
    )
    combination.save()

    tag_data = validated_data.pop('tag_id', None)
    if tag_data:
      tag = Tag.objects.get_or_create(**tag_data)[0]
      validated_data['tag_id'] = tag

    combination.tag_id.add(validated_data.get("tag_id"))
    return combination
</code>```

This is the problematic code:

```<code>tag_data = validated_data.pop('tag_id', None)
    if tag_data:
      tag = Tag.objects.get_or_create(**tag_data)[0]
      validated_data['tag_id'] = tag

    combination.tag_id.add(validated_data.get("tag_id"))
</code>```

This is the JSON object I am trying to send in Postman:

```<code>{
        "gameround_id": 2015685170,
        "resource_id": 327888,
        "tag_id": [{"id": 2001372884, "name": "combination", "language": "en"}]
}
</code>```

What am I doing wrong here? Can this be done any other way?

答:
The tag_id maps on a list of dictionaries, not a dictionary. You thus can enumerate over it:

```<code>tag_data = validated_data.pop('tag_id', None)
<strong>for tag_item in</strong> tag_data:
    tag = Tag.objects.get_or_create(<strong>**tag_item</strong>)[0]
    validated_data['tag_id'] = tag</code>```

since these are lists, it might be better however to make a list of tags in the validated data:

```<code>tag_data = validated_data.pop('tag_id', None)
validated_data['tag_id'] = <strong>[</strong>
    Tag.objects.get_or_create(**tag_item)[0]
    for tag_item in tag_data
<strong>]</strong></code>```

Body:
I'm creating a serializer for a model with a ManyToManyField (tag_id) that refers to a Tag table.

serializers.py

class CombinationSerializer(serializers.ModelSerializer):
  # tag_id = serializers.PrimaryKeyRelatedField(queryset=Tag.objects.all(), source='tag', required=False, many=True)
  tag_id = TagWithIdSerializer(many=True, required=False, write_only=False)
  resource_id = serializers.PrimaryKeyRelatedField(queryset=Resource.objects.all(),
                                                   required=True,
                                                   source='resource',
                                                   write_only=False)
  gameround_id = serializers.PrimaryKeyRelatedField(queryset=Gameround.objects.all(),
                                                    required=False,
                                                    source='gameround',
                                                    write_only=False)
  user_id = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all(),
                                               required=False,
                                               source='user',
                                               write_only=False)

  class Meta:
    model = Combination
    depth = 1
    fields = ('id', 'user_id', 'gameround_id', 'resource_id', 'tag_id', 'created', 'score')

  def create(self, validated_data):
    user = None
    request = self.context.get("request")
    if request and hasattr(request, "user"):
      user = request.user

    score = 0

    combination = Combination(
      user=user,
      gameround=validated_data.get("gameround"),
      resource=validated_data.get("resource"),
      created=datetime.now(),
      score=score
    )
    combination.save()

    tag_data = validated_data.pop('tag_id', None)
    if tag_data:
      tag = Tag.objects.get_or_create(**tag_data)[0]
      validated_data['tag_id'] = tag

    combination.tag_id.add(validated_data.get("tag_id"))
    return combination

This is the problematic code:

tag_data = validated_data.pop('tag_id', None)
    if tag_data:
      tag = Tag.objects.get_or_create(**tag_data)[0]
      validated_data['tag_id'] = tag

    combination.tag_id.add(validated_data.get("tag_id"))

This is the JSON object I am trying to send in Postman:

{
        "gameround_id": 2015685170,
        "resource_id": 327888,
        "tag_id": [{"id": 2001372884, "name": "combination", "language": "en"}]
}

What am I doing wrong here? Can this be done any other way?

Body:
The tag_id maps on a list of dictionaries, not a dictionary. You thus can enumerate over it:

tag_data = validated_data.pop('tag_id', None)
for tag_item in tag_data:
    tag = Tag.objects.get_or_create(**tag_item)[0]
    validated_data['tag_id'] = tag

since these are lists, it might be better however to make a list of tags in the validated data:

tag_data = validated_data.pop('tag_id', None)
validated_data['tag_id'] = [
    Tag.objects.get_or_create(**tag_item)[0]
    for tag_item in tag_data
]


问:
How to parse numbers in strings and sort them?
I have an array of strings and I need to sort them first numerically if it contains a number and then if not sort alphanumerically.

Example:

```<code>const array = ["test 3","test 1","some test","another test","test 2"];
</code>```

Expected result: test 1, test 2 , test 3, another test, some test

Preference for es6 solution.

答:
const array = ["test 3","test 1","some test","another test","test 2"];
array.sort(function(a, b) {
    let aNumber = a.replace( /^\D+/g, '');
    let bNumber = b.replace( /^\D+/g, '');
    if (aNumber.length * bNumber.length) {
        a = parseInt(aNumber);
        b = parseInt(bNumber);
    } else if (aNumber.length + bNumber.length) {
        return aNumber.length ? -1 : 1;
    }
    return ((a === b) ? 0 : ((a > b) ? 1 : -1));
})
console.log(array);```

So, you have three main cases

1: Both items contain numbers. In this case you need to extract the numbers from both and compare them

2: Exactly 1 item contains numbers. In this case it will precede the other value

3: None of the items contain numbers. In this case we compare the items as they are

Body:
I have an array of strings and I need to sort them first numerically if it contains a number and then if not sort alphanumerically.

Example:

const array = ["test 3","test 1","some test","another test","test 2"];

Expected result: test 1, test 2 , test 3, another test, some test

Preference for es6 solution.

Body:
const array = ["test 3","test 1","some test","another test","test 2"];
array.sort(function(a, b) {
    let aNumber = a.replace( /^\D+/g, '');
    let bNumber = b.replace( /^\D+/g, '');
    if (aNumber.length * bNumber.length) {
        a = parseInt(aNumber);
        b = parseInt(bNumber);
    } else if (aNumber.length + bNumber.length) {
        return aNumber.length ? -1 : 1;
    }
    return ((a === b) ? 0 : ((a > b) ? 1 : -1));
})
console.log(array);

So, you have three main cases

1: Both items contain numbers. In this case you need to extract the numbers from both and compare them

2: Exactly 1 item contains numbers. In this case it will precede the other value

3: None of the items contain numbers. In this case we compare the items as they are


问:
Setting id tag dynamically using vuejs
I have a vue.js template that has a todo prop. I want to dynamically set the id value of each element. This what I have tried so far, is something like this possible and if not what are some other options?</p>

```<code><canvas class="canvas" id="cv`${{todo.id}}`" width="500" height="700"></canvas>
</code>```

答:
This helped me to solve my problem :

<input v-bind:id="object.value1" v-model="object.value2"/>

Title: Setting id tag dynamically using vuejs

Body:
I have a vue.js template that has a todo prop. I want to dynamically set the id value of each element. This what I have tried so far, is something like this possible and if not what are some other options?

<canvas class="canvas" id="cv`${{todo.id}}`" width="500" height="700"></canvas>


问:
kustomize: how to pass `newTag` as Label
I am using https://kustomize.io/ have below is my kustomization.yaml file,

I would like to pass newTag image version to labels on deployment.yaml when i use ArgoCD to apply this file. Does anyone have any idea without using shell script to sed the newtag to deployment.yaml file.

deployment.yaml

```<code>apiVersion: "apps/v1"
kind: "Deployment"
metadata:
  name: "hellowolrd"
spec:
  template:
    metadata:
      labels:
        app: aggregate
        appversion: ${newtag} <<<<<
</code>```

kustomization.yaml

```<code>apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
images:
- name: hellowolrd
  newName: hellowolrd
  newTag: 12345
</code>```

答:
You can't do this directly with newTag value. However you can use a PatchTransformer built-in plugin to change appversion value.

Add this

resources:
  - deployment.yaml
patches:
  - patch: |-
      - op: replace
        path: /spec/template/metadata/labels/appversion
        value: v2
    target:
      kind: Deployment
```
<p>to your <em>kustomization.yaml</em>, and run <code>kustomize build</code>.<br />
The result will look like this</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: hellowolrd
spec:
  template:
    metadata:
      labels:
        app: aggregate
        appversion: v2
</code>```

Yo ucan read more here.

Body:
I am using https://kustomize.io/ have below is my kustomization.yaml file,

I would like to pass newTag image version to labels on deployment.yaml when i use ArgoCD to apply this file. Does anyone have any idea without using shell script to sed the newtag to deployment.yaml file.

deployment.yaml

apiVersion: "apps/v1"
kind: "Deployment"
metadata:
  name: "hellowolrd"
spec:
  template:
    metadata:
      labels:
        app: aggregate
        appversion: ${newtag} <<<<<

kustomization.yaml

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
images:
- name: hellowolrd
  newName: hellowolrd
  newTag: 12345

Body:
You can't do this directly with newTag value. However you can use a PatchTransformer built-in plugin to change appversion value.

Add this

resources:
  - deployment.yaml
patches:
  - patch: |-
      - op: replace
        path: /spec/template/metadata/labels/appversion
        value: v2
    target:
      kind: Deployment

to your kustomization.yaml, and run kustomize build.

The result will look like this

apiVersion: apps/v1
kind: Deployment
metadata:
  name: hellowolrd
spec:
  template:
    metadata:
      labels:
        app: aggregate
        appversion: v2

Yo ucan read more here.


问:
JPA named queries
I have a java class that implements serializable and the class begins with :

```<code>@NamedQueries( {
@NamedQuery(....)
@NamedQuery(....)
...
..})
</code>```

My question is at what stage these queries are going to be executed because i see no direct call to these queries by their name
Project is using JPA. I think IBM implementation of JPA...surely not hibernate.

Thank you

答:
Each named query has a name and the query is executed by invoking EntityManager.createnamedQuery().

If the name of the query is based on a constant, you can search the usages of the constant in your project or if it's just a string, you can a text search in your project.

If you don't find any usages, there's a chance that those queries are not used at all, unless there's another framework that is invoking them (by doing something like convention over configuration).

Title: JPA named queries

Body:
I have a java class that implements serializable and the class begins with :

@NamedQueries( {
@NamedQuery(....)
@NamedQuery(....)
...
..})

My question is at what stage these queries are going to be executed because i see no direct call to these queries by their name
Project is using JPA. I think IBM implementation of JPA...surely not hibernate.

Thank you


问:
Quickblox Video call Session creation in iOS
I am unable to create session for a user even user logged into the account.

here is my code:

```<code> //Create new session
  let session = QBRTCClient.instance().createNewSession(withOpponents: opponentsIDs, with: conferenceType)
        if session.id.isEmpty == false {
             self.session = session
             self.sessionID = session.id
        guard let uuid = UUID(uuidString: session.id) else {
                     return
        }
</code>```

the opponentsIDs I am passing from UsersDataSource()from Quickblox
conferenceType is .video

respone: 2021-03-12 15:31:11.888 rtc::[RTCClient] You have to be logged in in order to use Chat API

答:
Looks like you have to be connected to chat before creating a call session. Here is their guide - https://docs.quickblox.com/docs/ios-chat-connection#connect-to-chat-server

QuickBlox WebRTC signaling goes over XMPP protocol (that's why you have to be connected to chat first)

Body:
I am unable to create session for a user even user logged into the account.

here is my code:

 //Create new session
  let session = QBRTCClient.instance().createNewSession(withOpponents: opponentsIDs, with: conferenceType)
        if session.id.isEmpty == false {
             self.session = session
             self.sessionID = session.id
        guard let uuid = UUID(uuidString: session.id) else {
                     return
        }

the opponentsIDs I am passing from UsersDataSource()from Quickblox
conferenceType is .video

respone: 2021-03-12 15:31:11.888 rtc::[RTCClient] You have to be logged in in order to use Chat API


问:
How to create DynamoDB table using docker CMD instruction and the AWS CLI inside running container?
Hello have a simple Dockerfile which has to create the DynamoDB tables:

```<code>FROM amazon/aws-cli AS seed

CMD \
aws dynamodb --endpoint-url http://localhost:8080 create-table \
    --table-name mytable \
    --attribute-definitions AttributeName=user_id,AttributeType=N AttributeName=order_id,AttributeType=N \
    --key-schema AttributeName=user_id,KeyType=HASH AttributeName=order_id,KeyType=RANGE \
    --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \
    --region eu-west-2
</code>```

When I'm trying to run it I get the following output:

```<code>Attaching to my-container
my-container       |
my-container       | usage: aws [options] <command> <subcommand> [<subcommand> ...] [parameters]
my-container       | To see help text, you can run:
my-container       |
my-container       |   aws help
my-container       |   aws <command> help
my-container       |   aws <command> <subcommand> help
my-container       |
my-container       | aws: error: argument command: Invalid choice, valid choices are:
my-container       |
my-container       | accessanalyzer                           | account
my-container       | acm                                      | acm-pca
my-container       | alexaforbusiness                         | amp
my-container       | amplify                                  | amplifybackend
my-container       | amplifyuibuilder                         | apigateway
my-container       | apigatewaymanagementapi                  | apigatewayv2

// Lot of services in here

my-container       | s3                                       | ddb
my-container       | configure                                | deploy
my-container       | configservice                            | opsworks-cm
my-container       | history                                  | cli-dev
my-container       | help
my-container       |
my-container exited with code 252
</code>```

What am I doing wrong? Thanks for any help!

答:
In your command you must not have a space after \  that why maybe you recevie the error because the rest statements is ignored.

Try test again  with this :

```<code>aws dynamodb --endpoint-url http://localhost:8080 create-table \
--table-name mytable \
--attribute-definitions AttributeName=user_id,AttributeType=N AttributeName=order_id,AttributeType=N \
--key-schema AttributeName=user_id,KeyType=HASH AttributeName=order_id,KeyType=RANGE \
--provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \
--region eu-west-2
</code>```

And also try to have a fake profile, because its need an access key and a secret key even if its locally

Body:
Hello have a simple Dockerfile which has to create the DynamoDB tables:

FROM amazon/aws-cli AS seed

CMD \
aws dynamodb --endpoint-url http://localhost:8080 create-table \
    --table-name mytable \
    --attribute-definitions AttributeName=user_id,AttributeType=N AttributeName=order_id,AttributeType=N \
    --key-schema AttributeName=user_id,KeyType=HASH AttributeName=order_id,KeyType=RANGE \
    --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \
    --region eu-west-2

When I'm trying to run it I get the following output:

Attaching to my-container
my-container       |
my-container       | usage: aws [options] <command> <subcommand> [<subcommand> ...] [parameters]
my-container       | To see help text, you can run:
my-container       |
my-container       |   aws help
my-container       |   aws <command> help
my-container       |   aws <command> <subcommand> help
my-container       |
my-container       | aws: error: argument command: Invalid choice, valid choices are:
my-container       |
my-container       | accessanalyzer                           | account
my-container       | acm                                      | acm-pca
my-container       | alexaforbusiness                         | amp
my-container       | amplify                                  | amplifybackend
my-container       | amplifyuibuilder                         | apigateway
my-container       | apigatewaymanagementapi                  | apigatewayv2

// Lot of services in here

my-container       | s3                                       | ddb
my-container       | configure                                | deploy
my-container       | configservice                            | opsworks-cm
my-container       | history                                  | cli-dev
my-container       | help
my-container       |
my-container exited with code 252

What am I doing wrong? Thanks for any help!

Body:
In your command you must not have a space after \  that why maybe you recevie the error because the rest statements is ignored.

Try test again  with this :

aws dynamodb --endpoint-url http://localhost:8080 create-table \
--table-name mytable \
--attribute-definitions AttributeName=user_id,AttributeType=N AttributeName=order_id,AttributeType=N \
--key-schema AttributeName=user_id,KeyType=HASH AttributeName=order_id,KeyType=RANGE \
--provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \
--region eu-west-2

And also try to have a fake profile, because its need an access key and a secret key even if its locally


问:
"Publishing changes from background threads is not allowed" while fetching data using URLSession
I am trying to fetch data from the Unsplash API however I am getting the following error: "Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates."

Here is the model struct:

// MARK: - UnsplashData
struct UnsplashData: Codable {
    let id: String
    let createdAt, updatedAt, promotedAt: Date
    let width, height: Int
    let color, blurHash: String
    let unsplashDataDescription: String?
    let altDescription: String
    let urls: Urls
    let links: UnsplashDataLinks
    let categories: [String]
    let likes: Int
    let likedByUser: Bool
    let currentUserCollections: [String]
    let sponsorship: JSONNull?
    let user: User
    let exif: Exif
    let location: Location
    let views, downloads: Int

    enum CodingKeys: String, CodingKey {
        case id
        case createdAt = "created_at"
        case updatedAt = "updated_at"
        case promotedAt = "promoted_at"
        case width, height, color
        case blurHash = "blur_hash"
        case unsplashDataDescription = "description"
        case altDescription = "alt_description"
        case urls, links, categories, likes
        case likedByUser = "liked_by_user"
        case currentUserCollections = "current_user_collections"
        case sponsorship, user, exif, location, views, downloads
    }
}

// MARK: - Exif
struct Exif: Codable {
    let make, model, exposureTime, aperture: String
    let focalLength: String
    let iso: Int

    enum CodingKeys: String, CodingKey {
        case make, model
        case exposureTime = "exposure_time"
        case aperture
        case focalLength = "focal_length"
        case iso
    }
}

// MARK: - UnsplashDataLinks
struct UnsplashDataLinks: Codable {
    let linksSelf, html, download, downloadLocation: String

    enum CodingKeys: String, CodingKey {
        case linksSelf = "self"
        case html, download
        case downloadLocation = "download_location"
    }
}

// MARK: - Location
struct Location: Codable {
    let title, name, city, country: String?
    let position: Position
}

// MARK: - Position
struct Position: Codable {
    let latitude, longitude: Double?
}

// MARK: - Urls
struct Urls: Codable {
    let raw, full, regular, small: String
    let thumb: String
}

// MARK: - User
struct User: Codable {
    let id: String
    let updatedAt: Date
    let username, name, firstName, lastName: String
    let twitterUsername: String?
    let portfolioURL: String
    let bio: String?
    let location: String
    let links: UserLinks
    let profileImage: ProfileImage
    let instagramUsername: String
    let totalCollections, totalLikes, totalPhotos: Int
    let acceptedTos: Bool

    enum CodingKeys: String, CodingKey {
        case id
        case updatedAt = "updated_at"
        case username, name
        case firstName = "first_name"
        case lastName = "last_name"
        case twitterUsername = "twitter_username"
        case portfolioURL = "portfolio_url"
        case bio, location, links
        case profileImage = "profile_image"
        case instagramUsername = "instagram_username"
        case totalCollections = "total_collections"
        case totalLikes = "total_likes"
        case totalPhotos = "total_photos"
        case acceptedTos = "accepted_tos"
    }
}

// MARK: - UserLinks
struct UserLinks: Codable {
    let linksSelf, html, photos, likes: String
    let portfolio, following, followers: String

    enum CodingKeys: String, CodingKey {
        case linksSelf = "self"
        case html, photos, likes, portfolio, following, followers
    }
}

// MARK: - ProfileImage
struct ProfileImage: Codable {
    let small, medium, large: String
}

// MARK: - Encode/decode helpers

class JSONNull: Codable, Hashable {

    public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool {
        return true
    }

    public var hashValue: Int {
        return 0
    }

    public func hash(into hasher: inout Hasher) {
        // No-op
    }

    public init() {}

    public required init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        if !container.decodeNil() {
            throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull"))
        }
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encodeNil()
    }
}

```
<p>And here is my ObservableObject:</p>
<pre class="lang-swift prettyprint-override"><code>class UnsplashAPI: ObservableObject {
    enum State {
        case loading
        case loaded(UnsplashData)
    }

    @Published var state = State.loading

    let url = URL(string: "https://api.unsplash.com/")!

    func request() {
        guard var components = URLComponents(url: url.appendingPathComponent("photos/random"),
                                             resolvingAgainstBaseURL: true)
        else {
            fatalError("Couldn't append path component")
        }

        components.queryItems = [
            URLQueryItem(name: "client_id", value: "vMDQ3Vzix8FN6MJL5Qpl3y0F7GdQsTtOjBe_L-IG2ro")
        ]

        let request = URLRequest(url: components.url!)

        let urlSession = URLSession(configuration: URLSessionConfiguration.default)
        urlSession.dataTask(with: request) { data, urlResponse, error in
            if let data = data {
                let decoder = JSONDecoder()
                let dateFormatter = DateFormatter()
                dateFormatter.locale = Locale(identifier: "en_US_POSIX")
                dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
                decoder.dateDecodingStrategy = .formatted(dateFormatter)
                do {
                    let response = try decoder.decode(UnsplashData.self, from: data)
                    self.state = .loaded(response) //error here
                } catch {
                    print(error)
                    fatalError("Couldn't decode")
                }
            } else if let error = error {
                print(error.localizedDescription)
            } else {
                fatalError("Didn't receive data")
            }
        }.resume()
    }
}
</code>```

Finally here is an example response I requested using Postman:

{
    "id": "HWx5PYGudcI",
    "created_at": "2020-12-08T22:11:11-05:00",
    "updated_at": "2020-12-26T23:19:29-05:00",
    "promoted_at": "2020-12-09T03:14:06-05:00",
    "width": 4000,
    "height": 6000,
    "color": "#8ca6a6",
    "blur_hash": "LAD,r_D*_M?^%ER4%$-oyYp0m+WE",
    "description": null,
    "alt_description": "boy in gray crew neck shirt",
    "urls": {
        "raw": "https://images.unsplash.com/photo-1607483421673-181fb79394b3?ixid=MXwxMTU5MTR8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1",
        "full": "https://images.unsplash.com/photo-1607483421673-181fb79394b3?crop=entropy&cs=srgb&fm=jpg&ixid=MXwxMTU5MTR8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=85",
        "regular": "https://images.unsplash.com/photo-1607483421673-181fb79394b3?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxMTU5MTR8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=1080",
        "small": "https://images.unsplash.com/photo-1607483421673-181fb79394b3?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxMTU5MTR8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=400",
        "thumb": "https://images.unsplash.com/photo-1607483421673-181fb79394b3?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxMTU5MTR8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=200"
    },
    "links": {
        "self": "https://api.unsplash.com/photos/HWx5PYGudcI",
        "html": "https://unsplash.com/photos/HWx5PYGudcI",
        "download": "https://unsplash.com/photos/HWx5PYGudcI/download",
        "download_location": "https://api.unsplash.com/photos/HWx5PYGudcI/download"
    },
    "categories": [],
    "likes": 51,
    "liked_by_user": false,
    "current_user_collections": [],
    "sponsorship": null,
    "user": {
        "id": "3Bj-zCFL4-g",
        "updated_at": "2020-12-26T14:58:36-05:00",
        "username": "owensito",
        "name": "Owen Vangioni",
        "first_name": "Owen",
        "last_name": "Vangioni",
        "twitter_username": null,
        "portfolio_url": null,
        "bio": "Capturing magical moments...\nInstagram: @owensitens                        18 years",
        "location": "Argentina ",
        "links": {
            "self": "https://api.unsplash.com/users/owensito",
            "html": "https://unsplash.com/@owensito",
            "photos": "https://api.unsplash.com/users/owensito/photos",
            "likes": "https://api.unsplash.com/users/owensito/likes",
            "portfolio": "https://api.unsplash.com/users/owensito/portfolio",
            "following": "https://api.unsplash.com/users/owensito/following",
            "followers": "https://api.unsplash.com/users/owensito/followers"
        },
        "profile_image": {
            "small": "https://images.unsplash.com/profile-1583211530737-0c1a46227535image?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=32&w=32",
            "medium": "https://images.unsplash.com/profile-1583211530737-0c1a46227535image?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=64&w=64",
            "large": "https://images.unsplash.com/profile-1583211530737-0c1a46227535image?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=128&w=128"
        },
        "instagram_username": "owensitens",
        "total_collections": 1,
        "total_likes": 13,
        "total_photos": 135,
        "accepted_tos": true
    },
    "exif": {
        "make": "NIKON CORPORATION",
        "model": "NIKON D3300",
        "exposure_time": "1/320",
        "aperture": "5.3",
        "focal_length": "45.0",
        "iso": 200
    },
    "location": {
        "title": null,
        "name": null,
        "city": null,
        "country": null,
        "position": {
            "latitude": null,
            "longitude": null
        }
    },
    "views": 536045,
    "downloads": 1267
}
```

答: add @MainActor before your class definition.</p>

Body:
I am trying to fetch data from the Unsplash API however I am getting the following error: "Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates."

Here is the model struct:

// MARK: - UnsplashData
struct UnsplashData: Codable {
    let id: String
    let createdAt, updatedAt, promotedAt: Date
    let width, height: Int
    let color, blurHash: String
    let unsplashDataDescription: String?
    let altDescription: String
    let urls: Urls
    let links: UnsplashDataLinks
    let categories: [String]
    let likes: Int
    let likedByUser: Bool
    let currentUserCollections: [String]
    let sponsorship: JSONNull?
    let user: User
    let exif: Exif
    let location: Location
    let views, downloads: Int

    enum CodingKeys: String, CodingKey {
        case id
        case createdAt = "created_at"
        case updatedAt = "updated_at"
        case promotedAt = "promoted_at"
        case width, height, color
        case blurHash = "blur_hash"
        case unsplashDataDescription = "description"
        case altDescription = "alt_description"
        case urls, links, categories, likes
        case likedByUser = "liked_by_user"
        case currentUserCollections = "current_user_collections"
        case sponsorship, user, exif, location, views, downloads
    }
}

// MARK: - Exif
struct Exif: Codable {
    let make, model, exposureTime, aperture: String
    let focalLength: String
    let iso: Int

    enum CodingKeys: String, CodingKey {
        case make, model
        case exposureTime = "exposure_time"
        case aperture
        case focalLength = "focal_length"
        case iso
    }
}

// MARK: - UnsplashDataLinks
struct UnsplashDataLinks: Codable {
    let linksSelf, html, download, downloadLocation: String

    enum CodingKeys: String, CodingKey {
        case linksSelf = "self"
        case html, download
        case downloadLocation = "download_location"
    }
}

// MARK: - Location
struct Location: Codable {
    let title, name, city, country: String?
    let position: Position
}

// MARK: - Position
struct Position: Codable {
    let latitude, longitude: Double?
}

// MARK: - Urls
struct Urls: Codable {
    let raw, full, regular, small: String
    let thumb: String
}

// MARK: - User
struct User: Codable {
    let id: String
    let updatedAt: Date
    let username, name, firstName, lastName: String
    let twitterUsername: String?
    let portfolioURL: String
    let bio: String?
    let location: String
    let links: UserLinks
    let profileImage: ProfileImage
    let instagramUsername: String
    let totalCollections, totalLikes, totalPhotos: Int
    let acceptedTos: Bool

    enum CodingKeys: String, CodingKey {
        case id
        case updatedAt = "updated_at"
        case username, name
        case firstName = "first_name"
        case lastName = "last_name"
        case twitterUsername = "twitter_username"
        case portfolioURL = "portfolio_url"
        case bio, location, links
        case profileImage = "profile_image"
        case instagramUsername = "instagram_username"
        case totalCollections = "total_collections"
        case totalLikes = "total_likes"
        case totalPhotos = "total_photos"
        case acceptedTos = "accepted_tos"
    }
}

// MARK: - UserLinks
struct UserLinks: Codable {
    let linksSelf, html, photos, likes: String
    let portfolio, following, followers: String

    enum CodingKeys: String, CodingKey {
        case linksSelf = "self"
        case html, photos, likes, portfolio, following, followers
    }
}

// MARK: - ProfileImage
struct ProfileImage: Codable {
    let small, medium, large: String
}

// MARK: - Encode/decode helpers

class JSONNull: Codable, Hashable {

    public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool {
        return true
    }

    public var hashValue: Int {
        return 0
    }

    public func hash(into hasher: inout Hasher) {
        // No-op
    }

    public init() {}

    public required init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        if !container.decodeNil() {
            throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull"))
        }
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encodeNil()
    }
}

And here is my ObservableObject:

class UnsplashAPI: ObservableObject {
    enum State {
        case loading
        case loaded(UnsplashData)
    }

    @Published var state = State.loading

    let url = URL(string: "https://api.unsplash.com/")!

    func request() {
        guard var components = URLComponents(url: url.appendingPathComponent("photos/random"),
                                             resolvingAgainstBaseURL: true)
        else {
            fatalError("Couldn't append path component")
        }

        components.queryItems = [
            URLQueryItem(name: "client_id", value: "vMDQ3Vzix8FN6MJL5Qpl3y0F7GdQsTtOjBe_L-IG2ro")
        ]

        let request = URLRequest(url: components.url!)

        let urlSession = URLSession(configuration: URLSessionConfiguration.default)
        urlSession.dataTask(with: request) { data, urlResponse, error in
            if let data = data {
                let decoder = JSONDecoder()
                let dateFormatter = DateFormatter()
                dateFormatter.locale = Locale(identifier: "en_US_POSIX")
                dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
                decoder.dateDecodingStrategy = .formatted(dateFormatter)
                do {
                    let response = try decoder.decode(UnsplashData.self, from: data)
                    self.state = .loaded(response) //error here
                } catch {
                    print(error)
                    fatalError("Couldn't decode")
                }
            } else if let error = error {
                print(error.localizedDescription)
            } else {
                fatalError("Didn't receive data")
            }
        }.resume()
    }
}

Finally here is an example response I requested using Postman:

{
    "id": "HWx5PYGudcI",
    "created_at": "2020-12-08T22:11:11-05:00",
    "updated_at": "2020-12-26T23:19:29-05:00",
    "promoted_at": "2020-12-09T03:14:06-05:00",
    "width": 4000,
    "height": 6000,
    "color": "#8ca6a6",
    "blur_hash": "LAD,r_D*_M?^%ER4%$-oyYp0m+WE",
    "description": null,
    "alt_description": "boy in gray crew neck shirt",
    "urls": {
        "raw": "https://images.unsplash.com/photo-1607483421673-181fb79394b3?ixid=MXwxMTU5MTR8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1",
        "full": "https://images.unsplash.com/photo-1607483421673-181fb79394b3?crop=entropy&cs=srgb&fm=jpg&ixid=MXwxMTU5MTR8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=85",
        "regular": "https://images.unsplash.com/photo-1607483421673-181fb79394b3?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxMTU5MTR8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=1080",
        "small": "https://images.unsplash.com/photo-1607483421673-181fb79394b3?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxMTU5MTR8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=400",
        "thumb": "https://images.unsplash.com/photo-1607483421673-181fb79394b3?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxMTU5MTR8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=200"
    },
    "links": {
        "self": "https://api.unsplash.com/photos/HWx5PYGudcI",
        "html": "https://unsplash.com/photos/HWx5PYGudcI",
        "download": "https://unsplash.com/photos/HWx5PYGudcI/download",
        "download_location": "https://api.unsplash.com/photos/HWx5PYGudcI/download"
    },
    "categories": [],
    "likes": 51,
    "liked_by_user": false,
    "current_user_collections": [],
    "sponsorship": null,
    "user": {
        "id": "3Bj-zCFL4-g",
        "updated_at": "2020-12-26T14:58:36-05:00",
        "username": "owensito",
        "name": "Owen Vangioni",
        "first_name": "Owen",
        "last_name": "Vangioni",
        "twitter_username": null,
        "portfolio_url": null,
        "bio": "Capturing magical moments...\nInstagram: @owensitens                        18 years",
        "location": "Argentina ",
        "links": {
            "self": "https://api.unsplash.com/users/owensito",
            "html": "https://unsplash.com/@owensito",
            "photos": "https://api.unsplash.com/users/owensito/photos",
            "likes": "https://api.unsplash.com/users/owensito/likes",
            "portfolio": "https://api.unsplash.com/users/owensito/portfolio",
            "following": "https://api.unsplash.com/users/owensito/following",
            "followers": "https://api.unsplash.com/users/owensito/followers"
        },
        "profile_image": {
            "small": "https://images.unsplash.com/profile-1583211530737-0c1a46227535image?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=32&w=32",
            "medium": "https://images.unsplash.com/profile-1583211530737-0c1a46227535image?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=64&w=64",
            "large": "https://images.unsplash.com/profile-1583211530737-0c1a46227535image?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=128&w=128"
        },
        "instagram_username": "owensitens",
        "total_collections": 1,
        "total_likes": 13,
        "total_photos": 135,
        "accepted_tos": true
    },
    "exif": {
        "make": "NIKON CORPORATION",
        "model": "NIKON D3300",
        "exposure_time": "1/320",
        "aperture": "5.3",
        "focal_length": "45.0",
        "iso": 200
    },
    "location": {
        "title": null,
        "name": null,
        "city": null,
        "country": null,
        "position": {
            "latitude": null,
            "longitude": null
        }
    },
    "views": 536045,
    "downloads": 1267
}


问:
why localhost:3000/?age=12 works but localhost:3000/?age="12" doesn't in Express Node JS
When working on middleware's in Node JS, i have implemented a code on if age>=18 user can access the website otherwise not but when i type query like  localhost:3000/?age=12 it works but localhost:3000/?age="12" it doesn't works  anyone knew why it  happens and how to resolve it

code:

```<code>const express = require('express')
const app = express()
const port = 3000

// middleware
// req,res we need to modify so it is there
// next is a function it will proceed when route is called
    const reqFilter=(req,res,next)=>{
        console.log('reqFilter');
    // we have to call next otherwise it will keep loading in browaer
    // eg:-> if age is older then 18 user can access page

        if(req.query.age<18){
            res.send('Please Confirm You are over 18')
        }
        else if(!req.query.age){
            res.send("please put down age")
        }
        else{
            next();
        }

}

  // using the middleware
app.use(reqFilter)

app.get('/', (req, res) => {
    res.send("welcome to homepage")
})

app.get('/users', (req, res) => {
    res.send("welcome to users page")
})

app.listen(port, () => console.log(`Example app listening on port ${port}!`))
</code>```

答:
From express docs: https://expressjs.com/en/api.html.

```<code>As req.query’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, req.query.foo.toString() may fail in multiple ways, for example, foo may not be there or may not be a string, and toString may not be a function and instead of a string or other user-input.
</code>```

You're comparing the query parameter to the Number 18, You need to check the type of the query. You can do so with if (typeof req.query.age == 'string') and perhaps convert the "18" to a Number.
You can do so by adding + like that: +req.query.age

Body:
When working on middleware's in Node JS, i have implemented a code on if age>=18 user can access the website otherwise not but when i type query like  localhost:3000/?age=12 it works but localhost:3000/?age="12" it doesn't works  anyone knew why it  happens and how to resolve it

code:

const express = require('express')
const app = express()
const port = 3000

// middleware
// req,res we need to modify so it is there
// next is a function it will proceed when route is called
    const reqFilter=(req,res,next)=>{
        console.log('reqFilter');
    // we have to call next otherwise it will keep loading in browaer
    // eg:-> if age is older then 18 user can access page

        if(req.query.age<18){
            res.send('Please Confirm You are over 18')
        }
        else if(!req.query.age){
            res.send("please put down age")
        }
        else{
            next();
        }

}

  // using the middleware
app.use(reqFilter)

app.get('/', (req, res) => {
    res.send("welcome to homepage")
})

app.get('/users', (req, res) => {
    res.send("welcome to users page")
})

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

Body:
From express docs: https://expressjs.com/en/api.html.

As req.query’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, req.query.foo.toString() may fail in multiple ways, for example, foo may not be there or may not be a string, and toString may not be a function and instead of a string or other user-input.

You're comparing the query parameter to the Number 18, You need to check the type of the query. You can do so with if (typeof req.query.age == 'string') and perhaps convert the "18" to a Number.
You can do so by adding + like that: +req.query.age


问:
I want to make a function in C that prints a 2D array
I know how to print a 2D array without using a function (using nested for loops), but how would I implement a fuction that prints it.

This is what I tried

```<code>int print_matrix(int arr[M][N])
{
    for (int i = 0; i < M; i++)
    {
        for (int j = 0; j < N; j++)
        {
            printf("{%i}",arr[i][j]);
        }
        printf("\n");
    }
}

</code>```

答:
You want this:</p>
```<code>int print_matrix(int M, int N, int arr[M][N])
{
    for (int i = 0; i < M; i++)
    {
        for (int j = 0; j < N; j++)
        {
            printf("{%i}",arr[i][j]);
        }
        printf("\n");
    }
}

int main(int argc, char *argv[])
{
   int N = 4;
   int M = 4;
   //...
   int arr[M][N];
   //...
    print_matrix(M, N, arr);
}
</code>```

Body:
I know how to print a 2D array without using a function (using nested for loops), but how would I implement a fuction that prints it.

This is what I tried

int print_matrix(int arr[M][N])
{
    for (int i = 0; i < M; i++)
    {
        for (int j = 0; j < N; j++)
        {
            printf("{%i}",arr[i][j]);
        }
        printf("\n");
    }
}

Body:
You want this:

int print_matrix(int M, int N, int arr[M][N])
{
    for (int i = 0; i < M; i++)
    {
        for (int j = 0; j < N; j++)
        {
            printf("{%i}",arr[i][j]);
        }
        printf("\n");
    }
}

int main(int argc, char *argv[])
{
   int N = 4;
   int M = 4;
   //...
   int arr[M][N];
   //...
    print_matrix(M, N, arr);
}


问:
C# .Net Core Web API Check CustomSignature
I am new the API in general, let me give you the background of the API and what I want it to do.

I have a API have that are external facing and so every incoming request are required to check the signature from header. literality my code in every controller call are checking the signature and created many duplicated code.

my question is how can reduces those duplicated code ? do I use Custom Attributes, or AuthorizeAttribute

here are some of the example code:

```<code>[Route("[controller]")]
[ApiController]
public class ExampleController : ControllerBase
{
  public async Task<Result> Call_1(Rquest request)
  {
    string signaturel;
    signature = Util.getHeaderSignature(request);

    if(unit.IsSinatureValid(signaturel, someVar1, someVar2))
    {
      (My logic)
    }
    else{ return "InvalidSinaturemessage" }
  }
  public async Task<Result> Call_2(Rquest request)
  {
    string signaturel;
    signature = Util.getHeaderSignature(request);

    if(unit.IsSinatureValid(signaturel, someVar1, someVar2))
    {
      (My logic)
    }
    else{ return "InvalidSinaturemessage" }
  }
}
</code>```

above code is just for showing, the actual Sinature checking logic is around 20 lines of code on every single controller method.

答:
Yes, you can do that using action filters. It's described in documentation

Put your code for checking into OnActionExecuting method. So, you can write Result in the action filter if the signature isn't valid.

In case you need specific result structure you can create your own ObjectResult:

```<code>public class ForbiddenObjectResult : ObjectResult
{
    public string Message { get; private set; }
    public ForbiddenObjectResult(object value, string message)
        : base(value)
    {
        StatusCode = StatusCodes.Status403Forbidden;
        Message = message;
    }
}

...
string signaturel;
signature = Util.getHeaderSignature(context.HttpContext.Request);

if(!unit.IsSinatureValid(signaturel, someVar1, someVar2))
{
    context.Result = new ForbiddenObjectResult(filterContext.ModelState, "InvalidSinaturemessage");
}
</code>```

And to register it for all your endpoints(if needed):

```<code>services.AddControllersWithViews(options =>
{
    options.Filters.Add<YourActionFilter>();
});
</code>```

Body:
I am new the API in general, let me give you the background of the API and what I want it to do.

I have a API have that are external facing and so every incoming request are required to check the signature from header. literality my code in every controller call are checking the signature and created many duplicated code.

my question is how can reduces those duplicated code ? do I use Custom Attributes, or AuthorizeAttribute

here are some of the example code:

[Route("[controller]")]
[ApiController]
public class ExampleController : ControllerBase
{
  public async Task<Result> Call_1(Rquest request)
  {
    string signaturel;
    signature = Util.getHeaderSignature(request);

    if(unit.IsSinatureValid(signaturel, someVar1, someVar2))
    {
      (My logic)
    }
    else{ return "InvalidSinaturemessage" }
  }
  public async Task<Result> Call_2(Rquest request)
  {
    string signaturel;
    signature = Util.getHeaderSignature(request);

    if(unit.IsSinatureValid(signaturel, someVar1, someVar2))
    {
      (My logic)
    }
    else{ return "InvalidSinaturemessage" }
  }
}

above code is just for showing, the actual Sinature checking logic is around 20 lines of code on every single controller method.

Body:
Yes, you can do that using action filters. It's described in documentation

Put your code for checking into OnActionExecuting method. So, you can write Result in the action filter if the signature isn't valid.

In case you need specific result structure you can create your own ObjectResult:

public class ForbiddenObjectResult : ObjectResult
{
    public string Message { get; private set; }
    public ForbiddenObjectResult(object value, string message)
        : base(value)
    {
        StatusCode = StatusCodes.Status403Forbidden;
        Message = message;
    }
}

...
string signaturel;
signature = Util.getHeaderSignature(context.HttpContext.Request);

if(!unit.IsSinatureValid(signaturel, someVar1, someVar2))
{
    context.Result = new ForbiddenObjectResult(filterContext.ModelState, "InvalidSinaturemessage");
}

And to register it for all your endpoints(if needed):

services.AddControllersWithViews(options =>
{
    options.Filters.Add<YourActionFilter>();
});


问:
FileNotFoundError despite file existing
This is the function that uses a file to return some parameters

```<code>def load_network_params(agent_name: str, env_name: str,
                        network_root_folder: str = 'jax-models') -> flax.core.FrozenDict:

    filePathString=network_root_folder+r"/"+agent_name+r"/"+env_name+r"/2"
    fileNameStr=r"ckpt.199"
    fileString=os.path.join(filePathString,fileNameStr)
    with open(fileString, 'rb') as file:
     # file processing irrelevant to error
        })
    return network_params
</code>```

This is the way the function was subsequently used:

```<code>from dataset import *
generate_dataset(r"dqn", r"Breakout", 10_000, network_root_folder=r"C:/Users/jk5g19/Documents/Year3IP/scripts/jax")
</code>```

Edit: Basically the generate_dataset calls load_network_parameter, I tried to cut down the amount of code shared, so that people would get less confused. This is the Minimum Viable product.

```<code>def generate_dataset(agent_name: str, env_name: str, dataset_size: int, num_envs: int = 20, epsilon: float = 0.1,
                     network_root_folder: str = 'jax-models') -> Tuple[onp.ndarray, onp.ndarray, onp.ndarray,
                                                                       onp.ndarray, int]:

    num_actions = gym.make(f'{env_name}NoFrameskip-v0').action_space.n

    images_obs_dataset = onp.zeros((dataset_size, 84, 84, 4))
    ram_obs_dataset = onp.zeros((dataset_size, 128))
    q_values_dataset = onp.zeros((dataset_size, num_actions))
    action_dataset = onp.zeros(dataset_size)

    network_def, network_args = get_network_def(agent_name, num_actions)
    network_params = load_network_params(agent_name, env_name, network_root_folder=network_root_folder)

    return images_obs_dataset, ram_obs_dataset, q_values_dataset, action_dataset, episodes_run
</code>```

When I output the filestring and copy and paste it into the file explorer the desired file can be accessed. I used raw strings for the path and experimented with double back slashes and forward slashes.

I also added a test.txt file in the path too, the file path did not work hence it rules out the file type causing issues with open().

screenshot of error

答:
Turns out that for my dataset_setup.py I was supposed to do this:

```<code>from dataset import *
generate_dataset(r"dqn", r"Breakout", 10_000, network_root_folder=r"/mnt/c/Users/jk5g19/Documents/Year3IP/scripts/jax")
</code>```

This was because I was using WSL. Massive thank you to @gionni for helping me come to this conclusion.

Title: FileNotFoundError despite file existing

Body:
This is the function that uses a file to return some parameters

def load_network_params(agent_name: str, env_name: str,
                        network_root_folder: str = 'jax-models') -> flax.core.FrozenDict:

    filePathString=network_root_folder+r"/"+agent_name+r"/"+env_name+r"/2"
    fileNameStr=r"ckpt.199"
    fileString=os.path.join(filePathString,fileNameStr)
    with open(fileString, 'rb') as file:
     # file processing irrelevant to error
        })
    return network_params

This is the way the function was subsequently used:

from dataset import *
generate_dataset(r"dqn", r"Breakout", 10_000, network_root_folder=r"C:/Users/jk5g19/Documents/Year3IP/scripts/jax")

Edit: Basically the generate_dataset calls load_network_parameter, I tried to cut down the amount of code shared, so that people would get less confused. This is the Minimum Viable product.

def generate_dataset(agent_name: str, env_name: str, dataset_size: int, num_envs: int = 20, epsilon: float = 0.1,
                     network_root_folder: str = 'jax-models') -> Tuple[onp.ndarray, onp.ndarray, onp.ndarray,
                                                                       onp.ndarray, int]:

    num_actions = gym.make(f'{env_name}NoFrameskip-v0').action_space.n

    images_obs_dataset = onp.zeros((dataset_size, 84, 84, 4))
    ram_obs_dataset = onp.zeros((dataset_size, 128))
    q_values_dataset = onp.zeros((dataset_size, num_actions))
    action_dataset = onp.zeros(dataset_size)

    network_def, network_args = get_network_def(agent_name, num_actions)
    network_params = load_network_params(agent_name, env_name, network_root_folder=network_root_folder)

    return images_obs_dataset, ram_obs_dataset, q_values_dataset, action_dataset, episodes_run

When I output the filestring and copy and paste it into the file explorer the desired file can be accessed. I used raw strings for the path and experimented with double back slashes and forward slashes.

I also added a test.txt file in the path too, the file path did not work hence it rules out the file type causing issues with open().

screenshot of error

Body:
Turns out that for my dataset_setup.py I was supposed to do this:

from dataset import *
generate_dataset(r"dqn", r"Breakout", 10_000, network_root_folder=r"/mnt/c/Users/jk5g19/Documents/Year3IP/scripts/jax")

This was because I was using WSL. Massive thank you to @gionni for helping me come to this conclusion.


问:
Bash Post Increment
Just a little question about the right way of doing Post-increment in bash.

```<code>while true; do
  VAR=$((CONT++))
  echo "CONT: $CONT"
  sleep 1
done
</code>```

VAR starts at 1 in this case.

```<code>CONT: 1
CONT: 2
CONT: 3
</code>```

But if I do this:

```<code>while true; do
  echo "CONT: $((CONT++))"
  sleep 1
done
</code>```

It starts at 0.

```<code>CONT: 0
CONT: 1
CONT: 2
</code>```

Seems that the the first case is behaving ok, because ((CONT++)) would evaluate CONT (undefined,¿0?) and add +1.

How can I get a behaviour like in echo statement to assign to a variable?

EDIT: In my first example, instead of echoing CONT, I should have echoed VAR, that way it works OK, so it was my error from the beginning.

答: ((CONT++)) is what increments the variable. Adding the "$" is for other purposes.

Title: Bash Post Increment

Body:
Just a little question about the right way of doing Post-increment in bash.

while true; do
  VAR=$((CONT++))
  echo "CONT: $CONT"
  sleep 1
done

VAR starts at 1 in this case.

CONT: 1
CONT: 2
CONT: 3

But if I do this:

while true; do
  echo "CONT: $((CONT++))"
  sleep 1
done

It starts at 0.

CONT: 0
CONT: 1
CONT: 2

Seems that the the first case is behaving ok, because ((CONT++)) would evaluate CONT (undefined,¿0?) and add +1.

How can I get a behaviour like in echo statement to assign to a variable?

EDIT: In my first example, instead of echoing CONT, I should have echoed VAR, that way it works OK, so it was my error from the beginning.


问:
To insert a Nim variable into its PCRE regex
How can we insert and interpolate a Nim variable into its regex (procedure re( ... )) just like Perl does ?

答:
Not quite sure why you posted this both here and on the Nim community forums. But if this comes up in someone elses search you can find my original response here. The answer is as follows:

Since the re module and re procedure takes a raw string literal you can use fmt from strformat to do this:

```<code>import re, strformat

let
  num = r"\d*"
  wordNum = re(fmt"[a-z]\w*{num}")
  wordNum2 = re"[a-z]\w*\d*"

echo find("hello123", wordNum)
echo find("hello123", wordNum2)

echo find("       hello123", wordNum)
echo find("       hello123", wordNum2)
</code>```

Note that the num string needs to be a raw literal as well, or you'd have to escape the backslash.

Body:
Not quite sure why you posted this both here and on the Nim community forums. But if this comes up in someone elses search you can find my original response here. The answer is as follows:

Since the re module and re procedure takes a raw string literal you can use fmt from strformat to do this:

import re, strformat

let
  num = r"\d*"
  wordNum = re(fmt"[a-z]\w*{num}")
  wordNum2 = re"[a-z]\w*\d*"

echo find("hello123", wordNum)
echo find("hello123", wordNum2)

echo find("       hello123", wordNum)
echo find("       hello123", wordNum2)

Note that the num string needs to be a raw literal as well, or you'd have to escape the backslash.


问:
Rewriting "If element has scrolled down past another element, do the following" from JQuery to vanilla JS?
Hello is it possible to rewrite the following JQuery snippet:

```<code>$(window).scroll(function (event) {
  var scroll = $(window).scrollTop();
    $(".navigation").toggleClass("is-active", scroll >= $("example-div").offset().top);
});
$(window).scroll();
</code>```

Into vanilla JS? I've tried everything, and searched through some other questions, to no avail.

Thanks.

答:
You can use the Intersection Observer API like this :

const target = document.querySelector('#static');
const floating = document.querySelector('#floating');

const observer = new IntersectionObserver(
  ([entry]) => {
    if (entry.isIntersecting)
      floating.innerText = 'Red is visible'
    else
      floating.innerText = 'Red is invisible'
  }, {
    threshold: 0
  }
);

observer.observe(target)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    margin: 0
}

main {
    height: 200vh;
}

#static {
    background-color: red;
}

#floating {
    position: fixed;
    left: 55px;
    background-color: yellow;
}

#static,
#floating {
    width: 50px;
    height: 50px;
}</code>```

```

compatibility link

Body:
Hello is it possible to rewrite the following JQuery snippet:

$(window).scroll(function (event) {
  var scroll = $(window).scrollTop();
    $(".navigation").toggleClass("is-active", scroll >= $("example-div").offset().top);
});
$(window).scroll();

Into vanilla JS? I've tried everything, and searched through some other questions, to no avail.

Thanks.

Body:
You can use the Intersection Observer API like this :

const target = document.querySelector('#static');
const floating = document.querySelector('#floating');

const observer = new IntersectionObserver(
  ([entry]) => {
    if (entry.isIntersecting)
      floating.innerText = 'Red is visible'
    else
      floating.innerText = 'Red is invisible'
  }, {
    threshold: 0
  }
);

observer.observe(target)

body {
    margin: 0
}

main {
    height: 200vh;
}

#static {
    background-color: red;
}

#floating {
    position: fixed;
    left: 55px;
    background-color: yellow;
}

#static,
#floating {
    width: 50px;
    height: 50px;
}

<main>
  <div id="floating">
  </div>

  <div id="static">
  </div>
</main>

compatibility link


问:
Why is the service not injected into the controller?
I'm trying out AdonisJS, but I'm stuck trying to get a service injected into a controller. No matter what I try, the hs constructor argument in VersionsController remains undefined.

I've also experimented with annotating the VersionController constructor with @inject(['@ioc:Service/HashService']), but with no luck. I'm not sure though if @inject is the right way for Adonis.js v5.

How do I properly inject a service class into a controller?

/providers/AppProvider.ts

    import { ApplicationContract } from '@ioc:Adonis/Core/Application'
    import HashService from 'App/Services/HashService';

    export default class AppProvider {

        protected app: ApplicationContract;

        constructor(app: ApplicationContract) {
            this.app = app;
        }

        public register() {
            this.app.container.singleton('@ioc:Service/HashService', () => {
                return new HashService();
            });
        }

        public async boot() {
            // IoC container is ready
        }

        public async ready() {
            // App is ready
        }

        public async shutdown() {
            // Cleanup, since app is going down
        }
    }
```
<p><strong>/app/Services/HashService.ts</strong></p>
```    'use strict'

    export default class HashService {

        async test() {}

    }

    module.exports = HashService;
```
<p><strong>app/Controllers/Http/VersionsController.ts</strong></p>
```    import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
    import { HashService } from '@ioc:Service/HashService'

    export default class VersionsController {

        protected hs: HashService

        constructor(hs: HashService) {
            this.hs = hs;
            console.log("hashservice is " + hs);
        }

        public async get(ctx: HttpContextContract) {
            return [
                {
                    id: 1,
                    title: 'a'
                }
            ]
        }

        public async put(ctx: HttpContextContract) {
            return "PUT";
        }

    }
```
<p><strong>.adonisrc.json</strong></p>
<pre class="lang-json prettyprint-override"><code>    {
      "typescript": true,
      "commands": [
        "./commands",
        "@adonisjs/core/build/commands/index.js",
        "@adonisjs/repl/build/commands"
      ],
      "exceptionHandlerNamespace": "App/Exceptions/Handler",
      "aliases": {
        "App": "app",
        "Config": "config",
        "Database": "database",
        "Contracts": "contracts"
      },
      "preloads": [
        "./start/routes",
        "./start/kernel"
      ],
      "providers": [
        "./providers/AppProvider",
        "@adonisjs/core"
      ],
      "aceProviders": [
        "@adonisjs/repl"
      ]
    }
</code>```

答:
you can use Adonisjs/fold

simply use the @inject decorator in your services;

example;

import {HttpContextContract} from "@ioc:Adonis/Core/HttpContext";
import UserEditValidator from "App/Validators/UserEditValidator";
import UserRepository from "App/Repository/UserRepository";
import {inject} from "@adonisjs/fold";

@inject()
export default class UserService {

  constructor(private userRepository: UserRepository) {
  }

  async update(ctx: HttpContextContract) {
     //do your stuff

  }
}
```
<p>and then in your controller;</p>
<pre class="lang-js prettyprint-override"><code>import {HttpContextContract} from "@ioc:Adonis/Core/HttpContext";
import UserService from "App/Service/UserService";
import {inject} from "@adonisjs/fold";

@inject()
export default class UserController {

  constructor(private userService: UserService) {

  }

  async edit({ view }){
     return view.render('user/edit', {title: 'Edit Profile'})
  }

  async update(ctx : HttpContextContract){
      await this.userService.update(ctx);

      return ctx.response.redirect().back()

  }
}
</code>```

Body:
I'm trying out AdonisJS, but I'm stuck trying to get a service injected into a controller. No matter what I try, the hs constructor argument in VersionsController remains undefined.

I've also experimented with annotating the VersionController constructor with @inject(['@ioc:Service/HashService']), but with no luck. I'm not sure though if @inject is the right way for Adonis.js v5.

How do I properly inject a service class into a controller?

/providers/AppProvider.ts

    import { ApplicationContract } from '@ioc:Adonis/Core/Application'
    import HashService from 'App/Services/HashService';

    export default class AppProvider {

        protected app: ApplicationContract;

        constructor(app: ApplicationContract) {
            this.app = app;
        }

        public register() {
            this.app.container.singleton('@ioc:Service/HashService', () => {
                return new HashService();
            });
        }

        public async boot() {
            // IoC container is ready
        }

        public async ready() {
            // App is ready
        }

        public async shutdown() {
            // Cleanup, since app is going down
        }
    }

/app/Services/HashService.ts

    'use strict'

    export default class HashService {

        async test() {}

    }

    module.exports = HashService;

app/Controllers/Http/VersionsController.ts

    import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
    import { HashService } from '@ioc:Service/HashService'

    export default class VersionsController {

        protected hs: HashService

        constructor(hs: HashService) {
            this.hs = hs;
            console.log("hashservice is " + hs);
        }

        public async get(ctx: HttpContextContract) {
            return [
                {
                    id: 1,
                    title: 'a'
                }
            ]
        }

        public async put(ctx: HttpContextContract) {
            return "PUT";
        }

    }

.adonisrc.json

    {
      "typescript": true,
      "commands": [
        "./commands",
        "@adonisjs/core/build/commands/index.js",
        "@adonisjs/repl/build/commands"
      ],
      "exceptionHandlerNamespace": "App/Exceptions/Handler",
      "aliases": {
        "App": "app",
        "Config": "config",
        "Database": "database",
        "Contracts": "contracts"
      },
      "preloads": [
        "./start/routes",
        "./start/kernel"
      ],
      "providers": [
        "./providers/AppProvider",
        "@adonisjs/core"
      ],
      "aceProviders": [
        "@adonisjs/repl"
      ]
    }

Body:
you can use Adonisjs/fold

simply use the @inject decorator in your services;

example;

import {HttpContextContract} from "@ioc:Adonis/Core/HttpContext";
import UserEditValidator from "App/Validators/UserEditValidator";
import UserRepository from "App/Repository/UserRepository";
import {inject} from "@adonisjs/fold";

@inject()
export default class UserService {

  constructor(private userRepository: UserRepository) {
  }

  async update(ctx: HttpContextContract) {
     //do your stuff

  }
}

and then in your controller;

import {HttpContextContract} from "@ioc:Adonis/Core/HttpContext";
import UserService from "App/Service/UserService";
import {inject} from "@adonisjs/fold";

@inject()
export default class UserController {

  constructor(private userService: UserService) {

  }

  async edit({ view }){
     return view.render('user/edit', {title: 'Edit Profile'})
  }

  async update(ctx : HttpContextContract){
      await this.userService.update(ctx);

      return ctx.response.redirect().back()

  }
}


问:
maven-connector-java, module not found
Successfully I did my first JDBC program using MariaDB, Maven, Java-11.

Now I have to access MySQL and just exchanged the MariaDB dependency by

```<code><dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>8.0.28</version>
</dependency>
</code>```

I figured out, that com.mysql.jdbc and com.mysql.cj and other modules are hosted in the mysql-connector-java-8.0.28.jar.
Hence, in module-info.java I exchanged

```<code>requires org.mariadb.jdbc;
</code>```

by

```<code>requires com.mysql.jdbc;
</code>```

I also tried

```<code>requires com.mysql.cj;
</code>```

but still, the maven-compiler-plugin:3.9.0 complains

```<code>module not found
</code>```

What did I miss, here?

答:
khmarbaise has put me on the right track: I almost forgot that there are legacy jar files around not prepared for easy integration into JPMS.
To include the jar file mysql-connector-java-8.0.28.jar, which comes without a module-info.class, I had to enter

```<code>requires java.sql;
requires mysql.connector.java;
</code>```

to my module-info.java.

The module name mysql.connector.java is derived from the name of its jar file by omitting the version info and substituting the dashes by dots.

Title: maven-connector-java, module not found

Body:
Successfully I did my first JDBC program using MariaDB, Maven, Java-11.

Now I have to access MySQL and just exchanged the MariaDB dependency by

<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>8.0.28</version>
</dependency>

I figured out, that com.mysql.jdbc and com.mysql.cj and other modules are hosted in the mysql-connector-java-8.0.28.jar.
Hence, in module-info.java I exchanged

requires org.mariadb.jdbc;

by

requires com.mysql.jdbc;

I also tried

requires com.mysql.cj;

but still, the maven-compiler-plugin:3.9.0 complains

module not found

What did I miss, here?

Body:
khmarbaise has put me on the right track: I almost forgot that there are legacy jar files around not prepared for easy integration into JPMS.
To include the jar file mysql-connector-java-8.0.28.jar, which comes without a module-info.class, I had to enter

requires java.sql;
requires mysql.connector.java;

to my module-info.java.

The module name mysql.connector.java is derived from the name of its jar file by omitting the version info and substituting the dashes by dots.


问:
How to build a tree in Groovy from a database query?
It looks like it returns the structure, but the values aren't there...

```<code>g = TinkerGraphFactory.createTinkerGraph()
root = g.v(1)

def tree
def results = []
tree = { vertices ->
  vertices.each() {
    children = it.out().toList()
    if (children)
      results << tree(children)
  }
  results.toList()
}

println tree(root)
</code>```

Here are the results...

```<code>$ ./gremlin.sh -e treeTest.groovy
[[], [[]]]
</code>```

NOTE: I normally work in Python not Groovy so I am probably missing something obvious.

答:
```<code>tree = { vertices ->

  def results = []

  vertices.each() {
    results << it
    children = it."$direction"().toList()
    if (children) {
      child_tree = tree(children)
      results << child_tree
    }
  }
  results
}
</code>```

Body:
It looks like it returns the structure, but the values aren't there...

g = TinkerGraphFactory.createTinkerGraph()
root = g.v(1)

def tree
def results = []
tree = { vertices ->
  vertices.each() {
    children = it.out().toList()
    if (children)
      results << tree(children)
  }
  results.toList()
}

println tree(root)

Here are the results...

$ ./gremlin.sh -e treeTest.groovy
[[], [[]]]

NOTE: I normally work in Python not Groovy so I am probably missing something obvious.


问:
How to split a component when it gets big. ReactJs
I have just started learning ReactJs and I am using it in laravel project for practice.

Everything is going okay, but what I dont like is that my component is getting bigger. I can not think of an optimal way to split it in several, simpler files like .js and .jsx..

Here is the component and I will appreciate any corrections and recommendations.

答:
Like I Split your code I create a new Component of a new question modal and pass value through props. So you can split like this. I try only one but you can split all three modal.
You can think as it also click</p>
```<code>const NewQuestionModal = ({isOpen, close, titleValue, solutionValue, onAddQuestion, onTitleChange, onSolutionChange  }) => {
        return(<Modal isOpen={isOpen} toggle={close}>
        <ModalHeader toggle={close}>Add a new question</ModalHeader>
        <ModalBody>

            <FormGroup>
                <Label for="title">Question</Label>
                <Input id="title"
                        value={titleValue}
                        onChange={onTitleChange}
                >sda</Input>
            </FormGroup>

            <FormGroup>
                <Label for="solution">Solution</Label>
                <Input id="solution"
                       value={solutionValue}
                       onChange={onSolutionChange}
                >sda</Input>
            </FormGroup>

        </ModalBody>
        <ModalFooter>
            <Button color="primary" onClick={onAddQuestion}>Add question</Button>{' '}
            <Button color="secondary" onClick={close}>Cancel</Button>
        </ModalFooter>
    </Modal>)
    }

    <div className="App container">
                    <h1>Question list </h1>
                    <Button color="primary" onClick={this.toggleNewQuestionModal.bind(this)}>Add question</Button>
               {/*================New Question Modal==============*/}
                    <NewQuestionModal
                    isOpen={this.state.newQuestionModal}
                    close={this.toggleNewQuestionModal.bind(this)}
                    titleValue={this.state.newQuestionData.title}
                    onTitleChange={(e) => {
                        let {newQuestionData} = this.state
                        newQuestionData.title = e.target.value
                        this.setState({newQuestionData} )
                    }}
                    solutionValue={this.state.newQuestionData.solution}
                    onSolutionChange={(e) => {
                        let {newQuestionData} = this.state
                        newQuestionData.solution = e.target.value
                        this.setState({newQuestionData} )
                    }}
                    onAddQuestion={this.addQuestion.bind(this)}
                    />

                    <Modal isOpen={this.state.editQuestionModal} toggle={this.toggleEditQuestionModal.bind(this)}>
                        <ModalHeader toggle={this.toggleEditQuestionModal.bind(this)}>Edit question</ModalHeader>
                        <ModalBody>

                            <FormGroup>
                                <Label for="title">Question</Label>
                                <Input id="title"
                                       value={this.state.editQuestionData.title}
                                       onChange={(e) => {
                                           let {editQuestionData} = this.state
                                           editQuestionData.title = e.target.value
                                           this.setState({editQuestionData} )
                                       }}
                                >sda</Input>
                            </FormGroup>

                            <FormGroup>
                                <Label for="solution">Solution</Label>
                                <Input id="solution"
                                       value={this.state.editQuestionData.solution}
                                       onChange={(e) => {
                                           let {editQuestionData} = this.state
                                           editQuestionData.solution = e.target.value
                                           this.setState({editQuestionData} )
                                       }}
                                >sda</Input>
                            </FormGroup>

                        </ModalBody>
                        <ModalFooter>
                            <Button color="primary" onClick={this.updateQuestion.bind(this)}>Update question</Button>{' '}
                            <Button color="secondary" onClick={this.toggleEditQuestionModal.bind(this)}>Cancel</Button>
                        </ModalFooter>
                    </Modal>

                    <Modal isOpen={this.state.isOpen} toggle={this.toggleModal.bind(this.id)}>
                        <ModalHeader toggle={this.toggleModal.bind(this)}  className="btn-primary">Query result</ModalHeader>
                        <Table className="table">
                            <tbody>
                                <tr>
                                    <th>data:</th><td>{this.state.solutionData.data}</td>
                                </tr>
                            </tbody>
                        </Table>
                        <ModalFooter>
                            <Button color="secondary" onClick={this.toggleModal.bind(this)}>Cancel</Button>
                        </ModalFooter>
                    </Modal>

                    <Table>
                        <thead>
                        <tr>
                            <th>#</th>
                            <th>Question</th>
                            <th>Solution</th>
                            <th>Actions</th>
                        </tr>
                        </thead>
                        <tbody>
                        {questions}
                        </tbody>
                    </Table>
                </div>
</code>```

Body:
Like I Split your code I create a new Component of a new question modal and pass value through props. So you can split like this. I try only one but you can split all three modal.
You can think as it also click

const NewQuestionModal = ({isOpen, close, titleValue, solutionValue, onAddQuestion, onTitleChange, onSolutionChange  }) => {
        return(<Modal isOpen={isOpen} toggle={close}>
        <ModalHeader toggle={close}>Add a new question</ModalHeader>
        <ModalBody>

            <FormGroup>
                <Label for="title">Question</Label>
                <Input id="title"
                        value={titleValue}
                        onChange={onTitleChange}
                >sda</Input>
            </FormGroup>

            <FormGroup>
                <Label for="solution">Solution</Label>
                <Input id="solution"
                       value={solutionValue}
                       onChange={onSolutionChange}
                >sda</Input>
            </FormGroup>

        </ModalBody>
        <ModalFooter>
            <Button color="primary" onClick={onAddQuestion}>Add question</Button>{' '}
            <Button color="secondary" onClick={close}>Cancel</Button>
        </ModalFooter>
    </Modal>)
    }

    <div className="App container">
                    <h1>Question list </h1>
                    <Button color="primary" onClick={this.toggleNewQuestionModal.bind(this)}>Add question</Button>
               {/*================New Question Modal==============*/}
                    <NewQuestionModal
                    isOpen={this.state.newQuestionModal}
                    close={this.toggleNewQuestionModal.bind(this)}
                    titleValue={this.state.newQuestionData.title}
                    onTitleChange={(e) => {
                        let {newQuestionData} = this.state
                        newQuestionData.title = e.target.value
                        this.setState({newQuestionData} )
                    }}
                    solutionValue={this.state.newQuestionData.solution}
                    onSolutionChange={(e) => {
                        let {newQuestionData} = this.state
                        newQuestionData.solution = e.target.value
                        this.setState({newQuestionData} )
                    }}
                    onAddQuestion={this.addQuestion.bind(this)}
                    />

                    <Modal isOpen={this.state.editQuestionModal} toggle={this.toggleEditQuestionModal.bind(this)}>
                        <ModalHeader toggle={this.toggleEditQuestionModal.bind(this)}>Edit question</ModalHeader>
                        <ModalBody>

                            <FormGroup>
                                <Label for="title">Question</Label>
                                <Input id="title"
                                       value={this.state.editQuestionData.title}
                                       onChange={(e) => {
                                           let {editQuestionData} = this.state
                                           editQuestionData.title = e.target.value
                                           this.setState({editQuestionData} )
                                       }}
                                >sda</Input>
                            </FormGroup>

                            <FormGroup>
                                <Label for="solution">Solution</Label>
                                <Input id="solution"
                                       value={this.state.editQuestionData.solution}
                                       onChange={(e) => {
                                           let {editQuestionData} = this.state
                                           editQuestionData.solution = e.target.value
                                           this.setState({editQuestionData} )
                                       }}
                                >sda</Input>
                            </FormGroup>

                        </ModalBody>
                        <ModalFooter>
                            <Button color="primary" onClick={this.updateQuestion.bind(this)}>Update question</Button>{' '}
                            <Button color="secondary" onClick={this.toggleEditQuestionModal.bind(this)}>Cancel</Button>
                        </ModalFooter>
                    </Modal>

                    <Modal isOpen={this.state.isOpen} toggle={this.toggleModal.bind(this.id)}>
                        <ModalHeader toggle={this.toggleModal.bind(this)}  className="btn-primary">Query result</ModalHeader>
                        <Table className="table">
                            <tbody>
                                <tr>
                                    <th>data:</th><td>{this.state.solutionData.data}</td>
                                </tr>
                            </tbody>
                        </Table>
                        <ModalFooter>
                            <Button color="secondary" onClick={this.toggleModal.bind(this)}>Cancel</Button>
                        </ModalFooter>
                    </Modal>

                    <Table>
                        <thead>
                        <tr>
                            <th>#</th>
                            <th>Question</th>
                            <th>Solution</th>
                            <th>Actions</th>
                        </tr>
                        </thead>
                        <tbody>
                        {questions}
                        </tbody>
                    </Table>
                </div>