问:
Ionic Capacitor app give me lots of errors
I'm on Windows 10 and I've created a Ionic 5.0.7 app with Capacitor 2.0.0.

I use this command to build app:

```<code>ionic build
</code>```

After, I use this command:

```<code>npx cap sync
</code>```

And, to finish, I use this command to open Android Studio:

```<code>npx cap open android
</code>```

The first problem come during building on Android Studio:

org.gradle.api.reflect.ObjectInstantiationException: Could not create
  an instance of type
  com.novoda.release.internal.compat.gradle5_3.AndroidSoftwareComponentCompat_Gradle_5_3.

Caused by: org.gradle.api.reflect.ObjectInstantiationException: Could not create
  an instance of type
  com.novoda.release.internal.compat.gradle5_3.AndroidSoftwareComponentCompat_Gradle_5_3.

And...

java.lang.NoClassDefFoundError:
  org/gradle/api/internal/java/usagecontext/LazyConfigurationUsageContext

Caused by: java.lang.NoClassDefFoundError:
  org/gradle/api/internal/java/usagecontext/LazyConfigurationUsageContext

I've other random errors... It's weird...

答:
Update

Check  @Carl Pool 's answer
They fixed it in the new capacitor Version, no need to downgrade anymore

Old Answer

To fix this downgrade Gradle and Gradle plugin in Android Studio.

File -> Project Structure -> Project

If you keep the plugin to 4.0.0 it will require a minimum Gradle version of 6 so put it back to a lower version like 3.6.3

Version 6 of Gradle does not support LazyConfigurationUsageContext as mentionened by @NishaBhat, so use 5.6.4 instead.

This issue currently has a ticket on Github:
https://github.com/ionic-team/capacitor/issues/3003

Body:
I'm on Windows 10 and I've created a Ionic 5.0.7 app with Capacitor 2.0.0.

I use this command to build app:

ionic build

After, I use this command:

npx cap sync

And, to finish, I use this command to open Android Studio:

npx cap open android

The first problem come during building on Android Studio:

org.gradle.api.reflect.ObjectInstantiationException: Could not create
  an instance of type
  com.novoda.release.internal.compat.gradle5_3.AndroidSoftwareComponentCompat_Gradle_5_3.

Caused by: org.gradle.api.reflect.ObjectInstantiationException: Could not create
  an instance of type
  com.novoda.release.internal.compat.gradle5_3.AndroidSoftwareComponentCompat_Gradle_5_3.

And...

java.lang.NoClassDefFoundError:
  org/gradle/api/internal/java/usagecontext/LazyConfigurationUsageContext

Caused by: java.lang.NoClassDefFoundError:
  org/gradle/api/internal/java/usagecontext/LazyConfigurationUsageContext

I've other random errors... It's weird...


来源: stackexchange

问:
How to Determine the K^th character in the concatenated string
Given a list that contains N strings of lowercase English alphabets. Any number of contiguous strings can be found together to form a new string. The grouping function accepts two integers X and Y and concatenates all strings between indices X and Y (inclusive) and returns a modified string in which the alphabets of the concatenated string are sorted.

You are asked Q questions each containing two integers L and R. Determine the $K^{th}$. character in the concatenated string if we pass L and R to the grouping function.

Input Format

First Line: N(number of strings in the list)

Next N lines: String $S_i$

Next line Q(number of questions)

Next Q lines : Three space-separated integers L, R and K

Output Format

For each question, print the $K^{th}$ character of the concatenated string in a new line.

Sample Test Cases

```<code>Sample Input                 Sample Output

5                                 c
aaaaa                             d
bbbbb                             e
ccccc
ddddd
eeeee
3
3 3 3
1 5 16
3 5 15
</code>```

Explanation

Q1 Grouped String - ccccc. 3rd character is c

Q2 Grouped String - aaaaabbbbbcccccdddddeeeee. 16th character is d

Q3 Grouped String - cccccdddddeeeee. 15th character is e

Note: It is always guaranteed that the $K^{th}$ position is valid

CONTEXT:

This question came up in a Hiring Challenge I did back in October. I just remembered this question and thought I'd have a go but I am still struggling with it.

There are no worked solutions online so I'm reaching out to this website as a final resort. Any help would be greatly appreciated. Thank you!

答:
Once you have understood the problem, the code itself is straightforward. Here, I'll demonstrate using R.

Let's start by defining S, the set of strings we are given:

S <- letters[1:5]
S <- paste0(S, S, S, S, S)
S
#> [1] "aaaaa" "bbbbb" "ccccc" "ddddd" "eeeee"
```

<p>Now we can concatenate the <em>Lth</em> to the <em>Rth</em> string of a vector of strings, <em>Str</em> very easily by doing</p>

<pre class="lang-r prettyprint-override"><code>concat <- function(Str, L, R) paste0(Str[L:R], collapse = "")
</code>```

So, for example if we were given L = 1 and R = 2, we could do:

concat(S, 1, 2)
[1] "aaaaabbbbb"
```

<p>Furthermore, we can find the character at position <em>K</em> of any string <em>Str</em> like this:</p>

<pre class="lang-r prettyprint-override"><code>char_at <- function(Str, K) substr(Str, K, K)
</code>```

So if we combine these two, we get:

f <- function(L, R, K) char_at(concat(S, L, R), K)
```

<p>For example:</p>

<pre class="lang-r prettyprint-override"><code># Q1
f(3, 3, 3)
#> [1] "c"

# Q2
f(1, 5, 16)
#> [1] "d"

# Q3
f(3, 5, 15)
#> [1] "e"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Given a list that contains N strings of lowercase English alphabets. Any number of contiguous strings can be found together to form a new string. The grouping function accepts two integers X and Y and concatenates all strings between indices X and Y (inclusive) and returns a modified string in which the alphabets of the concatenated string are sorted.

You are asked Q questions each containing two integers L and R. Determine the $K^{th}$. character in the concatenated string if we pass L and R to the grouping function.

Input Format

First Line: N(number of strings in the list)

Next N lines: String $S_i$

Next line Q(number of questions)

Next Q lines : Three space-separated integers L, R and K

Output Format

For each question, print the $K^{th}$ character of the concatenated string in a new line.

Sample Test Cases

Sample Input                 Sample Output

5                                 c
aaaaa                             d
bbbbb                             e
ccccc
ddddd
eeeee
3
3 3 3
1 5 16
3 5 15

Explanation

Q1 Grouped String - ccccc. 3rd character is c

Q2 Grouped String - aaaaabbbbbcccccdddddeeeee. 16th character is d

Q3 Grouped String - cccccdddddeeeee. 15th character is e

Note: It is always guaranteed that the $K^{th}$ position is valid

CONTEXT:

This question came up in a Hiring Challenge I did back in October. I just remembered this question and thought I'd have a go but I am still struggling with it.

There are no worked solutions online so I'm reaching out to this website as a final resort. Any help would be greatly appreciated. Thank you!

Body:
Once you have understood the problem, the code itself is straightforward. Here, I'll demonstrate using R.

Let's start by defining S, the set of strings we are given:

S <- letters[1:5]
S <- paste0(S, S, S, S, S)
S
#> [1] "aaaaa" "bbbbb" "ccccc" "ddddd" "eeeee"

Now we can concatenate the Lth to the Rth string of a vector of strings, Str very easily by doing

concat <- function(Str, L, R) paste0(Str[L:R], collapse = "")

So, for example if we were given L = 1 and R = 2, we could do:

concat(S, 1, 2)
[1] "aaaaabbbbb"

Furthermore, we can find the character at position K of any string Str like this:

char_at <- function(Str, K) substr(Str, K, K)

So if we combine these two, we get:

f <- function(L, R, K) char_at(concat(S, L, R), K)

For example:

# Q1
f(3, 3, 3)
#> [1] "c"

# Q2
f(1, 5, 16)
#> [1] "d"

# Q3
f(3, 5, 15)
#> [1] "e"


问:
I am creating an ios app using xcode without using the story board but i have a problem, i need to make my displays full screen but its not working
Im currently creating an app using xcode (Swift) but most of my displays are not full screen and some are.
my projects so far includes four viewer controllers:

login

sign up

forgot password

and home

When i launch the app you are able to sign in and taken to the home screen into your account (Which i managed to make full screen), however when the app is launched and a user is not signed in you are presented with the sign in page with two buttons:

"Dont have an account? Sign up" -> which takes you to the sign up form

"Forgot password" -> which takes you to the forgot password form

these two buttons do not work when the app is launched but when a user is signed into an account and logs out and taken back the to sign in form the two above button now work.
im not sure why this happens and not sure how to fix this can someone please help?

this is the code that allows you to switch to the different controllers:

from the sign in form to get to the sign up form

```<code>let signUpButton: UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("Don't have an account? Sign up", for: .normal)
    button.setTitleColor(UIColor(red: 170/255, green: 170/255, blue: 170/255, alpha: 1), for: .normal)
    button.addTarget(self, action: #selector(handleShowSignUp), for: .touchUpInside)
    return button
}()

@objc func handleShowSignUp() {
      let signUpVC = SignUpVC()
        self.navigationController?.pushViewController(signUpVC, animated: true)
  }
</code>```

from the sign in form to get to the forgot password form:

```<code>let forgotPasswordButton: UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("Forgot password?", for: .normal)
    button.setTitleColor(UIColor(red: 170/255, green: 170/255, blue: 170/255, alpha: 1), for: .normal)
    button.addTarget(self, action: #selector(forgotPassword), for: .touchUpInside)
    return button
}()

@objc func forgotPassword() {
    let forgotPassword = ForgotPasswordVC()
    self.navigationController?.pushViewController(forgotPassword, animated: true)

     }
</code>```

Going back to my original question all the above is full screen until you log out from there everything goes back to the new card layout where you can see the previous view in the background and i have tried to add this line to all of the controllers but it doesn't seem to be working:

```<code>logInVC.modalPresentationStyle = .fullScreen
</code>```

(obviously formatted to the specific viewer controller)

how do i fix this?

i haven't added anything to my appdelegate file other than:

```<code>FirebaseApp.configure()
</code>```

i have added the following to my scene delegate:

```<code>       guard let mainScene = (scene as? UIWindowScene) else { return }
            window = UIWindow(windowScene: mainScene)
            let mainTabVC = MainTabVC()
            window?.rootViewController = UINavigationController(rootViewController: mainTabVC)
            window?.makeKeyAndVisible()
</code>```

答:
Use

```<code>navController.modalPresentationStyle = .fullScreen
</code>```

instead of

```<code>logInVC.modalPresentationStyle = .fullScreen
</code>```

Write this code before presenting navController.

I hope this will help you

Body:
Im currently creating an app using xcode (Swift) but most of my displays are not full screen and some are.
my projects so far includes four viewer controllers:

login

sign up

forgot password

and home

When i launch the app you are able to sign in and taken to the home screen into your account (Which i managed to make full screen), however when the app is launched and a user is not signed in you are presented with the sign in page with two buttons:

"Dont have an account? Sign up" -> which takes you to the sign up form

"Forgot password" -> which takes you to the forgot password form

these two buttons do not work when the app is launched but when a user is signed into an account and logs out and taken back the to sign in form the two above button now work.
im not sure why this happens and not sure how to fix this can someone please help?

this is the code that allows you to switch to the different controllers:

from the sign in form to get to the sign up form

let signUpButton: UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("Don't have an account? Sign up", for: .normal)
    button.setTitleColor(UIColor(red: 170/255, green: 170/255, blue: 170/255, alpha: 1), for: .normal)
    button.addTarget(self, action: #selector(handleShowSignUp), for: .touchUpInside)
    return button
}()

@objc func handleShowSignUp() {
      let signUpVC = SignUpVC()
        self.navigationController?.pushViewController(signUpVC, animated: true)
  }

from the sign in form to get to the forgot password form:

let forgotPasswordButton: UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("Forgot password?", for: .normal)
    button.setTitleColor(UIColor(red: 170/255, green: 170/255, blue: 170/255, alpha: 1), for: .normal)
    button.addTarget(self, action: #selector(forgotPassword), for: .touchUpInside)
    return button
}()

@objc func forgotPassword() {
    let forgotPassword = ForgotPasswordVC()
    self.navigationController?.pushViewController(forgotPassword, animated: true)

     }

Going back to my original question all the above is full screen until you log out from there everything goes back to the new card layout where you can see the previous view in the background and i have tried to add this line to all of the controllers but it doesn't seem to be working:

logInVC.modalPresentationStyle = .fullScreen

(obviously formatted to the specific viewer controller)

how do i fix this?

i haven't added anything to my appdelegate file other than:

FirebaseApp.configure()

i have added the following to my scene delegate:

       guard let mainScene = (scene as? UIWindowScene) else { return }
            window = UIWindow(windowScene: mainScene)
            let mainTabVC = MainTabVC()
            window?.rootViewController = UINavigationController(rootViewController: mainTabVC)
            window?.makeKeyAndVisible()

Body:
Use

navController.modalPresentationStyle = .fullScreen

instead of

logInVC.modalPresentationStyle = .fullScreen

Write this code before presenting navController.

I hope this will help you


问:
turn ... of a R function into a string
In R, I want to write a function that takes in set of arguments, but doesn't evaluate them and returns the entire set of arguments as a string. I have found the following way to do this:

```<code>ff = function(...) {
  dots = dplyr::enquos(...)
  strs = sub("^[~]","=",sapply(dots,deparse))
  return(paste(paste(names(strs),strs,sep=""),collapse=","))
}
</code>```

but it seems like there must be an easier, less fragile way to do this that does not depend on dplyr using the base R functions quote and deparse, but I can't figure it out.

Is there a better way to do this?

答:
Building off of Konrad's solution above, here is the final function that I am using:

```<code>ff = function (...) {
  args = match.call(expand.dots=FALSE)$...
  argvalues = vapply(args, deparse, character(1L))
  paste(ifelse(names(args)=="",argvalues,
               paste(names(args), argvalues, sep = ' = ')),
        collapse = ', ')
}
</code>```

Using this, I can do the following:

```<code>> ff(a=1,b=zzz)
[1] "a = 1, b = zzz"
> ff(a=1,zzz)
[1] "a = 1, zzz"
</code>```

Title: turn ... of a R function into a string

Body:
In R, I want to write a function that takes in set of arguments, but doesn't evaluate them and returns the entire set of arguments as a string. I have found the following way to do this:

ff = function(...) {
  dots = dplyr::enquos(...)
  strs = sub("^[~]","=",sapply(dots,deparse))
  return(paste(paste(names(strs),strs,sep=""),collapse=","))
}

but it seems like there must be an easier, less fragile way to do this that does not depend on dplyr using the base R functions quote and deparse, but I can't figure it out.

Is there a better way to do this?

Body:
Building off of Konrad's solution above, here is the final function that I am using:

ff = function (...) {
  args = match.call(expand.dots=FALSE)$...
  argvalues = vapply(args, deparse, character(1L))
  paste(ifelse(names(args)=="",argvalues,
               paste(names(args), argvalues, sep = ' = ')),
        collapse = ', ')
}

Using this, I can do the following:

> ff(a=1,b=zzz)
[1] "a = 1, b = zzz"
> ff(a=1,zzz)
[1] "a = 1, zzz"


问:
How do you test code that is not a model or controller
I have a class defined in a file my Rails project's lib dir that will implement a bunch of utility functions as class methods. I'd like to write tests against those methods using Test::Unit and have them run as part of the project's regular testing routine.

I tried sticking a file at the top level of the test dir...

```<code>require 'test_helper'

class UtilsTest < ActiveSupport::TestCase
  should 'be true' do
    assert false
  end
end
</code>```

...but that didn't work. The test didn't run.

What is the normal way to test code that is not one of the regular parts of Rails?

答: I just stick them in test/unit.  I'm not sure if that's the "correct" approach, but it seems to work for me...</p>

OwnerDisplayName: Ethan

ContentLicense: CC BY-SA 2.5

Body:
I have a class defined in a file my Rails project's lib dir that will implement a bunch of utility functions as class methods. I'd like to write tests against those methods using Test::Unit and have them run as part of the project's regular testing routine.

I tried sticking a file at the top level of the test dir...

require 'test_helper'

class UtilsTest < ActiveSupport::TestCase
  should 'be true' do
    assert false
  end
end

...but that didn't work. The test didn't run.

What is the normal way to test code that is not one of the regular parts of Rails?

OwnerDisplayName: Scotty Allen


问:
adding placeholder variables to the appSettings.json file
So when generating a new .NET Core web project there is an appSettings.json and appSettings.Development.json for configuration parts. By default, those are not ignored by the .gitignore file so I think they should stay in the repository.

I'm using a database and want to store my connection string to those files. Obviously the parameters contain sensitive information and shouldn't be in the repository. If the environment is the development I can add the local connection string to the appSettings.Development.json (but then every developer would have to use the same settings until I add the dev file to the .gitignore)

```<code>"Database": {
    "Server": "localhost",
    "Port": 5432,
    "UserId": "admin",
    "Password": "admin",
    "Name": "myDb"
}
</code>```

How can I set-up the appSettings.json for production or other purposes? Is there a way for something like

```<code>"Database": {
    "Server": "$DB_SERVER",
    "Port": "$DB_PORT",
    "UserId": "$DB_USER_ID",
    "Password": "$DB_PASSWORD",
    "Name": "$DB_NAME"
}
</code>```

and those placeholders would be replaced with the values from the environment variables?

答:
If you include any sort of sensitive information (like production connection strings) in source control they are usually considered compromised.

You have two options:

First option wopuld be to go for appsettings file override values. It is supported by all the established CI/CD tools. That step usually happen in the release pipeline right before you deploy.In this scenario you store your values encrypted in the CD tool.

Second option is to use Environment variables. In this case for development purposes you can just pass this variables in the launchSettings.json file. And you set the values of your environment variables in the server running your application.

If you want to use Environment variables you do not need place holders in appsettings file. You can read them directly

```<code>Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT ")
</code>```

Body:
So when generating a new .NET Core web project there is an appSettings.json and appSettings.Development.json for configuration parts. By default, those are not ignored by the .gitignore file so I think they should stay in the repository.

I'm using a database and want to store my connection string to those files. Obviously the parameters contain sensitive information and shouldn't be in the repository. If the environment is the development I can add the local connection string to the appSettings.Development.json (but then every developer would have to use the same settings until I add the dev file to the .gitignore)

"Database": {
    "Server": "localhost",
    "Port": 5432,
    "UserId": "admin",
    "Password": "admin",
    "Name": "myDb"
}

How can I set-up the appSettings.json for production or other purposes? Is there a way for something like

"Database": {
    "Server": "$DB_SERVER",
    "Port": "$DB_PORT",
    "UserId": "$DB_USER_ID",
    "Password": "$DB_PASSWORD",
    "Name": "$DB_NAME"
}

and those placeholders would be replaced with the values from the environment variables?

Body:
If you include any sort of sensitive information (like production connection strings) in source control they are usually considered compromised.

You have two options:

First option wopuld be to go for appsettings file override values. It is supported by all the established CI/CD tools. That step usually happen in the release pipeline right before you deploy.In this scenario you store your values encrypted in the CD tool.

Second option is to use Environment variables. In this case for development purposes you can just pass this variables in the launchSettings.json file. And you set the values of your environment variables in the server running your application.

If you want to use Environment variables you do not need place holders in appsettings file. You can read them directly

Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT ")


问:
How to sort data numbers with for-each group in XSLT
How to sort data numbers with xsl:for-each?

Input XML

```<code> <root>
    <p content-type="Sta_index2"><bold>6000–6243</bold></p>
    <p content-type="Sta_index2"><bold>5000–5158</bold></p>
    <p content-type="Sta_index2"><bold>6068(e)</bold></p>
    <p content-type="Sta_index2"><bold>6148</bold></p>
    <p content-type="Sta_index2"><bold>6200–6206</bold></p>
    <p content-type="Sta_index2"><bold>6203(b)</bold></p>
    <p content-type="Sta_index2"><bold>480</bold></p>
    <p content-type="Sta_index2"><bold>6500</bold></p>
    <p content-type="Sta_index2"><bold>6450</bold></p>
    <p content-type="Sta_index2"><bold>6500–6592</bold></p>
    <p content-type="Sta_index2"><bold>6501(f)(1)</bold></p>
    <p content-type="Sta_index2"><bold>6533.5</bold></p>
    <p content-type="Sta_index2"><bold>10018.15</bold></p>
    <p content-type="Sta_index2"><bold>10018.14</bold></p>
</root>
</code>```

XSLT

```<code><xsl:template match="root">
    <xsl:copy>
        <xsl:for-each select="p">
            <xsl:sort select="number(bold)" data-type="number" order="ascending"/>
            <xsl:text>
</xsl:text>
        <xsl:copy>
            <xsl:copy-of select="@*"/>
            <xsl:apply-templates select="node()"/>
        </xsl:copy>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>
</code>```

Expected Output

```<code>    <root>
    <p content-type="Sta_index2"><bold>480</bold></p>
    <p content-type="Sta_index2"><bold>5000–5158</bold></p>
    <p content-type="Sta_index2"><bold>6000–6243</bold></p>
    <p content-type="Sta_index2"><bold>6068(e)</bold></p>
    <p content-type="Sta_index2"><bold>6148</bold></p>
    <p content-type="Sta_index2"><bold>6200–6206</bold></p>
    <p content-type="Sta_index2"><bold>6203(b)</bold></p>
    <p content-type="Sta_index2"><bold>6450</bold></p>
    <p content-type="Sta_index2"><bold>6500</bold></p>
    <p content-type="Sta_index2"><bold>6500–6592</bold></p>
    <p content-type="Sta_index2"><bold>6501(f)(1)</bold></p>
    <p content-type="Sta_index2"><bold>6533.5</bold></p>
    <p content-type="Sta_index2"><bold>10018.14</bold></p>
    <p content-type="Sta_index2"><bold>10018.15</bold></p>
</root>
</code>```

CODE: https://xsltfiddle.liberty-development.net/3NSTbfj/29

答:
As Sebastien has indicated in a comment, you can try to strip anything after the decimal values you want to use for sorting:

```<code><xsl:template match="root">
    <xsl:copy>
        <xsl:perform-sort select="p">
            <xsl:sort select="bold => replace('[^0-9.].*$', '') => xs:decimal()"/>
        </xsl:perform-sort>
    </xsl:copy>
</xsl:template>
</code>```

https://xsltfiddle.liberty-development.net/3NSTbfj/30

Body:
How to sort data numbers with xsl:for-each?

Input XML

 <root>

<bold>6000–6243</bold>

<bold>5000–5158</bold>

<bold>6068(e)</bold>

<bold>6148</bold>

<bold>6200–6206</bold>

<bold>6203(b)</bold>

<bold>480</bold>

<bold>6500</bold>

<bold>6450</bold>

<bold>6500–6592</bold>

<bold>6501(f)(1)</bold>

<bold>6533.5</bold>

<bold>10018.15</bold>

<bold>10018.14</bold>

</root>

XSLT

<xsl:template match="root">
    <xsl:copy>
        <xsl:for-each select="p">
            <xsl:sort select="number(bold)" data-type="number" order="ascending"/>
            <xsl:text>
</xsl:text>
        <xsl:copy>
            <xsl:copy-of select="@*"/>
            <xsl:apply-templates select="node()"/>
        </xsl:copy>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

Expected Output

    <root>

<bold>480</bold>

<bold>5000–5158</bold>

<bold>6000–6243</bold>

<bold>6068(e)</bold>

<bold>6148</bold>

<bold>6200–6206</bold>

<bold>6203(b)</bold>

<bold>6450</bold>

<bold>6500</bold>

<bold>6500–6592</bold>

<bold>6501(f)(1)</bold>

<bold>6533.5</bold>

<bold>10018.14</bold>

<bold>10018.15</bold>

</root>

CODE: https://xsltfiddle.liberty-development.net/3NSTbfj/29

Body:
As Sebastien has indicated in a comment, you can try to strip anything after the decimal values you want to use for sorting:

<xsl:template match="root">
    <xsl:copy>
        <xsl:perform-sort select="p">
            <xsl:sort select="bold => replace('[^0-9.].*$', '') => xs:decimal()"/>
        </xsl:perform-sort>
    </xsl:copy>
</xsl:template>

https://xsltfiddle.liberty-development.net/3NSTbfj/30


问:
duplicate boolean value in swagger ui
I have created a Rest API endpoint to create an employee with isAvailable Boolean type as a property of bean class.
But in swagger UI it shows duplicate, one available and another one isAvailable.
That is very weird, below is the sample.

```<code>{
  available: true,
  "address": {
    "city": "string",
    "country": "string",
    "id": 0,
    "postalCode": "string",
    "street": "string"
  },
  "employeeId": 0,
  "employeeEmail": "string",
  "firstname": "string",
  "lastname": "string",
  "telephone": "string",
  "isAvailable": true
}
</code>```

I searched on swagger docs but did not find any clue nor in any blog post. I must not be the first one to encounter this problem.
How to solve this problem?

答:
Swagger strips the "is" if a variable is a boolean.
Can be fixed by annotating the getter:</p>

```<code>@JsonGetter("isAvailable")
public boolean isAvailable() {
    return isAvailable;
}
</code>```

Title: duplicate boolean value in swagger ui

Body:
I have created a Rest API endpoint to create an employee with isAvailable Boolean type as a property of bean class.
But in swagger UI it shows duplicate, one available and another one isAvailable.
That is very weird, below is the sample.

{
  available: true,
  "address": {
    "city": "string",
    "country": "string",
    "id": 0,
    "postalCode": "string",
    "street": "string"
  },
  "employeeId": 0,
  "employeeEmail": "string",
  "firstname": "string",
  "lastname": "string",
  "telephone": "string",
  "isAvailable": true
}

I searched on swagger docs but did not find any clue nor in any blog post. I must not be the first one to encounter this problem.
How to solve this problem?

Body:
Swagger strips the "is" if a variable is a boolean.
Can be fixed by annotating the getter:

@JsonGetter("isAvailable")
public boolean isAvailable() {
    return isAvailable;
}


问:
Create discrete color bar with varying interval widths and no spacing between legend levels
I'd like to reproduce this color scale in ggplot2:

(Source)

In the past I have found that creating discrete color scales with labels in-between in ggplot2 can be tricky.

Can this be accomplished at all? A similar, but not completely identical question I have recently posed is this one.

答:
You can use

```<code>scale_fill_gradientn (guide = guide_colourbar(nbin = 255))
</code>```

to achieve.

you can set nbin to whatever you like.

Body:
You can use

scale_fill_gradientn (guide = guide_colourbar(nbin = 255))

to achieve.

you can set nbin to whatever you like.


问:
What is the point of Node.js
Ok this is probably a little blunt and to the point, but what is the point/need for Node.js

I've noticed it mainly through CloudFoundry but just not too sure what its supposed to be doing. However I am guessing its probably something pretty big as why else would VMWare be supporting it.

Thanks in advance.

答:
Node leverages Javascript's first class functions to allow you to program the server in a dynamic scripting language while getting very competitive performance.

Node isn't as fast as Haskell, Erlang or Go. But it is competitive with Java, and it outperforms Ruby, Python and PHP.

Haskell, Erlang, Go, Java, Ruby, and Python all have evented IO webframeworks, but they also have blocking libraries to serve as pitfalls.

Despite it's warts, Javascript is the lingua franca of the web and since browsers are evented, not only is Javascript built for evented style programming, most web developers are used to writing evented Javascript.

Also check out this register article: http://www.theregister.co.uk/2011/03/01/the_rise_and_rise_of_node_dot_js/

ContentLicense: CC BY-SA 3.0

Title: What is the point of Node.js


问:
How to prevent event bubbling in Angular 8?
Please understand, I'm new in Angular and developing overall so this might be a very unexperienced problem.

The problem is that I am calling a function from a component's HTML template file with $event as an argument and it ends up capturing a different element from the one I wished to target. That exact element I am calling the event on has two children...

HTML:

```<code>          <div class="cursorPointer" (click)="answeredQuestion($event)">
                <div id="chickenTenders" class="backImageCov question_0Img"></div>
                <h3 class="questionSubTitle">Chicken Tenders</h3>
           </div>
</code>```

I am aiming to retrieve the div container with "cursorPointer" every single time I call this event. I hypothesize that it's an event bubbling problem because if I were to click on the div container with the id of "chickenTenders", that same container will be returned by the $event argument in the answeredQuestion()  function on my ts file...

I have already searched online (Stop mouse event propagation) but in this example the student is asking a question that came from a directive so I got confused as to what the solution could be...

I have already tried:

```<code>(click)="answeredQuestion(0, $event);false"
</code>```

And:

```<code>(click)="answeredQuestion(0, $event); $event.stopPropagation()"
</code>```

However, none seem to help the cause. Putting it simply, I hope the solution would give me a simple way to get access to that parent element (
) every single time, even if the child elements are the ones clicked.

Thank you for your time guys, I appreciate it.

答:
You can handle the event propagation(bubbling) in angular.

Use this in your child component.

```<code>onClick(event: Event) {
    event.stopPropagation();
    // do your stuff
  }
</code>```

Body:
Please understand, I'm new in Angular and developing overall so this might be a very unexperienced problem.

The problem is that I am calling a function from a component's HTML template file with $event as an argument and it ends up capturing a different element from the one I wished to target. That exact element I am calling the event on has two children...

HTML:

Chicken Tenders

I am aiming to retrieve the div container with "cursorPointer" every single time I call this event. I hypothesize that it's an event bubbling problem because if I were to click on the div container with the id of "chickenTenders", that same container will be returned by the $event argument in the answeredQuestion()  function on my ts file...

I have already searched online (Stop mouse event propagation) but in this example the student is asking a question that came from a directive so I got confused as to what the solution could be...

I have already tried:

(click)="answeredQuestion(0, $event);false"

And:

(click)="answeredQuestion(0, $event); $event.stopPropagation()"

However, none seem to help the cause. Putting it simply, I hope the solution would give me a simple way to get access to that parent element (
) every single time, even if the child elements are the ones clicked.

Thank you for your time guys, I appreciate it.

Body:
You can handle the event propagation(bubbling) in angular.

Use this in your child component.

onClick(event: Event) {
    event.stopPropagation();
    // do your stuff
  }


问:
How to loop through a json response with PL/SQL?
I am facing an issue when my json response is like this:

```<code>declare
sample_json   varchar2 (32767)
        := '{"items": [{"NAME":"AUDI","YEAR":"2000"},{"NAME":"BMW","YEAR":"2010"}]}';
BEGIN
for rec IN (
     select j.name,j.year
       from json_table(sample_json,'$[*]' COLUMNS
        name varchar2(20) PATH '$.items[0].NAME',
        year NUMBER       PATH '$.items[0].YEAR'
       ) j  )
     LOOP
       dbms_output.put_line (rec.name||','||rec.year);
     END LOOP;
END;
/
</code>```

I have to use $.items[0].NAME to get one value but i want to make it dynamic so that it can loop to give me both the values.

答:
I can not fully understand your needs about making your query dynamic but maybe below script can give you some idea about using JSON_VALUE and writing dynamic plsql statements.

```<code>DECLARE
   SAMPLE_JSON     VARCHAR2 (32767)
      := '{"items": [{"NAME":"AUDI","YEAR":"2000"},{"NAME":"BMW","YEAR":"2010"}]}';
   V_RESULT_NAME   VARCHAR2 (500);
   V_RESULT_YEAR   VARCHAR2 (500);
   V_KEY           VARCHAR (200) := 'items[0].NAME';
   V_KEY2          VARCHAR (200) := 'items[0].YEAR';
BEGIN
   EXECUTE IMMEDIATE 'SELECT JSON_VALUE(:1,''$.' || V_KEY || ''')  FROM DUAL'
      INTO V_RESULT_NAME
      USING SAMPLE_JSON;

   DBMS_OUTPUT.PUT_LINE (V_RESULT_NAME );
END;
/
</code>```

Here you can dynamically insert values from json data into your table.

```<code>DECLARE
SAMPLE_JSON   VARCHAR2 (32767)
        := '{"items": [{"NAME":"AUDI","YEAR":"2000"},{"NAME":"BMW","YEAR":"2010"}]}';
BEGIN
FOR REC IN (
     SELECT J.NAME,J.YEAR
       FROM JSON_TABLE(SAMPLE_JSON,'$[*]' COLUMNS
        NAME VARCHAR2(20) PATH '$.items[0].NAME',
        YEAR NUMBER       PATH '$.items[0].YEAR'
       ) J  )
     LOOP
     EXECUTE IMMEDIATE 'INSERT INTO YOUR_TABLE(NAME,YEAR) VALUES('||REC.NAME||','||REC.YEAR||'); COMMIT;'
--       DBMS_OUTPUT.PUT_LINE (REC.NAME||','||REC.YEAR);
     END LOOP;
END;
/

</code>```

Without using index.

```<code>DECLARE
SAMPLE_JSON   VARCHAR2 (32767)
        := '{"items": [{"NAME":"AUDI","YEAR":"2000"},{"NAME":"BMW","YEAR":"2010"},{"NAME":"TOFAS","YEAR":"1995"}]}';
BEGIN
FOR REC IN (
     SELECT J.NAME,J.YEAR
       FROM JSON_TABLE(SAMPLE_JSON,'$.items[*]' COLUMNS
        NAME VARCHAR2(20) PATH '$.NAME',
        YEAR NUMBER       PATH '$.YEAR'
       ) J  )
     LOOP
     --EXECUTE IMMEDIATE 'INSERT INTO YOUR_TABLE(NAMEE,YEARR) VALUES('||REC.NAME||','||REC.YEAR||'); COMMIT;';
      DBMS_OUTPUT.PUT_LINE (REC.NAME||','||REC.YEAR);
     END LOOP;
END;
/
</code>```

Note: If you want to dynamically describe columns from your json data as i know of oracle can not do that. You have to describe json tags one by one as JSON_TABLE columns before use them.

Body:
I am facing an issue when my json response is like this:

declare
sample_json   varchar2 (32767)
        := '{"items": [{"NAME":"AUDI","YEAR":"2000"},{"NAME":"BMW","YEAR":"2010"}]}';
BEGIN
for rec IN (
     select j.name,j.year
       from json_table(sample_json,'$[*]' COLUMNS
        name varchar2(20) PATH '$.items[0].NAME',
        year NUMBER       PATH '$.items[0].YEAR'
       ) j  )
     LOOP
       dbms_output.put_line (rec.name||','||rec.year);
     END LOOP;
END;
/

I have to use $.items[0].NAME to get one value but i want to make it dynamic so that it can loop to give me both the values.

Body:
I can not fully understand your needs about making your query dynamic but maybe below script can give you some idea about using JSON_VALUE and writing dynamic plsql statements.

DECLARE
   SAMPLE_JSON     VARCHAR2 (32767)
      := '{"items": [{"NAME":"AUDI","YEAR":"2000"},{"NAME":"BMW","YEAR":"2010"}]}';
   V_RESULT_NAME   VARCHAR2 (500);
   V_RESULT_YEAR   VARCHAR2 (500);
   V_KEY           VARCHAR (200) := 'items[0].NAME';
   V_KEY2          VARCHAR (200) := 'items[0].YEAR';
BEGIN
   EXECUTE IMMEDIATE 'SELECT JSON_VALUE(:1,''$.' || V_KEY || ''')  FROM DUAL'
      INTO V_RESULT_NAME
      USING SAMPLE_JSON;

   DBMS_OUTPUT.PUT_LINE (V_RESULT_NAME );
END;
/

Here you can dynamically insert values from json data into your table.

DECLARE
SAMPLE_JSON   VARCHAR2 (32767)
        := '{"items": [{"NAME":"AUDI","YEAR":"2000"},{"NAME":"BMW","YEAR":"2010"}]}';
BEGIN
FOR REC IN (
     SELECT J.NAME,J.YEAR
       FROM JSON_TABLE(SAMPLE_JSON,'$[*]' COLUMNS
        NAME VARCHAR2(20) PATH '$.items[0].NAME',
        YEAR NUMBER       PATH '$.items[0].YEAR'
       ) J  )
     LOOP
     EXECUTE IMMEDIATE 'INSERT INTO YOUR_TABLE(NAME,YEAR) VALUES('||REC.NAME||','||REC.YEAR||'); COMMIT;'
--       DBMS_OUTPUT.PUT_LINE (REC.NAME||','||REC.YEAR);
     END LOOP;
END;
/

Without using index.

DECLARE
SAMPLE_JSON   VARCHAR2 (32767)
        := '{"items": [{"NAME":"AUDI","YEAR":"2000"},{"NAME":"BMW","YEAR":"2010"},{"NAME":"TOFAS","YEAR":"1995"}]}';
BEGIN
FOR REC IN (
     SELECT J.NAME,J.YEAR
       FROM JSON_TABLE(SAMPLE_JSON,'$.items[*]' COLUMNS
        NAME VARCHAR2(20) PATH '$.NAME',
        YEAR NUMBER       PATH '$.YEAR'
       ) J  )
     LOOP
     --EXECUTE IMMEDIATE 'INSERT INTO YOUR_TABLE(NAMEE,YEARR) VALUES('||REC.NAME||','||REC.YEAR||'); COMMIT;';
      DBMS_OUTPUT.PUT_LINE (REC.NAME||','||REC.YEAR);
     END LOOP;
END;
/

Note: If you want to dynamically describe columns from your json data as i know of oracle can not do that. You have to describe json tags one by one as JSON_TABLE columns before use them.


问:
"Run > Stop on Objective-C exception" in Xcode 4?
Maybe somebody knows where is the "Run > Stop on Objective-C exception" menu in Xcode 4? I've used it sometimes in Xcode 3, but it disappeared in the new IDE.</p>

答:
In the left side column of xcode 4:

tap on the breakpoint tab (the 6th
tab over)

tap on the + button in the bottom
left of the window

tap 'add exception breakpoint'

tap 'done' on the popup


问:
Performance issue in updating Hashkey using HASHBYTES 'SHA2_256' for huge volume of ~20 million
I have a scenario wherein I need to update hash key value for nearly 20 million records. The hash key needs to be generated using nearly 70 attributes and will be used in frequent join conditions.

I am converting the HASHBYTES output to NVARCHAR and then updating the temp table which has nearly 20 million records. The update statement is taking 3+ hours to run.

```<code>UPDATE #TempSomeTable
SET HashKey = CONVERT(NVARCHAR(50), HASHBYTES('SHA2_256',CONCAT(ISNULL(COL_1,'NA'),ISNULL(COL_2,'NA'),ISNULL(COL_3,'NA'),.....ISNULL(COL_70,'NA'))),2)
</code>```

Here, the datatype of HashKey is NVARCHAR(50).

Can anyone here suggest how the performance can be improved?

Few options I am looking at it:

Converting the temp table to a MEMORY OPTIMIZED table

Applying ISNULL somewhere before the UPDATE statement

Changing datatype from NVARCHAR(50) to VARCHAR(50) OR BINARY(32)

Instead of UPDATE, Write the data into a new temp table and derive hash key in SELECT while inserting the record into new table (memory optimized table may be instead of temp table)

Please help and feedback.

答:
Get a faster computer

Do not use ONE update - find a way to split this into various updates, i.e. by range of primary key. Then you can issue those in parallel on multiple connections. If you have a 16 core machine, you can in theory split the update to 16 connections - though NOT on a temporary table, you will have to make it a GLOBAL temporary table (prefix ##) so all connections can see it (which is ok - give it a random name, i.e. a GUID and you are fine).

At the end, Hashbytes is serial as you use it (in an update) and is not the fastest out of necessity (it does quite a lot).

Body:
I have a scenario wherein I need to update hash key value for nearly 20 million records. The hash key needs to be generated using nearly 70 attributes and will be used in frequent join conditions.

I am converting the HASHBYTES output to NVARCHAR and then updating the temp table which has nearly 20 million records. The update statement is taking 3+ hours to run.

UPDATE #TempSomeTable
SET HashKey = CONVERT(NVARCHAR(50), HASHBYTES('SHA2_256',CONCAT(ISNULL(COL_1,'NA'),ISNULL(COL_2,'NA'),ISNULL(COL_3,'NA'),.....ISNULL(COL_70,'NA'))),2)

Here, the datatype of HashKey is NVARCHAR(50).

Can anyone here suggest how the performance can be improved?

Few options I am looking at it:

Converting the temp table to a MEMORY OPTIMIZED table

Applying ISNULL somewhere before the UPDATE statement

Changing datatype from NVARCHAR(50) to VARCHAR(50) OR BINARY(32)

Instead of UPDATE, Write the data into a new temp table and derive hash key in SELECT while inserting the record into new table (memory optimized table may be instead of temp table)

Please help and feedback.


问:
RxJs Wait for Promise to Resolve Before Continuing to Read Emitted Values
For every value emitted I want to do some asynchronous processing.

My goal is to wait before accepting the next value until myPromise has been resolved.

events.pipe(awaitPromise(async event => await myPromise(event))).subscribe();
```

Notes:

I don't know how long the promise will take to execute

Values emitted during the "pause" must not be discarded

I am not quite sure if this is even possible with RxJs. Maybe I need to implement some other kind of "queuing" system? But it would be really convenient for me to do it with RxJs!

答:
Use concatMap, you won't lose any events, they all queue up until promise resolved.

```<code>events.pipe(concatMap(event=>from(promiseFn(event)))
</code>```

Body:
For every value emitted I want to do some asynchronous processing.

My goal is to wait before accepting the next value until myPromise has been resolved.

events.pipe(awaitPromise(async event => await myPromise(event))).subscribe();

Notes:

I don't know how long the promise will take to execute

Values emitted during the "pause" must not be discarded

I am not quite sure if this is even possible with RxJs. Maybe I need to implement some other kind of "queuing" system? But it would be really convenient for me to do it with RxJs!

Body:
Use concatMap, you won't lose any events, they all queue up until promise resolved.

events.pipe(concatMap(event=>from(promiseFn(event)))


问:
What would be the correct design pattern to use
So I have a Generator interface:

```<code>public interface Generator
{
    public Generator getInstance(); (The problem is here - methods in interface can't be static)
    public Account generate() throws WalletInitializationException;
}
</code>```

And 2 other classes which implements the interface.

Now I'd like to have a GeneratorFactory class that receives the class Class object, invokes the getInstance() method and returns the class object.

Something like this:

```<code>public class GeneratorFactory
{
    private GeneratorFactory()
    {
    }

    public static Generator getGenerator(Class<Generator> generatorClass)
    {
        return (Generator) generatorClass.getMethod("getInstance", null).invoke((Need to have instance) null, null); (Should be runtime error)
    }
}
</code>```

But since the getInstance() method is an instance method and not a static method, I can't call invoke() with a null parameter for the instance.

I thought of doing an abstract class of a Factory which contains a getInstance() method and an abstract generate() method for the generators class to implement it, will that be the correct approach?

答:
I've ended up not using singleton. Just using a regular factory with the following method that uses reflection:</p>

```<code>    public static Generator getGenerator(Class<? extends Generator> generatorClass)
    {
        try
        {
            return generatorClass.newInstance();
        }
        catch (Exception e)
        {
            return null;
        }
    }
</code>```

Body:
So I have a Generator interface:

public interface Generator
{
    public Generator getInstance(); (The problem is here - methods in interface can't be static)
    public Account generate() throws WalletInitializationException;
}

And 2 other classes which implements the interface.

Now I'd like to have a GeneratorFactory class that receives the class Class object, invokes the getInstance() method and returns the class object.

Something like this:

public class GeneratorFactory
{
    private GeneratorFactory()
    {
    }

    public static Generator getGenerator(Class<Generator> generatorClass)
    {
        return (Generator) generatorClass.getMethod("getInstance", null).invoke((Need to have instance) null, null); (Should be runtime error)
    }
}

But since the getInstance() method is an instance method and not a static method, I can't call invoke() with a null parameter for the instance.

I thought of doing an abstract class of a Factory which contains a getInstance() method and an abstract generate() method for the generators class to implement it, will that be the correct approach?

Body:
I've ended up not using singleton. Just using a regular factory with the following method that uses reflection:

    public static Generator getGenerator(Class<? extends Generator> generatorClass)
    {
        try
        {
            return generatorClass.newInstance();
        }
        catch (Exception e)
        {
            return null;
        }
    }


问:
how to convert a binary string 128bit to decimal string in c++?
```<code>void convertBinaryToDecimal(std::string BinarySrc, std::string& DecimalDest)
{

}
</code>```

I need to convert a string binary length 128 bit to string Decimal

答:
For the answer given by user chqrlie, I would immediately ask, where we have nowadays 128 bit unsigned integer variables, and even if so, what will we do with 500 bit strings? So, this approach will of course not work.

What we need here, is an integer division for binary numbers. Then, we will do the same as we would do for decimals. Make an integer division by 10, and the remainder is the digit that we are interested in.

The below shown functionality works for arbitrary long strings with binary numbers. Also with other number bases

Please see:

EDIT

Updated according to the very good observation by user chux

```<code>#include <iostream>
#include <string>
#include <algorithm>

int main() {

    // This is the input number
    std::string binAsString{ "101010" };

    // Show orignial string to user
    std::cout << "\n\n" << binAsString;

    // Here we will store the resulting output
    std::string result{};

    // The conversion will also work for other  number bases
    // For base > 10 you need to adapt the creation of the digit at the bottom
    constexpr unsigned int numberBase{ 10 };

    // So, we will perfrom an integer division by 10, until the number is 0
    do {

        // The remainder is the digit that we are interested in
        unsigned int remainder{};
        // Temporary result of integer division
        std::string dividedNumberAsString{};

        // Do the division
        for (const char bit : binAsString) {

            // Calculate the remainder
            remainder = remainder * 2 + (bit - '0');

            // If we have a overflow (e.g. number is bigger than 10)
            if (remainder >= numberBase) {

                // Handle overflow
                remainder -= numberBase;
                // Add character 1 to the "devidedString"
                dividedNumberAsString += "1";
            }
            else {
                dividedNumberAsString += "0";
            }
        }
        // Now "dividedNumberAsString" as string is the result of the devision by e.g. 10 in binary form
        binAsString = dividedNumberAsString;
        // The remainder is the number that we are interested in
        result.insert(0, 1, '0' + remainder);

        // Continue the loop with the new binary string
    } while (std::count(binAsString.begin(), binAsString.end(), '1'));

    // Show result
    std::cout << "  -->\n" << result << "\n\n";
    return 0;
}
</code>```

Body:
void convertBinaryToDecimal(std::string BinarySrc, std::string& DecimalDest)
{

}

I need to convert a string binary length 128 bit to string Decimal

Body:
For the answer given by user chqrlie, I would immediately ask, where we have nowadays 128 bit unsigned integer variables, and even if so, what will we do with 500 bit strings? So, this approach will of course not work.

What we need here, is an integer division for binary numbers. Then, we will do the same as we would do for decimals. Make an integer division by 10, and the remainder is the digit that we are interested in.

The below shown functionality works for arbitrary long strings with binary numbers. Also with other number bases

Please see:

EDIT

Updated according to the very good observation by user chux

#include <iostream>
#include <string>
#include <algorithm>

int main() {

    // This is the input number
    std::string binAsString{ "101010" };

    // Show orignial string to user
    std::cout << "\n\n" << binAsString;

    // Here we will store the resulting output
    std::string result{};

    // The conversion will also work for other  number bases
    // For base > 10 you need to adapt the creation of the digit at the bottom
    constexpr unsigned int numberBase{ 10 };

    // So, we will perfrom an integer division by 10, until the number is 0
    do {

        // The remainder is the digit that we are interested in
        unsigned int remainder{};
        // Temporary result of integer division
        std::string dividedNumberAsString{};

        // Do the division
        for (const char bit : binAsString) {

            // Calculate the remainder
            remainder = remainder * 2 + (bit - '0');

            // If we have a overflow (e.g. number is bigger than 10)
            if (remainder >= numberBase) {

                // Handle overflow
                remainder -= numberBase;
                // Add character 1 to the "devidedString"
                dividedNumberAsString += "1";
            }
            else {
                dividedNumberAsString += "0";
            }
        }
        // Now "dividedNumberAsString" as string is the result of the devision by e.g. 10 in binary form
        binAsString = dividedNumberAsString;
        // The remainder is the number that we are interested in
        result.insert(0, 1, '0' + remainder);

        // Continue the loop with the new binary string
    } while (std::count(binAsString.begin(), binAsString.end(), '1'));

    // Show result
    std::cout << "  -->\n" << result << "\n\n";
    return 0;
}


问:
How to prevent blurry scrollbar on Windows Chrome after transform scale?
I'm facing a weird issue while trying to scale an HTML element. As demonstrated in this codepen, I want the element to appear scaled down (transform: scale(0.1)), then animate itself and scale up to its full size (transform: scale(1)). The element is a big list limited in height using overflow: auto;, which means a scrollbar is displayed.

My issue is that the scrollbar arrows are not scaled up correctly compared to the rest of the elements, which makes them extremely blurry and unrecognizable to the user. This only seems to happen on Windows (10) when using Chrome. cf screenshot below

I haven't been able to find any one on the Web talking about this issue, and it seems a bit confounding to me as it doesn't seem to be an edge case, and it is pretty simple to reproduce.

Thanks in advance for any advice :)

答:
A little change in your code seems to solve the issue.

Change scale by a perspective +  translateZ. this scales down the element (as it is now "far away"), and seems to not have the bug:

setInterval(() => {
  const className = document.getElementsByTagName('main')[0].className
document.getElementsByTagName('main')[0].className = className ? '' : "shazam"
}, 2000)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>main {
  height: 300px;
  width: 300px;
  border: 1px solid black;
  margin: auto;
  overflow: auto;
  transform: perspective(100px) translateZ(-1000px);
  transition: transform 1500ms;
  transform-origin: top left;
}

.shazam {
  transform: perspective(100px) translateZ(0px);
}</code>```

List of interesting things I've done during lockdown

… Who cares about lists anyway?

```

Body:
A little change in your code seems to solve the issue.

Change scale by a perspective +  translateZ. this scales down the element (as it is now "far away"), and seems to not have the bug:

setInterval(() => {
  const className = document.getElementsByTagName('main')[0].className
document.getElementsByTagName('main')[0].className = className ? '' : "shazam"
}, 2000)

main {
  height: 300px;
  width: 300px;
  border: 1px solid black;
  margin: auto;
  overflow: auto;
  transform: perspective(100px) translateZ(-1000px);
  transition: transform 1500ms;
  transform-origin: top left;
}

.shazam {
  transform: perspective(100px) translateZ(0px);
}

  <h1>List of interesting things I've done during lockdown</h1>
<main>
  <ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li>… Who cares about lists anyway?</li>
  </ul>
</main>


问:
How to create SSO URL in paperlesspipeline
i am trying to create SSO URL for the paperlesspipeline, so it no needs to credential for login

i have to use laravel 5.8 and it's GuzzleHttp package

$timestamp = date(DateTime::ISO8601);
        $userID = '*****';

```<code>    $url = "https://dev.paperlesspipeline.com/sso/signin-v1/";

    $hash = hash_hmac('SHA256', $userID.$timestamp,secret key,false);

    $client = new \GuzzleHttp\Client(['http_errors' => false]);

    $options = [
    'form_params' => [
        "USERID" => $userID,
        "timestamp" => $timestamp,
        "hash" => $hash
       ]
   ];

   $response  = $client->post($url, $options);
</code>```

I am not get sso url, can you halp me what wrong.

答:
You can try this</p>

```<code>$response = $client->request('POST', $url, $options);
</code>```

Body:
i am trying to create SSO URL for the paperlesspipeline, so it no needs to credential for login

i have to use laravel 5.8 and it's GuzzleHttp package

$timestamp = date(DateTime::ISO8601);
        $userID = '*****';

    $url = "https://dev.paperlesspipeline.com/sso/signin-v1/";

    $hash = hash_hmac('SHA256', $userID.$timestamp,secret key,false);

    $client = new \GuzzleHttp\Client(['http_errors' => false]);

    $options = [
    'form_params' => [
        "USERID" => $userID,
        "timestamp" => $timestamp,
        "hash" => $hash
       ]
   ];

   $response  = $client->post($url, $options);

I am not get sso url, can you halp me what wrong.

Body:
You can try this

$response = $client->request('POST', $url, $options);


问:
How do I compare values of BigInteger to be used as a condition in a loop?
I am trying to compare if the value of one BigInteger(base) is > (greater than) the value of another BigInteger(prime) and if the value of 'a' is not equal to one. If value of a is not 1, it should break out of the loop. How should I compare them?

Random ran = new Random();
BigInteger prime = new BigInteger(16,ran);
BigInteger base,a,one;
one = new BigInteger("1");

for (int i = 0; i < 65535; i++){

    while (base>prime){
        base = new BigInteger(16,ran);
    }
    a = base.modPow(prime.subtract(one),prime);
    System.out.println("a: "+a);
    if (a != one){
        break;
    }
}
```

答:
Since BigIntegers are objects, you should use caution when using the equality operators. Right now, you're performing a reference comparison (which in this case, will more than likely fail). You'll need to use the equals() or compareTo() methods.

BigInteger has a built-in static variable representing one. Use the equals() method or the compareTo() method to compare values:

```<code>if (!a.equals(BigInteger.ONE)) {
    ...
}
</code>```

-or-

```<code>if (a.compareTo(BigInteger.ONE) != 0) {
    ...
}
</code>```

Hope that helps! See here for more information: http://download.oracle.com/javase/6/docs/api/java/math/BigInteger.html

Body:
Since BigIntegers are objects, you should use caution when using the equality operators. Right now, you're performing a reference comparison (which in this case, will more than likely fail). You'll need to use the equals() or compareTo() methods.

BigInteger has a built-in static variable representing one. Use the equals() method or the compareTo() method to compare values:

if (!a.equals(BigInteger.ONE)) {
    ...
}

-or-

if (a.compareTo(BigInteger.ONE) != 0) {
    ...
}

Hope that helps! See here for more information: http://download.oracle.com/javase/6/docs/api/java/math/BigInteger.html


问:
slightly different results on scikit-learn decision trees regression
The 2 codes below should IMO deliver exactly the same output, but they don't, even though the results differ only marginally. The train_test split is fixed with a specified random_state which AFAIU should guarantee reproducible results. The only code difference is that code#0 uses an explicit variable for the decision tree model.

Code #0

```<code>from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_squared_error

boston = load_boston()
y = boston.target
X = boston.data

X_train, X_test, y_train, y_test = train_test_split(
            X, y, test_size=0.33, random_state=42)

DT_regressor = DecisionTreeRegressor()
DT_model = DT_regressor.fit(X_train, y_train)
y_DT_pred = DT_model.predict(X_test)

def mse(actual, preds):
    delta = np.sum((actual-preds)*(actual-preds))
    return delta/len(preds)

# Check your solution matches sklearn
print('decision trees')
print(mse(y_test, y_DT_pred))
print(mean_squared_error(y_test, y_DT_pred))
print("If the above match, you are all set!")
print('predicted')
print(y_DT_pred)
print('labels')
print(y_test)
</code>```

Code #1

```<code>from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn.ensemble import RandomForestRegressor, AdaBoostRegressor
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error

boston = load_boston()
y = boston.target
X = boston.data

X_train, X_test, y_train, y_test = train_test_split(
            X, y, test_size=0.33, random_state=42)

tree_mod = DecisionTreeRegressor()
tree_mod.fit(X_train, y_train)
preds_tree = tree_mod.predict(X_test)

def mse(actual, preds):
    return np.sum((actual-preds)**2)/len(actual)

# Check your solution matches sklearn
print(mse(y_test, preds_tree))
print(mean_squared_error(y_test, preds_tree))
print("If the above match, you are all set!")
print('predicted')
print(preds_tree)
print('labels')
print(y_test)
</code>```

Even after changing random_state=0, there are differences.

output of code#0

```<code>26.12281437125748
26.12281437125748
If the above match, you are all set!
predicted
[23.4 24.5 20.1 11.7 20.7 20.4 21.8 20.5 22.7 16.1 10.8 17.9 14.9  8.8
 50.  37.  21.2 32.7 28.  18.9 23.1 22.7 23.1 24.8 19.7 10.9 19.3 13.1
 37.6 18.4 12.5 17.7 24.5 23.1 23.2 17.7  8.3 19.5 12.7 17.9 22.9 19.7
 23.9 12.5 22.  20.5 22.4 13.8 15.6 28.7 13.8 18.3 18.2 35.2 19.  22.4
 21.7 20.7 10.9 19.5 20.6 23.1 34.9 30.1 17.7 32.  16.1 18.9 16.7 21.7
 20.6 23.8 23.2 33.1 28.4  8.8 41.7 23.1 22.  21.8 27.1 19.3 20.2 37.6
 37.6 25.  19.3 13.8 24.3 14.3 17.5 11.8 23.1 35.1 21.6 23.8 10.2 20.7
 14.3 23.1 25.  20.1 33.8 24.5 25.  23.1  8.3 19.5 23.8 22.  23.6 17.9
 18.9 18.3 20.  20.   9.5 14.5  9.5 50.  32.   6.3 14.4 21.7 25.  17.3
 34.9 22.5 18.9 36.1 12.5  9.5 15.2 19.6 10.5 34.9 20.  15.6 28.6  8.3
 10.9 21.8 23.6 24.4 24.2 14.5 37.3 37.3 12.8  6.3 28.4 25.  15.6 32.4
 17.4 23.7 17.3 19.7 21.8 13.1  8.3 17.5 34.9 31.6 31.  23.1 23.1]
labels
[22.6 50.  23.   8.3 21.2 19.9 20.6 18.7 16.1 18.6  8.8 17.2 14.9 10.5
 50.  29.  23.  33.3 29.4 21.  23.8 19.1 20.4 29.1 19.3 23.1 19.6 19.4
 38.7 18.7 14.6 20.  20.5 20.1 23.6 16.8  5.6 50.  14.5 13.3 23.9 20.
 19.8 13.8 16.5 21.6 20.3 17.  11.8 27.5 15.6 23.1 24.3 42.8 15.6 21.7
 17.1 17.2 15.  21.7 18.6 21.  33.1 31.5 20.1 29.8 15.2 15.  27.5 22.6
 20.  21.4 23.5 31.2 23.7  7.4 48.3 24.4 22.6 18.3 23.3 17.1 27.9 44.8
 50.  23.  21.4 10.2 23.3 23.2 18.9 13.4 21.9 24.8 11.9 24.3 13.8 24.7
 14.1 18.7 28.1 19.8 26.7 21.7 22.  22.9 10.4 21.9 20.6 26.4 41.3 17.2
 27.1 20.4 16.5 24.4  8.4 23.   9.7 50.  30.5 12.3 19.4 21.2 20.3 18.8
 33.4 18.5 19.6 33.2 13.1  7.5 13.6 17.4  8.4 35.4 24.  13.4 26.2  7.2
 13.1 24.5 37.2 25.  24.1 16.6 32.9 36.2 11.   7.2 22.8 28.7 14.4 24.4
 18.1 22.5 20.5 15.2 17.4 13.6  8.7 18.2 35.4 31.7 33.  22.2 20.4]

</code>```

output of code#1

```<code>28.135568862275445
28.135568862275445
If the above match, you are all set!
predicted
[23.1 24.5 20.1 19.1 20.7 20.4 21.8 19.  21.8 16.1 10.8 17.9 14.9  8.8
 50.  37.  21.2 32.7 24.5 18.9 23.1 21.5 20.1 24.8 19.7 10.9 19.3 15.6
 37.6 18.8 12.5 19.1 24.5 23.1 23.9 17.7  7.  19.5 12.7 17.9 22.9 19.7
 23.9 12.5 22.  20.5 22.5 13.3 15.6 28.4 13.3 18.4 18.2 21.9 18.4 22.4
 21.7 20.7 10.9 19.3 19.4 23.1 35.1 30.1 19.1 32.  16.1 18.9 16.7 21.7
 20.6 23.8 23.7 33.1 28.6  7.2 41.7 23.1 22.  21.7 27.1 19.2 20.2 37.6
 37.6 25.  19.3 13.8 24.3 14.3 17.5 11.8 23.2 34.9 21.6 23.8 10.9 22.3
 14.3 23.1 25.  20.1 30.3 24.5 21.  23.1  8.3 19.9 23.8 22.  23.6 17.9
 20.  18.4 18.9 20.7  9.5 14.5 10.2 50.  32.   6.3 14.4 21.7 25.  17.4
 34.9 22.5 18.9 37.3 12.7  9.5 15.2 19.6 10.8 34.9 22.2 15.6 28.6  7.
 10.9 21.7 23.6 24.4 24.2 16.  37.3 37.3 12.8  8.8 28.6 25.3 14.3 32.5
 17.4 23.7 17.4 19.9 21.7 12.7  7.  17.6 35.1 31.5 30.3 23.1 22.1]
labels
[22.6 50.  23.   8.3 21.2 19.9 20.6 18.7 16.1 18.6  8.8 17.2 14.9 10.5
 50.  29.  23.  33.3 29.4 21.  23.8 19.1 20.4 29.1 19.3 23.1 19.6 19.4
 38.7 18.7 14.6 20.  20.5 20.1 23.6 16.8  5.6 50.  14.5 13.3 23.9 20.
 19.8 13.8 16.5 21.6 20.3 17.  11.8 27.5 15.6 23.1 24.3 42.8 15.6 21.7
 17.1 17.2 15.  21.7 18.6 21.  33.1 31.5 20.1 29.8 15.2 15.  27.5 22.6
 20.  21.4 23.5 31.2 23.7  7.4 48.3 24.4 22.6 18.3 23.3 17.1 27.9 44.8
 50.  23.  21.4 10.2 23.3 23.2 18.9 13.4 21.9 24.8 11.9 24.3 13.8 24.7
 14.1 18.7 28.1 19.8 26.7 21.7 22.  22.9 10.4 21.9 20.6 26.4 41.3 17.2
 27.1 20.4 16.5 24.4  8.4 23.   9.7 50.  30.5 12.3 19.4 21.2 20.3 18.8
 33.4 18.5 19.6 33.2 13.1  7.5 13.6 17.4  8.4 35.4 24.  13.4 26.2  7.2
 13.1 24.5 37.2 25.  24.1 16.6 32.9 36.2 11.   7.2 22.8 28.7 14.4 24.4
 18.1 22.5 20.5 15.2 17.4 13.6  8.7 18.2 35.4 31.7 33.  22.2 20.4]
</code>```

答:
The model itself has also a random component. So fixing just the split won't be enough. Try to set
DecisionTreeRegressor(random_state=0)
as well.

If that doesn't help it would be useful if you post your results.

Body:
The 2 codes below should IMO deliver exactly the same output, but they don't, even though the results differ only marginally. The train_test split is fixed with a specified random_state which AFAIU should guarantee reproducible results. The only code difference is that code#0 uses an explicit variable for the decision tree model.

Code #0

from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_squared_error

boston = load_boston()
y = boston.target
X = boston.data

X_train, X_test, y_train, y_test = train_test_split(
            X, y, test_size=0.33, random_state=42)

DT_regressor = DecisionTreeRegressor()
DT_model = DT_regressor.fit(X_train, y_train)
y_DT_pred = DT_model.predict(X_test)

def mse(actual, preds):
    delta = np.sum((actual-preds)*(actual-preds))
    return delta/len(preds)

# Check your solution matches sklearn
print('decision trees')
print(mse(y_test, y_DT_pred))
print(mean_squared_error(y_test, y_DT_pred))
print("If the above match, you are all set!")
print('predicted')
print(y_DT_pred)
print('labels')
print(y_test)

Code #1

from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn.ensemble import RandomForestRegressor, AdaBoostRegressor
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error

boston = load_boston()
y = boston.target
X = boston.data

X_train, X_test, y_train, y_test = train_test_split(
            X, y, test_size=0.33, random_state=42)

tree_mod = DecisionTreeRegressor()
tree_mod.fit(X_train, y_train)
preds_tree = tree_mod.predict(X_test)

def mse(actual, preds):
    return np.sum((actual-preds)**2)/len(actual)

# Check your solution matches sklearn
print(mse(y_test, preds_tree))
print(mean_squared_error(y_test, preds_tree))
print("If the above match, you are all set!")
print('predicted')
print(preds_tree)
print('labels')
print(y_test)

Even after changing random_state=0, there are differences.

output of code#0

26.12281437125748
26.12281437125748
If the above match, you are all set!
predicted
[23.4 24.5 20.1 11.7 20.7 20.4 21.8 20.5 22.7 16.1 10.8 17.9 14.9  8.8
 50.  37.  21.2 32.7 28.  18.9 23.1 22.7 23.1 24.8 19.7 10.9 19.3 13.1
 37.6 18.4 12.5 17.7 24.5 23.1 23.2 17.7  8.3 19.5 12.7 17.9 22.9 19.7
 23.9 12.5 22.  20.5 22.4 13.8 15.6 28.7 13.8 18.3 18.2 35.2 19.  22.4
 21.7 20.7 10.9 19.5 20.6 23.1 34.9 30.1 17.7 32.  16.1 18.9 16.7 21.7
 20.6 23.8 23.2 33.1 28.4  8.8 41.7 23.1 22.  21.8 27.1 19.3 20.2 37.6
 37.6 25.  19.3 13.8 24.3 14.3 17.5 11.8 23.1 35.1 21.6 23.8 10.2 20.7
 14.3 23.1 25.  20.1 33.8 24.5 25.  23.1  8.3 19.5 23.8 22.  23.6 17.9
 18.9 18.3 20.  20.   9.5 14.5  9.5 50.  32.   6.3 14.4 21.7 25.  17.3
 34.9 22.5 18.9 36.1 12.5  9.5 15.2 19.6 10.5 34.9 20.  15.6 28.6  8.3
 10.9 21.8 23.6 24.4 24.2 14.5 37.3 37.3 12.8  6.3 28.4 25.  15.6 32.4
 17.4 23.7 17.3 19.7 21.8 13.1  8.3 17.5 34.9 31.6 31.  23.1 23.1]
labels
[22.6 50.  23.   8.3 21.2 19.9 20.6 18.7 16.1 18.6  8.8 17.2 14.9 10.5
 50.  29.  23.  33.3 29.4 21.  23.8 19.1 20.4 29.1 19.3 23.1 19.6 19.4
 38.7 18.7 14.6 20.  20.5 20.1 23.6 16.8  5.6 50.  14.5 13.3 23.9 20.
 19.8 13.8 16.5 21.6 20.3 17.  11.8 27.5 15.6 23.1 24.3 42.8 15.6 21.7
 17.1 17.2 15.  21.7 18.6 21.  33.1 31.5 20.1 29.8 15.2 15.  27.5 22.6
 20.  21.4 23.5 31.2 23.7  7.4 48.3 24.4 22.6 18.3 23.3 17.1 27.9 44.8
 50.  23.  21.4 10.2 23.3 23.2 18.9 13.4 21.9 24.8 11.9 24.3 13.8 24.7
 14.1 18.7 28.1 19.8 26.7 21.7 22.  22.9 10.4 21.9 20.6 26.4 41.3 17.2
 27.1 20.4 16.5 24.4  8.4 23.   9.7 50.  30.5 12.3 19.4 21.2 20.3 18.8
 33.4 18.5 19.6 33.2 13.1  7.5 13.6 17.4  8.4 35.4 24.  13.4 26.2  7.2
 13.1 24.5 37.2 25.  24.1 16.6 32.9 36.2 11.   7.2 22.8 28.7 14.4 24.4
 18.1 22.5 20.5 15.2 17.4 13.6  8.7 18.2 35.4 31.7 33.  22.2 20.4]

output of code#1

28.135568862275445
28.135568862275445
If the above match, you are all set!
predicted
[23.1 24.5 20.1 19.1 20.7 20.4 21.8 19.  21.8 16.1 10.8 17.9 14.9  8.8
 50.  37.  21.2 32.7 24.5 18.9 23.1 21.5 20.1 24.8 19.7 10.9 19.3 15.6
 37.6 18.8 12.5 19.1 24.5 23.1 23.9 17.7  7.  19.5 12.7 17.9 22.9 19.7
 23.9 12.5 22.  20.5 22.5 13.3 15.6 28.4 13.3 18.4 18.2 21.9 18.4 22.4
 21.7 20.7 10.9 19.3 19.4 23.1 35.1 30.1 19.1 32.  16.1 18.9 16.7 21.7
 20.6 23.8 23.7 33.1 28.6  7.2 41.7 23.1 22.  21.7 27.1 19.2 20.2 37.6
 37.6 25.  19.3 13.8 24.3 14.3 17.5 11.8 23.2 34.9 21.6 23.8 10.9 22.3
 14.3 23.1 25.  20.1 30.3 24.5 21.  23.1  8.3 19.9 23.8 22.  23.6 17.9
 20.  18.4 18.9 20.7  9.5 14.5 10.2 50.  32.   6.3 14.4 21.7 25.  17.4
 34.9 22.5 18.9 37.3 12.7  9.5 15.2 19.6 10.8 34.9 22.2 15.6 28.6  7.
 10.9 21.7 23.6 24.4 24.2 16.  37.3 37.3 12.8  8.8 28.6 25.3 14.3 32.5
 17.4 23.7 17.4 19.9 21.7 12.7  7.  17.6 35.1 31.5 30.3 23.1 22.1]
labels
[22.6 50.  23.   8.3 21.2 19.9 20.6 18.7 16.1 18.6  8.8 17.2 14.9 10.5
 50.  29.  23.  33.3 29.4 21.  23.8 19.1 20.4 29.1 19.3 23.1 19.6 19.4
 38.7 18.7 14.6 20.  20.5 20.1 23.6 16.8  5.6 50.  14.5 13.3 23.9 20.
 19.8 13.8 16.5 21.6 20.3 17.  11.8 27.5 15.6 23.1 24.3 42.8 15.6 21.7
 17.1 17.2 15.  21.7 18.6 21.  33.1 31.5 20.1 29.8 15.2 15.  27.5 22.6
 20.  21.4 23.5 31.2 23.7  7.4 48.3 24.4 22.6 18.3 23.3 17.1 27.9 44.8
 50.  23.  21.4 10.2 23.3 23.2 18.9 13.4 21.9 24.8 11.9 24.3 13.8 24.7
 14.1 18.7 28.1 19.8 26.7 21.7 22.  22.9 10.4 21.9 20.6 26.4 41.3 17.2
 27.1 20.4 16.5 24.4  8.4 23.   9.7 50.  30.5 12.3 19.4 21.2 20.3 18.8
 33.4 18.5 19.6 33.2 13.1  7.5 13.6 17.4  8.4 35.4 24.  13.4 26.2  7.2
 13.1 24.5 37.2 25.  24.1 16.6 32.9 36.2 11.   7.2 22.8 28.7 14.4 24.4
 18.1 22.5 20.5 15.2 17.4 13.6  8.7 18.2 35.4 31.7 33.  22.2 20.4]


问:
How to stop a foreground service from the notification in android?
I am using a foreground service in my application I need to stop this service from a button that is present on the notification itself without opening the activity.
My current code

This is my activity from where I am starting the service.

```<code>serviceIntent = new Intent(getApplicationContext(),BackgroundService.class);
        serviceIntent.putExtra("ip",ipAdd);
        serviceIntent.putExtra("token",token);
        serviceIntent.putExtra("port",portNo);
        serviceIntent.putExtra("resource",resourceId);
        serviceIntent.putExtra("userName",username);
        startService(serviceIntent);
        ClosingBackGroundService.getMainActivityContext(MainActivity.this);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopService(serviceIntent);
            }
        });

</code>```

I am using a class to show the button on the notification and trying to close the activity

```<code>public class ClosingBackGroundService extends BroadcastReceiver {

   static Context mainActContext;
    public static void getMainActivityContext(Context context){
        mainActContext = context;
    }
    @Override
    public void onReceive(Context context, Intent intent) {
       mainActContext.stopService(MainActivity.serviceIntent);
        Log.i("Service","closed");
    }
}
</code>```

```<code> @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
       registerReceiver(broadcastReceiver, filter);
        Intent notificationIntent = new Intent(this,LoginActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,notificationIntent,0);
        Intent closingIntent = new Intent(this,ClosingBackGroundService.class);
        PendingIntent actionIntent = PendingIntent.getBroadcast(this,0,closingIntent,PendingIntent.FLAG_UPDATE_CURRENT);
    Notification notification = new NotificationCompat.Builder(this,CHANNEL_ID)
            .setOngoing(true)
             .setSmallIcon(R.drawable.logo)
            .addAction(R.mipmap.ic_launcher,"Close Services",actionIntent)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .setContentText("Processes Running In BackGround").build();
    ipAdd = intent.getStringExtra("ip");
    port = intent.getStringExtra("port");
    token = intent.getStringExtra("token");
    resourceId = intent.getIntExtra("resource",0);
    username = intent.getStringExtra("userName");
    runnableForGps.run();
    runnableForSendingGpsData.run();
    runnableForBluetooth.run();
    runnableForsendingBTData.run();
    startForeground(1,notification);

    return START_STICKY;
    }
</code>```

When I press the button the notification disappears but the process keeps on working.

答:
You don't need to create BroadCast to stop Service. Try this

```<code>private static final String ACTION_STOP_LISTEN = "action_stop_listen";
</code>```

```<code>Intent intent = new Intent(this, ClosingBackGroundService.class);
intent.setAction(ACTION_STOP_LISTEN);
PendingIntent actionIntent = PendingIntent.getService(this, 123, intent, PendingIntent.FLAG_UPDATE_CURRENT);
addAction(R.mipmap.ic_launcher,"Close Services",actionIntent)
</code>```

In onStartCommand check your Intent action

```<code>@Override
public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null && ACTION_STOP_LISTEN.equals(intent.getAction())) {
            stopForeground(true);
            stopSelf();
            return START_NOT_STICKY;
        }
        // your code
}
</code>```

Body:
I am using a foreground service in my application I need to stop this service from a button that is present on the notification itself without opening the activity.
My current code

This is my activity from where I am starting the service.

serviceIntent = new Intent(getApplicationContext(),BackgroundService.class);
        serviceIntent.putExtra("ip",ipAdd);
        serviceIntent.putExtra("token",token);
        serviceIntent.putExtra("port",portNo);
        serviceIntent.putExtra("resource",resourceId);
        serviceIntent.putExtra("userName",username);
        startService(serviceIntent);
        ClosingBackGroundService.getMainActivityContext(MainActivity.this);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopService(serviceIntent);
            }
        });

I am using a class to show the button on the notification and trying to close the activity

public class ClosingBackGroundService extends BroadcastReceiver {

   static Context mainActContext;
    public static void getMainActivityContext(Context context){
        mainActContext = context;
    }
    @Override
    public void onReceive(Context context, Intent intent) {
       mainActContext.stopService(MainActivity.serviceIntent);
        Log.i("Service","closed");
    }
}

 @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
       registerReceiver(broadcastReceiver, filter);
        Intent notificationIntent = new Intent(this,LoginActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,notificationIntent,0);
        Intent closingIntent = new Intent(this,ClosingBackGroundService.class);
        PendingIntent actionIntent = PendingIntent.getBroadcast(this,0,closingIntent,PendingIntent.FLAG_UPDATE_CURRENT);
    Notification notification = new NotificationCompat.Builder(this,CHANNEL_ID)
            .setOngoing(true)
             .setSmallIcon(R.drawable.logo)
            .addAction(R.mipmap.ic_launcher,"Close Services",actionIntent)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .setContentText("Processes Running In BackGround").build();
    ipAdd = intent.getStringExtra("ip");
    port = intent.getStringExtra("port");
    token = intent.getStringExtra("token");
    resourceId = intent.getIntExtra("resource",0);
    username = intent.getStringExtra("userName");
    runnableForGps.run();
    runnableForSendingGpsData.run();
    runnableForBluetooth.run();
    runnableForsendingBTData.run();
    startForeground(1,notification);

    return START_STICKY;
    }

When I press the button the notification disappears but the process keeps on working.

Body:
You don't need to create BroadCast to stop Service. Try this

private static final String ACTION_STOP_LISTEN = "action_stop_listen";

Intent intent = new Intent(this, ClosingBackGroundService.class);
intent.setAction(ACTION_STOP_LISTEN);
PendingIntent actionIntent = PendingIntent.getService(this, 123, intent, PendingIntent.FLAG_UPDATE_CURRENT);
addAction(R.mipmap.ic_launcher,"Close Services",actionIntent)

In onStartCommand check your Intent action

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null && ACTION_STOP_LISTEN.equals(intent.getAction())) {
            stopForeground(true);
            stopSelf();
            return START_NOT_STICKY;
        }
        // your code
}


问:
Warning: mysqli_stmt_init() expects parameter 1 to be mysqli, null given
I'm making a chat feature for a site and am not good with PHP:

```<code><?php

if (isset($_POST['send'])) {
    require 'database.php';

    $input = $_POST['input'];
} else {
    $sql = "INSERT INTO chatsys (chat) VALUES (?)";
    $stmt = mysqli_stmt_init($conn);
    if (!mysqli_stmt_prepare($stmt, $sql)) {
        header("index.html?error=sqlerror");
        exit();
    } else {
        mysqli_stmt_bind_param($stmt, "sss", $input);
        mysqli_stmt_execute($stmt);
        header("index.html?request=success");
        exit();
    }
}
{
    mysqli_stmt_close($stmt);
    mysqli_close($conn);
}
</code>```

And database code:

```<code><?php

$servername = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "chatsys";

$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);

if (!$conn) {
    die("Connection failed: ".mysqli_connect_error());
}
?>
</code>```

This results in:

Notice: Undefined variable: conn in C:\Users\John Doe\Desktop\server\htdocs\php\message\chat.php on line 11

  Warning: mysqli_stmt_init() expects parameter 1 to be mysqli, null given in C:\Users\John Doe\Desktop\server\htdocs\php\message\chat.php on line 11

  Warning: mysqli_stmt_prepare() expects parameter 1 to be mysqli_stmt, null given in C:\Users\john doe\Desktop\server\htdocs\php\message\chat.php on line 12

What have I done wrong?

答:
You are overcomplicating your code. You do not need all these braces or if statements. You do not need to check the return value of mysqli calls if you enable error reporting.

```<code><?php

// If value was posted to the server
if (isset($_POST['send'])) {
    // include mysqli connection
    require 'database.php';

    // perform prepared statement. (prepare/bind/execute)
    $stmt = $conn->prepare("INSERT INTO chatsys (chat) VALUES (?)");
    $stmt->bind_param("sss", $_POST['input']);
    $stmt->execute();
    // redirect on success
    header("index.html?request=success");
    exit();
}
</code>```

and your connection file:

```<code><?php

$servername = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "chatsys";

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);
$conn->set_charset('utf8mb4'); // always set the charset
</code>```

Body:
I'm making a chat feature for a site and am not good with PHP:

<?php

if (isset($_POST['send'])) {
    require 'database.php';

    $input = $_POST['input'];
} else {
    $sql = "INSERT INTO chatsys (chat) VALUES (?)";
    $stmt = mysqli_stmt_init($conn);
    if (!mysqli_stmt_prepare($stmt, $sql)) {
        header("index.html?error=sqlerror");
        exit();
    } else {
        mysqli_stmt_bind_param($stmt, "sss", $input);
        mysqli_stmt_execute($stmt);
        header("index.html?request=success");
        exit();
    }
}
{
    mysqli_stmt_close($stmt);
    mysqli_close($conn);
}

And database code:

<?php

$servername = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "chatsys";

$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);

if (!$conn) {
    die("Connection failed: ".mysqli_connect_error());
}
?>

This results in:

Notice: Undefined variable: conn in C:\Users\John Doe\Desktop\server\htdocs\php\message\chat.php on line 11

  Warning: mysqli_stmt_init() expects parameter 1 to be mysqli, null given in C:\Users\John Doe\Desktop\server\htdocs\php\message\chat.php on line 11

  Warning: mysqli_stmt_prepare() expects parameter 1 to be mysqli_stmt, null given in C:\Users\john doe\Desktop\server\htdocs\php\message\chat.php on line 12

What have I done wrong?

Body:
You are overcomplicating your code. You do not need all these braces or if statements. You do not need to check the return value of mysqli calls if you enable error reporting.

<?php

// If value was posted to the server
if (isset($_POST['send'])) {
    // include mysqli connection
    require 'database.php';

    // perform prepared statement. (prepare/bind/execute)
    $stmt = $conn->prepare("INSERT INTO chatsys (chat) VALUES (?)");
    $stmt->bind_param("sss", $_POST['input']);
    $stmt->execute();
    // redirect on success
    header("index.html?request=success");
    exit();
}

and your connection file:

<?php

$servername = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "chatsys";

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);
$conn->set_charset('utf8mb4'); // always set the charset


问:
SELECT column based on conditions
I have a table similar to the following:

```<code>+---------+--------------+
| user_id | distance     |
+---------+--------------+
|     101 | 12.05        |
|     103 | 4.8          |
|     207 | 37.1         |
|     991 | 3.51         |
|     215 | 15.9         |
+---------+--------------+
</code>```

Then I want the number of users that cover different range of distances: 0-5km as short_distance, 5-10km as medium_distance, >10km as long_distance.

I'm kind of confused when aggregating.

答:
You want the count of users category wise. Try This

```<code>select
       case
         when distance > 10 then 'long_distance'
         when distance > 5  then 'medium_distance'
         else 'short_distance'
      end as "distance_type", count(*) as "Count"
from user_distance

group by "distance_type"
</code>```

DEMO

Title: SELECT column based on conditions

Body:
I have a table similar to the following:

+---------+--------------+
| user_id | distance     |
+---------+--------------+
|     101 | 12.05        |
|     103 | 4.8          |
|     207 | 37.1         |
|     991 | 3.51         |
|     215 | 15.9         |
+---------+--------------+

Then I want the number of users that cover different range of distances: 0-5km as short_distance, 5-10km as medium_distance, >10km as long_distance.

I'm kind of confused when aggregating.

Body:
You want the count of users category wise. Try This

select
       case
         when distance > 10 then 'long_distance'
         when distance > 5  then 'medium_distance'
         else 'short_distance'
      end as "distance_type", count(*) as "Count"
from user_distance

group by "distance_type"

DEMO


问:
How to use categorical colour scheme in matplotlib with missing values?
I want to make a scatter plot in python coloured by a categorical variable that handles and plots missing values for the categorical colour variable.

Using the iris dataset as an example

```<code>import seaborn as sns
iris = sns.load_dataset('iris')
</code>```

Seaborn can plot by colour:

```<code>sns.lmplot('sepal_length', 'sepal_width', hue='species', data=iris, fit_reg=False)
</code>```

With a little more work so can matplotlib (taken from this answer)

```<code>colours = {'setosa':'skyblue', 'versicolor':'orangered', 'virginica':'forestgreen'}
plt.scatter(iris.sepal_length, iris.sepal_width, c=iris.species.apply(lambda x:colours[x]))
</code>```

But neither will plot missing colours. If we set the species variable (which we use to colour the plot) to np.nan for one species seaborn doesn't plot those points and matplotlib won't plot anything.

```<code>iris.species[iris.species == 'setosa'] = np.nan

sns.lmplot('sepal_length', 'sepal_width', hue='species', data=iris, fit_reg=False)
iris.plot('sepal_length', 'sepal_width', kind="scatter", c=iris.species.apply(lambda x:colours[x]))
</code>```

答:
I haven't found a solution with seaborn but you can tweak the lambda function to work it in matplotlib. If the species is in your colour dictionary it looks the colour up there but if the species is null it return a novel colour.

```<code>import seaborn as sns
iris = sns.load_dataset('iris')

#colour dictionary
colours = {'setosa':'skyblue', 'versicolor':'orangered', 'virginica':'forestgreen'}

col_convert = np.vectorize(lambda x: 'grey' if pd.isnull(x) else colours[x])

plt.scatter(iris.sepal_length, iris.sepal_width, c=col_convert(iris.species))
</code>```

Body:
I want to make a scatter plot in python coloured by a categorical variable that handles and plots missing values for the categorical colour variable.

Using the iris dataset as an example

import seaborn as sns
iris = sns.load_dataset('iris')

Seaborn can plot by colour:

sns.lmplot('sepal_length', 'sepal_width', hue='species', data=iris, fit_reg=False)

With a little more work so can matplotlib (taken from this answer)

colours = {'setosa':'skyblue', 'versicolor':'orangered', 'virginica':'forestgreen'}
plt.scatter(iris.sepal_length, iris.sepal_width, c=iris.species.apply(lambda x:colours[x]))

But neither will plot missing colours. If we set the species variable (which we use to colour the plot) to np.nan for one species seaborn doesn't plot those points and matplotlib won't plot anything.

iris.species[iris.species == 'setosa'] = np.nan

sns.lmplot('sepal_length', 'sepal_width', hue='species', data=iris, fit_reg=False)
iris.plot('sepal_length', 'sepal_width', kind="scatter", c=iris.species.apply(lambda x:colours[x]))

Body:
I haven't found a solution with seaborn but you can tweak the lambda function to work it in matplotlib. If the species is in your colour dictionary it looks the colour up there but if the species is null it return a novel colour.

import seaborn as sns
iris = sns.load_dataset('iris')

#colour dictionary
colours = {'setosa':'skyblue', 'versicolor':'orangered', 'virginica':'forestgreen'}

col_convert = np.vectorize(lambda x: 'grey' if pd.isnull(x) else colours[x])

plt.scatter(iris.sepal_length, iris.sepal_width, c=col_convert(iris.species))


答:
Maybe</p>

```<code>while (base.compareTo(prime)>0){
//rest of your loop
}
</code>```

Title: How do I compare values of BigInteger to be used as a condition in a loop?

Body:
I am trying to compare if the value of one BigInteger(base) is > (greater than) the value of another BigInteger(prime) and if the value of 'a' is not equal to one. If value of a is not 1, it should break out of the loop. How should I compare them?

Random ran = new Random();
BigInteger prime = new BigInteger(16,ran);
BigInteger base,a,one;
one = new BigInteger("1");

for (int i = 0; i < 65535; i++){

    while (base>prime){
        base = new BigInteger(16,ran);
    }
    a = base.modPow(prime.subtract(one),prime);
    System.out.println("a: "+a);
    if (a != one){
        break;
    }
}

Body:
Maybe

while (base.compareTo(prime)>0){
//rest of your loop
}