问:
Connecting to codefresh image registry via kubectl, problem with secrets
I am trying to deploy an application via kubectl using an image stored on Codefresh. I have it running perfectly when i place the image on a public registry.

The problem is when I apply the deployment.yaml I get a "ImagePullBackOff" error on the pods. I'm assuming, i think correctly, that this is because I need a secret to be able to access my Codefresh image.

This is the container part of my current deployment.yaml:

```<code>spec:
      containers:
        - name: dockapp
        #States the image that will be put inside the pod. Secret to get access is declared below
        #registry.hub.docker.com/jamiedovu/dockapp:latest
          image:  r.cfcr.io/jamiew87/my-app-image:master
          ports:
          - containerPort: 8080
            name: http
      imagePullSecrets:
      - name: regcred
</code>```

My question is, what is it i need to put into the secret "regcred" to be able to connect to this private registry. The Kubernetes documentation only demonstrates how to do one for docker.

答:
For people in the future with problems,
The codefresh repository is an actual docker repository. Not knowing this was giving me the problems.
So in the docker-username etc places you put your codefresh credentials, and instead of the password you put a secret that you generate within codefresh. This gives you access to the r.cfcr.io repository.</p>

Body:
I am trying to deploy an application via kubectl using an image stored on Codefresh. I have it running perfectly when i place the image on a public registry.

The problem is when I apply the deployment.yaml I get a "ImagePullBackOff" error on the pods. I'm assuming, i think correctly, that this is because I need a secret to be able to access my Codefresh image.

This is the container part of my current deployment.yaml:

spec:
      containers:
        - name: dockapp
        #States the image that will be put inside the pod. Secret to get access is declared below
        #registry.hub.docker.com/jamiedovu/dockapp:latest
          image:  r.cfcr.io/jamiew87/my-app-image:master
          ports:
          - containerPort: 8080
            name: http
      imagePullSecrets:
      - name: regcred

My question is, what is it i need to put into the secret "regcred" to be able to connect to this private registry. The Kubernetes documentation only demonstrates how to do one for docker.


来源: stackexchange

问:
How to divide the data set into train, test and validation purpose
My data frame consist of 44.2 billions rows. I want to split it into 3 sets (train,test and validation). So that no points are overlapped.

I have done (1st process) -

```<code>train, valid, test = np.split(df.sample(frac=1), [int(.8*len(df)), int(.95*len(df))])
</code>```

Checking any value is present or not -

```<code>len(valid[valid.id.isin(test.id)])
len(train[train.id.isin(test.id)])
</code>```

2nd process -

```<code>train = df[(np.random.rand(len(df)) < 0.8)]
valid = df[(np.random.rand(len(df)) > 0.8) & (np.random.rand(len(df)) < 0.95)]
test = df[(np.random.rand(len(df)) > 0.95) & (np.random.rand(len(df)) < 1)]
</code>```

But as per my understanding the above two methods are not perfect. Can anybody help me

答:
```<code>from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test  = train_test_split(X, y, test_size=0.2, random_state=1)

X_val, X_test, y_val, y_test = train_test_split(X_test, y_test, test_size=0.25, random_state=1)
</code>```

The first line splits the dataset into 80:20 ratio. You can use the same function to split the 20% data into 15:5.

ContentLicense: CC BY-SA 4.0

Body:
My data frame consist of 44.2 billions rows. I want to split it into 3 sets (train,test and validation). So that no points are overlapped.

I have done (1st process) -

train, valid, test = np.split(df.sample(frac=1), [int(.8*len(df)), int(.95*len(df))])

Checking any value is present or not -

len(valid[valid.id.isin(test.id)])
len(train[train.id.isin(test.id)])

2nd process -

train = df[(np.random.rand(len(df)) < 0.8)]
valid = df[(np.random.rand(len(df)) > 0.8) & (np.random.rand(len(df)) < 0.95)]
test = df[(np.random.rand(len(df)) > 0.95) & (np.random.rand(len(df)) < 1)]

But as per my understanding the above two methods are not perfect. Can anybody help me

Body:
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test  = train_test_split(X, y, test_size=0.2, random_state=1)

X_val, X_test, y_val, y_test = train_test_split(X_test, y_test, test_size=0.25, random_state=1)

The first line splits the dataset into 80:20 ratio. You can use the same function to split the 20% data into 15:5.


问:
Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable
When trying to reference a managed bean in EL like so #{bean.entity.property}, sometimes a javax.el.PropertyNotFoundException: Target Unreachable exception is being thrown, usually when a bean property is to be set, or when a bean action is to be invoked.

There seem to be five different kinds of messages:

Target Unreachable, identifier 'bean' resolved to null

Target Unreachable, 'entity' returned null

Target Unreachable, 'null' returned null

Target Unreachable, ''0'' returned null

Target Unreachable, 'BracketSuffix' returned null

What do they all mean? How are they caused and how should they be solved?

答:
For 1. topic (Target Unreachable, identifier 'bean' resolved to null);

I checked valuable answers the @BalusC and the other sharers but I exceed the this problem like this on my scenario.
After the creating a new xhtml with different name and creating bean class with different name then I wrote (not copy-paste) the codes step by step to the new bean class and new xhtml file.

ContentLicense: CC BY-SA 3.0


问:
Flip effect between images
I'm developing an eBook Reader and need to have the flip effect between pages.

I want has support to flip from right or left.

How can I do that on Android?

答:
This solve my problem:

http://code.google.com/p/android-page-curl/

This doesn't have the effect of the reflected image but help a lot.

ContentLicense: CC BY-SA 2.5

Title: Flip effect between images


问:
UserDefaults not working on didload in my project
I have a login screen LoginViewController and homescreen HomeScreenController which is pushed when the user is successfully logged in).
I have declared a variable for UserDefaults as below in a seperate class:

```<code>class User {
    static var isLoggedIn = UserDefaults.standard.bool(forKey:"islogged")
}
</code>```

When the  user clicks login Button, the code is as below

```<code>ButtonAction:
{
    User.isLoggedin = true
    //Performsegue........to homescreen
}

ViewDidload {

    if user.isloggedin == true {
        //Performsegue......homescreen
    }
    else {
        Show some alerts
    }
}
</code>```

Here in my case...nothing happens...sorry for the rough code since I am using my smartphone to ask this question.

Am I missing something in appdelegate or somewhere else.
I just want to use the variables as it is because I don't want to change the entire code in my project.
The project is actually complicated and I just made an example to make you guys understand my situation.
This is not the exact code.

答:
I think you need to hide login vc if user was logined, right?

Do it in HomeVC

```<code>@IBAction func login(_ sender : Any)  {
   if login == true{
      UserDefaults.standart.set("true", forKey:"islogged")
    }
}
</code>```

And paste it to AppDelegate

```<code>var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    self.window = UIWindow(frame: UIScreen.main.bounds)
    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    var initialViewController: UIViewController

    if UserDefaults.standard.string(forKey: "islogged") == "true"//your condition if user is already logged in or not
    {
        // if already logged in then redirect to MainViewController

        initialViewController = mainStoryboard.instantiateViewController(withIdentifier: "HomeVC") as! UITabBarController // 'MainController' is the storyboard id of HomeViewController
    }
    else
    {
        //If not logged in then show LoginViewController
        initialViewController = mainStoryboard.instantiateViewController(withIdentifier: "LoginVC") as! SignInViewController // 'LoginController' is the storyboard id of LoginViewController

    }

    self.window?.rootViewController = initialViewController

    self.window?.makeKeyAndVisible()

    return true
}
</code>```

Body:
I have a login screen LoginViewController and homescreen HomeScreenController which is pushed when the user is successfully logged in).
I have declared a variable for UserDefaults as below in a seperate class:

class User {
    static var isLoggedIn = UserDefaults.standard.bool(forKey:"islogged")
}

When the  user clicks login Button, the code is as below

ButtonAction:
{
    User.isLoggedin = true
    //Performsegue........to homescreen
}

ViewDidload {

    if user.isloggedin == true {
        //Performsegue......homescreen
    }
    else {
        Show some alerts
    }
}

Here in my case...nothing happens...sorry for the rough code since I am using my smartphone to ask this question.

Am I missing something in appdelegate or somewhere else.
I just want to use the variables as it is because I don't want to change the entire code in my project.
The project is actually complicated and I just made an example to make you guys understand my situation.
This is not the exact code.

Body:
I think you need to hide login vc if user was logined, right?

Do it in HomeVC

@IBAction func login(_ sender : Any)  {
   if login == true{
      UserDefaults.standart.set("true", forKey:"islogged")
    }
}

And paste it to AppDelegate

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    self.window = UIWindow(frame: UIScreen.main.bounds)
    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    var initialViewController: UIViewController

    if UserDefaults.standard.string(forKey: "islogged") == "true"//your condition if user is already logged in or not
    {
        // if already logged in then redirect to MainViewController

        initialViewController = mainStoryboard.instantiateViewController(withIdentifier: "HomeVC") as! UITabBarController // 'MainController' is the storyboard id of HomeViewController
    }
    else
    {
        //If not logged in then show LoginViewController
        initialViewController = mainStoryboard.instantiateViewController(withIdentifier: "LoginVC") as! SignInViewController // 'LoginController' is the storyboard id of LoginViewController

    }

    self.window?.rootViewController = initialViewController

    self.window?.makeKeyAndVisible()

    return true
}


问:
Wait until an event is fired in NodeJs
I am writing a function in my server to return data from client A to client B at the time client B is sending request. When function is called, my server send request to client A and then client A send data back to server. The problem is how to make this function wait until server received data from client A.

I already use setTimeout and it worked for me but it not flexible

```<code>//the code for receiving data from client A is written in another file
socketA.emit('getData', JSON.stringify(json));
//I want my function will stopping here
socketB.emit('sendData', somedata);
</code>```

This is my code for receiving data from client

```<code>socket.on('getData', (data) =>{
   storage_data = data;
});
</code>```

I expect there is a way to stop my function without using setTimeout or if I make something wrong, please tell me.

Thanks.

答:
I think Promise is a definitely way (I not sure, but just give it a try).This
Asynchronous in NodeJS might be helpful.</p>

Title: Wait until an event is fired in NodeJs

Body:
I am writing a function in my server to return data from client A to client B at the time client B is sending request. When function is called, my server send request to client A and then client A send data back to server. The problem is how to make this function wait until server received data from client A.

I already use setTimeout and it worked for me but it not flexible

//the code for receiving data from client A is written in another file
socketA.emit('getData', JSON.stringify(json));
//I want my function will stopping here
socketB.emit('sendData', somedata);

This is my code for receiving data from client

socket.on('getData', (data) =>{
   storage_data = data;
});

I expect there is a way to stop my function without using setTimeout or if I make something wrong, please tell me.

Thanks.


问:
Modifying the Input file to required output file
I have an input file. I want to modify the input file as below:-

Input File:-

```<code>foo bar flower

dragon smile

friends few are there. Here it is

...

..

..

.

foo bar flower

beauty good

ugly bad

...

..

.
</code>```

My Output Fie:-

```<code>foo bar flower

dragon smile

friends few are there. Here it is

...

..

..

.

//foo bar flower

//beauty good

//ugly bad

//...

//..

//.Rest of the file
</code>```

I wanted to look back. But could not figureout.

From the last occurrence of foo bar till the EOF in the file, I need to prefix the outputs with '//'

答:
if the file is not too big, you can read it's lines into a list and then process it looking back and forward how many times you want.

here's an example, let me know if this works for you (notice you should replace input.txt with your real file name):

content = []
with open('input.txt') as f:
    content = f.readlines()

# we find the last index by finding the first occurrence in the reversed list, then subtracting it from the list length
last_foobar_index = len(content) - 1 - content[::-1].index('foo bar flower\n')

# now we go over each line from that index and add leading "//"
for i in range(last_foobar_index,len(content)):
    content[i] = "//"+content[i]

# now just write it to an output file
with open('output.txt', 'w+') as f:
    f.writelines(content)

```

<p><strong>EDIT - BECAUSE THE FILE IS INDEED BIG</strong></p>

<p>because the file might be too big to fit in memory, we want to iterate the file in a memory-efficient way, as described in Methods of File Objects.</p>

<p>we'll make 2 passes over the file, in the first one we'll just find the index of the latest <code>foo bar</code>, and in the second one we will create output.txt:</p>

<pre class="lang-py prettyprint-override"><code>
latest_foobar_index = 0

with open('input.txt') as f:
    for i, line in enumerate(f):
        if line.startswith('foo bar'):
            latest_foobar_index = i

    f.seek(0) # go back to the start of the file

    with open('output.txt', 'w+') as out:
        for i, line in enumerate(f):
            if i >= latest_foobar_index:
                out.write('//')
            out.write(line)

</code>```

Body:
I have an input file. I want to modify the input file as below:-

Input File:-

foo bar flower

dragon smile

friends few are there. Here it is

...

..

..

.

foo bar flower

beauty good

ugly bad

...

..

.

My Output Fie:-

foo bar flower

dragon smile

friends few are there. Here it is

...

..

..

.

//foo bar flower

//beauty good

//ugly bad

//...

//..

//.Rest of the file

I wanted to look back. But could not figureout.

From the last occurrence of foo bar till the EOF in the file, I need to prefix the outputs with '//'

Body:
if the file is not too big, you can read it's lines into a list and then process it looking back and forward how many times you want.

here's an example, let me know if this works for you (notice you should replace input.txt with your real file name):

content = []
with open('input.txt') as f:
    content = f.readlines()

# we find the last index by finding the first occurrence in the reversed list, then subtracting it from the list length
last_foobar_index = len(content) - 1 - content[::-1].index('foo bar flower\n')

# now we go over each line from that index and add leading "//"
for i in range(last_foobar_index,len(content)):
    content[i] = "//"+content[i]

# now just write it to an output file
with open('output.txt', 'w+') as f:
    f.writelines(content)

EDIT - BECAUSE THE FILE IS INDEED BIG

because the file might be too big to fit in memory, we want to iterate the file in a memory-efficient way, as described in Methods of File Objects.

we'll make 2 passes over the file, in the first one we'll just find the index of the latest foo bar, and in the second one we will create output.txt:

latest_foobar_index = 0

with open('input.txt') as f:
    for i, line in enumerate(f):
        if line.startswith('foo bar'):
            latest_foobar_index = i

    f.seek(0) # go back to the start of the file

    with open('output.txt', 'w+') as out:
        for i, line in enumerate(f):
            if i >= latest_foobar_index:
                out.write('//')
            out.write(line)


问:
How Deserialize JSON Api result
I take thi result by Api. I don't realize which class need to cofigurate to dessirialize this.

```<code>"{
  \"errors\":{\"Email\": [\"This field should be filled in\"],
            \"Password\": [\"This field should be filled in\"]},
  \"title\":\"One or more validation errors occurred.\",
  \"status\":400,
  \"traceId\":\"8000006c-0002-fe00-b63f-84710c7967bb\"
}"
</code>```

i write this classes to deserialize

```<code>public class Content
{
    public List<Error> Errors { get; set; }
    public string Tutle { get; set; }
    public int Status { get; set; }
    public string TraceId { get; set; }
}

public class Error
{
    public string Email { get; set; }
    public string Password { get; set; }
}
</code>```

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[AppStore.WPF.Services.Helpers.Error]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

it was later and later, accually doesn't mean how write the class correctly

答:
You can use JSON.NET.
There is plenty of information here:
https://www.newtonsoft.com/json/help/html/SerializingJSON.htm

You can use a dynamic JObject, or deserialize to a concrete class

Title: How Deserialize JSON Api result

Body:
I take thi result by Api. I don't realize which class need to cofigurate to dessirialize this.

"{
  \"errors\":{\"Email\": [\"This field should be filled in\"],
            \"Password\": [\"This field should be filled in\"]},
  \"title\":\"One or more validation errors occurred.\",
  \"status\":400,
  \"traceId\":\"8000006c-0002-fe00-b63f-84710c7967bb\"
}"

i write this classes to deserialize

public class Content
{
    public List<Error> Errors { get; set; }
    public string Tutle { get; set; }
    public int Status { get; set; }
    public string TraceId { get; set; }
}

public class Error
{
    public string Email { get; set; }
    public string Password { get; set; }
}

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[AppStore.WPF.Services.Helpers.Error]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

it was later and later, accually doesn't mean how write the class correctly


问:
Why is this query slow, where id in (sub select that returns null)
I'm having a hard time understanding why this query is taking more than 1ms.

```<code>EXPLAIN ANALYZE SELECT AVG("adverts"."price")
FROM "adverts" WHERE "adverts"."type" IN ('Businesses::Restaurant')
AND "adverts"."discarded_at" IS NULL AND "adverts"."visible" = true
AND ("adverts"."city_location_id" = 56
     OR "adverts"."city_location_id" IN (SELECT "city_locations"."id"
                                         FROM "city_locations"
                                         WHERE "city_locations"."type" IN ('Arrondissement')
                                        AND "city_locations"."arrondissement_city_id" = 56));

QUERY PLAN

 Aggregate  (cost=6583.49..6583.50 rows=1 width=32) (actual time=21.702..21.702 rows=1 loops=1)
   ->  Seq Scan on adverts  (cost=6.31..6533.88 rows=19842 width=4) (actual time=0.462..21.684 rows=44 loops=1)
         Filter: ((discarded_at IS NULL) AND visible AND ((type)::text = 'Businesses::Restaurant'::text) AND ((city_location_id = 56) OR (hashed SubPlan 1)))
         Rows Removed by Filter: 46217
         SubPlan 1
           ->  Index Scan using index_city_locations_on_arrondissement_city_id on city_locations  (cost=0.29..6.31 rows=1 width=8) (actual time=0.008..0.008 rows=0 loops=1)
                 Index Cond: (arrondissement_city_id = 56)
                 Filter: ((type)::text = 'Arrondissement'::text)
 Planning Time: 0.173 ms
 Execution Time: 21.739 ms
</code>```

The execution time is 21ms

If I execute the sub request I get:

```<code>EXPLAIN ANALYZE SELECT "city_locations"."id" FROM "city_locations" WHERE "city_locations"."type" IN ('Arrondissement') AND "city_locations"."arrondissement_city_id" = 56;
 id
----
(0 rows)

QUERY PLAN

 Index Scan using index_city_locations_on_arrondissement_city_id on city_locations  (cost=0.29..6.31 rows=1 width=8) (actual time=0.028..0.028 rows=0 loops=1)
   Index Cond: (arrondissement_city_id = 56)
   Filter: ((type)::text = 'Arrondissement'::text)
 Planning Time: 0.233 ms
 Execution Time: 0.075 ms
</code>```

execution time is: 0.075ms, super fast and the result is NULL.

When I replace the sub request by its result NULL it is super fast.

```<code>EXPLAIN ANALYZE SELECT AVG("adverts"."price")
FROM "adverts" WHERE "adverts"."type" IN ('Businesses::Restaurant')
AND "adverts"."discarded_at" IS NULL AND "adverts"."visible" = true
AND ("adverts"."city_location_id" = 56
     OR "adverts"."city_location_id" IN (NULL));

QUERY PLAN

 Aggregate  (cost=162.66..162.67 rows=1 width=32) (actual time=0.309..0.310 rows=1 loops=1)
   ->  Bitmap Heap Scan on adverts  (cost=4.72..162.55 rows=42 width=4) (actual time=0.082..0.278 rows=44 loops=1)
         Recheck Cond: (city_location_id = 56)
         Filter: ((discarded_at IS NULL) AND visible AND ((type)::text = 'Businesses::Restaurant'::text))
         Heap Blocks: exact=42
         ->  Bitmap Index Scan on index_adverts_on_city_location_id_and_visible  (cost=0.00..4.71 rows=42 width=0) (actual time=0.043..0.044 rows=44 loops=1)
               Index Cond: ((city_location_id = 56) AND (visible = true))
 Planning Time: 0.395 ms
 Execution Time: 0.412 ms
</code>```

The execution time is 0.412 ms

My question is why is the first request slow when its separate requests are fast?

Do I miss some optimization due to the WHERE IN clause?

答:
What seems to be happening in your scenario, is that the sub-query is being executed once for each row in your parent result set. So multiply the run-time of the sub-query by the number of records in your parent result set.

A way to re-write this query to speed it up would be to use a WITH clause at the start of your query:

```<code>WITH cities AS (
    SELECT "city_locations"."id" AS id
    FROM "city_locations"
    WHERE "city_locations"."type" IN ('Arrondissement')
        AND "city_locations"."arrondissement_city_id" = 56
)
SELECT AVG("adverts"."price")
FROM "adverts"
WHERE "adverts"."type" IN ('Businesses::Restaurant')
    AND "adverts"."discarded_at" IS NULL AND "adverts"."visible" = true
    AND ("adverts"."city_location_id" = 56
    OR "adverts"."city_location_id" IN (SELECT id FROM cities));
</code>```

This may speed it up some in the case of no records or very few, but it is still executing a SELECT for each record. This just cuts down on accessing and filtering the city_locations table directly.

Body:
I'm having a hard time understanding why this query is taking more than 1ms.

EXPLAIN ANALYZE SELECT AVG("adverts"."price")
FROM "adverts" WHERE "adverts"."type" IN ('Businesses::Restaurant')
AND "adverts"."discarded_at" IS NULL AND "adverts"."visible" = true
AND ("adverts"."city_location_id" = 56
     OR "adverts"."city_location_id" IN (SELECT "city_locations"."id"
                                         FROM "city_locations"
                                         WHERE "city_locations"."type" IN ('Arrondissement')
                                        AND "city_locations"."arrondissement_city_id" = 56));

QUERY PLAN

 Aggregate  (cost=6583.49..6583.50 rows=1 width=32) (actual time=21.702..21.702 rows=1 loops=1)
   ->  Seq Scan on adverts  (cost=6.31..6533.88 rows=19842 width=4) (actual time=0.462..21.684 rows=44 loops=1)
         Filter: ((discarded_at IS NULL) AND visible AND ((type)::text = 'Businesses::Restaurant'::text) AND ((city_location_id = 56) OR (hashed SubPlan 1)))
         Rows Removed by Filter: 46217
         SubPlan 1
           ->  Index Scan using index_city_locations_on_arrondissement_city_id on city_locations  (cost=0.29..6.31 rows=1 width=8) (actual time=0.008..0.008 rows=0 loops=1)
                 Index Cond: (arrondissement_city_id = 56)
                 Filter: ((type)::text = 'Arrondissement'::text)
 Planning Time: 0.173 ms
 Execution Time: 21.739 ms

The execution time is 21ms

If I execute the sub request I get:

EXPLAIN ANALYZE SELECT "city_locations"."id" FROM "city_locations" WHERE "city_locations"."type" IN ('Arrondissement') AND "city_locations"."arrondissement_city_id" = 56;
 id
----
(0 rows)

QUERY PLAN

 Index Scan using index_city_locations_on_arrondissement_city_id on city_locations  (cost=0.29..6.31 rows=1 width=8) (actual time=0.028..0.028 rows=0 loops=1)
   Index Cond: (arrondissement_city_id = 56)
   Filter: ((type)::text = 'Arrondissement'::text)
 Planning Time: 0.233 ms
 Execution Time: 0.075 ms

execution time is: 0.075ms, super fast and the result is NULL.

When I replace the sub request by its result NULL it is super fast.

EXPLAIN ANALYZE SELECT AVG("adverts"."price")
FROM "adverts" WHERE "adverts"."type" IN ('Businesses::Restaurant')
AND "adverts"."discarded_at" IS NULL AND "adverts"."visible" = true
AND ("adverts"."city_location_id" = 56
     OR "adverts"."city_location_id" IN (NULL));

QUERY PLAN

 Aggregate  (cost=162.66..162.67 rows=1 width=32) (actual time=0.309..0.310 rows=1 loops=1)
   ->  Bitmap Heap Scan on adverts  (cost=4.72..162.55 rows=42 width=4) (actual time=0.082..0.278 rows=44 loops=1)
         Recheck Cond: (city_location_id = 56)
         Filter: ((discarded_at IS NULL) AND visible AND ((type)::text = 'Businesses::Restaurant'::text))
         Heap Blocks: exact=42
         ->  Bitmap Index Scan on index_adverts_on_city_location_id_and_visible  (cost=0.00..4.71 rows=42 width=0) (actual time=0.043..0.044 rows=44 loops=1)
               Index Cond: ((city_location_id = 56) AND (visible = true))
 Planning Time: 0.395 ms
 Execution Time: 0.412 ms

The execution time is 0.412 ms

My question is why is the first request slow when its separate requests are fast?

Do I miss some optimization due to the WHERE IN clause?

Body:
What seems to be happening in your scenario, is that the sub-query is being executed once for each row in your parent result set. So multiply the run-time of the sub-query by the number of records in your parent result set.

A way to re-write this query to speed it up would be to use a WITH clause at the start of your query:

WITH cities AS (
    SELECT "city_locations"."id" AS id
    FROM "city_locations"
    WHERE "city_locations"."type" IN ('Arrondissement')
        AND "city_locations"."arrondissement_city_id" = 56
)
SELECT AVG("adverts"."price")
FROM "adverts"
WHERE "adverts"."type" IN ('Businesses::Restaurant')
    AND "adverts"."discarded_at" IS NULL AND "adverts"."visible" = true
    AND ("adverts"."city_location_id" = 56
    OR "adverts"."city_location_id" IN (SELECT id FROM cities));

This may speed it up some in the case of no records or very few, but it is still executing a SELECT for each record. This just cuts down on accessing and filtering the city_locations table directly.


问:
Cucumber feature file does not identify the steps
I have written my firsy cucumber feature file. When I run the feature file as Cucumber Feature, I get below errors

"WARNING: Cucumber-JVM's --format option is deprecated. Please use --plugin instead." - I used "plugin" in my @CucumberOptions of runner class, but still getting the same error

2.It says I do not have any scenario and steps
Feature: Validate Modular GUI pages

Scenario: Validate Login Page # C:/Selenium/RegressionTest/ModularRegression/src/GUI/features/Validate.feature:3
    Given: Modular GUI is opened
    When: Validate the login page
    Then: Login to the Modular

0 Scenarios
0 Steps

I'm not getting snippets for my steps.

I have added following jars to the library
Jars

This is my runner class,
package GUI;

```<code>import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(
        format = {"pretty", "json:target/"},
        features = {"src/GUI/"}
        )
public class GUIRunner {

}
</code>```

This is my feature file,

```<code>Feature: Validate Modular GUI pages

  Scenario: Validate Login Page
    Given: Modular GUI is opened
    When: Validate the login page
    Then: Login to the Modular
</code>```

I would really appreciate if someone can point out what is missing in my code.

Thank you very much

[EDITED]
This is the actual error:

WARNING: Cucumber-JVM's --format option is deprecated. Please use
  --plugin instead. Feature: Validate Modular GUI pages

Scenario: Validate Login Page #
  C:/Selenium/RegressionTest/ModularRegression/src/GUI/features/Validate.feature:3
      Given: Modular GUI is opened
      When: Validate the login page
      Then: Login to the Modular

0 Scenarios 0 Steps 0m0.000s

答:
Replace format with plugin as format option was deprecated from v1.2.0 onwards on 30-October-2014. Example below -

```<code>@RunWith(Cucumber.class)
@CucumberOptions(features = "classpath:features/functional/",
                     glue = {"com.jacksparrow.automation.steps_definitions.functional" },
                   plugin = { "pretty","json:target/cucumber-json/cucumber.json",
                            "junit:target/cucumber-reports/Cucumber.xml", "html:target/cucumber-reports"},
                   tags = { "@BAMS_Submitted_State_Guest_User" },
                   strict = false,
                   dryRun = false,
               monochrome = true)
</code>```

Body:
I have written my firsy cucumber feature file. When I run the feature file as Cucumber Feature, I get below errors

"WARNING: Cucumber-JVM's --format option is deprecated. Please use --plugin instead." - I used "plugin" in my @CucumberOptions of runner class, but still getting the same error

2.It says I do not have any scenario and steps
Feature: Validate Modular GUI pages

Scenario: Validate Login Page # C:/Selenium/RegressionTest/ModularRegression/src/GUI/features/Validate.feature:3
    Given: Modular GUI is opened
    When: Validate the login page
    Then: Login to the Modular

0 Scenarios
0 Steps

I'm not getting snippets for my steps.

I have added following jars to the library
Jars

This is my runner class,
package GUI;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(
        format = {"pretty", "json:target/"},
        features = {"src/GUI/"}
        )
public class GUIRunner {

}

This is my feature file,

Feature: Validate Modular GUI pages

  Scenario: Validate Login Page
    Given: Modular GUI is opened
    When: Validate the login page
    Then: Login to the Modular

I would really appreciate if someone can point out what is missing in my code.

Thank you very much

[EDITED]
This is the actual error:

WARNING: Cucumber-JVM's --format option is deprecated. Please use
  --plugin instead. Feature: Validate Modular GUI pages

Scenario: Validate Login Page #
  C:/Selenium/RegressionTest/ModularRegression/src/GUI/features/Validate.feature:3
      Given: Modular GUI is opened
      When: Validate the login page
      Then: Login to the Modular

0 Scenarios 0 Steps 0m0.000s

Body:
Replace format with plugin as format option was deprecated from v1.2.0 onwards on 30-October-2014. Example below -

@RunWith(Cucumber.class)
@CucumberOptions(features = "classpath:features/functional/",
                     glue = {"com.jacksparrow.automation.steps_definitions.functional" },
                   plugin = { "pretty","json:target/cucumber-json/cucumber.json",
                            "junit:target/cucumber-reports/Cucumber.xml", "html:target/cucumber-reports"},
                   tags = { "@BAMS_Submitted_State_Guest_User" },
                   strict = false,
                   dryRun = false,
               monochrome = true)


问:
Verify Mock calls in a particular test
In one of my Unit tests, I am trying to verify if one of my mock methods was never called. And the issue is that this mock is a global @beforeClass mock common for a lot of other tests.

So, when I try to verify if the mock is never called or not, it always fails, as other tests are calling that mock. Is there a way using Mockito to verify the mock invocation only for that test ?

One solution I can think of is converting my common mock from @BeforeClass to @Before (so that before each test, the mock is is re-created). But wanted to check if there are any other solutions without touching the common BeforeClass mocks.

@BeforeClass
  public void before() {
    someClassMock = mock(someClass.class);
    when(someClassMock.aMethodCall(any()).thenReturn(true);
  }

// Bunch of tests

  @Test
  public void oneOfTheManytest(){
  //some code where someClassMock.aMethodCall is NOT called

    verify(someClassMock, never()).aMethodCall(any());
    // ^^ This always fails, even when I am sure this mock
    // is not called for this test.
    // I think this looks if this mock is called or not overall for this test file.

  }

```

Can someone help with a solution where I can verify mock method invocation for a specific test ?

答:
I can infer here that your tests don't follow AAA. Each test should be runnable individually and it's success shouldn't depend on the execution of other tests.

Your best bet would be to extract the mock setup you need to repeat into a helper method, and call it within the arrange section of your test.

Title: Verify Mock calls in a particular test

Body:
In one of my Unit tests, I am trying to verify if one of my mock methods was never called. And the issue is that this mock is a global @beforeClass mock common for a lot of other tests.

So, when I try to verify if the mock is never called or not, it always fails, as other tests are calling that mock. Is there a way using Mockito to verify the mock invocation only for that test ?

One solution I can think of is converting my common mock from @BeforeClass to @Before (so that before each test, the mock is is re-created). But wanted to check if there are any other solutions without touching the common BeforeClass mocks.

@BeforeClass
  public void before() {
    someClassMock = mock(someClass.class);
    when(someClassMock.aMethodCall(any()).thenReturn(true);
  }

// Bunch of tests

  @Test
  public void oneOfTheManytest(){
  //some code where someClassMock.aMethodCall is NOT called

    verify(someClassMock, never()).aMethodCall(any());
    // ^^ This always fails, even when I am sure this mock
    // is not called for this test.
    // I think this looks if this mock is called or not overall for this test file.

  }

Can someone help with a solution where I can verify mock method invocation for a specific test ?


问:
Get key value from string using Powershell
I am trying to get key value using Regex in powershell.

```<code>$string = "key1:value1,key2:value2,key3:value3"
$name = [Regex]::Matches($string, ':([^/]+),') | Select -ExpandProperty Value
Write-Host "Name :" $name
</code>```

I want output like this :

```<code>$key1 = "value1"
$key2 = "value2"
$key3 = "value3"
</code>```

Output i am getting :

```<code>Name : :value1,key2:value2,
</code>```

答:
If you are using the comma to separate the key:value pairs this should accomplish what you are after.

```<code>$string = "key1:value1,key2:value2,key3:value3"
$ht = @{} # declare empty hashtable
$string -split ',' | % { $s = $_ -split ':'; $ht += @{$s[0] =  $s[1]}}
# split the string by ',', then split each new string on ':' and map them to the hashtable
</code>```

Outputs the following (note by default they are not ordered)

```<code>PS C:\> $ht

Name                           Value
----                           -----
key3                           value3
key1                           value1
key2                           value2
</code>```

Body:
I am trying to get key value using Regex in powershell.

$string = "key1:value1,key2:value2,key3:value3"
$name = [Regex]::Matches($string, ':([^/]+),') | Select -ExpandProperty Value
Write-Host "Name :" $name

I want output like this :

$key1 = "value1"
$key2 = "value2"
$key3 = "value3"

Output i am getting :

Name : :value1,key2:value2,

Body:
If you are using the comma to separate the key:value pairs this should accomplish what you are after.

$string = "key1:value1,key2:value2,key3:value3"
$ht = @{} # declare empty hashtable
$string -split ',' | % { $s = $_ -split ':'; $ht += @{$s[0] =  $s[1]}}
# split the string by ',', then split each new string on ':' and map them to the hashtable

Outputs the following (note by default they are not ordered)

PS C:\> $ht

Name                           Value
----                           -----
key3                           value3
key1                           value1
key2                           value2


问:
Deleting conflicting record for composite key before update statement
I have a table which has composite key on type, entityId, userid. Now i want to alter table record for some reason. Issue with updating record that update statement gives error like duplicate key.

For example my query is like —

```<code>UPDATE iap SET type = 'tour', entityId = 3 WHERE type = 'bundle' AND
entityId = 2
</code>```

But with update statement it look out for exiting record where already that user has tour and entityID is same which we wants to update.
Now in that case i want to delete that record with type bundle as i want all bundle with id 2 become tour with id 3.
So if tour with id 3 exist then simply i want to delete bundle with id 2 and no need to update.

Any possible query around, please?

答:
Try this.

```<code>CREATE TEMPORARY TABLE IF NOT EXISTS tmp_iap AS (SELECT id, user_id, type, entityId FROM iap where type='tour' AND
entityId = 3);

DELETE from iap where type='bundle' AND entityId = 2 AND EXISTS (SELECT 1 FROM tmp_iap Where tmp_iap.user_id = iap.user_id)
</code>```

Please take a backup first if there is any important data.

Body:
I have a table which has composite key on type, entityId, userid. Now i want to alter table record for some reason. Issue with updating record that update statement gives error like duplicate key.

For example my query is like —

UPDATE iap SET type = 'tour', entityId = 3 WHERE type = 'bundle' AND
entityId = 2

But with update statement it look out for exiting record where already that user has tour and entityID is same which we wants to update.
Now in that case i want to delete that record with type bundle as i want all bundle with id 2 become tour with id 3.
So if tour with id 3 exist then simply i want to delete bundle with id 2 and no need to update.

Any possible query around, please?

Body:
Try this.

CREATE TEMPORARY TABLE IF NOT EXISTS tmp_iap AS (SELECT id, user_id, type, entityId FROM iap where type='tour' AND
entityId = 3);

DELETE from iap where type='bundle' AND entityId = 2 AND EXISTS (SELECT 1 FROM tmp_iap Where tmp_iap.user_id = iap.user_id)

Please take a backup first if there is any important data.


问:
SSRS get previous total
I am working on SSRS 2008. A simple tablix with one row group (product) and one column group (month), at the intersection of row and column is the data (number of sales). Now I add a total row, which equals to sum(number of sales) for each month. Also I add a total column, which equals to sum(number of sales) for each product. At the intersection of the total row/column, the value is the grand total sum of number of sales for all products and all months. Now I want to change this to total of all products but for all months except the last month. E.g. there are product 1, 2, 3 and month 1, 2, 3. I want total of sales for product 1,2, 3 and month 1,2 in that cell. How to do that? Something like this pic, in the lower right corner, there should be 6 (for Feb and Jan).

----------update, added script to create this report, so maybe someone can try it.

The dataset:

```<code>    select 'Jan'  as mon, 'p1' as prod, 1 as id
    union all
    select 'Feb'  as mon, 'p1' as prod, 1
    union all
    select 'Mar'  as mon, 'p1' as prod, 1

    union all
    select 'Jan'  as mon, 'p2' as prod, 1
    union all
    select 'Feb'  as mon, 'p2' as prod, 1
    union all
    select 'Mar'  as mon, 'p2' as prod, 1

    union all
    select 'Jan'  as mon, 'p3' as prod, 1
    union all
    select 'Feb'  as mon, 'p3' as prod, 1
    union all
    select 'Mar'  as mon, 'p3' as prod, 1
</code>```

The report definition:

There is one row group (group on prod), one column group (group on mon).
Actually, I can do that in T-SQL by calculating total without last month then join this back to the main dataset. But just wondering is it achievable by SSRS alone.

答:
Try with this:

```<code>RunningValue(Fields!totalField.Value,Sum,"DataSourceName")
</code>```

You can modify the aggregator (by using for example Count instead of Sum) and, if you wanted to reset the value within each iteration, you can change the DataSourceName by the word Nothing

Title: SSRS get previous total

Body:
I am working on SSRS 2008. A simple tablix with one row group (product) and one column group (month), at the intersection of row and column is the data (number of sales). Now I add a total row, which equals to sum(number of sales) for each month. Also I add a total column, which equals to sum(number of sales) for each product. At the intersection of the total row/column, the value is the grand total sum of number of sales for all products and all months. Now I want to change this to total of all products but for all months except the last month. E.g. there are product 1, 2, 3 and month 1, 2, 3. I want total of sales for product 1,2, 3 and month 1,2 in that cell. How to do that? Something like this pic, in the lower right corner, there should be 6 (for Feb and Jan).

----------update, added script to create this report, so maybe someone can try it.

The dataset:

    select 'Jan'  as mon, 'p1' as prod, 1 as id
    union all
    select 'Feb'  as mon, 'p1' as prod, 1
    union all
    select 'Mar'  as mon, 'p1' as prod, 1

    union all
    select 'Jan'  as mon, 'p2' as prod, 1
    union all
    select 'Feb'  as mon, 'p2' as prod, 1
    union all
    select 'Mar'  as mon, 'p2' as prod, 1

    union all
    select 'Jan'  as mon, 'p3' as prod, 1
    union all
    select 'Feb'  as mon, 'p3' as prod, 1
    union all
    select 'Mar'  as mon, 'p3' as prod, 1

The report definition:

There is one row group (group on prod), one column group (group on mon).
Actually, I can do that in T-SQL by calculating total without last month then join this back to the main dataset. But just wondering is it achievable by SSRS alone.

Body:
Try with this:

RunningValue(Fields!totalField.Value,Sum,"DataSourceName")

You can modify the aggregator (by using for example Count instead of Sum) and, if you wanted to reset the value within each iteration, you can change the DataSourceName by the word Nothing


问:
"the request was rejected because its size " Spring, tomcat
I'm trying to make a simple upload app with springboot and it works fine until i try to upload 10Mb+ files, i receive this message on my screen:

```<code>There was an unexpected error (type=Internal Server Error, status=500).
Could not parse multipart servlet request; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (14326061) exceeds the configured maximum (10485760)
</code>```

I've done some research, and nothing have worked until now. I'll leave here below the things i've tried so far.

put this code(In various ways) in my "application.yml"

```<code>multipart:
 maxFileSize: 51200KB
 maxRequestFile: 51200KB
</code>```

I've also tried this in my principal class:

```<code>    @Bean
public TomcatEmbeddedServletContainerFactory containerFactory() {
    TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
     factory.addConnectorCustomizers(new TomcatConnectorCustomizer() {
        @Override
        public void customize(Connector connector) {
         ((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
        }
     });
     return factory;
}
</code>```

And some strange thing. If i enter in my tomcat web.xml, the multipart-config is:

```<code><multipart-config>
      <!-- 50MB max -->
      <max-file-size>52428800</max-file-size>
      <max-request-size>52428800</max-request-size>
      <file-size-threshold>0</file-size-threshold>
    </multipart-config>
</code>```

So where the hell this "...configured maximum (10485760)" is coming from ?
(Sidenote: I'm using netbeans 8.1 and springboot 1.5).

Thx guys.(And sorry for the english s2)

Since asked, this is my application.yml

```<code> server:
      port: 9999
      context-path: /client
    logging:
      level:
        org.springframework.security: DEBUG
    endpoints:
      trace:
        sensitive: false

    spring:
        thymeleaf:
            cache: false
        multipart:
          maxFileSize: 51200KB
          maxRequestFile: 51200KB

    #################################################################################

    security:
      basic:
        enabled: false
      oauth2:
        client:
          client-id: acme2
          client-secret: acmesecret2
          access-token-uri: http://localhost:8080/oauth/token
          user-authorization-uri: http://localhost:8080/oauth/authorize
        resource:
          user-info-uri: http://localhost:8080/me
    #
</code>```

答:
For SpringBoot 1.5.7 till 2.1.2 the property need to set in application.properties file are:

```<code>spring.http.multipart.max-file-size=100MB
spring.http.multipart.max-request-size=100MB
</code>```

Also make sure you have application.properties file in "resources" folder.

Body:
I'm trying to make a simple upload app with springboot and it works fine until i try to upload 10Mb+ files, i receive this message on my screen:

There was an unexpected error (type=Internal Server Error, status=500).
Could not parse multipart servlet request; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (14326061) exceeds the configured maximum (10485760)

I've done some research, and nothing have worked until now. I'll leave here below the things i've tried so far.

put this code(In various ways) in my "application.yml"

multipart:
 maxFileSize: 51200KB
 maxRequestFile: 51200KB

I've also tried this in my principal class:

    @Bean
public TomcatEmbeddedServletContainerFactory containerFactory() {
    TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
     factory.addConnectorCustomizers(new TomcatConnectorCustomizer() {
        @Override
        public void customize(Connector connector) {
         ((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
        }
     });
     return factory;
}

And some strange thing. If i enter in my tomcat web.xml, the multipart-config is:

<multipart-config>

      <max-file-size>52428800</max-file-size>
      <max-request-size>52428800</max-request-size>
      <file-size-threshold>0</file-size-threshold>
    </multipart-config>

So where the hell this "...configured maximum (10485760)" is coming from ?
(Sidenote: I'm using netbeans 8.1 and springboot 1.5).

Thx guys.(And sorry for the english s2)

Since asked, this is my application.yml

 server:
      port: 9999
      context-path: /client
    logging:
      level:
        org.springframework.security: DEBUG
    endpoints:
      trace:
        sensitive: false

    spring:
        thymeleaf:
            cache: false
        multipart:
          maxFileSize: 51200KB
          maxRequestFile: 51200KB

    #################################################################################

    security:
      basic:
        enabled: false
      oauth2:
        client:
          client-id: acme2
          client-secret: acmesecret2
          access-token-uri: http://localhost:8080/oauth/token
          user-authorization-uri: http://localhost:8080/oauth/authorize
        resource:
          user-info-uri: http://localhost:8080/me
    #

Body:
For SpringBoot 1.5.7 till 2.1.2 the property need to set in application.properties file are:

spring.http.multipart.max-file-size=100MB
spring.http.multipart.max-request-size=100MB

Also make sure you have application.properties file in "resources" folder.


问:
Initialize array whose size is a compile-time constant to single value
I have a c-style array whose size is defined by a #define and can change based on compiling options, e.g.

```<code>#if LINUX
# define SIZE 4
#else
# define SIZE 5
#endif
static int myArr[SIZE] = { /* ??? */ };
</code>```

How can I initialize the whole array to a non-zero value, for example all 42?

答:
If you insist on builtin arrays, you can use static variables in functions:

```<code>template <std::size_t N, std::size_t... Is>
auto arr_helper2(std::index_sequence<Is...>) -> int (&)[N]
{
    static int arr[N] = {((void)Is, 42)...};
    return arr;
}

template <std::size_t N>
auto arr_helper() -> int (&)[N]
{
    return arr_helper2<N>(std::make_index_sequence<N>{});
}

static int (&arr)[SIZE] = arr_helper<SIZE>();
</code>```

For example:

```<code>int main()
{
    for (std::size_t i = 0; i < SIZE; ++i)
        std::cout << arr[i] << " ";
}
</code>```

live demo

Body:
I have a c-style array whose size is defined by a #define and can change based on compiling options, e.g.

#if LINUX
# define SIZE 4
#else
# define SIZE 5
#endif
static int myArr[SIZE] = { /* ??? */ };

How can I initialize the whole array to a non-zero value, for example all 42?

Body:
If you insist on builtin arrays, you can use static variables in functions:

template <std::size_t N, std::size_t... Is>
auto arr_helper2(std::index_sequence<Is...>) -> int (&)[N]
{
    static int arr[N] = {((void)Is, 42)...};
    return arr;
}

template <std::size_t N>
auto arr_helper() -> int (&)[N]
{
    return arr_helper2<N>(std::make_index_sequence<N>{});
}

static int (&arr)[SIZE] = arr_helper<SIZE>();

For example:

int main()
{
    for (std::size_t i = 0; i < SIZE; ++i)
        std::cout << arr[i] << " ";
}

live demo


问:
upgrade to angular 8 from 7 errors with incompatible peer dependency
ng update @angular/cli @angular/core . -  Getting the below error when upgrading from 7 to 8, following the guide from https://update.angular.io/#7.0:8.0</p>

```<code>> "@angular/core" (requires "^6.0.0" (extended), would install "8.0.0").```

Incompatible peer dependencies found. See above.

package.json has the below versions

"dependencies": {
    "@angular/animations": "^7.0.4",
    "@angular/common": "^7.0.3",
    "@angular/compiler": "^7.0.3",
    "@angular/core": "^7.0.3",
    "@angular/forms": "^7.0.3",
    "@angular/http": "^7.0.3",
    .....
    ````

</code>```

答:
As the error message indicates the problem is that your version of @ngrx/store is not compatible with Angular 8 yet. Currently there are only 3 beta releases of @ngrx/store that supports Angular 8:

```<code>8.0.0-beta.0
8.0.0-beta.1
8.0.0-beta.2
</code>```

The latest (8.0.0-beta.2) was published to NPM 15 days ago (15-05-2018). To install it run

```<code>npm install @ngrx/store@8.0.0-beta.2
</code>```

Body:
ng update @angular/cli @angular/core . -  Getting the below error when upgrading from 7 to 8, following the guide from https://update.angular.io/#7.0:8.0

> "@angular/core" (requires "^6.0.0" (extended), would install "8.0.0").```

Incompatible peer dependencies found. See above.

package.json has the below versions

"dependencies": {
    "@angular/animations": "^7.0.4",
    "@angular/common": "^7.0.3",
    "@angular/compiler": "^7.0.3",
    "@angular/core": "^7.0.3",
    "@angular/forms": "^7.0.3",
    "@angular/http": "^7.0.3",
    .....
    ````

Body:
As the error message indicates the problem is that your version of @ngrx/store is not compatible with Angular 8 yet. Currently there are only 3 beta releases of @ngrx/store that supports Angular 8:

8.0.0-beta.0
8.0.0-beta.1
8.0.0-beta.2

The latest (8.0.0-beta.2) was published to NPM 15 days ago (15-05-2018). To install it run

npm install @ngrx/store@8.0.0-beta.2


问:
Solve coupled differential equation using the function scipy.integrate.RK45
```<code>x' = f(x,y,t)
y' = g(x,y,t)
</code>```

Initial conditions have been given as x0 and y0 with t0. Find the solution graph in the range t0 to a.

I have tried doing this for non-coupled equations but there seems to be a problem there as well. I have to solve this exactly using this function so other functions are not the options.

```<code>from numpy import *
from matplotlib import pyplot as plt
def f(t,x):
    return -x
import scipy
from scipy import integrate as inte

solution = inte.RK45(f, 0 , [1] , 10 ,1, 0.001, e**-6)
print (solution)
</code>```

I expect the output to be an array of all the values.

But <scipy.integrate._ivp.rk.RK45 at 0x1988ba806d8> is what I get.

Body:
x' = f(x,y,t)
y' = g(x,y,t)

Initial conditions have been given as x0 and y0 with t0. Find the solution graph in the range t0 to a.

I have tried doing this for non-coupled equations but there seems to be a problem there as well. I have to solve this exactly using this function so other functions are not the options.

from numpy import *
from matplotlib import pyplot as plt
def f(t,x):
    return -x
import scipy
from scipy import integrate as inte

solution = inte.RK45(f, 0 , [1] , 10 ,1, 0.001, e**-6)
print (solution)

I expect the output to be an array of all the values.

But <scipy.integrate._ivp.rk.RK45 at 0x1988ba806d8> is what I get.

Body:
You need to collect data with calling step() function:

from math import e
from scipy import integrate as inte

def f(t,x):
    return -x

solution = inte.RK45(f, 0 , [1] , 10 ,1, 0.001, e**-6)

# collect data
t_values = []
y_values = []
for i in range(100):
    # get solution step state
    solution.step()
    t_values.append(solution.t)
    y_values.append(solution.y[0])
    # break loop after modeling is finished
    if solution.status == 'finished':
        break

data = zip(t_values, y_values)

Output:

(0.12831714796342164, 0.879574381033538)
(1.1283171479634215, 0.3239765636806864)
(2.1283171479634215, 0.11933136762238628)
(3.1283171479634215, 0.043953720407578944)
(4.128317147963422, 0.01618962035012491)
(5.128317147963422, 0.005963176828962677)
(6.128317147963422, 0.002196436798667919)
(7.128317147963422, 0.0008090208875093502)
(8.128317147963422, 0.00029798936023261037)
(9.128317147963422, 0.0001097594143523445)
(10, 4.5927433621121034e-05)


问:
Json to Dataframe: error: error in 1:nrow(test) : argument of length 0
I'm trying to convert my complicated JSON file with 150.000 observations to a dataframe. Someone generously helped me constructing the code, but I keep running into the same error: Error in 1:nrow(test) : argument of length 0. I've searched the topic on the community but none of the answers provided work in my case. Any tips are welcome!

These two lines give the error:

```<code>valid<-which(sapply(1:nrow(test),  function(j) {length(test[[1]][[j]])}) >0)
NullResponses<-which(sapply(1:nrow(test),  function(j) {length(test[[1]][[j]])}) == 0)
</code>```

Structure of json:

This is the whole code:

```<code>#test<- result from converting the JSON response.
#vector of reviewid, used to make the initial request to the API
reviewid<-c(98338143, 58929813, 65945346)

#find only the responses that are not Null or blank
valid<-which(sapply(1:nrow(test),  function(j) {length(test[[1]][[j]])}) >0)
NullResponses<-which(sapply(1:nrow(test),  function(j) {length(test[[1]][[j]])}) == 0)

#create a list of data frames with the data from row of the response
dflist<-lapply( valid, function(j) {
  temp<-t(as.matrix(unlist(test[j,])))
  df<-data.frame(reviewid=reviewid[j], temp, stringsAsFactors = FALSE)
  df
})

#bind the rows together.
answer<-bind_rows(dflist)
</code>```

Json:

```<code> [{},
    {"daily":
       [{"time":"2010-03-18",
       "summary":"Partly cloudy throughout the day.",
       "icon":"partly-cloudy-day",
       "sunriseTime":"2010-03-18 07:22:51",
       "sunsetTime":"2010-03-18 19:25:28",
       "moonPhase":0.08,
       "precipIntensity":0,
       "precipIntensityMax":0,
       "precipProbability":0,
       "temperatureHigh":63.14,
       "temperatureHighTime":1268928000,
       "temperatureLow":45.16,
       "temperatureLowTime":1268971200,
       "apparentTemperatureHigh":63.14,
       "apparentTemperatureHighTime":1268928000,
       "apparentTemperatureLow":45.16,
       "apparentTemperatureLowTime":1268971200,
       "dewPoint":36.97,
       "humidity":0.58,
       "pressure":1025.96,
       "windSpeed":1.24,
       "windGust":7.87,
       "windGustTime":1268866800,
       "windBearing":48,
       "cloudCover":0.54,
       "uvIndex":5,
       "uvIndexTime":1268913600,
       "visibility":6.19,
       "temperatureMin":43.97,
       "temperatureMinTime":"2010-03-18 07:00:00",
       "temperatureMax":63.14,
       "temperatureMaxTime":"2010-03-18 17:00:00",
       "apparentTemperatureMin":42.03,
       "apparentTemperatureMinTime":"2010-03-18 08:00:00",
       "apparentTemperatureMax":63.14,
       "apparentTemperatureMaxTime":"2010-03-18 17:00:00"}]},

    {"daily":
       [{"time":"2010-05-30 01:00:00",
       "summary":"Mostly cloudy until evening.",
       "icon":"partly-cloudy-day",
       "sunriseTime":"2010-05-30 05:38:39",
       "sunsetTime":"2010-05-30 22:44:55",
       "moonPhase":0.58,
       "precipIntensity":0.0038,
       "precipIntensityMax":0.0766,
       "precipIntensityMaxTime”:"2010-05-30 04:00:00",
       "precipProbability":1,
       "precipType":"rain",
       "temperatureHigh":58.99,
       "temperatureHighTime":1275242400,
       "temperatureLow":36.62,
       "temperatureLowTime":1275278400,
       "apparentTemperatureHigh":58.99,
       "apparentTemperatureHighTime":1275242400,
       "apparentTemperatureLow":36.62,
       "apparentTemperatureLowTime":1275278400,
       "dewPoint":43.61,
       "humidity":0.76,
       "pressure":1011.52,
       "windSpeed":4.65,
       "windGust":21.4,
       "windGustTime":1275224400,
       "windBearing":350,
       "cloudCover":0.61,
       "uvIndex":5,
       "uvIndexTime":1275213600,
       "visibility":5.85,
       "temperatureMin":45.99,
       "temperatureMinTime":"2010-05-30 07:00:00",
       "temperatureMax":58.99,
       "temperatureMaxTime":"2010-05-30 20:00:00",
       "apparentTemperatureMin":43.31,
       "apparentTemperatureMinTime":"2010-05-30 06:00:00",
       "apparentTemperatureMax":58.99,
       "apparentTemperatureMaxTime":"2010-05-30 20:00:00"}]}]
</code>```

答:
That's because the converted json is a list of lists, which won't work with the nrow() funcition. Can you try this code instead and check if the result is what you expect?

```<code>valid         <- which(sapply(1:NROW(test),  function(j) {length(test[[j]])}) > 0)
NullResponses <- which(sapply(1:NROW(test),  function(j) {length(test[[j]])}) == 0)

dflist <- lapply(valid, function(j) {
  temp <- t(as.matrix(unlist(test[j])))
  df   <- data.frame(reviewid = reviewid[j], temp, stringsAsFactors = FALSE)
  df
})

answer <- bind_rows(dflist)
</code>```

Body:
I'm trying to convert my complicated JSON file with 150.000 observations to a dataframe. Someone generously helped me constructing the code, but I keep running into the same error: Error in 1:nrow(test) : argument of length 0. I've searched the topic on the community but none of the answers provided work in my case. Any tips are welcome!

These two lines give the error:

valid<-which(sapply(1:nrow(test),  function(j) {length(test[[1]][[j]])}) >0)
NullResponses<-which(sapply(1:nrow(test),  function(j) {length(test[[1]][[j]])}) == 0)

Structure of json:

This is the whole code:

#test<- result from converting the JSON response.
#vector of reviewid, used to make the initial request to the API
reviewid<-c(98338143, 58929813, 65945346)

#find only the responses that are not Null or blank
valid<-which(sapply(1:nrow(test),  function(j) {length(test[[1]][[j]])}) >0)
NullResponses<-which(sapply(1:nrow(test),  function(j) {length(test[[1]][[j]])}) == 0)

#create a list of data frames with the data from row of the response
dflist<-lapply( valid, function(j) {
  temp<-t(as.matrix(unlist(test[j,])))
  df<-data.frame(reviewid=reviewid[j], temp, stringsAsFactors = FALSE)
  df
})

#bind the rows together.
answer<-bind_rows(dflist)

Json:

 [{},
    {"daily":
       [{"time":"2010-03-18",
       "summary":"Partly cloudy throughout the day.",
       "icon":"partly-cloudy-day",
       "sunriseTime":"2010-03-18 07:22:51",
       "sunsetTime":"2010-03-18 19:25:28",
       "moonPhase":0.08,
       "precipIntensity":0,
       "precipIntensityMax":0,
       "precipProbability":0,
       "temperatureHigh":63.14,
       "temperatureHighTime":1268928000,
       "temperatureLow":45.16,
       "temperatureLowTime":1268971200,
       "apparentTemperatureHigh":63.14,
       "apparentTemperatureHighTime":1268928000,
       "apparentTemperatureLow":45.16,
       "apparentTemperatureLowTime":1268971200,
       "dewPoint":36.97,
       "humidity":0.58,
       "pressure":1025.96,
       "windSpeed":1.24,
       "windGust":7.87,
       "windGustTime":1268866800,
       "windBearing":48,
       "cloudCover":0.54,
       "uvIndex":5,
       "uvIndexTime":1268913600,
       "visibility":6.19,
       "temperatureMin":43.97,
       "temperatureMinTime":"2010-03-18 07:00:00",
       "temperatureMax":63.14,
       "temperatureMaxTime":"2010-03-18 17:00:00",
       "apparentTemperatureMin":42.03,
       "apparentTemperatureMinTime":"2010-03-18 08:00:00",
       "apparentTemperatureMax":63.14,
       "apparentTemperatureMaxTime":"2010-03-18 17:00:00"}]},

    {"daily":
       [{"time":"2010-05-30 01:00:00",
       "summary":"Mostly cloudy until evening.",
       "icon":"partly-cloudy-day",
       "sunriseTime":"2010-05-30 05:38:39",
       "sunsetTime":"2010-05-30 22:44:55",
       "moonPhase":0.58,
       "precipIntensity":0.0038,
       "precipIntensityMax":0.0766,
       "precipIntensityMaxTime”:"2010-05-30 04:00:00",
       "precipProbability":1,
       "precipType":"rain",
       "temperatureHigh":58.99,
       "temperatureHighTime":1275242400,
       "temperatureLow":36.62,
       "temperatureLowTime":1275278400,
       "apparentTemperatureHigh":58.99,
       "apparentTemperatureHighTime":1275242400,
       "apparentTemperatureLow":36.62,
       "apparentTemperatureLowTime":1275278400,
       "dewPoint":43.61,
       "humidity":0.76,
       "pressure":1011.52,
       "windSpeed":4.65,
       "windGust":21.4,
       "windGustTime":1275224400,
       "windBearing":350,
       "cloudCover":0.61,
       "uvIndex":5,
       "uvIndexTime":1275213600,
       "visibility":5.85,
       "temperatureMin":45.99,
       "temperatureMinTime":"2010-05-30 07:00:00",
       "temperatureMax":58.99,
       "temperatureMaxTime":"2010-05-30 20:00:00",
       "apparentTemperatureMin":43.31,
       "apparentTemperatureMinTime":"2010-05-30 06:00:00",
       "apparentTemperatureMax":58.99,
       "apparentTemperatureMaxTime":"2010-05-30 20:00:00"}]}]

Body:
That's because the converted json is a list of lists, which won't work with the nrow() funcition. Can you try this code instead and check if the result is what you expect?

valid         <- which(sapply(1:NROW(test),  function(j) {length(test[[j]])}) > 0)
NullResponses <- which(sapply(1:NROW(test),  function(j) {length(test[[j]])}) == 0)

dflist <- lapply(valid, function(j) {
  temp <- t(as.matrix(unlist(test[j])))
  df   <- data.frame(reviewid = reviewid[j], temp, stringsAsFactors = FALSE)
  df
})

answer <- bind_rows(dflist)


问:
How non static method working statically on localhost
I made a class and in that class made a public method. now am calling that method as static method and its working fine. How?

if I upload this code on PHP fiddle its giving error which I was expecting. But why it's not giving error on localhost

```<code> class A
    {
        public function b()
        {
            echo "i am b";
        }
    }
    print_r(A::b());
</code>```

答:
Statical call of a non-statical method is deprecated since 5.6 version of PHP. It means if you call a non-statical method like statical you get an error of E_DEPRECATED level.
If you don't see this error you should reconfigure error reporting and enable display errors.
For example:</p>

```<code>ini_set('display_errors', 1);
error_reporting(E_ALL);
</code>```

Body:
I made a class and in that class made a public method. now am calling that method as static method and its working fine. How?

if I upload this code on PHP fiddle its giving error which I was expecting. But why it's not giving error on localhost

 class A
    {
        public function b()
        {
            echo "i am b";
        }
    }
    print_r(A::b());

Body:
Statical call of a non-statical method is deprecated since 5.6 version of PHP. It means if you call a non-statical method like statical you get an error of E_DEPRECATED level.
If you don't see this error you should reconfigure error reporting and enable display errors.
For example:

ini_set('display_errors', 1);
error_reporting(E_ALL);


问:
Sample project throwing NoClassDefFoundError: com/fasterxml/jackson/databind/ObjectMapper
I have implemented the project as per https://spring.io/guides/gs/batch-processing/

But i am getting :

Error creating bean with name 'batchConfigurer': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/ObjectMapper

I am new to spring-batch
Can anyone please help

答:
The following is working as expected:

```<code>$>git clone https://github.com/spring-guides/gs-batch-processing.git
$>cd gs-batch-processing/complete
$>./mvnw clean install
$>./mvnw spring-boot:run
</code>```

The output is the following:

```<code>  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.4.RELEASE)

2019-05-30 12:23:12.642  INFO 90644 --- [           main] hello.Application                        : Starting Application on localhost with PID 90644 (/private/tmp/gs-batch-processing/complete/target/classes started by mbenhassine in /private/tmp/gs-batch-processing/complete)
2019-05-30 12:23:12.646  INFO 90644 --- [           main] hello.Application                        : No active profile set, falling back to default profiles: default
2019-05-30 12:23:13.333  INFO 90644 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-05-30 12:23:13.338  WARN 90644 --- [           main] com.zaxxer.hikari.util.DriverDataSource  : Registered driver with driverClassName=org.hsqldb.jdbcDriver was not found, trying direct instantiation.
2019-05-30 12:23:13.683  INFO 90644 --- [           main] com.zaxxer.hikari.pool.PoolBase          : HikariPool-1 - Driver does not support get/set network timeout for connections. (feature not supported)
2019-05-30 12:23:13.687  INFO 90644 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2019-05-30 12:23:14.091  INFO 90644 --- [           main] o.s.b.c.r.s.JobRepositoryFactoryBean     : No database type set, using meta data indicating: HSQL
2019-05-30 12:23:14.277  INFO 90644 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : No TaskExecutor has been set, defaulting to synchronous executor.
2019-05-30 12:23:14.437  INFO 90644 --- [           main] hello.Application                        : Started Application in 2.114 seconds (JVM running for 5.2)
2019-05-30 12:23:14.438  INFO 90644 --- [           main] o.s.b.a.b.JobLauncherCommandLineRunner   : Running default command line with: []
2019-05-30 12:23:14.503  INFO 90644 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [FlowJob: [name=importUserJob]] launched with the following parameters: [{run.id=1}]
2019-05-30 12:23:14.530  INFO 90644 --- [           main] o.s.batch.core.job.SimpleStepHandler     : Executing step: [step1]
2019-05-30 12:23:14.590  INFO 90644 --- [           main] hello.PersonItemProcessor                : Converting (firstName: Jill, lastName: Doe) into (firstName: JILL, lastName: DOE)
2019-05-30 12:23:14.590  INFO 90644 --- [           main] hello.PersonItemProcessor                : Converting (firstName: Joe, lastName: Doe) into (firstName: JOE, lastName: DOE)
2019-05-30 12:23:14.590  INFO 90644 --- [           main] hello.PersonItemProcessor                : Converting (firstName: Justin, lastName: Doe) into (firstName: JUSTIN, lastName: DOE)
2019-05-30 12:23:14.590  INFO 90644 --- [           main] hello.PersonItemProcessor                : Converting (firstName: Jane, lastName: Doe) into (firstName: JANE, lastName: DOE)
2019-05-30 12:23:14.590  INFO 90644 --- [           main] hello.PersonItemProcessor                : Converting (firstName: John, lastName: Doe) into (firstName: JOHN, lastName: DOE)
2019-05-30 12:23:14.604  INFO 90644 --- [           main] hello.JobCompletionNotificationListener  : !!! JOB FINISHED! Time to verify the results
2019-05-30 12:23:14.607  INFO 90644 --- [           main] hello.JobCompletionNotificationListener  : Found <firstName: JILL, lastName: DOE> in the database.
2019-05-30 12:23:14.607  INFO 90644 --- [           main] hello.JobCompletionNotificationListener  : Found <firstName: JOE, lastName: DOE> in the database.
2019-05-30 12:23:14.607  INFO 90644 --- [           main] hello.JobCompletionNotificationListener  : Found <firstName: JUSTIN, lastName: DOE> in the database.
2019-05-30 12:23:14.607  INFO 90644 --- [           main] hello.JobCompletionNotificationListener  : Found <firstName: JANE, lastName: DOE> in the database.
2019-05-30 12:23:14.607  INFO 90644 --- [           main] hello.JobCompletionNotificationListener  : Found <firstName: JOHN, lastName: DOE> in the database.
2019-05-30 12:23:14.610  INFO 90644 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [FlowJob: [name=importUserJob]] completed with the following parameters: [{run.id=1}] and the following status: [COMPLETED]
</code>```

As you can see, there is no NoClassDefFoundError.

Body:
The following is working as expected:

$>git clone https://github.com/spring-guides/gs-batch-processing.git
$>cd gs-batch-processing/complete
$>./mvnw clean install
$>./mvnw spring-boot:run

The output is the following:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.4.RELEASE)

2019-05-30 12:23:12.642  INFO 90644 --- [           main] hello.Application                        : Starting Application on localhost with PID 90644 (/private/tmp/gs-batch-processing/complete/target/classes started by mbenhassine in /private/tmp/gs-batch-processing/complete)
2019-05-30 12:23:12.646  INFO 90644 --- [           main] hello.Application                        : No active profile set, falling back to default profiles: default
2019-05-30 12:23:13.333  INFO 90644 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-05-30 12:23:13.338  WARN 90644 --- [           main] com.zaxxer.hikari.util.DriverDataSource  : Registered driver with driverClassName=org.hsqldb.jdbcDriver was not found, trying direct instantiation.
2019-05-30 12:23:13.683  INFO 90644 --- [           main] com.zaxxer.hikari.pool.PoolBase          : HikariPool-1 - Driver does not support get/set network timeout for connections. (feature not supported)
2019-05-30 12:23:13.687  INFO 90644 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2019-05-30 12:23:14.091  INFO 90644 --- [           main] o.s.b.c.r.s.JobRepositoryFactoryBean     : No database type set, using meta data indicating: HSQL
2019-05-30 12:23:14.277  INFO 90644 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : No TaskExecutor has been set, defaulting to synchronous executor.
2019-05-30 12:23:14.437  INFO 90644 --- [           main] hello.Application                        : Started Application in 2.114 seconds (JVM running for 5.2)
2019-05-30 12:23:14.438  INFO 90644 --- [           main] o.s.b.a.b.JobLauncherCommandLineRunner   : Running default command line with: []
2019-05-30 12:23:14.503  INFO 90644 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [FlowJob: [name=importUserJob]] launched with the following parameters: [{run.id=1}]
2019-05-30 12:23:14.530  INFO 90644 --- [           main] o.s.batch.core.job.SimpleStepHandler     : Executing step: [step1]
2019-05-30 12:23:14.590  INFO 90644 --- [           main] hello.PersonItemProcessor                : Converting (firstName: Jill, lastName: Doe) into (firstName: JILL, lastName: DOE)
2019-05-30 12:23:14.590  INFO 90644 --- [           main] hello.PersonItemProcessor                : Converting (firstName: Joe, lastName: Doe) into (firstName: JOE, lastName: DOE)
2019-05-30 12:23:14.590  INFO 90644 --- [           main] hello.PersonItemProcessor                : Converting (firstName: Justin, lastName: Doe) into (firstName: JUSTIN, lastName: DOE)
2019-05-30 12:23:14.590  INFO 90644 --- [           main] hello.PersonItemProcessor                : Converting (firstName: Jane, lastName: Doe) into (firstName: JANE, lastName: DOE)
2019-05-30 12:23:14.590  INFO 90644 --- [           main] hello.PersonItemProcessor                : Converting (firstName: John, lastName: Doe) into (firstName: JOHN, lastName: DOE)
2019-05-30 12:23:14.604  INFO 90644 --- [           main] hello.JobCompletionNotificationListener  : !!! JOB FINISHED! Time to verify the results
2019-05-30 12:23:14.607  INFO 90644 --- [           main] hello.JobCompletionNotificationListener  : Found <firstName: JILL, lastName: DOE> in the database.
2019-05-30 12:23:14.607  INFO 90644 --- [           main] hello.JobCompletionNotificationListener  : Found <firstName: JOE, lastName: DOE> in the database.
2019-05-30 12:23:14.607  INFO 90644 --- [           main] hello.JobCompletionNotificationListener  : Found <firstName: JUSTIN, lastName: DOE> in the database.
2019-05-30 12:23:14.607  INFO 90644 --- [           main] hello.JobCompletionNotificationListener  : Found <firstName: JANE, lastName: DOE> in the database.
2019-05-30 12:23:14.607  INFO 90644 --- [           main] hello.JobCompletionNotificationListener  : Found <firstName: JOHN, lastName: DOE> in the database.
2019-05-30 12:23:14.610  INFO 90644 --- [           main] o.s.b.c.l.support.SimpleJobLauncher      : Job: [FlowJob: [name=importUserJob]] completed with the following parameters: [{run.id=1}] and the following status: [COMPLETED]

As you can see, there is no NoClassDefFoundError.


答:
Think you might be assuming that the query inside the IN is definitely executed first, as though it were standalone, and then the result fed into the outer, at which point "it should realize that it's null and wont produce any result, so quit early" - so you're expecting the big query to take the same time as it takes the DB to decide the small query produces NULL. In practice the big query will be rewritten by the db optimizer in some way so that the way it's executed is different to the conceptual model of execution you've formed in your mind. This time round the DB's picked a sub-optimal optimization for it and is taking longer to connect the data up, then realize the result is null.

This is a very different scenario to hard coding your NULL like SELECT * FROM table WHERE x IN (null) - there'll be a specific optimization that that decides this is a no-op and you may even find parts of a complex query that includes an operation that is always false, such as this, are not executed at all. Th MySQL manual goes into some fantastic detail about query optimization, if your curiosity is intense enough :)

Title: Why is this query slow, where id in (sub select that returns null)

Body:
I'm having a hard time understanding why this query is taking more than 1ms.

EXPLAIN ANALYZE SELECT AVG("adverts"."price")
FROM "adverts" WHERE "adverts"."type" IN ('Businesses::Restaurant')
AND "adverts"."discarded_at" IS NULL AND "adverts"."visible" = true
AND ("adverts"."city_location_id" = 56
     OR "adverts"."city_location_id" IN (SELECT "city_locations"."id"
                                         FROM "city_locations"
                                         WHERE "city_locations"."type" IN ('Arrondissement')
                                        AND "city_locations"."arrondissement_city_id" = 56));

QUERY PLAN

 Aggregate  (cost=6583.49..6583.50 rows=1 width=32) (actual time=21.702..21.702 rows=1 loops=1)
   ->  Seq Scan on adverts  (cost=6.31..6533.88 rows=19842 width=4) (actual time=0.462..21.684 rows=44 loops=1)
         Filter: ((discarded_at IS NULL) AND visible AND ((type)::text = 'Businesses::Restaurant'::text) AND ((city_location_id = 56) OR (hashed SubPlan 1)))
         Rows Removed by Filter: 46217
         SubPlan 1
           ->  Index Scan using index_city_locations_on_arrondissement_city_id on city_locations  (cost=0.29..6.31 rows=1 width=8) (actual time=0.008..0.008 rows=0 loops=1)
                 Index Cond: (arrondissement_city_id = 56)
                 Filter: ((type)::text = 'Arrondissement'::text)
 Planning Time: 0.173 ms
 Execution Time: 21.739 ms

The execution time is 21ms

If I execute the sub request I get:

EXPLAIN ANALYZE SELECT "city_locations"."id" FROM "city_locations" WHERE "city_locations"."type" IN ('Arrondissement') AND "city_locations"."arrondissement_city_id" = 56;
 id
----
(0 rows)

QUERY PLAN

 Index Scan using index_city_locations_on_arrondissement_city_id on city_locations  (cost=0.29..6.31 rows=1 width=8) (actual time=0.028..0.028 rows=0 loops=1)
   Index Cond: (arrondissement_city_id = 56)
   Filter: ((type)::text = 'Arrondissement'::text)
 Planning Time: 0.233 ms
 Execution Time: 0.075 ms

execution time is: 0.075ms, super fast and the result is NULL.

When I replace the sub request by its result NULL it is super fast.

EXPLAIN ANALYZE SELECT AVG("adverts"."price")
FROM "adverts" WHERE "adverts"."type" IN ('Businesses::Restaurant')
AND "adverts"."discarded_at" IS NULL AND "adverts"."visible" = true
AND ("adverts"."city_location_id" = 56
     OR "adverts"."city_location_id" IN (NULL));

QUERY PLAN

 Aggregate  (cost=162.66..162.67 rows=1 width=32) (actual time=0.309..0.310 rows=1 loops=1)
   ->  Bitmap Heap Scan on adverts  (cost=4.72..162.55 rows=42 width=4) (actual time=0.082..0.278 rows=44 loops=1)
         Recheck Cond: (city_location_id = 56)
         Filter: ((discarded_at IS NULL) AND visible AND ((type)::text = 'Businesses::Restaurant'::text))
         Heap Blocks: exact=42
         ->  Bitmap Index Scan on index_adverts_on_city_location_id_and_visible  (cost=0.00..4.71 rows=42 width=0) (actual time=0.043..0.044 rows=44 loops=1)
               Index Cond: ((city_location_id = 56) AND (visible = true))
 Planning Time: 0.395 ms
 Execution Time: 0.412 ms

The execution time is 0.412 ms

My question is why is the first request slow when its separate requests are fast?

Do I miss some optimization due to the WHERE IN clause?


问:
How to use document.onload Properly
I am currently learning window.onload and document.onload as attributes on html. But i fail to use them properly. In my code i want to focus a specific text area named "emri", using the document.onload but without success. Some would say to use it as a script or smth, but i want to use it as an attribute inside the tag. What am i doing wrong?

```<code> <!doctype html>
  <html lang="en">

  <head>
     <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1,
  shrink-to-fit=no">

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB"
    crossorigin="anonymous">

<link rel="stylesheet" href="App.css">

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ"
    crossorigin="anonymous">

   </head>

   <body onload="document.my-form1.emri.focus();" >

  <main class="my-form">
      <div class="container">
          <div class="row justify-content-flex-start">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">Apliko</div>
                    <div class="card-body">
                        <form name="my-form1" onsubmit=" return formValidation();">
                            <div class="form-group row">
                                <label for="emri" class="col-md-3 col-form-label text-md-right">Emri juaj:</label>
                                <div class="col-md-6">
                                    <input type="text"  class="form-control" name="emri">
                                </div>
                            </div>
</code>```

答:
You need to select like this

```

If you are using HTML5, you can use like autofocus attribute in input.

Title: How to use document.onload Properly

Body:
I am currently learning window.onload and document.onload as attributes on html. But i fail to use them properly. In my code i want to focus a specific text area named "emri", using the document.onload but without success. Some would say to use it as a script or smth, but i want to use it as an attribute inside the tag. What am i doing wrong?

 <!doctype html>

     <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1,
  shrink-to-fit=no">

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB"
    crossorigin="anonymous">

<link rel="stylesheet" href="App.css">

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ"
    crossorigin="anonymous">

Apliko

                        <form name="my-form1" onsubmit=" return formValidation();">

                                Emri juaj:

                                    <input type="text"  class="form-control" name="emri">

Body:
You need to select like this

<body onload="document.getElementsByName('emri')[0].focus();">

If you are using HTML5, you can use like autofocus attribute in input.


问:
JpaRepository findAll returns empty List
findAll() method from JpaRepository returns empty value, but correct number of empty values

I'm using h2 database and everything has worked fine until some unknown moment. Simple GET at http://localhost:8080/users returns {} x number of users previously added to the database. I tried implementing a method that would return id based on username and that works just fine.

Here is my User.java:

```<code>@Entity
@Table(name = "Users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "username")
    @NotBlank(message = "Username is mandatory")
    @Size(min = 1, max = 20, message = "Username must be less than 20 characters long")
    private String username;
    @Column(name = "balance")
    private Double balance = 0.0;

    Long getId() {
        return id;
    }

    void setId(Long id) {
        this.id = id;
    }

    String getUsername() {
        return username;
    }

    void setUsername(String username) {
        this.username = username;
    }

    Double getBalance() {
        return balance;
    }

    void setBalance(Double balance) {
        this.balance = balance;
    }
}
</code>```

Here is UserService which implements methods from IUserService:

```<code>@Service
public class UserService implements IUserService {

    @Autowired
    private UserRepository repository;

    @Override
    public void createNewUser(User user) {
        repository.save(user);
    }

    @Override
    public List<User> findAll() {
        return repository.findAll();
    }

    @Override
    public Long findByUsername(String username) {
        return repository.findByUsername(username);
    }

    @Override
    public User findById(Long id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public boolean checkIfUsernameIsTaken(User user) {
        return repository.findByUsername(user.getUsername()) != null;
    }

    @Override
    public void deleteUser(Long id) {
        repository.deleteById(id);
    }

    @Override
    public void updateBalance(Long id, Double balance) {
        repository.updateBalance(id, balance);
    }
}
</code>```

I tried with and without @Column annotations and it doesn't seem to do anything.

The output I get from Postman is [{}] if I added only one user via createNewuser(), [{},{}] if I added two users and so on. I don't understand what broke the findAll() method.

P.S. updateBalance() doesn't work either, but that's for some other time.

Edit: some ov you asked for UserController:

```<code>@RestController
public class UserController {

    @Autowired
    IUserService userService;

    @GetMapping("/users")
    public List<User> findUsers() {
        return userService.findAll();
    }

    @GetMapping("/users/{id}")
    public User findUserById(@PathVariable Long id) {
        return userService.findById(id);
    }

    @PostMapping("/users")
    public ResponseEntity<Object> createUser(@RequestBody User user) {

        if (userService.checkIfUsernameIsTaken(user)) {

            Map<String, Object> response = new HashMap<>();
            response.put("status", HttpStatus.NOT_ACCEPTABLE);
            response.put("errors", "Username is already taken");
            response.put("timestamp", new Date());

            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        } else {
            userService.createNewUser(user);
            User currentUser = userService.findById(userService.findByUsername(user.getUsername()));
            Map<String, Object> response = new HashMap<>();
            response.put("id", currentUser.getId());
            response.put("username", currentUser.getUsername());
            response.put("balance", currentUser.getBalance());
            return new ResponseEntity<>(response, HttpStatus.OK);
        }
    }

    @DeleteMapping("/users/{id}")
    public void deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
    }

    @PutMapping("/users/{id}/{balance}")
    public void updateBalance(@PathVariable Long id, @PathVariable Double balance) {
        userService.updateBalance(id, balance);
    }
}
</code>```

and UserRepository:

```<code>@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    @Query("SELECT id FROM User WHERE username = ?1")
    Long findByUsername(String username);

    @Transactional
    @Modifying
    @Query("UPDATE User SET balance = ?2 WHERE id = ?1")
    void updateBalance(Long id, Double balance);
}
</code>```

My problems first appeared (or so I think) after I implmented the update query, but I tried running a version where I know it worked on a different computer, but it didn't work.

答: The problem is that your properties are not mutable. You have exposed getters and setters but you didn't specify access level, and they are not public by default, so hibernate can not see them and hence can not populate your entity with the record returned from the database. Making them public should resolve the issue.

Body:
findAll() method from JpaRepository returns empty value, but correct number of empty values

I'm using h2 database and everything has worked fine until some unknown moment. Simple GET at http://localhost:8080/users returns {} x number of users previously added to the database. I tried implementing a method that would return id based on username and that works just fine.

Here is my User.java:

@Entity
@Table(name = "Users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "username")
    @NotBlank(message = "Username is mandatory")
    @Size(min = 1, max = 20, message = "Username must be less than 20 characters long")
    private String username;
    @Column(name = "balance")
    private Double balance = 0.0;

    Long getId() {
        return id;
    }

    void setId(Long id) {
        this.id = id;
    }

    String getUsername() {
        return username;
    }

    void setUsername(String username) {
        this.username = username;
    }

    Double getBalance() {
        return balance;
    }

    void setBalance(Double balance) {
        this.balance = balance;
    }
}

Here is UserService which implements methods from IUserService:

@Service
public class UserService implements IUserService {

    @Autowired
    private UserRepository repository;

    @Override
    public void createNewUser(User user) {
        repository.save(user);
    }

    @Override
    public List<User> findAll() {
        return repository.findAll();
    }

    @Override
    public Long findByUsername(String username) {
        return repository.findByUsername(username);
    }

    @Override
    public User findById(Long id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public boolean checkIfUsernameIsTaken(User user) {
        return repository.findByUsername(user.getUsername()) != null;
    }

    @Override
    public void deleteUser(Long id) {
        repository.deleteById(id);
    }

    @Override
    public void updateBalance(Long id, Double balance) {
        repository.updateBalance(id, balance);
    }
}

I tried with and without @Column annotations and it doesn't seem to do anything.

The output I get from Postman is [{}] if I added only one user via createNewuser(), [{},{}] if I added two users and so on. I don't understand what broke the findAll() method.

P.S. updateBalance() doesn't work either, but that's for some other time.

Edit: some ov you asked for UserController:

@RestController
public class UserController {

    @Autowired
    IUserService userService;

    @GetMapping("/users")
    public List<User> findUsers() {
        return userService.findAll();
    }

    @GetMapping("/users/{id}")
    public User findUserById(@PathVariable Long id) {
        return userService.findById(id);
    }

    @PostMapping("/users")
    public ResponseEntity<Object> createUser(@RequestBody User user) {

        if (userService.checkIfUsernameIsTaken(user)) {

            Map<String, Object> response = new HashMap<>();
            response.put("status", HttpStatus.NOT_ACCEPTABLE);
            response.put("errors", "Username is already taken");
            response.put("timestamp", new Date());

            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        } else {
            userService.createNewUser(user);
            User currentUser = userService.findById(userService.findByUsername(user.getUsername()));
            Map<String, Object> response = new HashMap<>();
            response.put("id", currentUser.getId());
            response.put("username", currentUser.getUsername());
            response.put("balance", currentUser.getBalance());
            return new ResponseEntity<>(response, HttpStatus.OK);
        }
    }

    @DeleteMapping("/users/{id}")
    public void deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
    }

    @PutMapping("/users/{id}/{balance}")
    public void updateBalance(@PathVariable Long id, @PathVariable Double balance) {
        userService.updateBalance(id, balance);
    }
}

and UserRepository:

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    @Query("SELECT id FROM User WHERE username = ?1")
    Long findByUsername(String username);

    @Transactional
    @Modifying
    @Query("UPDATE User SET balance = ?2 WHERE id = ?1")
    void updateBalance(Long id, Double balance);
}

My problems first appeared (or so I think) after I implmented the update query, but I tried running a version where I know it worked on a different computer, but it didn't work.