问:
Socket.io app ... should I use emit or use a regular http request and handle it with express?
I am creating Socket.io app that at times needs to retrieve information from a database. I am having a hard time figuring out if those requests should be sent and processed using socket.io, or if they should be sent like a regular http request and processed in the server using Express.

I could use socket.emit("my-event) and then process it in the server using socket.on("my-event", () =>{... make request to the database...}) and then upon getting the results from the database I can emit another event to send the results to the client using socket.emit("result-from-the-DB", dataFromDB).

I know you may be thinking "You do not need Socket.io for that", but the most important part of the app will need it since it will function very much like a Chat app. For instance, let's say a user clicks on "See my profile" in this app. Should the request to the server be sent using socket.io (using the steps described above) or just a regular http request?

答:
Socket.io app … should I use emit or use a regular http request and handle it with express?

There's no totally correct answer.  Honestly, you can make it work fine either way.  Here are some advantages of each:

Advantages of sending via an http request:

http is a request/response protocol.  If you're sending a request and expecting a response to a specific request, then http is a bit better designed for that.  socket.io doesn't really have a "response" to a specific "request".  You can mimic that by sending back a message or using the confirmation callback.

If you envision any other public use for this API/functionality or any use outside of a socket.io app, then http is more often the appropriate public API.

If you ever have to send large amounts of data (like uploading files), then there are more mature solutions already built for http.

socket.io error handling is more at the global level, rather than for a specific message.  For example, there's no way to listen specifically whether there was an error on sending a particular message.  If the socket.io library encounters a socket problem, it will close the socket and attempt to reconnect.  Sometimes this is a feature, sometimes this is an obstacle to knowing if your data actually got there or not.  An http request will give you clear and direct feedback whether your request was delivered or not.

If what you're doing in processing this message has nothing to do with the other things you're doing with socket.io, then it may be cleaner (from a module design point of view) to handle it with http so you don't have to mix in code in your socket.io module that isn't related to the other stuff.

Advantages of sending via a socket.io message:

Once you already have a socket.io connection active, it's much lower overhead to send a small message to your server using socket.io.  so, particularly if you were sending lots of small messages this way, socket.io could be significantly more efficient.

If there's any benefit to socket.io features such as namespaces and rooms in processing this request, then it may be easier to handle it on the server with socket.io.

If the message you're sending is directly related to the other things you've doing with socket.io on the server, then it may be cleaner (from a module design point of view) to handle that request in your socket.io module.


来源: stackexchange

问:
How to call a ddev web command from another one
As answered in ddev exec: command not found (.bash_aliases) shell scripts in .ddev/commands/web are fantastic.

Is it also possible to call a command from another one?
Like

```<code>#!/bin/bash

# pull prod content to local

dump_remote_database
sync_down_files
import_database
</code>```

Which would (theoretically) call three separate commands defined in . ddev/commands/web

Currently I get

```<code>/mnt/ddev_config/commands/web/sync_down: line 5: dump_remote_database: command not found
/mnt/ddev_config/commands/web/sync_down: line 6: sync_down_files: command not found
/mnt/ddev_config/commands/web/sync_down: line 7: import_database: command not found
</code>```

答:
On a host command you could call another ddev command, but not web or other command, because they're executing inside the container and done even know that ddev exists.

So with a host command, for example ddev relaunch in .ddev/commands/host/relaunch, you could have this, where relaunch calls ddev launch:

```<code>#!/bin/bash

## Description: Launch a browser with drupal /user
## Usage: relaunch [path]
## Example: "ddev relaunch"

ddev launch /user
</code>```

With a web container command though, you're executing inside the web container (which doesn't even know that ddev exists, it's its own little world). So in that case you might have to copy/paste some feature of another web command.

Lets say you don't like the built-in drush.example enough and you want just a "drushuli" command. Whereas the drush.example uses drush directly, you can just use drush directly yourself (inside the web container) with drush uli. So I'll copy .ddev/commands/drush.example and come up with:

```<code>#!/bin/bash

## Description: Run drush uli inside the web container
## Usage: drushuli [flags] [args]
## Example: "ddev drushuli"

drush uli
</code>```

It's a pretty silly example, but you get the picture. Use the tools that are available to you in the environment you're working with.

ContentLicense: CC BY-SA 4.0

Body:
As answered in ddev exec: command not found (.bash_aliases) shell scripts in .ddev/commands/web are fantastic.

Is it also possible to call a command from another one?
Like

#!/bin/bash

# pull prod content to local

dump_remote_database
sync_down_files
import_database

Which would (theoretically) call three separate commands defined in . ddev/commands/web

Currently I get

/mnt/ddev_config/commands/web/sync_down: line 5: dump_remote_database: command not found
/mnt/ddev_config/commands/web/sync_down: line 6: sync_down_files: command not found
/mnt/ddev_config/commands/web/sync_down: line 7: import_database: command not found

Body:
On a host command you could call another ddev command, but not web or other command, because they're executing inside the container and done even know that ddev exists.

So with a host command, for example ddev relaunch in .ddev/commands/host/relaunch, you could have this, where relaunch calls ddev launch:

#!/bin/bash

## Description: Launch a browser with drupal /user
## Usage: relaunch [path]
## Example: "ddev relaunch"

ddev launch /user

With a web container command though, you're executing inside the web container (which doesn't even know that ddev exists, it's its own little world). So in that case you might have to copy/paste some feature of another web command.

Lets say you don't like the built-in drush.example enough and you want just a "drushuli" command. Whereas the drush.example uses drush directly, you can just use drush directly yourself (inside the web container) with drush uli. So I'll copy .ddev/commands/drush.example and come up with:

#!/bin/bash

## Description: Run drush uli inside the web container
## Usage: drushuli [flags] [args]
## Example: "ddev drushuli"

drush uli

It's a pretty silly example, but you get the picture. Use the tools that are available to you in the environment you're working with.


问:
Passing data from view to net-mvc controller using AngularJS
```<code> public class Home
{
    string CustEmail { get;set;}
    string CustName { get; set;}

    int id { get; set;}
}
</code>```

Model

```<code>[HttpPost]
    public void CreateCustomer(Home cust)
    {
        if (ModelState.IsValid)
        {

        }

    }
</code>```

Controller

```<code>angular.module('myFormApp', []).controller('CustomerController', function ($scope, $http, $location, $window) {
    debugger;
    $scope.cust = {};
    $scope.message = '';
    $scope.result = "color-default";
    $scope.isViewLoading = false;

    //get called when user submits the form
    $scope.submitForm = function () {
        $scope.isViewLoading = true;
        console.log('Form is submitted with:', $scope.cust);
        //$http service that send or receive data from the remote server

        var cust = {
            CustEmail: $scope.cust.CustEmail,
            CustName: $scope.cust.CustName,
            id: 1,
        };

        $http(
        {
            method: 'POST',
            url: '/Home/CreateCustomer',
            data: cust,
        }).then(function (data, status, headers, config) {
            $scope.errors = [];
            if (data.success === true) {
                $scope.cust = {};
                $scope.message = 'Form data Submitted!';
                $scope.result = "color-green";
                $location.path(data.redirectUrl);
                $window.location.reload();
            }
            else {
                $scope.errors = data.errors;
            }
        })
        $scope.isViewLoading = false;
    }
}).config(function ($locationProvider) {
  //default = 'false'
  $locationProvider.html5Mode(true);
});
</code>```

I get the data in the proper format in front-end and the post-back call is also working but I cannot get value in MVC controller. I don't know what am I doing wrong. I have tried using the individual item in controller then it's working fine but i want it through model only.

答:
The .then method of a promise only exposes one value, not four values.

```<code>$http(
{
    method: 'POST',
    url: '/Home/CreateCustomer',
    data: cust,
̶}̶)̶.̶t̶h̶e̶n̶(̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶(̶d̶a̶t̶a̶,̶ ̶s̶t̶a̶t̶u̶s̶,̶ ̶h̶e̶a̶d̶e̶r̶s̶,̶ ̶c̶o̶n̶f̶i̶g̶)̶ ̶{̶
}).then(function (response) {
    var data = response.data;
    var status = response.status;
    var headers = response.headers;
    var config = response.config;
    $scope.errors = [];
    if (data.success === true) {
        $scope.cust = {};
        $scope.message = 'Form data Submitted!';
        $scope.result = "color-green";
        $location.path(data.redirectUrl);
        $window.location.reload();
    }
    else {
        $scope.errors = data.errors;
    }
})
</code>```

For more information, see

AngularJS $http Service API Reference - returns

UPDATE

You can add a .catch block to console log any errors:

```<code>$http(
{
    method: 'POST',
    url: '/Home/CreateCustomer',
    data: cust,
̶}̶)̶.̶t̶h̶e̶n̶(̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶(̶d̶a̶t̶a̶,̶ ̶s̶t̶a̶t̶u̶s̶,̶ ̶h̶e̶a̶d̶e̶r̶s̶,̶ ̶c̶o̶n̶f̶i̶g̶)̶ ̶{̶
}).then(function (response) {
    var data = response.data;
    var status = response.status;
    var headers = response.headers;
    var config = response.config;
    $scope.errors = [];
    if (data.success === true) {
        $scope.cust = {};
        $scope.message = 'Form data Submitted!';
        $scope.result = "color-green";
        $location.path(data.redirectUrl);
        $window.location.reload();
    }
    else {
        $scope.errors = data.errors;
    }
    console.log("OK:", response.data);
}).catch(function(response) {
    console.log("ERROR:", response);
});
</code>```

Body:
 public class Home
{
    string CustEmail { get;set;}
    string CustName { get; set;}

    int id { get; set;}
}

Model

[HttpPost]
    public void CreateCustomer(Home cust)
    {
        if (ModelState.IsValid)
        {

        }

    }

Controller

angular.module('myFormApp', []).controller('CustomerController', function ($scope, $http, $location, $window) {
    debugger;
    $scope.cust = {};
    $scope.message = '';
    $scope.result = "color-default";
    $scope.isViewLoading = false;

    //get called when user submits the form
    $scope.submitForm = function () {
        $scope.isViewLoading = true;
        console.log('Form is submitted with:', $scope.cust);
        //$http service that send or receive data from the remote server

        var cust = {
            CustEmail: $scope.cust.CustEmail,
            CustName: $scope.cust.CustName,
            id: 1,
        };

        $http(
        {
            method: 'POST',
            url: '/Home/CreateCustomer',
            data: cust,
        }).then(function (data, status, headers, config) {
            $scope.errors = [];
            if (data.success === true) {
                $scope.cust = {};
                $scope.message = 'Form data Submitted!';
                $scope.result = "color-green";
                $location.path(data.redirectUrl);
                $window.location.reload();
            }
            else {
                $scope.errors = data.errors;
            }
        })
        $scope.isViewLoading = false;
    }
}).config(function ($locationProvider) {
  //default = 'false'
  $locationProvider.html5Mode(true);
});

I get the data in the proper format in front-end and the post-back call is also working but I cannot get value in MVC controller. I don't know what am I doing wrong. I have tried using the individual item in controller then it's working fine but i want it through model only.

Body:
The .then method of a promise only exposes one value, not four values.

$http(
{
    method: 'POST',
    url: '/Home/CreateCustomer',
    data: cust,
̶}̶)̶.̶t̶h̶e̶n̶(̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶(̶d̶a̶t̶a̶,̶ ̶s̶t̶a̶t̶u̶s̶,̶ ̶h̶e̶a̶d̶e̶r̶s̶,̶ ̶c̶o̶n̶f̶i̶g̶)̶ ̶{̶
}).then(function (response) {
    var data = response.data;
    var status = response.status;
    var headers = response.headers;
    var config = response.config;
    $scope.errors = [];
    if (data.success === true) {
        $scope.cust = {};
        $scope.message = 'Form data Submitted!';
        $scope.result = "color-green";
        $location.path(data.redirectUrl);
        $window.location.reload();
    }
    else {
        $scope.errors = data.errors;
    }
})

For more information, see

AngularJS $http Service API Reference - returns

UPDATE

You can add a .catch block to console log any errors:

$http(
{
    method: 'POST',
    url: '/Home/CreateCustomer',
    data: cust,
̶}̶)̶.̶t̶h̶e̶n̶(̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶(̶d̶a̶t̶a̶,̶ ̶s̶t̶a̶t̶u̶s̶,̶ ̶h̶e̶a̶d̶e̶r̶s̶,̶ ̶c̶o̶n̶f̶i̶g̶)̶ ̶{̶
}).then(function (response) {
    var data = response.data;
    var status = response.status;
    var headers = response.headers;
    var config = response.config;
    $scope.errors = [];
    if (data.success === true) {
        $scope.cust = {};
        $scope.message = 'Form data Submitted!';
        $scope.result = "color-green";
        $location.path(data.redirectUrl);
        $window.location.reload();
    }
    else {
        $scope.errors = data.errors;
    }
    console.log("OK:", response.data);
}).catch(function(response) {
    console.log("ERROR:", response);
});


问:
javascript - hide / show div based on selection
I have a rails form where user has to select a value from a drop down menu and based on that value, the rest fo the form elements are displayed.

```<code><div id="A">
a
b
c
</div>

<div id="B">
x
y
z
c
</div>

<div id="B">
w
a
q
c
</div>
</code>```

When user selects value A from the select menu, the div with id A is displayed and the rest of the divs are hidden.

The problem is some fields are repeated in the different divs and when user enters a value for field 'a' in div A, this value gets overwritten by the blank value in div B, although div B is hidden from view.

I would like to know whether it's possible to have the same fields in different divs and be able to store the value of the field found in the displayed div only, even if that field is found in other divs.

Many many thanks for any suggestion provided.

答:
When you hide your div, turn on the disabled attribute for all children and when you show a div remove it.  Something like this:</p>

```<code>var showDiv = function ( id ) {
    var all = [document.getElementById( 'A' ),
               document.getElementById( 'B' ),
               document.getElementById( 'C' )],
        cur = document.getElementById( id ),
        inps;

    for (var i = 0, il = all.length; i < il; i++) {

        inps = all[i].getElementsByTagName('input');

        for (var j = 0, jl = inps.length; j < jl; j++) {
            inps[j].setAttribute('disabled', 'disabled');
        }

        all[i].style.display = 'none';

    }

    inps = cur.getElementsByTagName('input');

    for (j = 0, jl = inps.length; j < jl; j++) {
        inps[j].removeAttribute('disabled');
    }

    cur.style.display = 'block';
};
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a rails form where user has to select a value from a drop down menu and based on that value, the rest fo the form elements are displayed.

a
b
c

x
y
z
c

w
a
q
c

When user selects value A from the select menu, the div with id A is displayed and the rest of the divs are hidden.

The problem is some fields are repeated in the different divs and when user enters a value for field 'a' in div A, this value gets overwritten by the blank value in div B, although div B is hidden from view.

I would like to know whether it's possible to have the same fields in different divs and be able to store the value of the field found in the displayed div only, even if that field is found in other divs.

Many many thanks for any suggestion provided.

Body:
When you hide your div, turn on the disabled attribute for all children and when you show a div remove it.  Something like this:

var showDiv = function ( id ) {
    var all = [document.getElementById( 'A' ),
               document.getElementById( 'B' ),
               document.getElementById( 'C' )],
        cur = document.getElementById( id ),
        inps;

    for (var i = 0, il = all.length; i < il; i++) {

        inps = all[i].getElementsByTagName('input');

        for (var j = 0, jl = inps.length; j < jl; j++) {
            inps[j].setAttribute('disabled', 'disabled');
        }

        all[i].style.display = 'none';

    }

    inps = cur.getElementsByTagName('input');

    for (j = 0, jl = inps.length; j < jl; j++) {
        inps[j].removeAttribute('disabled');
    }

    cur.style.display = 'block';
};


问:
Find matching item across multiple store arrays in VueX
Currently when I want to find single item in an array that is in store I use this:

```<code>this.matched = this.$store.state.itemlist.find(itemId=> {
      return itemId.id == "someid";
    });
</code>```

Lets says I want to go over multiple arrays to find the matching item given provided ID? Like i have itemlist1 itemlist2 itemgetter()...  Some of the arrays are getters ( but I think it doesnt change much). So basically I want to search over different state and getter items in this component instead of searching over one as in example above.

答:
if you just want to find if its exist in one the arrays you can simply write function like this

```<code>function find(search,...arrs){
  return arrs.flat(1).find(item => item == search)
}
</code>```

this function merge all arrays to one long array and search in it

example of usage

```<code>let a=[1,2,3,4]
let b=[5,6,7,8]
let c=[9,10,11,12]

let i=find(6,a,b)
console.log(i)
</code>```

Body:
Currently when I want to find single item in an array that is in store I use this:

this.matched = this.$store.state.itemlist.find(itemId=> {
      return itemId.id == "someid";
    });

Lets says I want to go over multiple arrays to find the matching item given provided ID? Like i have itemlist1 itemlist2 itemgetter()...  Some of the arrays are getters ( but I think it doesnt change much). So basically I want to search over different state and getter items in this component instead of searching over one as in example above.

Body:
if you just want to find if its exist in one the arrays you can simply write function like this

function find(search,...arrs){
  return arrs.flat(1).find(item => item == search)
}

this function merge all arrays to one long array and search in it

example of usage

let a=[1,2,3,4]
let b=[5,6,7,8]
let c=[9,10,11,12]

let i=find(6,a,b)
console.log(i)


问:
Using HAL with Hateoas on springboot 2.2.4
I have a model response that extends RepresentationModel :

```<code>@Getter @Setter
public class AddressRestResponseModel extends RepresentationModel<AddressRestResponseModel> {
    private String addressKeyId;
    private String city;
    private String country;
    private String streetName;
    private String zipCode;
}
</code>```

I also have a controller that uses HateOAS and should return hal+json:

```<code>@GetMapping(
        path="/{userKeyId}/addresses",
        produces = {
                MediaType.APPLICATION_XML_VALUE,
                MediaType.APPLICATION_JSON_VALUE,
                "application/hal+json"
        }
)
public List<AddressRestResponseModel> getUserAddresses(@PathVariable String userKeyId) {
    List<AddressRestResponseModel> returnValue = new ArrayList<>();
    List<AddressDto> addressDtos = addressService.getAddresses(userKeyId);
    if (addressDtos != null && !addressDtos.isEmpty()) {
        ModelMapper modelMapper = new ModelMapper();
        Type listType = new TypeToken<List<AddressRestResponseModel>>() {}.getType();
        returnValue = modelMapper.map(addressDtos, listType);

        for (AddressRestResponseModel address: returnValue) {
            Link addressLink = linkTo(methodOn(UserController.class).getUserAddress(userKeyId, address.getAddressKeyId())).withSelfRel();
            address.add(addressLink);

            Link userLink = linkTo(methodOn(UserController.class).getUser(userKeyId)).withRel("user");
            address.add(userLink);
        }
    }
    return returnValue;
}
</code>```

I also added the pom dependency for hateoas :

```<code><!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-hateoas -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-hateoas</artifactId>
    <version>2.2.4.RELEASE</version>
</dependency>
</code>```

I tried this entry point in postman and set the accept header to "application/hal+json". I should receive something like with "_links" and with objects in it:

Unfortunatelly as response I do not have hal format and it looks like it's not using this format :

```<code>[
    {
        "addressKeyId": "0eLoiLVfuAmNIPdUH8rZSGFntYGnRF",
        "city": "Somewhere",
        "country": "Somewhere",
        "streetName": "123, mystreet",
        "zipCode": "12345F",
        "links": [
            {
                "rel": "self",
                "href": "http://localhost:8080/appws/users/MxQp8LEUYCELQzmvVx9RpLtWOH1bIY/addresses/0eLoiLVfuAmNIPdUH8rZSGFntYGnRF"
            },
            {
                "rel": "user",
                "href": "http://localhost:8080/appws/users/MxQp8LEUYCELQzmvVx9RpLtWOH1bIY"
            }
        ]
    },...
</code>```

答:
I just noticed that i do not return the right stuff. I return List  instead of CollectionModel</p>

```<code>public CollectionModel<AddressRestResponseModel> getUserAddresses(@PathVariable String userKeyId) {
    // same code
    return new CollectionModel<>(returnValue);
}
</code>```

Body:
I have a model response that extends RepresentationModel :

@Getter @Setter
public class AddressRestResponseModel extends RepresentationModel<AddressRestResponseModel> {
    private String addressKeyId;
    private String city;
    private String country;
    private String streetName;
    private String zipCode;
}

I also have a controller that uses HateOAS and should return hal+json:

@GetMapping(
        path="/{userKeyId}/addresses",
        produces = {
                MediaType.APPLICATION_XML_VALUE,
                MediaType.APPLICATION_JSON_VALUE,
                "application/hal+json"
        }
)
public List<AddressRestResponseModel> getUserAddresses(@PathVariable String userKeyId) {
    List<AddressRestResponseModel> returnValue = new ArrayList<>();
    List<AddressDto> addressDtos = addressService.getAddresses(userKeyId);
    if (addressDtos != null && !addressDtos.isEmpty()) {
        ModelMapper modelMapper = new ModelMapper();
        Type listType = new TypeToken<List<AddressRestResponseModel>>() {}.getType();
        returnValue = modelMapper.map(addressDtos, listType);

        for (AddressRestResponseModel address: returnValue) {
            Link addressLink = linkTo(methodOn(UserController.class).getUserAddress(userKeyId, address.getAddressKeyId())).withSelfRel();
            address.add(addressLink);

            Link userLink = linkTo(methodOn(UserController.class).getUser(userKeyId)).withRel("user");
            address.add(userLink);
        }
    }
    return returnValue;
}

I also added the pom dependency for hateoas :

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-hateoas</artifactId>
    <version>2.2.4.RELEASE</version>
</dependency>

I tried this entry point in postman and set the accept header to "application/hal+json". I should receive something like with "_links" and with objects in it:

Unfortunatelly as response I do not have hal format and it looks like it's not using this format :

[
    {
        "addressKeyId": "0eLoiLVfuAmNIPdUH8rZSGFntYGnRF",
        "city": "Somewhere",
        "country": "Somewhere",
        "streetName": "123, mystreet",
        "zipCode": "12345F",
        "links": [
            {
                "rel": "self",
                "href": "http://localhost:8080/appws/users/MxQp8LEUYCELQzmvVx9RpLtWOH1bIY/addresses/0eLoiLVfuAmNIPdUH8rZSGFntYGnRF"
            },
            {
                "rel": "user",
                "href": "http://localhost:8080/appws/users/MxQp8LEUYCELQzmvVx9RpLtWOH1bIY"
            }
        ]
    },...

Body:
I just noticed that i do not return the right stuff. I return List  instead of CollectionModel

public CollectionModel<AddressRestResponseModel> getUserAddresses(@PathVariable String userKeyId) {
    // same code
    return new CollectionModel<>(returnValue);
}


问:
Handle NULL Parameter in SQL Server Table Valued Function
```<code>CREATE FUNCTION fn_roles(@userid varchar(36))
RETURNS TABLE
AS
    RETURN
        SELECT *
        FROM user_roles
        WHERE userid = @userid
</code>```

My function accepts a parameter @userid and returns roles that the user is assigned to from the user_roles table.

What if I want to return all records from the user_roles table if a NULL value for the parameter is passed? What would be the most elegant way to handle that?

答:
you can check parameter is null using ISNULL in this situation it will return userId  so it will return all roles as following :

```<code>CREATE FUNCTION fn_roles(@userid varchar(36))
RETURNS TABLE
AS
RETURN
select * from  user_roles
where userid = ISNULL(@userid,userid)
</code>```

Body:
CREATE FUNCTION fn_roles(@userid varchar(36))
RETURNS TABLE
AS
    RETURN
        SELECT *
        FROM user_roles
        WHERE userid = @userid

My function accepts a parameter @userid and returns roles that the user is assigned to from the user_roles table.

What if I want to return all records from the user_roles table if a NULL value for the parameter is passed? What would be the most elegant way to handle that?

Body:
you can check parameter is null using ISNULL in this situation it will return userId  so it will return all roles as following :

CREATE FUNCTION fn_roles(@userid varchar(36))
RETURNS TABLE
AS
RETURN
select * from  user_roles
where userid = ISNULL(@userid,userid)


问:
Java, How does the compiler know which constructor to call in this lambda expression
I have a question, I'm learning java with a Book, and as I've copied some code in there (and made some changes) and made some investigations, I noticed something odd..., here is the code

```<code>public static void main(String[] args)
{
    Timer timer = new Timer(1000, (event) ->
    {
        System.out.println("At the Tone, the time is" + Instant.ofEpochMilli(event.getWhen()));
        Toolkit.getDefaultToolkit().beep();
    });

    timer.start();
    JOptionPane.showMessageDialog(null, "Quit?");
    System.exit(0);

}
</code>```

It's just a code that notifies you if a second passes. (this code compiles and runs smoothly)

as you can see Timer Constructor requires 2 pars (int, ActionListener)

```<code>public Timer(int delay, ActionListener listener)
</code>```

and the ActionListener Interface has one method that is actionPerformed and requires ActionEvent parameter

```<code>public void actionPerformed(ActionEvent e);
</code>```

Now here is my question, when calling this actionPerformed Method in that lambda expression above
How does the compiler know which constructor to call to instantiate ActionEvent without feeding him any clues about the parameters, ActionEvent has no "No argument Constructor" and the method getWhen() is not static (obj must be instantiated)

Here are all the constructors of ActionEvent:

```<code>public ActionEvent(Object source, int id, String command)

public ActionEvent(Object source, int id, String command, int modifiers)

public ActionEvent(Object source, int id, String command, long when,
                   int modifiers)
</code>```

I really hope I made myself clear!, Thank you

答:
If we look at the source code of javax.swing.Timer, we note that all the ActionListeners of the Timer are stored on a javax.swing.event.EventListenerList, called listenerList.
They are called in this line(s):

fireActionPerformed(new ActionEvent(Timer.this, 0, getActionCommand(),
                                                    System.currentTimeMillis(),
                                                    0));
```

<p>With fireActionPerformed:</p>

<pre class="lang-java prettyprint-override"><code>protected void fireActionPerformed(ActionEvent e) {
        // Guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList();

        // Process the listeners last to first, notifying
        // those that are interested in this event
        for (int i=listeners.length-2; i>=0; i-=2) {
            if (listeners[i]==ActionListener.class) {
                ((ActionListener)listeners[i+1]).actionPerformed(e);
            }
        }
    }
</code>```

The regular constructor selection process applies.

Body:
I have a question, I'm learning java with a Book, and as I've copied some code in there (and made some changes) and made some investigations, I noticed something odd..., here is the code

public static void main(String[] args)
{
    Timer timer = new Timer(1000, (event) ->
    {
        System.out.println("At the Tone, the time is" + Instant.ofEpochMilli(event.getWhen()));
        Toolkit.getDefaultToolkit().beep();
    });

    timer.start();
    JOptionPane.showMessageDialog(null, "Quit?");
    System.exit(0);

}

It's just a code that notifies you if a second passes. (this code compiles and runs smoothly)

as you can see Timer Constructor requires 2 pars (int, ActionListener)

public Timer(int delay, ActionListener listener)

and the ActionListener Interface has one method that is actionPerformed and requires ActionEvent parameter

public void actionPerformed(ActionEvent e);

Now here is my question, when calling this actionPerformed Method in that lambda expression above
How does the compiler know which constructor to call to instantiate ActionEvent without feeding him any clues about the parameters, ActionEvent has no "No argument Constructor" and the method getWhen() is not static (obj must be instantiated)

Here are all the constructors of ActionEvent:

public ActionEvent(Object source, int id, String command)

public ActionEvent(Object source, int id, String command, int modifiers)

public ActionEvent(Object source, int id, String command, long when,
                   int modifiers)

I really hope I made myself clear!, Thank you

Body:
If we look at the source code of javax.swing.Timer, we note that all the ActionListeners of the Timer are stored on a javax.swing.event.EventListenerList, called listenerList.
They are called in this line(s):

fireActionPerformed(new ActionEvent(Timer.this, 0, getActionCommand(),
                                                    System.currentTimeMillis(),
                                                    0));

With fireActionPerformed:

protected void fireActionPerformed(ActionEvent e) {
        // Guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList();

        // Process the listeners last to first, notifying
        // those that are interested in this event
        for (int i=listeners.length-2; i>=0; i-=2) {
            if (listeners[i]==ActionListener.class) {
                ((ActionListener)listeners[i+1]).actionPerformed(e);
            }
        }
    }

The regular constructor selection process applies.


问:
Is there a way to gain recursive read access to a a user specified folder in Silverlight?
If I'm operating within the Sandbox clearly I can't just start randomly reading from the HDD.  Is there a way for the user to open up access to a folder including all its sub folders without using full trust?</p>

答:
Just to toss out the info if it helps...

This should be possible in Silverlight 5, but I don't think it is in the Silverlight 5 Beta that was released at Mix this year.  Here is one of my co-workers, Nick Kramer, giving a demo of it working (with code):


问:
Does Amplify SDK support PKCE out of the box for your React site?
I am working on a web app built with the AWS Amplify framework and react.  The app will use a Cognito Hosted UI to log in its users, preferably using the Authorization Code Grant with PKCE flow.

Does anybody know if the Amplify SDK supports this flow out of the box?  I know it supports the Authorization Code Grant part, but I am mostly wondering if it implements the PKCE extension too.

My apologies if this info was in the docs, and I just missed it. Thank you for your advise!

答: yes it does. PKCE will be used automatically when using the HostedUI and Amplify. I am not aware of this being in the docs but the simple answer is yes :)</p>


问:
Youtube videos not played in Electron app but in a website does
I'm working on two related projects, a web page and an application in Electron, among other things, both have to play Youtube videos embedded in an iframe. Everything works perfectly on the website,

```<code>var newUrl = 'http://www.youtube.com/embed/' + $scope.youtube_parser(video.url);
        $scope.videoURL = $sce.trustAsResourceUrl(newUrl + '?enablejsapi=1&showinfo=0&rel=0');
$scope.setYTPlayer();

$scope.setYTPlayer = function(){
    $scope.player;
    $scope.player = new YT.Player('player', {
        height: '360',
        width: '640',
        videoId: $scope.videoSelected,
        events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
        }
    });
}
<iframe id="player" frameborder="0" allowfullscreen ng-src="{{videoURL}}" style="width: 100%;height: 100%;"></iframe>
</code>```

but in the Electron application many of the videos are not played, a message is read on the player: "video not available"

```<code>var youtubeId = $scope.getYoutubeId(video.url)
    $scope.currentVideo = $sce.trustAsResourceUrl(
      'https://www.youtube.com/embed/' + youtubeId + '?rel=0'
    )
<iframe width="100%" height="442" ng-src="{{ currentVideo }}" frameborder="0" allowfullscreen></iframe>
</code>```

Capture of the player

The same link, with the same method, on the page reproduces without any problem. Try with the iframe only, with the api, changing the playback parameters and the problem continues.
The question is, is there any Youtube policy that does not allow videos to be played in certain places? Or what can be the error?

Electron versión: v3.0.3

Thanks and apologies if I can not express myself well.

答:
This problem appears due to the protocol through which you open the electron window.
If you open a local html file, then "file://" protocol is used.I found 2 solutions to this problem:

You can raise a local temporary http server to transfer the html file for the window, and then disable it.

```<code>import http from 'http';
import fs from 'fs';
import path from 'path';

//at start
let server;
server = http.createServer((req, res) => {
const filePath = path.join(app.getAppPath(), 'public', req.url);
const file = fs.readFileSync(filePath);
res.end(file.toString());
if (req.url.includes('index.js'))
   server.close();
}).listen(8080);

//after app-ready event
mainWindow.loadURL('http://localhost:8080/index.html');
</code>```

A more preferable option is to intercept the http protocol and transfer files, but you must disable interception after transferring all local files, otherwise it will affect all subsequent http requests.

```<code>import path from 'path';

//before window.loadURL
session.defaultSession.protocol.interceptFileProtocol('http', (request, callback) => {
    const fileUrl = request.url.replace('http://localhost/', '');
    const filePath = path.join(app.getAppPath(), 'public', fileUrl);

    if(request.url.includes('index.js')) {
        session.defaultSession.protocol.uninterceptProtocol('http');
    }
    callback(filePath);
});
//after app-ready event
mainWindow.loadURL('http://localhost:8080/index.html');
</code>```

Also, if you get an error with the header "x-frame-options" = "sameorigin", you can delete this header after receiving a response.

```<code>const filter = {
    urls: ['https://www.youtube.com/*']
};
session.defaultSession.webRequest.onHeadersReceived(filter, (details, callback) => {
    for (const header in details.responseHeaders) {
        if (header.toLocaleLowerCase() === 'x-frame-options') {
            delete details.responseHeaders[header];
        }
    }
    callback({ cancel: false, responseHeaders: details.responseHeaders });
});
</code>```

Body:
I'm working on two related projects, a web page and an application in Electron, among other things, both have to play Youtube videos embedded in an iframe. Everything works perfectly on the website,

var newUrl = 'http://www.youtube.com/embed/' + $scope.youtube_parser(video.url);
        $scope.videoURL = $sce.trustAsResourceUrl(newUrl + '?enablejsapi=1&showinfo=0&rel=0');
$scope.setYTPlayer();

$scope.setYTPlayer = function(){
    $scope.player;
    $scope.player = new YT.Player('player', {
        height: '360',
        width: '640',
        videoId: $scope.videoSelected,
        events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
        }
    });
}

but in the Electron application many of the videos are not played, a message is read on the player: "video not available"

var youtubeId = $scope.getYoutubeId(video.url)
    $scope.currentVideo = $sce.trustAsResourceUrl(
      'https://www.youtube.com/embed/' + youtubeId + '?rel=0'
    )

Capture of the player

The same link, with the same method, on the page reproduces without any problem. Try with the iframe only, with the api, changing the playback parameters and the problem continues.
The question is, is there any Youtube policy that does not allow videos to be played in certain places? Or what can be the error?

Electron versión: v3.0.3

Thanks and apologies if I can not express myself well.

Body:
This problem appears due to the protocol through which you open the electron window.
If you open a local html file, then "file://" protocol is used.I found 2 solutions to this problem:

You can raise a local temporary http server to transfer the html file for the window, and then disable it.

import http from 'http';
import fs from 'fs';
import path from 'path';

//at start
let server;
server = http.createServer((req, res) => {
const filePath = path.join(app.getAppPath(), 'public', req.url);
const file = fs.readFileSync(filePath);
res.end(file.toString());
if (req.url.includes('index.js'))
   server.close();
}).listen(8080);

//after app-ready event
mainWindow.loadURL('http://localhost:8080/index.html');

A more preferable option is to intercept the http protocol and transfer files, but you must disable interception after transferring all local files, otherwise it will affect all subsequent http requests.

import path from 'path';

//before window.loadURL
session.defaultSession.protocol.interceptFileProtocol('http', (request, callback) => {
    const fileUrl = request.url.replace('http://localhost/', '');
    const filePath = path.join(app.getAppPath(), 'public', fileUrl);

    if(request.url.includes('index.js')) {
        session.defaultSession.protocol.uninterceptProtocol('http');
    }
    callback(filePath);
});
//after app-ready event
mainWindow.loadURL('http://localhost:8080/index.html');

Also, if you get an error with the header "x-frame-options" = "sameorigin", you can delete this header after receiving a response.

const filter = {
    urls: ['https://www.youtube.com/*']
};
session.defaultSession.webRequest.onHeadersReceived(filter, (details, callback) => {
    for (const header in details.responseHeaders) {
        if (header.toLocaleLowerCase() === 'x-frame-options') {
            delete details.responseHeaders[header];
        }
    }
    callback({ cancel: false, responseHeaders: details.responseHeaders });
});


问:
How to pass data from one component to another while using API in reactjs
In React, we can pass data from one component to another using props but I want to know how to pass data from one component to another while issueing an API request.

In the backend, the signin credentials are authenticated using "JWT authentication".

How to pass the the username while the user is getting logged in?
When the user get's logged in, my page should show "welcome ".

You can check out the code in this CodeSanbox

Here is the json data from the API:

```<code>{
  item: [
    {
      "id": "145741863",
      "firstName": "ABCDEF",
      "email": "qwerty@yahoo.com",
      "password": "Aertyuio",
    }
  ]
}
</code>```

答:
You can do it like this:

```<code>axios
      .post(`/api/Login/auth`, data, {
        headers: { "Content-Type": "application/json" }
      })
      .then(res => {
        console.log(res);
        this.props.history.push("/Welcome", { ...res });
      })
      .catch(err => {
        console.log(err.response.data.message);
        var res = err.response.data.message;
        this.setState({ errorMsg: res });
      });
</code>```

And as you are sending JSON Web Token as data, you can access it as:

```<code>this.props.data.item[0].firstName
</code>```

Hope this works for you.

Body:
In React, we can pass data from one component to another using props but I want to know how to pass data from one component to another while issueing an API request.

In the backend, the signin credentials are authenticated using "JWT authentication".

How to pass the the username while the user is getting logged in?
When the user get's logged in, my page should show "welcome ".

You can check out the code in this CodeSanbox

Here is the json data from the API:

{
  item: [
    {
      "id": "145741863",
      "firstName": "ABCDEF",
      "email": "qwerty@yahoo.com",
      "password": "Aertyuio",
    }
  ]
}

Body:
You can do it like this:

axios
      .post(`/api/Login/auth`, data, {
        headers: { "Content-Type": "application/json" }
      })
      .then(res => {
        console.log(res);
        this.props.history.push("/Welcome", { ...res });
      })
      .catch(err => {
        console.log(err.response.data.message);
        var res = err.response.data.message;
        this.setState({ errorMsg: res });
      });

And as you are sending JSON Web Token as data, you can access it as:

this.props.data.item[0].firstName

Hope this works for you.


问:
Check for proper list in Common Lisp
Is there a standard function in Common Lisp that can check against improper lists (i.e. circular and dotted lists) without signaling an error? list-length can check against circular lists (it returns nil for them), but signals type-error when given a dotted list.

Scheme's list? traverses the whole list to make sure it is not dotted or circular; Common Lisp's listp only checks that it's given nil or a cons cell.

Here's the simplest I could come up with:

```<code>(defun proper-list-p (x)
  (not (null (handler-case (list-length x) (type-error () nil)))))
</code>```

Since several implementations have been suggested and many unexpected problems have been found, here's a test suite for aspiring proper-list-p writers:

```<code>(defun circular (xs)
  (let ((xs (copy-list xs)))
    (setf (cdr (last xs)) xs)
    xs))

(assert (eql t (proper-list-p '())))
(assert (eql t (proper-list-p '(1))))
(assert (eql t (proper-list-p '(1 2))))
(assert (eql t (proper-list-p '(1 2 3))))

(assert (not (proper-list-p 1)))
(assert (not (proper-list-p '(1 . 2))))
(assert (not (proper-list-p '(1 2 . 3))))
(assert (not (proper-list-p '(1 2 3 . 4))))

(assert (not (proper-list-p (circular '(1)))))
(assert (not (proper-list-p (circular '(1 2)))))
(assert (not (proper-list-p (circular '(1 2 3)))))
(assert (not (proper-list-p (list* 1 (circular '(2))))))
(assert (not (proper-list-p (list* 1 2 (circular '(3 4))))))
</code>```

答:
in addition, something slightly less verbose, than the accepted answer:

```<code>(defun improper-tail (ls)
  (do ((x ls (cdr x))
       (visited nil (cons x visited)))
      ((or (not (consp x)) (member x visited)) x)))

(defun proper-list-p (ls)
  (null (improper-tail ls)))
</code>```

or just like this:

```<code>(defun proper-list-p (ls)
  (do ((x ls (cdr x))
       (visited nil (cons x visited)))
      ((or (not (consp x)) (member x visited)) (null x))))
</code>```

seen to pass all the op's test assertions

Title: Check for proper list in Common Lisp

Body:
Is there a standard function in Common Lisp that can check against improper lists (i.e. circular and dotted lists) without signaling an error? list-length can check against circular lists (it returns nil for them), but signals type-error when given a dotted list.

Scheme's list? traverses the whole list to make sure it is not dotted or circular; Common Lisp's listp only checks that it's given nil or a cons cell.

Here's the simplest I could come up with:

(defun proper-list-p (x)
  (not (null (handler-case (list-length x) (type-error () nil)))))

Since several implementations have been suggested and many unexpected problems have been found, here's a test suite for aspiring proper-list-p writers:

(defun circular (xs)
  (let ((xs (copy-list xs)))
    (setf (cdr (last xs)) xs)
    xs))

(assert (eql t (proper-list-p '())))
(assert (eql t (proper-list-p '(1))))
(assert (eql t (proper-list-p '(1 2))))
(assert (eql t (proper-list-p '(1 2 3))))

(assert (not (proper-list-p 1)))
(assert (not (proper-list-p '(1 . 2))))
(assert (not (proper-list-p '(1 2 . 3))))
(assert (not (proper-list-p '(1 2 3 . 4))))

(assert (not (proper-list-p (circular '(1)))))
(assert (not (proper-list-p (circular '(1 2)))))
(assert (not (proper-list-p (circular '(1 2 3)))))
(assert (not (proper-list-p (list* 1 (circular '(2))))))
(assert (not (proper-list-p (list* 1 2 (circular '(3 4))))))

Body:
in addition, something slightly less verbose, than the accepted answer:

(defun improper-tail (ls)
  (do ((x ls (cdr x))
       (visited nil (cons x visited)))
      ((or (not (consp x)) (member x visited)) x)))

(defun proper-list-p (ls)
  (null (improper-tail ls)))

or just like this:

(defun proper-list-p (ls)
  (do ((x ls (cdr x))
       (visited nil (cons x visited)))
      ((or (not (consp x)) (member x visited)) (null x))))

seen to pass all the op's test assertions


答:
The Timer constructor just receives a listener and registers it in its listeners list. When the timer ticks (where listener should be called), the Timer instance creates a new ActionEvent (See Timer.java:245) and passes it over to the registered listeners.

So simply saying, the compiler doesn't create it for you. Instead Timer class does.

Title: Java, How does the compiler know which constructor to call in this lambda expression


问:
Laravel Carbon get start + end of last week?
I have laravel carbon for get start + end of current week :

```<code>$startofcurrentweek =Carbon::now()->startOfWeek(); //2020-02-17 00:00:00
$endofcurrentweek =Carbon::now()->endOfWeek(); //2020-02-23 23:59:59
</code>```

How To get Start of Last Week  using carbon ,... So i can get,

```<code>$startoflasttweek  = 2020-02-10 00:00:00
$endoflastweek  = 2020-02-16 23:59:59
</code>```

答:
You can subtract 7 days to the start of current week or subtract 7 days from now and get the start of the week.

```<code>$startOfCurrentWeek = Carbon::now()->startOfWeek();

$startOfLastWeek  = $startOfCurrentWeek->copy()->subDays(7);
$startOfLastWeek  = Carbon::now()->subDays(7)->startOfWeek();
</code>```

And the same to get the end of the last week.

Body:
I have laravel carbon for get start + end of current week :

$startofcurrentweek =Carbon::now()->startOfWeek(); //2020-02-17 00:00:00
$endofcurrentweek =Carbon::now()->endOfWeek(); //2020-02-23 23:59:59

How To get Start of Last Week  using carbon ,... So i can get,

$startoflasttweek  = 2020-02-10 00:00:00
$endoflastweek  = 2020-02-16 23:59:59

Body:
You can subtract 7 days to the start of current week or subtract 7 days from now and get the start of the week.

$startOfCurrentWeek = Carbon::now()->startOfWeek();

$startOfLastWeek  = $startOfCurrentWeek->copy()->subDays(7);
$startOfLastWeek  = Carbon::now()->subDays(7)->startOfWeek();

And the same to get the end of the last week.


问:
Sockets: Send strings from Java to C#?
I need to send string messages from Java program to C# program in real time.
There are many examples in the Internet but U can't find anything good for my purpose that is (probably) Java client (sockets code) and c# server (sockets code).
Thank you.</p>

答:
I think I've found a good, working solution. Using UDP sockets:

Java code

```<code>public void runJavaSocket() {
    System.out.println("Java Sockets Program has started."); int i=0;

    try {
        DatagramSocket socket = new DatagramSocket();
        System.out.println("Sending the udp socket...");
        // Send the Message "HI"
        socket.send(toDatagram("HI",InetAddress.getByName("127.0.0.1"),3800));
        while (true) {
            System.out.println("Sending hi " + i);
            Thread.currentThread();
            Thread.sleep(1000);
            socket.send(toDatagram("HI " +
                String.valueOf(i),InetAddress.getByName("127.0.0.1"),3800));
            i++;
       }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public DatagramPacket toDatagram(
    String s, InetAddress destIA, int destPort) {
    // Deprecated in Java 1.1, but it works:
    byte[] buf = new byte[s.length() + 1];
    s.getBytes(0, s.length(), buf, 0);
    // The correct Java 1.1 approach, but it's
    // Broken (it truncates the String):
    // byte[] buf = s.getBytes();
    return new DatagramPacket(buf, buf.length, destIA, destPort);
}
</code>```

C# code

```<code>string returnData;
byte[] receiveBytes;
//ConsoleKeyInfo cki = new ConsoleKeyInfo();

using (UdpClient udpClient =
    new UdpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3800)))
{
    IPEndPoint remoteIpEndPoint =
        new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3800);
    while (true)
    {
        receiveBytes = udpClient.Receive(ref remoteIpEndPoint);
        returnData = Encoding.ASCII.GetString(receiveBytes);
        Console.WriteLine(returnData);
    }
}
</code>```

Title: Sockets: Send strings from Java to C#?

Body:
I think I've found a good, working solution. Using UDP sockets:

Java code

public void runJavaSocket() {
    System.out.println("Java Sockets Program has started."); int i=0;

    try {
        DatagramSocket socket = new DatagramSocket();
        System.out.println("Sending the udp socket...");
        // Send the Message "HI"
        socket.send(toDatagram("HI",InetAddress.getByName("127.0.0.1"),3800));
        while (true) {
            System.out.println("Sending hi " + i);
            Thread.currentThread();
            Thread.sleep(1000);
            socket.send(toDatagram("HI " +
                String.valueOf(i),InetAddress.getByName("127.0.0.1"),3800));
            i++;
       }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public DatagramPacket toDatagram(
    String s, InetAddress destIA, int destPort) {
    // Deprecated in Java 1.1, but it works:
    byte[] buf = new byte[s.length() + 1];
    s.getBytes(0, s.length(), buf, 0);
    // The correct Java 1.1 approach, but it's
    // Broken (it truncates the String):
    // byte[] buf = s.getBytes();
    return new DatagramPacket(buf, buf.length, destIA, destPort);
}

C# code

string returnData;
byte[] receiveBytes;
//ConsoleKeyInfo cki = new ConsoleKeyInfo();

using (UdpClient udpClient =
    new UdpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3800)))
{
    IPEndPoint remoteIpEndPoint =
        new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3800);
    while (true)
    {
        receiveBytes = udpClient.Receive(ref remoteIpEndPoint);
        returnData = Encoding.ASCII.GetString(receiveBytes);
        Console.WriteLine(returnData);
    }
}


答:
Simply add it to the where clause with or:

```<code>select *
from   user_roles
where  userid = @userid or @userid is null
</code>```

Title: Handle NULL Parameter in SQL Server Table Valued Function

Body:
Simply add it to the where clause with or:

select *
from   user_roles
where  userid = @userid or @userid is null


问:
Puppeteer: Storing and accessing contextual or meta data per page visit
I'm experimenting with auto-generating outcomes using @xstate/test and combining it with puppeteer and jest. Using jest's beforeAll and afterAll hooks I'm calling page.setRequestInterception and registering a callback to intercept network requests and mock their response.

XState generates the pathways that I want to test and from each path I can determine whether the test wants to test what should occur when the API fails or succeeds. I'm stuck on how to properly communicate that back to puppeteer and access that information in my request handler.

答:
One option I discovered is using query parameters. The Request object that is passed to the event handler has access to the frame that made the request.

In my test:

```<code>it(..., async () => {
  await page.goto('http://localhost:3000?failApi=true')
  ..
</code>```

and in my request handler:

```<code>page.on('request', req => {
   // check req.frame.url() here and make choices
...
</code>```

Body:
One option I discovered is using query parameters. The Request object that is passed to the event handler has access to the frame that made the request.

In my test:

it(..., async () => {
  await page.goto('http://localhost:3000?failApi=true')
  ..

and in my request handler:

page.on('request', req => {
   // check req.frame.url() here and make choices
...


答:
Using one object to group all the arrays, so that will be possible to iterate over them. The idea is something like below:</p>

```<code>const store = new Vuex.Store({
 state: {
    itemsGroupArrays: {
      items1: [{ id: 1, text: "item1 - 1" }, { id: 2, text: "item1 - 2" }],
      items2: [{ id: 3, text: "item2 - 1" }, { id: 4, text: "item2 - 2" }]
    }
  },
  getters: {
    getItemByIdFromStateGroupArrays: state => (id) => {
      let returnedItem = null;
      Object.values(state.itemsGroupArrays).forEach((itemStateArray) => {
        if (itemStateArray.some(item => item.id === id))  {
          returnedItem = itemStateArray.find(item => item.id === id);
        }
      })
      return returnedItem;
    }
  }
});
</code>```

Title: Find matching item across multiple store arrays in VueX

Body:
Currently when I want to find single item in an array that is in store I use this:

this.matched = this.$store.state.itemlist.find(itemId=> {
      return itemId.id == "someid";
    });

Lets says I want to go over multiple arrays to find the matching item given provided ID? Like i have itemlist1 itemlist2 itemgetter()...  Some of the arrays are getters ( but I think it doesnt change much). So basically I want to search over different state and getter items in this component instead of searching over one as in example above.

Body:
Using one object to group all the arrays, so that will be possible to iterate over them. The idea is something like below:

const store = new Vuex.Store({
 state: {
    itemsGroupArrays: {
      items1: [{ id: 1, text: "item1 - 1" }, { id: 2, text: "item1 - 2" }],
      items2: [{ id: 3, text: "item2 - 1" }, { id: 4, text: "item2 - 2" }]
    }
  },
  getters: {
    getItemByIdFromStateGroupArrays: state => (id) => {
      let returnedItem = null;
      Object.values(state.itemsGroupArrays).forEach((itemStateArray) => {
        if (itemStateArray.some(item => item.id === id))  {
          returnedItem = itemStateArray.find(item => item.id === id);
        }
      })
      return returnedItem;
    }
  }
});