问:
Python 3 urllib.request data struggles
Can anyone explain me why 'version 1' of my code doesn't work and 'version 2' does?
Output of both versions are below. For some reason the my_data is incorrectly inserted in the urllib request but I cannot figure out why. I tried 20 different examples and methods also straight from Python documentation but it's no bueno. It's not only the 'action' key, also when i want to insert the username and password as keys it's no success. Scratching my brain here...

```<code>import urllib.request
import urllib.error
import urllib.parse

my_url = 'http://{0}:{1}/?username=myuser&password=mypass'.format('10.10.127.47', 80)
my_headers = { "Content-Type" : "application/x-www-form-urlencoded" }

# ---- begin version 1 / not working ----------------------------------------------
my_data = { "action" : "getmetadata" }
my_uedata = urllib.parse.urlencode(my_data)
my_edata = my_uedata.encode('utf-8')
req = urllib.request.Request(url=my_url, data=my_edata, headers=my_headers)
# ---- end version 1 --------------------------------------------------------------

# ---- begin version 2 / works fine -----------------------------------------------
req = urllib.request.Request(url=''.join([my_url, '&action=getmetadata']), data=None, headers=my_headers)
# ---- end version 2 --------------------------------------------------------------

response = urllib.request.urlopen(req)
html = response.read()
print(html)
</code>```

Version 1 output:

```<code>b'{"schemaVersion":"3.0.0","action":"Unknown","actionDetail":null,"userName":"myuser","password":"mypass","metadata":[],"configurations":[],"commandItems":[]}'
</code>```

Version 2 output:

```<code>b'{"schemaVersion":"3.0.0","action":"GetMetadata","actionDetail":null,"userName":"myuser","password":"mypass","metadata":[{"key":"permissions","value":[]},{"key":"Title","value":"Blabla"},{"key":"Description","value":"fjshkfsdhskjhfsk"},{"key":"Keyword","value":""},{"key":"Learningdescription","value":""},{"key":"Rightsdescription","value":"Creative Commons"},{"key":"SessionId","value":""},{"key":"PauseAndResumeVideoTime","value":""},{"key":"VideoSegments","value":""},{"key":"VideoTrackPosition","value":"0,25:50,75;50,25:100,75"},{"key":"SlideTrackPositionIndex","value":"2"},{"key":"Coverage","value":""},{"key":"Language","value":"en"},{"key":"Structure","value":"linear"},{"key":"Aggregationlevel","value":"3"},{"key":"SubjectAreas","value":"NBC1"},{"key":"Version","value":"1.0"},{"key":"Status","value":"final"},{"key":"EducationalLearningResourceType","value":"informatiebron"},{"key":"intendedenduserrole","value":"learner"},{"key":"EducationalContext","value":"HBO"},{"key":"Typicalagerange","value":"18-24"},{"key":"Difficulty","value":"medium"},{"key":"Typicallearningtime","value":""},{"key":"EducationalLanguage","value":"en"},{"key":"Cost","value":"No"},{"key":"Copyrights","value":"Yes"},{"key":"Showincatalogue","value":"True"},{"key":"PublishDate","value":""},{"key":"ExpirationTime","value":"730"},{"key":"Duration","value":"0"},{"key":"contributors","value":[]}],"configurations":[],"commandItems":[]}'
</code>```

答:
Looks like in the first version you're specifying a payload that is to be sent, but eventually is not used, since urllib.request.Request assumes GET as default method, which does not include any body. If you'd like to send the payload, please specify as constructor argument method='POST', which will allow the server to read the body of your request.

In the second scenario, you're passing the payload as URL parameters, which are normally recognized by GET method.

For reference, please see the documentation.

Title: Python 3 urllib.request data struggles

Body:
Can anyone explain me why 'version 1' of my code doesn't work and 'version 2' does?
Output of both versions are below. For some reason the my_data is incorrectly inserted in the urllib request but I cannot figure out why. I tried 20 different examples and methods also straight from Python documentation but it's no bueno. It's not only the 'action' key, also when i want to insert the username and password as keys it's no success. Scratching my brain here...

import urllib.request
import urllib.error
import urllib.parse

my_url = 'http://{0}:{1}/?username=myuser&password=mypass'.format('10.10.127.47', 80)
my_headers = { "Content-Type" : "application/x-www-form-urlencoded" }

# ---- begin version 1 / not working ----------------------------------------------
my_data = { "action" : "getmetadata" }
my_uedata = urllib.parse.urlencode(my_data)
my_edata = my_uedata.encode('utf-8')
req = urllib.request.Request(url=my_url, data=my_edata, headers=my_headers)
# ---- end version 1 --------------------------------------------------------------

# ---- begin version 2 / works fine -----------------------------------------------
req = urllib.request.Request(url=''.join([my_url, '&action=getmetadata']), data=None, headers=my_headers)
# ---- end version 2 --------------------------------------------------------------

response = urllib.request.urlopen(req)
html = response.read()
print(html)

Version 1 output:

b'{"schemaVersion":"3.0.0","action":"Unknown","actionDetail":null,"userName":"myuser","password":"mypass","metadata":[],"configurations":[],"commandItems":[]}'

Version 2 output:

b'{"schemaVersion":"3.0.0","action":"GetMetadata","actionDetail":null,"userName":"myuser","password":"mypass","metadata":[{"key":"permissions","value":[]},{"key":"Title","value":"Blabla"},{"key":"Description","value":"fjshkfsdhskjhfsk"},{"key":"Keyword","value":""},{"key":"Learningdescription","value":""},{"key":"Rightsdescription","value":"Creative Commons"},{"key":"SessionId","value":""},{"key":"PauseAndResumeVideoTime","value":""},{"key":"VideoSegments","value":""},{"key":"VideoTrackPosition","value":"0,25:50,75;50,25:100,75"},{"key":"SlideTrackPositionIndex","value":"2"},{"key":"Coverage","value":""},{"key":"Language","value":"en"},{"key":"Structure","value":"linear"},{"key":"Aggregationlevel","value":"3"},{"key":"SubjectAreas","value":"NBC1"},{"key":"Version","value":"1.0"},{"key":"Status","value":"final"},{"key":"EducationalLearningResourceType","value":"informatiebron"},{"key":"intendedenduserrole","value":"learner"},{"key":"EducationalContext","value":"HBO"},{"key":"Typicalagerange","value":"18-24"},{"key":"Difficulty","value":"medium"},{"key":"Typicallearningtime","value":""},{"key":"EducationalLanguage","value":"en"},{"key":"Cost","value":"No"},{"key":"Copyrights","value":"Yes"},{"key":"Showincatalogue","value":"True"},{"key":"PublishDate","value":""},{"key":"ExpirationTime","value":"730"},{"key":"Duration","value":"0"},{"key":"contributors","value":[]}],"configurations":[],"commandItems":[]}'


来源: stackexchange

问:
Call useQuery after retrieving router query object (NextJS with GraphQL)
I am retrieving the query param in NextJS using:
const qry_flightNumber = Number(router.query.flightNumber);
Then i want to send a request to my GraphQL server by doing this:
PAGE: LaunchDetails.js

```<code>import React, { useEffect, useState } from "react";
import classNames from "classnames";
import gql from "graphql-tag";
import { useQuery } from "@apollo/react-hooks";
import PropTypes from "prop-types";

const LAUNCH_QUERY = gql`
  query LaunchQuery($flight_number: Int!) {
    launch(flight_number: $flight_number) {
      flight_number
      mission_name
      launch_year
      launch_success
      launch_date_local
      rocket {
        rocket_id
        rocket_name
        rocket_type
      }
    }
  }
`;

export default function LaunchDetails({ flightNum }) {
  const { loading, error, data } = useQuery(LAUNCH_QUERY, {
    variables: { flight_number: flightNum },
  });

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error</p>;

  console.log("data.launch: ", data.launch);

  const flightNumber = data.launch.flight_number;
  const launchDate = data.launch.launch_date_local;
  const launchSuccess = data.launch.launch_success;
  const launchYear = data.launch.launch_year;
  const missionName = data.launch.mission_name;
  const { rocket } = data.launch;

  return (
    <div>
      <h1 className="display-4 my-3">
        <span className="text-dark">Mission: {missionName}</span>
      </h1>
      <h2 className="mb-3">Launch details</h2>
      <ul className="list-group">
        <li className="list-group-item">Flight number: {flightNumber}</li>
        <li className="list-group-item">Launch year: {launchYear}</li>
        <li className="list-group-item">
          Launch successful:{" "}
          <span
            className={classNames({
              "text-success": launchSuccess,
              "text-danger": launchSuccess === false,
            })}
          >
            {launchSuccess ? "yes" : "no"}
          </span>
        </li>
      </ul>
      <h4 className="my-3">Rocket details:</h4>
      <ul className="list-group">
        <li className="list-group-item">Rocket ID: {rocket.rocket_id}</li>
        <li className="list-group-item">Rocket name: {rocket.rocket_name}</li>
        <li className="list-group-item">Rocket type: {rocket.rocket_type}</li>
      </ul>
      <hr />
    </div>
  );
}

LaunchDetails.propTypes = {
  flightNum: PropTypes.number.isRequired,
};

</code>```

Dynamic PAGE containing the component ([flight_number].js):

```<code>import { ApolloProvider } from "@apollo/react-hooks";
import React from "react";
import Link from "next/link";
import { useRouter } from "next/router";
import APOLLO_CLIENT from "../../graphql/config";
import LaunchDetails from "../../components/launches/LaunchDetails";

export default function Home() {
  const router = useRouter();
  const flightNum = Number(router.query.flightNumber);

  return (
    <>
      {/* <Head>
        <title>SpaceX launch</title>
      </Head> */}

      <ApolloProvider client={APOLLO_CLIENT}>
        <div className="container">
          <h1 className="title">Apollo launch details</h1>
          <LaunchDetails flightNum={flightNum} />

          <Link href="/">
            <a className="btn btn-secondary">Back</a>
          </Link>
        </div>
      </ApolloProvider>
    </>
  );
}
</code>```

The issue is have is that on first page load, the GraphQL query executes with flight_number being null. So i end up with this warning in console:

```<code>[GraphQL error]: Message: Variable "$flight_number" of non-null type "Int!" must not be null., Location: [object Object], Path: undefined
</code>```

I have tried using an IF statement to make sure that flight_number is !NaN before running the query however react complains about the order of the hooks being called.

Obviously after the component has fully loaded, the GraphQl variable becomes defined and then executes correctly however I will still be getting the console warning.

Console warning screenshot:

What are my options to stop the console warning?
Thank you.

答:
I have got an answer to this now. You can pass a skip parameter to the useQuery to only exec the query if the variable is defined or not NaN:</p>

```<code>const { loading, error, data } = useQuery(LAUNCH_QUERY, {
    variables: { flight_number: flightNum },
    skip: Number.isNaN(flightNum),
  });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am retrieving the query param in NextJS using:
const qry_flightNumber = Number(router.query.flightNumber);
Then i want to send a request to my GraphQL server by doing this:
PAGE: LaunchDetails.js

import React, { useEffect, useState } from "react";
import classNames from "classnames";
import gql from "graphql-tag";
import { useQuery } from "@apollo/react-hooks";
import PropTypes from "prop-types";

const LAUNCH_QUERY = gql`
  query LaunchQuery($flight_number: Int!) {
    launch(flight_number: $flight_number) {
      flight_number
      mission_name
      launch_year
      launch_success
      launch_date_local
      rocket {
        rocket_id
        rocket_name
        rocket_type
      }
    }
  }
`;

export default function LaunchDetails({ flightNum }) {
  const { loading, error, data } = useQuery(LAUNCH_QUERY, {
    variables: { flight_number: flightNum },
  });

  if (loading) return
Loading...
;
  if (error) return
Error
;

  console.log("data.launch: ", data.launch);

  const flightNumber = data.launch.flight_number;
  const launchDate = data.launch.launch_date_local;
  const launchSuccess = data.launch.launch_success;
  const launchYear = data.launch.launch_year;
  const missionName = data.launch.mission_name;
  const { rocket } = data.launch;

  return (

        Mission: {missionName}

Launch details

Flight number: {flightNumber}

Launch year: {launchYear}

          Launch successful:{" "}

            {launchSuccess ? "yes" : "no"}

Rocket details:

Rocket ID: {rocket.rocket_id}

Rocket name: {rocket.rocket_name}

Rocket type: {rocket.rocket_type}

  );
}

LaunchDetails.propTypes = {
  flightNum: PropTypes.number.isRequired,
};

Dynamic PAGE containing the component ([flight_number].js):

import { ApolloProvider } from "@apollo/react-hooks";
import React from "react";
import Link from "next/link";
import { useRouter } from "next/router";
import APOLLO_CLIENT from "../../graphql/config";
import LaunchDetails from "../../components/launches/LaunchDetails";

export default function Home() {
  const router = useRouter();
  const flightNum = Number(router.query.flightNumber);

  return (
    <>
      {/*
        <title>SpaceX launch</title>
       */}

      <ApolloProvider client={APOLLO_CLIENT}>

Apollo launch details

          <LaunchDetails flightNum={flightNum} />

          <Link href="/">
            Back
          </Link>

      </ApolloProvider>
    </>
  );
}

The issue is have is that on first page load, the GraphQL query executes with flight_number being null. So i end up with this warning in console:

[GraphQL error]: Message: Variable "$flight_number" of non-null type "Int!" must not be null., Location: [object Object], Path: undefined

I have tried using an IF statement to make sure that flight_number is !NaN before running the query however react complains about the order of the hooks being called.

Obviously after the component has fully loaded, the GraphQl variable becomes defined and then executes correctly however I will still be getting the console warning.

Console warning screenshot:

What are my options to stop the console warning?
Thank you.

Body:
I have got an answer to this now. You can pass a skip parameter to the useQuery to only exec the query if the variable is defined or not NaN:

const { loading, error, data } = useQuery(LAUNCH_QUERY, {
    variables: { flight_number: flightNum },
    skip: Number.isNaN(flightNum),
  });


问:
why my sign up page don't work even i enter my fire base code correctly
when i try to sign up this error appear

this.props.firebase.signupwithemail is not a function.(In'_this.props.firebase.signupWithEmail(email,password)',
  '_this.props.firebase.signupWithEmail'is undefined)

that's my code

```<code>handleOnSignup = async (values, actions) => {
const { name, email, password } = values

try {
  const response = await this.props.firebase.signupWithEmail(
    email,
    password
  )

  if (response.user.uid) {
    const { uid } = response.user
    const userData = { email, name, uid }
    await this.props.firebase.createNewUser(userData)
    this.props.navigation.navigate('App')
  }
} catch (error) {
  // console.error(error)
  actions.setFieldError('general', error.message)
} finally {
  actions.setSubmitting(false)
}
</code>```

答:
Change this:

```<code>this.props.firebase.signInWithEmail
</code>```

into this:

```<code>this.props.firebase.signInWithEmailAndPassword
</code>```

Body:
when i try to sign up this error appear

this.props.firebase.signupwithemail is not a function.(In'_this.props.firebase.signupWithEmail(email,password)',
  '_this.props.firebase.signupWithEmail'is undefined)

that's my code

handleOnSignup = async (values, actions) => {
const { name, email, password } = values

try {
  const response = await this.props.firebase.signupWithEmail(
    email,
    password
  )

  if (response.user.uid) {
    const { uid } = response.user
    const userData = { email, name, uid }
    await this.props.firebase.createNewUser(userData)
    this.props.navigation.navigate('App')
  }
} catch (error) {
  // console.error(error)
  actions.setFieldError('general', error.message)
} finally {
  actions.setSubmitting(false)
}

Body:
Change this:

this.props.firebase.signInWithEmail

into this:

this.props.firebase.signInWithEmailAndPassword


问:
I'm using Visual studio 2019 and my project's name ends with .Sln insted of .cpp
I'm new to programming I use visual studio 2019 and when I'm creating a new project the project's name always end with .Sln instead of .cpp</p>

答: SLN is the solution file. It is used to compile the solution and other informations. You can add classes (.cpp/.h) in your project where you can write C++ code.</p>


问:
how do I find differences between similar strings?
I have a vector of strings (file names to be exact).

```<code>pav <- c("Sn_4Khz_3W_45_130_02_30cm_101mm_",
         "Sn_4Khz_4W_45_130_02_30cm_101mm_",
         "Sn_4Khz_4W_50_130_02_30cm_101mm_")
</code>```

I'm looking for a simple way to find difference between these strings.

```<code>`> char_position_fun(pav) # gives unique character position
[1] 9 12 13 `

`> char_diff_fun(pav) # removes matching components (position and value)
[1] 3_4_5  4_4_5  4_5_0`
</code>```

答:
Here is my attempt. I decided to split all letters and create a data frame for each string containing position and letter information. Then, for each position, I checked if there is one unique letter or not. If FALSE, that suggests that not all letters are identical. Finally, subset the data frame with a logical condition. In this way, you can see position and letter information together.

```<code>library(tidyverse)

strsplit(mytext, split = "") %>%
map_dfr(.x = .,
        .f = function(x) enframe(x, name = "position", value = "word"),
        .id = "id") %>%
group_by(position) %>%
mutate(check = n_distinct(word) == 1) %>%
filter(check == FALSE)

  id    position word  check
  <chr>    <int> <chr> <lgl>
1 1            9 3     FALSE
2 1           12 4     FALSE
3 1           13 5     FALSE
4 2            9 4     FALSE
5 2           12 4     FALSE
6 2           13 5     FALSE
7 3            9 4     FALSE
8 3           12 5     FALSE
9 3           13 0     FALSE
</code>```

If you want to have the outcome as you described, you can add a bit more operation.

```<code>strsplit(mytext, split = "") %>%
map_dfr(.x = .,
        .f = function(x) enframe(x, name = "position", value = "word"),
        .id = "id") %>%
group_by(position) %>%
mutate(check = n_distinct(word) == 1) %>%
filter(check == FALSE) %>%
group_by(id) %>%
summarize_at(vars(position:word),
             .funs = list(~paste0(., collapse = "_")))

  id    position word
  <chr> <chr>    <chr>
1 1     9_12_13  3_4_5
2 2     9_12_13  4_4_5
3 3     9_12_13  4_5_0
</code>```

DATA

```<code>mytext <- c("Sn_4Khz_3W_45_130_02_30cm_101mm_", "Sn_4Khz_4W_45_130_02_30cm_101mm_",
"Sn_4Khz_4W_50_130_02_30cm_101mm_")
</code>```

Body:
I have a vector of strings (file names to be exact).

pav <- c("Sn_4Khz_3W_45_130_02_30cm_101mm_",
         "Sn_4Khz_4W_45_130_02_30cm_101mm_",
         "Sn_4Khz_4W_50_130_02_30cm_101mm_")

I'm looking for a simple way to find difference between these strings.

`> char_position_fun(pav) # gives unique character position
[1] 9 12 13 `

`> char_diff_fun(pav) # removes matching components (position and value)
[1] 3_4_5  4_4_5  4_5_0`

Body:
Here is my attempt. I decided to split all letters and create a data frame for each string containing position and letter information. Then, for each position, I checked if there is one unique letter or not. If FALSE, that suggests that not all letters are identical. Finally, subset the data frame with a logical condition. In this way, you can see position and letter information together.

library(tidyverse)

strsplit(mytext, split = "") %>%
map_dfr(.x = .,
        .f = function(x) enframe(x, name = "position", value = "word"),
        .id = "id") %>%
group_by(position) %>%
mutate(check = n_distinct(word) == 1) %>%
filter(check == FALSE)

  id    position word  check
  <chr>    <int> <chr> <lgl>
1 1            9 3     FALSE
2 1           12 4     FALSE
3 1           13 5     FALSE
4 2            9 4     FALSE
5 2           12 4     FALSE
6 2           13 5     FALSE
7 3            9 4     FALSE
8 3           12 5     FALSE
9 3           13 0     FALSE

If you want to have the outcome as you described, you can add a bit more operation.

strsplit(mytext, split = "") %>%
map_dfr(.x = .,
        .f = function(x) enframe(x, name = "position", value = "word"),
        .id = "id") %>%
group_by(position) %>%
mutate(check = n_distinct(word) == 1) %>%
filter(check == FALSE) %>%
group_by(id) %>%
summarize_at(vars(position:word),
             .funs = list(~paste0(., collapse = "_")))

  id    position word
  <chr> <chr>    <chr>
1 1     9_12_13  3_4_5
2 2     9_12_13  4_4_5
3 3     9_12_13  4_5_0

DATA

mytext <- c("Sn_4Khz_3W_45_130_02_30cm_101mm_", "Sn_4Khz_4W_45_130_02_30cm_101mm_",
"Sn_4Khz_4W_50_130_02_30cm_101mm_")


问:
Remove an item from a list of objects - Typescript
I want to remove a specific object from a list. The object model looks like this:

```<code>export class Task {
  taskId: number;
  projectId: Project;
  userId: User;
  state: string;
  description: string;
}
</code>```

I created a list of Task objects and I want to delete a Task that has a specific taskId.

```<code> moveTaskInProgress(task: Task) {
    console.log('The task is in progress...');
    task.state = 'IN_PROGRESS';
    this.taskService.updateTask(task).subscribe((nbOfUpdates) => {
      console.log('Number of updates: ' + JSON.stringify(nbOfUpdates));
      this.removeItemFromAListOfTasks(task, this.openTasks);
      console.log('List of task task: ' + JSON.stringify(this.openTasks));
    });
 }

  removeItemFromAListOfTasks(task: Task, listOfTasks: Task[]) {
    let filteredList: Task[];
    filteredList = listOfTasks.filter(item => item.taskId !== task.taskId);
  }
</code>```

I have a method that receive a task, call a method that updates some properties, and after that i want to delete the task from the list.

But it seems that nothing happen. Could you, please, help me with this?

答:
Filtering an array returns a new array with a subset of the original items. It does not modify the original array.

Instead you need to splice it.

```<code>moveTaskInProgress(task: Task) {
  console.log('The task is in progress...');
  task.state = 'IN_PROGRESS';
  this.taskService.updateTask(task).subscribe((nbOfUpdates) => {
    console.log('Number of updates: ' + JSON.stringify(nbOfUpdates));
    this.removeItemFromAListOfTasks(task, this.openTasks);
    console.log('List of task task: ' + JSON.stringify(this.openTasks));
  });
}

removeItemFromAListOfTasks(task: Task, listOfTasks: Task[]) {
  const index = listOfTasks.indexOf(task);
  if (index === -1) {
    // the task doesn't exist in the array, no need to continue
    return;
  }

  // delete 1 item starting at the given index
  listOfTasks.splice(index, 1);
}
</code>```

This is assuming that the task originated from the array. Otherwise you will need to find the index:

```<code>const index = listOfTasks.findIndex(x => x.taskId === task.taskId);
</code>```

Body:
I want to remove a specific object from a list. The object model looks like this:

export class Task {
  taskId: number;
  projectId: Project;
  userId: User;
  state: string;
  description: string;
}

I created a list of Task objects and I want to delete a Task that has a specific taskId.

 moveTaskInProgress(task: Task) {
    console.log('The task is in progress...');
    task.state = 'IN_PROGRESS';
    this.taskService.updateTask(task).subscribe((nbOfUpdates) => {
      console.log('Number of updates: ' + JSON.stringify(nbOfUpdates));
      this.removeItemFromAListOfTasks(task, this.openTasks);
      console.log('List of task task: ' + JSON.stringify(this.openTasks));
    });
 }

  removeItemFromAListOfTasks(task: Task, listOfTasks: Task[]) {
    let filteredList: Task[];
    filteredList = listOfTasks.filter(item => item.taskId !== task.taskId);
  }

I have a method that receive a task, call a method that updates some properties, and after that i want to delete the task from the list.

But it seems that nothing happen. Could you, please, help me with this?

Body:
Filtering an array returns a new array with a subset of the original items. It does not modify the original array.

Instead you need to splice it.

moveTaskInProgress(task: Task) {
  console.log('The task is in progress...');
  task.state = 'IN_PROGRESS';
  this.taskService.updateTask(task).subscribe((nbOfUpdates) => {
    console.log('Number of updates: ' + JSON.stringify(nbOfUpdates));
    this.removeItemFromAListOfTasks(task, this.openTasks);
    console.log('List of task task: ' + JSON.stringify(this.openTasks));
  });
}

removeItemFromAListOfTasks(task: Task, listOfTasks: Task[]) {
  const index = listOfTasks.indexOf(task);
  if (index === -1) {
    // the task doesn't exist in the array, no need to continue
    return;
  }

  // delete 1 item starting at the given index
  listOfTasks.splice(index, 1);
}

This is assuming that the task originated from the array. Otherwise you will need to find the index:

const index = listOfTasks.findIndex(x => x.taskId === task.taskId);


问:
Get regex of words that starts with @ sign
All answers that I found get rough solution for example this and this ( /\b@\w+\b/gi ) is cover not only the "@abcdef" but "abc@abcdf" too, but what I need is a regex that match all words that starts with "@" sign and more than 6 characters length and non of following solutions give me what I need

```<code>/@\b[a-zA-Z0-9]{5,}\b/gi
/\b@[a-zA-Z0-9]{5,}\b/gi
</code>```

Examples that should be matched:

```<code>@abcdefjh
</code>```

Examples that shouldn't be matched:

```<code>abc@absdefgh
</code>```

Added:
PS: Is there a way to improve this question that it can be more helpful for not experienced users like me?

答:
var test = [
    '@abcdefjh',
    '@abc',
    'abc@absdefgh',
    '#*$@abc123',
    'abc123',
];
console.log(test.map(function (a) {
  return a + ' :' + /(?:\s|^)@[a-zA-Z0-9]{5,}/.test(a);
}));```
</div>
</div>
</p>

<hr>

<p>If your browser supports it, you can use a negaitve lookbehind:</p>

```/(?<!\S)@[a-zA-Z0-9]{5,}/
```

Body:
All answers that I found get rough solution for example this and this ( /\b@\w+\b/gi ) is cover not only the "@abcdef" but "abc@abcdf" too, but what I need is a regex that match all words that starts with "@" sign and more than 6 characters length and non of following solutions give me what I need

/@\b[a-zA-Z0-9]{5,}\b/gi
/\b@[a-zA-Z0-9]{5,}\b/gi

Examples that should be matched:

@abcdefjh

Examples that shouldn't be matched:

abc@absdefgh

Added:
PS: Is there a way to improve this question that it can be more helpful for not experienced users like me?

Body:
var test = [
    '@abcdefjh',
    '@abc',
    'abc@absdefgh',
    '#*$@abc123',
    'abc123',
];
console.log(test.map(function (a) {
  return a + ' :' + /(?:\s|^)@[a-zA-Z0-9]{5,}/.test(a);
}));

If your browser supports it, you can use a negaitve lookbehind:

/(?<!\S)@[a-zA-Z0-9]{5,}/


问:
java.lang.OutOfMemoryError: unable to create new native thread error using ChromeDriver and Chrome through Selenium in Spring boot
We have selenium based web application developed using spring boot. The server is located as VM Instance at google cloud server.

We have a thread base mechanism using Executor. Using selenium we open a chrome browser (headless) to perform operation and for each operation we create new thread.

After facing outOfMemory error, if we restart cloud instance then within 1 hour it breaks again with the same error.

Please find below the snippet which we used to create a new instance of executor service for each request.

```<code>executorService = Executors.newFixedThreadPool(1);
Future<Object> futureDetails = executorService.submit(new Callable<Object>() {

        @Override
        public Object call() throws Exception {

            Object response = client.getDetails(number);

            return response;
        }
    });

    executorService.shutdown();
</code>```

We have (16 vCPUs, 64 GB memory) server configuration.

Please find below the details of the version.

Spring Boot - 2.0.0.RELEASE

Selenium - 3.9.1

Linux - Debian 4.9.130-2 (2018-10-27) x86_64 GNU/Linux

Chrome Driver - 2.35.528139 (47ead77cb35ad2a9a83248b292151462a66cd881)

Google Chrome - 70.0.3538.110

JDK - 1.8.0_232

Please find below resource report using: ulimit -a.

```<code>core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 257648
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 10240
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 257648
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited
</code>```

Also, I did check the memory using: free -m

```<code>              total        used        free      shared  buff/cache   available
Mem:          64433        9479       54490         279         463       54132
Swap:             0           0           0
</code>```

Please find below the error stack trace:

org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.OutOfMemoryError: unable to create new native thread
      at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1006) ~[spring-webmvc-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978) ~[spring-webmvc-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:881) ~[spring-webmvc-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855) ~[spring-webmvc-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-embed-websocket-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter.doFilter(OAuth2AuthenticationProcessingFilter.java:176) [spring-security-oauth2-2.2.1.RELEASE.jar!/:na]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_241]
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_241]
      at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at java.lang.Thread.run(Thread.java:748) [na:1.8.0_241]
  Caused by: java.lang.OutOfMemoryError: unable to create new native thread

Please help me to understand the issue and root cause of this problem. It would be better if you can suggest a solution as well.

Thanks in advance.

答:
This error message...

```<code>java.lang.OutOfMemoryError: unable to create new native thread
</code>```

...implies that JVM was unable to create any new native thread as your system have run OutOfMemory

OutOfMemoryError

Out of Memory error messages can appear when you attempt to start new programs or you try to use programs that are already running, even though you still have plenty of physical and pagefile memory available. When you run a java program or java application, os allocates some memory to the JVM. JVM divides this memory into two parts. One is the Stack Memory and another is the Heap Memory. Stack Memory is used for execution of methods while Heap Memory is used to store the objects. When the heap becomes full, JVM throws java.lang.OutOfMemoryError.

java.lang.OutOfMemoryError

java.lang.OutOfMemoryError is thrown when the Heap Memory is full and JVM is unable to allocate the memory to new objects. As the objects you create in Java are stored in the Heap Memory, so when ever the objects are no more required, they must be removed from the memory. Garbage Collector automatically removes the unwanted objects from the Heap Memory. If your objects have live references, garbage collector doesn’t remove them. It removes only those objects which don’t have live references. in this process if at any point of time there is no space left for new objects in the heap memory then JVM will throw java.lang.OutOfMemoryError.

This usecase

As per your code trials, you have implemented Multithreading using ThreadPoolExecutor to create and use a thread for each request while opening a google-chrome-headless browsing context.

Multithreading using Selenium

As you mentioned, within 1 hour it breaks agian with the same error, I suspect this due to the fact that WebDriver is not thread-safe. Having said that, if you can serialize access to the underlying driver instance, you can share a reference in more than one thread. This is not advisable. But you can always instantiate one WebDriver instance for each thread.

Ideally the issue of thread-safety isn't in your code but in the actual browser bindings. They all assume there will only be one command at a time (e.g. like a real user). But on the other hand you can always instantiate one WebDriver instance for each thread which will launch multiple browsing tabs/windows. Till this point it seems your program is perfect.

Now, different threads can be run on same Webdriver, but then the results of the tests would not be what you expect. The reason behind is, when you use multi-threading to run different tests on different tabs/windows a little bit of thread safety coding is required or else the actions you will perform like click() or send_keys() will go to the opened tab/window that is currently having the focus regardless of the thread you expect to be running. Which essentially means all the test will run simultaneously on the same tab/window that has focus but not on the intended tab/window.

Additional Consideration

However another issue is the incompatibility between the version of the binaries you are using as follows:

You are using chromedriver=2.35

Release Notes of chromedriver=2.35 clearly mentions the following :

Supports Chrome v62-64

You are using chrome=70.0

Release Notes of ChromeDriver vv2.44 clearly mentions the following :

Supports Chrome v69-71

Your Selenium Client version is 3.9.1 which is almost 2 years older.

So there is a clear mismatch between Selenium Client v3.9.1 , ChromeDriver v2.35 and the Chrome Browser v70.0

Solution

Ensure that:

JDK is upgraded to  current levels JDK 8u241.

Selenium is upgraded to  current levels Version 3.141.59.

ChromeDriver is updated to  current ChromeDriver v80.0 level.

Chrome is updated to  current Chrome Version 80.0 level. (as per ChromeDriver v80.0 release notes)

If your base Web Client version is too old, then uninstall it through Revo Uninstaller and install a recent GA and released version of Web Client.

Take a System Reboot.

Always invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully.

tl; dr

How to set memory limit for OOM Killer for chrome?

Body:
We have selenium based web application developed using spring boot. The server is located as VM Instance at google cloud server.

We have a thread base mechanism using Executor. Using selenium we open a chrome browser (headless) to perform operation and for each operation we create new thread.

After facing outOfMemory error, if we restart cloud instance then within 1 hour it breaks again with the same error.

Please find below the snippet which we used to create a new instance of executor service for each request.

executorService = Executors.newFixedThreadPool(1);
Future<Object> futureDetails = executorService.submit(new Callable<Object>() {

        @Override
        public Object call() throws Exception {

            Object response = client.getDetails(number);

            return response;
        }
    });

    executorService.shutdown();

We have (16 vCPUs, 64 GB memory) server configuration.

Please find below the details of the version.

Spring Boot - 2.0.0.RELEASE

Selenium - 3.9.1

Linux - Debian 4.9.130-2 (2018-10-27) x86_64 GNU/Linux

Chrome Driver - 2.35.528139 (47ead77cb35ad2a9a83248b292151462a66cd881)

Google Chrome - 70.0.3538.110

JDK - 1.8.0_232

Please find below resource report using: ulimit -a.

core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 257648
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 10240
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 257648
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

Also, I did check the memory using: free -m

              total        used        free      shared  buff/cache   available
Mem:          64433        9479       54490         279         463       54132
Swap:             0           0           0

Please find below the error stack trace:

org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.OutOfMemoryError: unable to create new native thread
      at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1006) ~[spring-webmvc-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978) ~[spring-webmvc-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:881) ~[spring-webmvc-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:661) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855) ~[spring-webmvc-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-embed-websocket-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter.doFilter(OAuth2AuthenticationProcessingFilter.java:176) [spring-security-oauth2-2.2.1.RELEASE.jar!/:na]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) [spring-security-web-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
      at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-5.0.4.RELEASE.jar!/:5.0.4.RELEASE]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_241]
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_241]
      at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.28.jar!/:8.5.28]
      at java.lang.Thread.run(Thread.java:748) [na:1.8.0_241]
  Caused by: java.lang.OutOfMemoryError: unable to create new native thread

Please help me to understand the issue and root cause of this problem. It would be better if you can suggest a solution as well.

Thanks in advance.

Body:
This error message...

java.lang.OutOfMemoryError: unable to create new native thread

...implies that JVM was unable to create any new native thread as your system have run OutOfMemory

OutOfMemoryError

Out of Memory error messages can appear when you attempt to start new programs or you try to use programs that are already running, even though you still have plenty of physical and pagefile memory available. When you run a java program or java application, os allocates some memory to the JVM. JVM divides this memory into two parts. One is the Stack Memory and another is the Heap Memory. Stack Memory is used for execution of methods while Heap Memory is used to store the objects. When the heap becomes full, JVM throws java.lang.OutOfMemoryError.

java.lang.OutOfMemoryError

java.lang.OutOfMemoryError is thrown when the Heap Memory is full and JVM is unable to allocate the memory to new objects. As the objects you create in Java are stored in the Heap Memory, so when ever the objects are no more required, they must be removed from the memory. Garbage Collector automatically removes the unwanted objects from the Heap Memory. If your objects have live references, garbage collector doesn’t remove them. It removes only those objects which don’t have live references. in this process if at any point of time there is no space left for new objects in the heap memory then JVM will throw java.lang.OutOfMemoryError.

This usecase

As per your code trials, you have implemented Multithreading using ThreadPoolExecutor to create and use a thread for each request while opening a google-chrome-headless browsing context.

Multithreading using Selenium

As you mentioned, within 1 hour it breaks agian with the same error, I suspect this due to the fact that WebDriver is not thread-safe. Having said that, if you can serialize access to the underlying driver instance, you can share a reference in more than one thread. This is not advisable. But you can always instantiate one WebDriver instance for each thread.

Ideally the issue of thread-safety isn't in your code but in the actual browser bindings. They all assume there will only be one command at a time (e.g. like a real user). But on the other hand you can always instantiate one WebDriver instance for each thread which will launch multiple browsing tabs/windows. Till this point it seems your program is perfect.

Now, different threads can be run on same Webdriver, but then the results of the tests would not be what you expect. The reason behind is, when you use multi-threading to run different tests on different tabs/windows a little bit of thread safety coding is required or else the actions you will perform like click() or send_keys() will go to the opened tab/window that is currently having the focus regardless of the thread you expect to be running. Which essentially means all the test will run simultaneously on the same tab/window that has focus but not on the intended tab/window.

Additional Consideration

However another issue is the incompatibility between the version of the binaries you are using as follows:

You are using chromedriver=2.35

Release Notes of chromedriver=2.35 clearly mentions the following :

Supports Chrome v62-64

You are using chrome=70.0

Release Notes of ChromeDriver vv2.44 clearly mentions the following :

Supports Chrome v69-71

Your Selenium Client version is 3.9.1 which is almost 2 years older.

So there is a clear mismatch between Selenium Client v3.9.1 , ChromeDriver v2.35 and the Chrome Browser v70.0

Solution

Ensure that:

JDK is upgraded to  current levels JDK 8u241.

Selenium is upgraded to  current levels Version 3.141.59.

ChromeDriver is updated to  current ChromeDriver v80.0 level.

Chrome is updated to  current Chrome Version 80.0 level. (as per ChromeDriver v80.0 release notes)

If your base Web Client version is too old, then uninstall it through Revo Uninstaller and install a recent GA and released version of Web Client.

Take a System Reboot.

Always invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully.

tl; dr

How to set memory limit for OOM Killer for chrome?


问:
Table without a identity column but this column can't have repeated values
I'm creating a table that needs to have 2 columns. The first column can't be repeated. The thing is, I will insert the value of the first column. How do I create this column?
SQLServer 2005</p>

答:
Create it the same way you would any other column: create table sometable (column1 varchar(10), column2 varchar(20)) or whatever.

Do you mean: How can you get the database to force it to be unique? Either declare it to be the primary key, or create a unique index on the column.

Perhaps you're thinking that a primary key must be auto-generated? There's no such rule. Whether you invent the value yourself or use an autonumber feature has nothing to do with whether a field can be a primary key.

ContentLicense: CC BY-SA 3.0


问:
Compare 2 set of 3D cloud points
I am working on the classification of a 3D point cloud using several python libraries (whitebox, PCL, PDAL). My goal is to classify the soil. The data set has been classified by a company so I am based on their classification as ground truth.

For the moment I am able to classify the soil, to do that I declassified the data set and redo a classification with PDAL. Now I'm at the stage of comparing the two datasets to see the quality of my classification.

I made a script which takes the XYZ coordinates of the 2 sets and puts it in a list and I compare them one by one, however the dataset contains around 5 millions points and it takes 1 minute by 5 points at the begining. After few minutes everything crash. Can anyone give me tips? Here a picture of my clouds The set at the lets is the ground truth and at the right is the one classified by me

答:
Your problem is that you are not using any spatial data structure to ease your point proximity queries. There are several ways you can mitigate this issue, such as KD tree and Octree.

By using such spatial structures you will be able to discard a large portion of unnecessary distance computations, thus improving the performance.

Title: Compare 2 set of 3D cloud points


问:
Spring Session with Hazelcast 4
I'm trying to upgrade to Hazelcast 4.0 in our Spring Boot 2.2.1 application.
We use the @EnableHazelcastHttpSession annotation, which pulls in HazelcastHttpSessionConfiguration, which pulls in HazelcastIndexedSessionRepository from the spring-session-hazelcast jar.
However, this class won't compile because it imports Hazelcast's IMap which has moved to a different package in Hz 4.0.

Is there any way to fix this so that Spring Session works with Hazelcast 4?

答:
I just copied the HazelcastIndexedSessionRepository into my own source code, changed the import from com.hazelcast.core.IMap to com.hazelcast.map.IMap, and swapped the sessionListenerId from String to UUID. If I keep it in the same package, then it loads my class instead of the one in the jar, and everything compiles and works fine.

Edit: We no longer get the SessionExpiredEvent, so something's not quite right, but manual testing shows us that our sessions do time out and force the user to log in again, even across multiple servers.

Title: Spring Session with Hazelcast 4


问:
getopt always return -1 if begin from third arguments
I'm making a simple console that do something based on the command of the second argument. Below is the simplified code. My console however doesn't print any NSLog, and after checking, opt is always -1.

Usage is myconsole firstMethod -t "this is a test string"

```<code>int main(int argc, char *argv[], char *envp[]) {

    NSString *stringArgument = [NSString stringWithFormat:@"%s", argv[1]];

    if([stringArgument caseInsensitiveCompare:@"firstMethod"] == NSOrderedSame) {
        extern char *optarg;
        extern int optind;
        int opt;

        while ((opt = getopt(argc, argv, "t:")) != -1) {
            switch (opt){
                case 't':
                    NSLog(@"Case t");
                break;
                default:
                    NSLog(@"Default");
            }
        }
    }
}
</code>```

Any idea why this failed? Thanks in advance.

答:
You should use Foundation classes instead of getopt if you are developing a console app in Objective-C. With NSUserDefaults you can find the value for t much easier:

```<code>NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *valueForT = [userDefaults stringForKey:@"t"];
NSLog(@"%@", valueForT);
</code>```

To check if user passed firstMethod to your console app use NSProcessInfo:

```<code>NSArray<NSString*> *arguments = [[NSProcessInfo processInfo] arguments];
if (arguments.count >= 2) {
    NSLog(@"%@", arguments[1]);
}
</code>```

Body:
I'm making a simple console that do something based on the command of the second argument. Below is the simplified code. My console however doesn't print any NSLog, and after checking, opt is always -1.

Usage is myconsole firstMethod -t "this is a test string"

int main(int argc, char *argv[], char *envp[]) {

    NSString *stringArgument = [NSString stringWithFormat:@"%s", argv[1]];

    if([stringArgument caseInsensitiveCompare:@"firstMethod"] == NSOrderedSame) {
        extern char *optarg;
        extern int optind;
        int opt;

        while ((opt = getopt(argc, argv, "t:")) != -1) {
            switch (opt){
                case 't':
                    NSLog(@"Case t");
                break;
                default:
                    NSLog(@"Default");
            }
        }
    }
}

Any idea why this failed? Thanks in advance.

Body:
You should use Foundation classes instead of getopt if you are developing a console app in Objective-C. With NSUserDefaults you can find the value for t much easier:

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *valueForT = [userDefaults stringForKey:@"t"];
NSLog(@"%@", valueForT);

To check if user passed firstMethod to your console app use NSProcessInfo:

NSArray<NSString*> *arguments = [[NSProcessInfo processInfo] arguments];
if (arguments.count >= 2) {
    NSLog(@"%@", arguments[1]);
}


问:
How to fix scss styles leaking across pages?
I have a project with the following files:

/* styles/1.scss */
body {
  /* Some other stuff not related to background-color */
}
```

<pre class="lang-css prettyprint-override"><code>/* styles/2.scss */
body {
  background-color: blue;
}
</code>```

```<code>// pages/one.js
import "../styles/1.scss";

export default ()=>(
  <div>Hello, One!</div>
)
</code>```

When visiting localhost:3000/one I notice that the background is blue, even though background-color is never styled in 1.scss!

I believe this has something to do with css modules, so I tried wrapping 2.scss with :local.
Also, I tried renaming 2.scss to 2.module.scss, to no avail.

How do I fix this? Thank you for your help!

Edit:
See this issue on codesandbox: https://codesandbox.io/s/priceless-flower-oswh1

If the background is not orange, click "Go to two" then come back to one, the orange body will persist.

答:
You need some global styles to style the body element or provide css resets.

Option 1:

```<code>// one.js
import Link from "next/link";

export default () => (
  <div>

    <style jsx global>{`
      body {
        background-color: red;
      }
    `}</style>

    Hello, One!
    <Link href="/two">
      <a>Go to two</a>
    </Link>
  </div>
);
</code>```

and

```<code>// two.js
import Link from "next/link";

export default () => (
  <div>

    <style jsx global>{`
      body {
        background-color: orange;
      }
    `}</style>

    Hello, Two!
    <Link href="/one">
      <a>Go to one</a>
    </Link>
  </div>
);
</code>```

You can also keep the style in a separate file and then import it where you need.

Option 2:

```<code>// styles/one_style.js
import css from "styled-jsx/css";

export default css.global`
  body {
    background-color: red;
  }
`;
</code>```

and

```<code>// one.js
import globalStyles from "../styles/one_style";
import Link from "next/link";

export default () => (
  <div>

    <style jsx global>
      {globalStyles}
    </style>

    Hello, One!
    <Link href="/two">
      <a>Go to two</a>
    </Link>
  </div>
);
</code>```

Code Sandbox

I hope this helps.

Body:
I have a project with the following files:

/* styles/1.scss */
body {
  /* Some other stuff not related to background-color */
}

/* styles/2.scss */
body {
  background-color: blue;
}

// pages/one.js
import "../styles/1.scss";

export default ()=>(

Hello, One!

)

When visiting localhost:3000/one I notice that the background is blue, even though background-color is never styled in 1.scss!

I believe this has something to do with css modules, so I tried wrapping 2.scss with :local.
Also, I tried renaming 2.scss to 2.module.scss, to no avail.

How do I fix this? Thank you for your help!

Edit:
See this issue on codesandbox: https://codesandbox.io/s/priceless-flower-oswh1

If the background is not orange, click "Go to two" then come back to one, the orange body will persist.

Body:
You need some global styles to style the body element or provide css resets.

Option 1:

// one.js
import Link from "next/link";

export default () => (
  <div>

    <style jsx global>{`
      body {
        background-color: red;
      }
    `}</style>

    Hello, One!
    <Link href="/two">
      <a>Go to two</a>
    </Link>
  </div>
);

and

// two.js
import Link from "next/link";

export default () => (
  <div>

    <style jsx global>{`
      body {
        background-color: orange;
      }
    `}</style>

    Hello, Two!
    <Link href="/one">
      <a>Go to one</a>
    </Link>
  </div>
);

You can also keep the style in a separate file and then import it where you need.

Option 2:

// styles/one_style.js
import css from "styled-jsx/css";

export default css.global`
  body {
    background-color: red;
  }
`;

and

// one.js
import globalStyles from "../styles/one_style";
import Link from "next/link";

export default () => (
  <div>

    <style jsx global>
      {globalStyles}
    </style>

    Hello, One!
    <Link href="/two">
      <a>Go to two</a>
    </Link>
  </div>
);

Code Sandbox

I hope this helps.


问:
Bigger value without greater than or less than operators
this is just for fun.

Can you give me a way to determine the greater value of two numbers? You can use other operators except greater than or less than operator.

Use any tool you like (programming language, pencil paper, etc.).
And another thing you cannot do the following:

int main()
{
    int num1, num2;
    cin >> num1 >> num2;

    if( (num1-num2) + abs(num1-num2) )
        cout << num1 << " is bigger" << endl;
    else
        cout << num2 << " is bigger" << endl;
    return 0;
}
```

答:
This works for positive integers:</p>

```<code>#! /usr/bin/python
import math

def bigger (a, b):
    length = int (math.log (a, 2) + math.log (b, 2) + 1)
    a = toFixedBitString (a, length)
    b = toFixedBitString (b, length)
    print a, b
    while a:
        if a [0] == '1' and b [0] == '0':
            print "First number is bigger."
            return
        if a [0] == '0' and b [0] == '1':
            print "Second number is bigger."
            return
        a = a [1:]
        b = b [1:]
    print "Numbes are equal."

def toFixedBitString (a, length):
    retVal = ''
    for x in range (length): retVal = ['0', '1'] [a >> x & 1] + retVal
    return retVal
</code>```

Body:
This works for positive integers:

#! /usr/bin/python
import math

def bigger (a, b):
    length = int (math.log (a, 2) + math.log (b, 2) + 1)
    a = toFixedBitString (a, length)
    b = toFixedBitString (b, length)
    print a, b
    while a:
        if a [0] == '1' and b [0] == '0':
            print "First number is bigger."
            return
        if a [0] == '0' and b [0] == '1':
            print "Second number is bigger."
            return
        a = a [1:]
        b = b [1:]
    print "Numbes are equal."

def toFixedBitString (a, length):
    retVal = ''
    for x in range (length): retVal = ['0', '1'] [a >> x & 1] + retVal
    return retVal


问:
Rollback in Postgres
As far as I know, we can't use start transaction within functions, thus we can't use COMMIT and ROLLBACK in functions.

But how then we ROLLBACK by some if-condition?

How then we can perform a sequence of statements in a specific level of isolation? I mean a situation when an application wants to call a SQL (plpgsql) function and that function really needs to be run in a transaction with a certain isolation level. What to do in such a case?

In which cases then it is really practical to run ROLLBACK? Only when we manually write a script, check something and then ROLLBACK manually if we don't like the result. And in the same case, I see the practicality of savepoints. However, I feel like it is a serious constraint.

答:
If you want to rollback the complete transaction, RAISE an exception.

If you only want to roll back part of your work, start a new block with a BEGIN at the point to which you want to roll back and add an EXCEPTION clause to the block.

Since the transaction is started outside the function, the isolation level already has to be set properly when you are in the function.

You can query

```<code>SELECT current_setting('transaction_isolation', TRUE);
</code>```

and throw an error if the setting is not correct.

is too general or too simple to answer.

You roll back a transaction if you have reached a point in your processing where you want to undo everything you have done so far in the transaction.

Often, that happens implicitly rather than explicitly by throwing an error.

Title: Rollback in Postgres

Body:
If you want to rollback the complete transaction, RAISE an exception.

If you only want to roll back part of your work, start a new block with a BEGIN at the point to which you want to roll back and add an EXCEPTION clause to the block.

Since the transaction is started outside the function, the isolation level already has to be set properly when you are in the function.

You can query

SELECT current_setting('transaction_isolation', TRUE);

and throw an error if the setting is not correct.

is too general or too simple to answer.

You roll back a transaction if you have reached a point in your processing where you want to undo everything you have done so far in the transaction.

Often, that happens implicitly rather than explicitly by throwing an error.


问:
Bash script to get specific user(s) id and processes count
I need bash script to count processes of SPECIFIC users or all users. We can enter 0, 1 or more arguments. For example

```<code>./myScript.sh root deamon
</code>```

should execute like this:

```<code>root      92
deamon     8
2 users has total processes: 100
</code>```

If nothing is entered as parameter, then all users should be listed:

```<code>uuidd      1
awkd       2
daemon     1
root     210
kklmn      6
  5 users has total processes: 220
</code>```

What I have till now is script for all users, and it works fine (with some warnings). I just need part where arguments are entered (some kind of filter results). Here is script for all users:

```<code>cntp = 0  #process counter
cntu = 0  #user counter

ps aux |
awk 'NR>1{tot[$1]++; cntp++}
     END{for(id in tot){printf "%s\t%4d\n",id,tot[id]; cntu++}
     printf "%4d users has total processes:%4d\n", cntu, cntp}'
</code>```

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

users=$@
args=()
if [ $# -eq 0 ]; then
  # all processes
  args+=(ax)
else
  # user processes, comma-separated list of users
  args+=(-u${users// /,})
fi

# print the user field without header
args+=(-ouser=)

ps "${args[@]}" | awk '
  { tot[$1]++ }
  END{ for(id in tot){ printf "%s\t%4d\n", id, tot[id]; cntu++ }
  printf "%4d users has total processes:%4d\n", cntu, NR}'
</code>```

The ps arguments are stored in array args and list either all processes with ax or user processes in the form -uuser1,user2
and -ouser= only lists the user field without header.

In the awk script I only removed the NR>1 test and variable cntp which can be replaced by NR.

Possible invocations:

```<code>./myScript.sh
./myScript.sh root daemon
./myScript.sh root,daemon
</code>```

Body:
I need bash script to count processes of SPECIFIC users or all users. We can enter 0, 1 or more arguments. For example

./myScript.sh root deamon

should execute like this:

root      92
deamon     8
2 users has total processes: 100

If nothing is entered as parameter, then all users should be listed:

uuidd      1
awkd       2
daemon     1
root     210
kklmn      6
  5 users has total processes: 220

What I have till now is script for all users, and it works fine (with some warnings). I just need part where arguments are entered (some kind of filter results). Here is script for all users:

cntp = 0  #process counter
cntu = 0  #user counter

ps aux |
awk 'NR>1{tot[$1]++; cntp++}
     END{for(id in tot){printf "%s\t%4d\n",id,tot[id]; cntu++}
     printf "%4d users has total processes:%4d\n", cntu, cntp}'

Body:
#!/bin/bash

users=$@
args=()
if [ $# -eq 0 ]; then
  # all processes
  args+=(ax)
else
  # user processes, comma-separated list of users
  args+=(-u${users// /,})
fi

# print the user field without header
args+=(-ouser=)

ps "${args[@]}" | awk '
  { tot[$1]++ }
  END{ for(id in tot){ printf "%s\t%4d\n", id, tot[id]; cntu++ }
  printf "%4d users has total processes:%4d\n", cntu, NR}'

The ps arguments are stored in array args and list either all processes with ax or user processes in the form -uuser1,user2
and -ouser= only lists the user field without header.

In the awk script I only removed the NR>1 test and variable cntp which can be replaced by NR.

Possible invocations:

./myScript.sh
./myScript.sh root daemon
./myScript.sh root,daemon


问:
How to keep a button inside an image when screen gets smaller
I would like to keep a button inside an image. But when the screen gets smaller the button leaves the image field and just floats around. How could I fix it?

.slider-button {
  background: gold;
  border-radius: 8px;
  color: #262626;
  border: none;
  padding: 22px 72px;
  text-decoration: none;
  font-size: 16px;
  position: absolute;
  left: 25%;
  bottom: 25%;
}

.slider-img {
  position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src = "https://www.mundiario.com/media/mundiario/images/2019/10/02/2019100220032812226.png" / class="slider-img">
<button class="slider-button">Press W to win</button></code>```

答:
Just put the button inside of your image container:</p>

```<code><img src = "https://www.mundiario.com/media/mundiario/images/2019/10/02/2019100220032812226.png" class="slider-img">
<button class="slider-button">Press W to win</button>
</img>
</code>```

Body:
I would like to keep a button inside an image. But when the screen gets smaller the button leaves the image field and just floats around. How could I fix it?

.slider-button {
  background: gold;
  border-radius: 8px;
  color: #262626;
  border: none;
  padding: 22px 72px;
  text-decoration: none;
  font-size: 16px;
  position: absolute;
  left: 25%;
  bottom: 25%;
}

.slider-img {
  position: relative;
}

<button class="slider-button">Press W to win</button>

Body:
Just put the button inside of your image container:

<img src = "https://www.mundiario.com/media/mundiario/images/2019/10/02/2019100220032812226.png" class="slider-img">
<button class="slider-button">Press W to win</button>
</img>